Public: anyone can read this; the crew can change it.

Access 3, terminal, games and infrastructure: the entries' own gates are deleted once may() has been asked beside them and agrees #18428

opened this

Merged 11h 32m ago, live in production

scout/forge:scout/18425-access-3-terminal-games-and-infrastructu → main 0 commits fork

  • Merged. scout/18425-access-3-terminal-games-and-infrastructu was merged into main as be10e7a.

Review

Sign in to review this change.
6 files changed +76 −63
docs/features/may.md +9
@@ -55,6 +55,15 @@ than reading. The page's old check (`isAdmin`, an account
5555 behind the request) still decides; `may` is worked out beside it, and where the two part the count's door is
5656 `web <page>`, the page's module. Nothing you can open on the web changes while the count is read.
5757
58 **The infrastructure pages and the cloud API ask it alone.** Every `/infra` page and change, and
59 `GET /api/v1/cloud/accounts`, decide by `forge.administer` (`src/http/infra_routes.ts`, `src/http/api/cloud.ts`);
60 their inline `isAdmin` checks are gone (#18425), and `test/door-inline-checks.test.ts` keeps them gone. A page asks it of
61 the account behind the request and every change reads its form with an `admin` scope, so an admin's `ro` token still
62 opens the pages and is refused a change (403), as before; the cloud API asks with the credential you send, so an `ro`
63 token is refused (403), a person who is not the admin is told not found and a stranger is asked to authenticate. An
64 admin's look at `GET /api/v1/places` refreshes a stale catalog only when `may` grants `forge.administer` with the
65 credential sent.
66
5867 **The terminal's screens ask it.** A palette entry whose gate is the forge's admin names `forge.administer` beside it,
5968 and one whose gate is an account names `forge.read` (opening a screen is a read); the palette asks `may` that action as
6069 the terminal's account, once a session for each entry and answer, not on every build (`src/tui/screens/entries.ts`, the
src/design/door_checks.ts +11 −4
@@ -1,6 +1,7 @@
11 /**
22 * The inline access check does not come back into a moved door (#18406, Access 3's last step). The
3 * repository routes under `src/http/api/` and the MCP tools (`src/http/mcp.ts`, `src/http/mcp/`)
3 * repository routes under `src/http/api/`, the MCP tools (`src/http/mcp.ts`, `src/http/mcp/`), the
4 * infrastructure pages and the cloud API (`src/http/infra_routes.ts`, `src/http/api/cloud.ts`)
45 * now ask `may`; this ratchet reads their source and finds each line that gates on the account
56 * inline: a refusal on `isAdmin` (`!user.isAdmin`, `isAdmin !== true`, or `isAdmin` in an `if`), a
67 * `scopeAllows(…, "rw")` write floor, or a signed-out test (`!ctx.auth.user`, `ctx.auth.user ===
@@ -57,10 +58,16 @@ export function doorChecks(src: Source): DoorFound[] {
5758 });
5859 }
5960
60 /** The files the moved doors live in: repository route modules under src/http/api, and the MCP. */
61 /** The moved doors outside those: the infrastructure pages and the cloud API (#18425). */
62 const MOVED = new Set(["src/http/mcp.ts", "src/http/infra_routes.ts"]);
63
64 /**
65 * The files the moved doors live in: repository route modules and the cloud API under
66 * src/http/api, the infrastructure pages, and the MCP.
67 */
6168 export function doorSources(root: string): Source[] {
62 const api = tsSources(root, "src/http/api").filter((f) => f.text.includes("/api/v1/repos/"));
63 const mcp = tsSources(root, "src/http").filter((f) => f.path === "src/http/mcp.ts");
69 const api = tsSources(root, "src/http/api").filter((f) => f.text.includes("/api/v1/repos/") || f.path === "src/http/api/cloud.ts");
70 const mcp = tsSources(root, "src/http").filter((f) => MOVED.has(f.path));
6471 return [...api, ...mcp, ...tsSources(root, "src/http/mcp")];
6572 }
6673
src/http/api/cloud.ts +8 −11
@@ -8,15 +8,15 @@
88
99 import { usesByVendor, type VendorUse } from "../../cloud/declared.ts";
1010 import { cloudOverview } from "../../cloud/overview.ts";
11 import { scopeAllows } from "../../core/tokens.ts";
1211 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1312 import type { Handler } from "../context.ts";
14 import { holds, weakEtag } from "../etag.ts";
13 import { holds as etagHolds, weakEtag } from "../etag.ts";
1514 import { pinPlace, placesCatalog } from "../../actions/places.ts";
1615 import { refreshIfDue } from "../../actions/places_refresh.ts";
1716 import { MAX_ID } from "../../cloud/places_read.ts";
1817 import { accountAdmin } from "./admin.ts";
19 import { mayBeside } from "../may_beside.ts";
18 import { holds } from "../../core/may.ts";
19 import { principalOf } from "../../core/principal.ts";
2020 import { apiError, body, json, notFound, str, unauthorized } from "../respond.ts";
2121 import type { Router } from "../router.ts";
2222
@@ -25,12 +25,10 @@ export function cloudRoutes(router: Router<Handler>): void {
2525 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2626 const user = ctx.auth.user;
2727 if (!user || ctx.auth.scope === undefined) return unauthorized();
28 if (!scopeAllows(ctx.auth.scope, "rw"))
28 if (!holds(ctx.app.db, principalOf(ctx.auth), "forge.write"))
2929 return apiError("forbidden", 403, "a read-only token cannot list cloud accounts");
30 // Access 3 (#18404): the admin check decides; `may` is asked beside it and a parting counted.
31 const admin = user.isAdmin;
32 mayBeside(ctx, "infra cloud accounts", "forge.administer", admin);
33 if (!admin) return notFound();
30 // Access 3 (#18425): `may` decides, with the credential sent; an `ro` token was refused above.
31 if (!holds(ctx.app.db, principalOf(ctx.auth), "forge.administer")) return notFound();
3432 const uses = await usesByVendor(ctx.app.db, ctx.app.reposRoot, user).catch(
3533 () => new Map<string, VendorUse[]>(),
3634 );
@@ -41,7 +39,7 @@ export function cloudRoutes(router: Router<Handler>): void {
4139 const text = JSON.stringify(seen.value);
4240 const etag = weakEtag(text);
4341 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
44 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
42 if (etagHolds(ctx.request, etag)) return new Response(null, { status: 304, headers });
4543 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
4644 });
4745
@@ -52,8 +50,7 @@ export function cloudRoutes(router: Router<Handler>): void {
5250 if (!user || ctx.auth.scope === undefined) return unauthorized();
5351 // An admin's look refreshes a stale catalog first; a failed read leaves the last good one
5452 // standing. Every vendor call is audited, so only a write-scoped token starts one.
55 const refresh = user.isAdmin && scopeAllows(ctx.auth.scope, "rw");
56 mayBeside(ctx, "infra places refresh", "forge.administer", refresh);
53 const refresh = holds(ctx.app.db, principalOf(ctx.auth), "forge.administer");
5754 if (refresh) await refreshIfDue(ctx.app, user);
5855 const url = new URL(ctx.request.url);
5956 const q = (k: string) => url.searchParams.get(k) ?? undefined;
src/http/infra_routes.ts +27 −23
@@ -27,7 +27,8 @@ import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTree
2727 import { filesByNode } from "../cloud/declared_read.ts";
2828 import { logsOfContainer } from "../cloud/containers.ts";
2929 import { nodeAt, tabOf, type CloudNode, type CloudView } from "../cloud/tree.ts";
30 import { mayBeside } from "./may_beside.ts";
30 import { may } from "../core/may.ts";
31 import { principalOfUser } from "../core/principal.ts";
3132 import { pinnedBlock } from "./pinned_routes.ts";
3233 import { containerConsole } from "../web/pages/games.ts";
3334 import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts";
@@ -88,7 +89,7 @@ function placeOf(pathname: string): string[] | undefined {
8889 // GET /infra/-/<cloud>/<account>/<project>/<id>, or any level above it: the tree with that open
8990 // beside it. `?fragment=1` is what opens alone, `?fragment=explorer` a branch's rows.
9091 async function infraResource(ctx: Ctx): Promise<Response> {
91 const denied = guard(ctx, "resource");
92 const denied = guard(ctx);
9293 if (denied) return denied;
9394 const path = placeOf(ctx.url.pathname) ?? [];
9495 const tree = timePhase(ctx.request, "tree", () => treeOf(ctx));
@@ -139,13 +140,16 @@ async function render(
139140 const toBuild = (planId: string): Response => new Response(null, { status: 303, headers: { location: `/infra/build?plan=${planId}` } });
140141
141142 /**
142 * Access 3 (#18404): the admin check still decides; `may` is asked `forge.administer` beside it and
143 * a parting is counted in `access_disagreement` under `infra <route>`. Only the boolean goes in.
143 * Access 3 (#18404, #18425): `may` alone decides who reaches `/infra`, asked `forge.administer` of
144 * the account behind the request. A token's scope is judged where it was before: every change reads
145 * its form with `readForm(ctx, "admin")`, so an admin's `ro` token still reads these pages and is
146 * refused (403) a change, and nobody's status moved when the inline `isAdmin` went.
144147 */
145 function guard(ctx: Ctx, route: string): Response | undefined {
146 const admin = ctx.auth.user?.isAdmin === true;
147 mayBeside(ctx, `infra ${route}`, "forge.administer", admin);
148 return admin ? undefined : !ctx.auth.user ? signInFirst(ctx) : notFoundPage(ctx);
148 const administers = (ctx: Ctx) => may(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer");
149
150 function guard(ctx: Ctx): Response | undefined {
151 const asked = administers(ctx);
152 return asked.ok ? undefined : asked.why === "unauthorized" ? signInFirst(ctx) : notFoundPage(ctx);
149153 }
150154
151155 /** What the forge runs, with what each provider says of it as kept: no page waits on a provider. */
@@ -169,7 +173,7 @@ const endsOf = (ctx: Ctx) => {
169173 };
170174
171175 function infraGet(ctx: Ctx): Response {
172 const denied = guard(ctx, "overview");
176 const denied = guard(ctx);
173177 if (denied) return denied;
174178 // A build's old address, kept for the links a talk already holds.
175179 const planId = ctx.url.searchParams.get("plan");
@@ -185,7 +189,7 @@ function infraGet(ctx: Ctx): Response {
185189 // GET /infra/build, /infra/build?app=owner/name from an app's page, and ?plan=<id> for a build's
186190 // progress.
187191 function infraBuild(ctx: Ctx): Promise<Response> | Response {
188 const denied = guard(ctx, "build");
192 const denied = guard(ctx);
189193 if (denied) return denied;
190194 const planId = ctx.url.searchParams.get("plan") ?? undefined;
191195 return render(ctx, undefined, planId === undefined ? { app: ctx.url.searchParams.get("app") ?? "" } : { planId });
@@ -193,11 +197,11 @@ function infraBuild(ctx: Ctx): Promise<Response> | Response {
193197
194198 // GET /infra/live?part=running | ?plan=<id>: a live region alone, refetched on an event.
195199 function infraLive(ctx: Ctx): Response {
196 mayBeside(ctx, "infra live", "forge.administer", ctx.auth.user?.isAdmin === true);
197 if (!ctx.auth.user?.isAdmin) return fragment(html``, { status: 404 });
200 const user = ctx.auth.user;
201 if (!administers(ctx).ok || user === undefined) return fragment(html``, { status: 404 });
198202 const planId = ctx.url.searchParams.get("plan");
199203 if (planId !== null) {
200 const b = buildOf(ctx.app, ctx.auth.user, planId);
204 const b = buildOf(ctx.app, user, planId);
201205 return b === undefined ? fragment(html``, { status: 404 }) : fragment(buildTray(b), { request: ctx.request });
202206 }
203207 // The place picker, narrowed by a filter's words on the server: the catalog never rides the page.
@@ -220,7 +224,7 @@ function infraLive(ctx: Ctx): Response {
220224 // POST /infra/plan: the tray for what the form says now (a fragment for the page's script), or the
221225 // whole page with it for a browser without one.
222226 async function infraPlan(ctx: Ctx): Promise<Response> {
223 const denied = guard(ctx, "plan");
227 const denied = guard(ctx);
224228 if (denied) return denied;
225229 const form = await readForm(ctx, "admin");
226230 if (form instanceof Response) return form;
@@ -232,7 +236,7 @@ async function infraPlan(ctx: Ctx): Promise<Response> {
232236
233237 // POST /infra/apply: build what the form says, if it is the plan the person was shown.
234238 async function infraApply(ctx: Ctx): Promise<Response> {
235 const denied = guard(ctx, "apply");
239 const denied = guard(ctx);
236240 if (denied) return denied;
237241 const form = await readForm(ctx, "admin");
238242 if (form instanceof Response) return form;
@@ -258,7 +262,7 @@ async function infraApply(ctx: Ctx): Promise<Response> {
258262 // POST /infra/record: plan the DNS record the form says and start it; a record costs nothing, so
259263 // this one press is the Build. Every refusal comes back as a flash.
260264 async function infraRecord(ctx: Ctx): Promise<Response> {
261 const denied = guard(ctx, "record");
265 const denied = guard(ctx);
262266 if (denied) return denied;
263267 const form = await readForm(ctx, "admin");
264268 if (form instanceof Response) return form;
@@ -279,7 +283,7 @@ async function infraRecord(ctx: Ctx): Promise<Response> {
279283
280284 // POST /infra/rebuild: the same wants again, after a build stopped.
281285 async function infraRebuild(ctx: Ctx): Promise<Response> {
282 const denied = guard(ctx, "rebuild");
286 const denied = guard(ctx);
283287 if (denied) return denied;
284288 const form = await readForm(ctx, "admin");
285289 if (form instanceof Response) return form;
@@ -291,7 +295,7 @@ async function infraRebuild(ctx: Ctx): Promise<Response> {
291295
292296 // POST /infra/projects: read every account into its projects now (GETs only), then back to them.
293297 async function infraProjects(ctx: Ctx): Promise<Response> {
294 const denied = guard(ctx, "projects");
298 const denied = guard(ctx);
295299 if (denied) return denied;
296300 const form = await readForm(ctx, "admin");
297301 if (form instanceof Response) return form;
@@ -308,7 +312,7 @@ async function infraProjects(ctx: Ctx): Promise<Response> {
308312
309313 // POST /infra/:name/keep and /infra/:name/end (End now arrives from the confirm page).
310314 async function infraMachine(ctx: Ctx): Promise<Response> {
311 const denied = guard(ctx, "machine");
315 const denied = guard(ctx);
312316 if (denied) return denied;
313317 const form = await readForm(ctx, "admin");
314318 if (form instanceof Response) return form;
@@ -361,7 +365,7 @@ async function infraMachine(ctx: Ctx): Promise<Response> {
361365
362366 // GET /infra/:name/ending: the offer to snapshot before End.
363367 function infraEnding(ctx: Ctx): Response {
364 const denied = guard(ctx, "ending");
368 const denied = guard(ctx);
365369 if (denied) return denied;
366370 const m = machineOf(ctx.app, ctx.auth.user, ctx.params.name ?? "");
367371 if (!m.ok || m.value === undefined || !m.value.atProvider || m.value.offer === "") return notFoundPage(ctx);
@@ -370,7 +374,7 @@ function infraEnding(ctx: Ctx): Response {
370374
371375 // GET /infra/:name/cloud: what the provider's API says of the machine, read on open.
372376 async function infraCloud(ctx: Ctx): Promise<Response> {
373 const denied = guard(ctx, "cloud");
377 const denied = guard(ctx);
374378 if (denied) return denied;
375379 const name = ctx.params.name ?? "";
376380 const seen = await machineView(ctx.app, ctx.auth.user, name);
@@ -380,7 +384,7 @@ async function infraCloud(ctx: Ctx): Promise<Response> {
380384 // POST /infra/snapshot/:id/restore (a new forge's name) and /delete (arrives from the confirm
381385 // page).
382386 async function infraSnapshot(ctx: Ctx): Promise<Response> {
383 const denied = guard(ctx, "snapshot");
387 const denied = guard(ctx);
384388 if (denied) return denied;
385389 const form = await readForm(ctx, "admin");
386390 if (form instanceof Response) return form;
@@ -399,7 +403,7 @@ async function infraSnapshot(ctx: Ctx): Promise<Response> {
399403
400404 // GET /infra/end/:act/<path>: the plan of a stop or a delete. POST: the confirm.
401405 async function infraEnd(ctx: Ctx): Promise<Response> {
402 const denied = guard(ctx, "end");
406 const denied = guard(ctx);
403407 if (denied) return denied;
404408 const act = endActOf(ctx.params.act);
405409 const path = placeOf(`/infra/-/${ctx.url.pathname.split("/").slice(4).join("/")}`);
test/door-inline-checks.test.ts +2
@@ -22,6 +22,8 @@ test("the scan reads the repository route modules and every MCP file", () => {
2222 expect(paths).toContain("src/http/mcp.ts");
2323 expect(paths).toContain("src/http/mcp/shared.ts");
2424 expect(paths).toContain("src/http/mcp/tools/system.ts");
25 expect(paths).toContain("src/http/infra_routes.ts");
26 expect(paths).toContain("src/http/api/cloud.ts");
2527 // A forge-wide module with no repository route is the other door's.
2628 expect(paths.every((p) => !p.startsWith("src/http/api/") || !p.endsWith("/admin.ts"))).toBe(true);
2729 });
test/infra-routes-may.test.ts +19 −25
@@ -1,8 +1,8 @@
11 /**
2 * Access 3, infrastructure and clouds (#18404): the admin-only `/infra` routes and the cloud API
3 * ask `may` beside their old admin check (`mayBeside`, door `infra <route>`), and the old check
4 * still decides. An admin, an everyday person, an agent's token and an anonymous visitor each get
5 * the answer they got before, with no row; a forced parting writes one.
2 * Access 3, infrastructure and clouds (#18404, #18425): the admin-only `/infra` routes and the
3 * cloud API decide by `may(forge.administer)` alone; their inline `isAdmin` checks are gone. An
4 * admin, an everyday person, an agent's token, an admin's `ro` token and an anonymous visitor each
5 * get the status they got while the old check decided, and nothing is counted any more.
66 */
77 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
@@ -13,9 +13,7 @@ import { createApp, type App } from "../src/app.ts";
1313 import { createSession } from "../src/core/sessions.ts";
1414 import { createToken } from "../src/core/tokens.ts";
1515 import { createUser, type User } from "../src/core/users.ts";
16 import type { Ctx } from "../src/http/context.ts";
17 import { mayBeside } from "../src/http/may_beside.ts";
18 import { forgeHttp, resolveAuth } from "../src/http/server.ts";
16 import { forgeHttp } from "../src/http/server.ts";
1917 import { quietLogs } from "./helpers/globals.ts";
2018 import { promote } from "./helpers/members.ts";
2119
@@ -60,8 +58,8 @@ const rows = () => app.db.query("SELECT door, action, principal, may FROM access
6058 const session = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` });
6159 const bearer = (u: User, scope: "ro" | "rw" | "admin" = "rw") => ({ authorization: `Bearer ${createToken(app.db, u.id, scope, scope).token}` });
6260
63 async function status(path: string, headers: Record<string, string>): Promise<number> {
64 const res = await http.handle(new Request(`http://${HOST}${path}`, { headers }));
61 async function status(path: string, headers: Record<string, string>, method = "GET"): Promise<number> {
62 const res = await http.handle(new Request(`http://${HOST}${path}`, { method, headers: { ...headers, origin: `http://${HOST}` } }));
6563 await res.body?.cancel();
6664 return res.status;
6765 }
@@ -95,11 +93,19 @@ test("an anonymous visitor is sent to sign in, or told to authenticate, as befor
9593 expect(rows()).toEqual([]);
9694 });
9795
98 test("a forced parting writes one row under the door's name, and the old answer still decides", async () => {
99 // The old check asks only isAdmin; may also asks the token's scope, and an ro token may not
100 // administer. The admin's ro token is still let in, and the parting is counted once.
96 test("an admin's ro token reads the pages as before and is refused a change (403), as before: no row", async () => {
97 // `may` is asked of the account behind the request; the token's scope is judged by the form read.
10198 expect(await status("/infra/build", bearer(users.boss, "ro"))).toBe(200);
102 expect(rows()).toEqual([{ door: "infra build", action: "forge.administer", principal: "ro_token", may: 0 }]);
99 expect(await status("/infra/live?part=running", bearer(users.boss, "ro"))).toBe(200);
100 expect(await status("/infra/projects", bearer(users.boss, "ro"), "POST")).toBe(403);
101 expect(await status("/api/v1/cloud/accounts", bearer(users.boss, "ro"))).toBe(403);
102 expect(rows()).toEqual([]);
103 });
104
105 test("a change by someone who may not administer: sign in first, or not found, as before", async () => {
106 expect(await status("/infra/projects", {}, "POST")).toBe(303);
107 expect(await status("/infra/projects", bearer(users.bot), "POST")).toBe(404);
108 expect(await status("/infra/build", bearer(users.bot, "admin"))).toBe(404);
103109 });
104110
105111 test("the places catalog: an admin's rw token, an agent's token and an admin's ro token are all answered, and no row", async () => {
@@ -109,15 +115,3 @@ test("the places catalog: an admin's rw token, an agent's token and an admin's r
109115 expect(await status("/api/v1/places", bearer(users.boss, "ro"))).toBe(200);
110116 expect(rows()).toEqual([]);
111117 });
112
113 test("the cloud doors count a parting under their own names; no request can force one", async () => {
114 // Both cloud checks already require an rw token, which is all may adds to isAdmin, so the parting
115 // is forced by handing mayBeside an old answer that differs from the admin's ro token's.
116 const request = new Request(`http://${HOST}/api/v1/places`, { headers: bearer(users.boss, "ro") });
117 const ctx = { app, auth: await resolveAuth(app, request), request, url: new URL(request.url) } as unknown as Ctx;
118 for (const door of ["infra cloud accounts", "infra places refresh"]) expect(mayBeside(ctx, door, "forge.administer", true)).toBe(false);
119 expect(rows()).toEqual([
120 { door: "infra cloud accounts", action: "forge.administer", principal: "ro_token", may: 0 },
121 { door: "infra places refresh", action: "forge.administer", principal: "ro_token", may: 0 },
122 ]);
123 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs