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

Access 3, infrastructure and clouds: the admin-only routes ask may() in shadow #18409

opened this

Merged 1h 49m ago, live in production

scout/forge:scout/18404-access-3-infrastructure-and-clouds-the-a → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/18404-access-3-infrastructure-and-clouds-the-a was merged into main as 7855bb1.

Review

Sign in to review this change.
3 files changed +155 −17
src/http/api/cloud.ts +8 −2
@@ -16,6 +16,7 @@ import { pinPlace, placesCatalog } from "../../actions/places.ts";
1616 import { refreshIfDue } from "../../actions/places_refresh.ts";
1717 import { MAX_ID } from "../../cloud/places_read.ts";
1818 import { accountAdmin } from "./admin.ts";
19 import { mayBeside } from "../may_beside.ts";
1920 import { apiError, body, json, notFound, str, unauthorized } from "../respond.ts";
2021 import type { Router } from "../router.ts";
2122
@@ -26,7 +27,10 @@ export function cloudRoutes(router: Router<Handler>): void {
2627 if (!user || ctx.auth.scope === undefined) return unauthorized();
2728 if (!scopeAllows(ctx.auth.scope, "rw"))
2829 return apiError("forbidden", 403, "a read-only token cannot list cloud accounts");
29 if (!user.isAdmin) return notFound();
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();
3034 const uses = await usesByVendor(ctx.app.db, ctx.app.reposRoot, user).catch(
3135 () => new Map<string, VendorUse[]>(),
3236 );
@@ -48,7 +52,9 @@ export function cloudRoutes(router: Router<Handler>): void {
4852 if (!user || ctx.auth.scope === undefined) return unauthorized();
4953 // An admin's look refreshes a stale catalog first; a failed read leaves the last good one
5054 // standing. Every vendor call is audited, so only a write-scoped token starts one.
51 if (user.isAdmin && scopeAllows(ctx.auth.scope, "rw")) await refreshIfDue(ctx.app, user);
55 const refresh = user.isAdmin && scopeAllows(ctx.auth.scope, "rw");
56 mayBeside(ctx, "infra places refresh", "forge.administer", refresh);
57 if (refresh) await refreshIfDue(ctx.app, user);
5258 const url = new URL(ctx.request.url);
5359 const q = (k: string) => url.searchParams.get(k) ?? undefined;
5460 const seen = placesCatalog(ctx.app, { plan: q("plan"), provider: q("provider"), country: q("country") });
src/http/infra_routes.ts +24 −15
@@ -27,6 +27,7 @@ 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";
3031 import { pinnedBlock } from "./pinned_routes.ts";
3132 import { containerConsole } from "../web/pages/games.ts";
3233 import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts";
@@ -87,7 +88,7 @@ function placeOf(pathname: string): string[] | undefined {
8788 // GET /infra/-/<cloud>/<account>/<project>/<id>, or any level above it: the tree with that open
8889 // beside it. `?fragment=1` is what opens alone, `?fragment=explorer` a branch's rows.
8990 async function infraResource(ctx: Ctx): Promise<Response> {
90 const denied = guard(ctx);
91 const denied = guard(ctx, "resource");
9192 if (denied) return denied;
9293 const path = placeOf(ctx.url.pathname) ?? [];
9394 const tree = timePhase(ctx.request, "tree", () => treeOf(ctx));
@@ -137,8 +138,15 @@ async function render(
137138 /** To the build's tray, which says what is happening better than a flash could. */
138139 const toBuild = (planId: string): Response => new Response(null, { status: 303, headers: { location: `/infra/build?plan=${planId}` } });
139140
140 const guard = (ctx: Ctx): Response | undefined =>
141 !ctx.auth.user ? signInFirst(ctx) : !ctx.auth.user.isAdmin ? notFoundPage(ctx) : undefined;
141 /**
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.
144 */
145 function guard(ctx: Ctx, route: string): Response | undefined {
outdated

This wrapper only calls mayBeside and returns old. Call mayBeside directly in guard and infraLive.

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);
149 }
142150
143151 /** What the forge runs, with what each provider says of it as kept: no page waits on a provider. */
144152 function runningNow(ctx: Ctx): Html | undefined {
@@ -161,7 +169,7 @@ const endsOf = (ctx: Ctx) => {
161169 };
162170
163171 function infraGet(ctx: Ctx): Response {
164 const denied = guard(ctx);
172 const denied = guard(ctx, "overview");
165173 if (denied) return denied;
166174 // A build's old address, kept for the links a talk already holds.
167175 const planId = ctx.url.searchParams.get("plan");
@@ -177,7 +185,7 @@ function infraGet(ctx: Ctx): Response {
177185 // GET /infra/build, /infra/build?app=owner/name from an app's page, and ?plan=<id> for a build's
178186 // progress.
179187 function infraBuild(ctx: Ctx): Promise<Response> | Response {
180 const denied = guard(ctx);
188 const denied = guard(ctx, "build");
181189 if (denied) return denied;
182190 const planId = ctx.url.searchParams.get("plan") ?? undefined;
183191 return render(ctx, undefined, planId === undefined ? { app: ctx.url.searchParams.get("app") ?? "" } : { planId });
@@ -185,6 +193,7 @@ function infraBuild(ctx: Ctx): Promise<Response> | Response {
185193
186194 // GET /infra/live?part=running | ?plan=<id>: a live region alone, refetched on an event.
187195 function infraLive(ctx: Ctx): Response {
196 mayBeside(ctx, "infra live", "forge.administer", ctx.auth.user?.isAdmin === true);
188197 if (!ctx.auth.user?.isAdmin) return fragment(html``, { status: 404 });
189198 const planId = ctx.url.searchParams.get("plan");
190199 if (planId !== null) {
@@ -211,7 +220,7 @@ function infraLive(ctx: Ctx): Response {
211220 // POST /infra/plan: the tray for what the form says now (a fragment for the page's script), or the
212221 // whole page with it for a browser without one.
213222 async function infraPlan(ctx: Ctx): Promise<Response> {
214 const denied = guard(ctx);
223 const denied = guard(ctx, "plan");
215224 if (denied) return denied;
216225 const form = await readForm(ctx, "admin");
217226 if (form instanceof Response) return form;
@@ -223,7 +232,7 @@ async function infraPlan(ctx: Ctx): Promise<Response> {
223232
224233 // POST /infra/apply: build what the form says, if it is the plan the person was shown.
225234 async function infraApply(ctx: Ctx): Promise<Response> {
226 const denied = guard(ctx);
235 const denied = guard(ctx, "apply");
227236 if (denied) return denied;
228237 const form = await readForm(ctx, "admin");
229238 if (form instanceof Response) return form;
@@ -249,7 +258,7 @@ async function infraApply(ctx: Ctx): Promise<Response> {
249258 // POST /infra/record: plan the DNS record the form says and start it; a record costs nothing, so
250259 // this one press is the Build. Every refusal comes back as a flash.
251260 async function infraRecord(ctx: Ctx): Promise<Response> {
252 const denied = guard(ctx);
261 const denied = guard(ctx, "record");
253262 if (denied) return denied;
254263 const form = await readForm(ctx, "admin");
255264 if (form instanceof Response) return form;
@@ -270,7 +279,7 @@ async function infraRecord(ctx: Ctx): Promise<Response> {
270279
271280 // POST /infra/rebuild: the same wants again, after a build stopped.
272281 async function infraRebuild(ctx: Ctx): Promise<Response> {
273 const denied = guard(ctx);
282 const denied = guard(ctx, "rebuild");
274283 if (denied) return denied;
275284 const form = await readForm(ctx, "admin");
276285 if (form instanceof Response) return form;
@@ -282,7 +291,7 @@ async function infraRebuild(ctx: Ctx): Promise<Response> {
282291
283292 // POST /infra/projects: read every account into its projects now (GETs only), then back to them.
284293 async function infraProjects(ctx: Ctx): Promise<Response> {
285 const denied = guard(ctx);
294 const denied = guard(ctx, "projects");
286295 if (denied) return denied;
287296 const form = await readForm(ctx, "admin");
288297 if (form instanceof Response) return form;
@@ -299,7 +308,7 @@ async function infraProjects(ctx: Ctx): Promise<Response> {
299308
300309 // POST /infra/:name/keep and /infra/:name/end (End now arrives from the confirm page).
301310 async function infraMachine(ctx: Ctx): Promise<Response> {
302 const denied = guard(ctx);
311 const denied = guard(ctx, "machine");
303312 if (denied) return denied;
304313 const form = await readForm(ctx, "admin");
305314 if (form instanceof Response) return form;
@@ -352,7 +361,7 @@ async function infraMachine(ctx: Ctx): Promise<Response> {
352361
353362 // GET /infra/:name/ending: the offer to snapshot before End.
354363 function infraEnding(ctx: Ctx): Response {
355 const denied = guard(ctx);
364 const denied = guard(ctx, "ending");
356365 if (denied) return denied;
357366 const m = machineOf(ctx.app, ctx.auth.user, ctx.params.name ?? "");
358367 if (!m.ok || m.value === undefined || !m.value.atProvider || m.value.offer === "") return notFoundPage(ctx);
@@ -361,7 +370,7 @@ function infraEnding(ctx: Ctx): Response {
361370
362371 // GET /infra/:name/cloud: what the provider's API says of the machine, read on open.
363372 async function infraCloud(ctx: Ctx): Promise<Response> {
364 const denied = guard(ctx);
373 const denied = guard(ctx, "cloud");
365374 if (denied) return denied;
366375 const name = ctx.params.name ?? "";
367376 const seen = await machineView(ctx.app, ctx.auth.user, name);
@@ -371,7 +380,7 @@ async function infraCloud(ctx: Ctx): Promise<Response> {
371380 // POST /infra/snapshot/:id/restore (a new forge's name) and /delete (arrives from the confirm
372381 // page).
373382 async function infraSnapshot(ctx: Ctx): Promise<Response> {
374 const denied = guard(ctx);
383 const denied = guard(ctx, "snapshot");
375384 if (denied) return denied;
376385 const form = await readForm(ctx, "admin");
377386 if (form instanceof Response) return form;
@@ -390,7 +399,7 @@ async function infraSnapshot(ctx: Ctx): Promise<Response> {
390399
391400 // GET /infra/end/:act/<path>: the plan of a stop or a delete. POST: the confirm.
392401 async function infraEnd(ctx: Ctx): Promise<Response> {
393 const denied = guard(ctx);
402 const denied = guard(ctx, "end");
394403 if (denied) return denied;
395404 const act = endActOf(ctx.params.act);
396405 const path = placeOf(`/infra/-/${ctx.url.pathname.split("/").slice(4).join("/")}`);
test/infra-routes-may.test.ts added +123
@@ -0,0 +1,123 @@
1 /**
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.
6 */
7 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createAgent } from "../src/actions/crew.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 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";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { promote } from "./helpers/members.ts";
21
22 quietLogs();
23
24 const HOST = "forge.test";
25 const cellsBefore = process.env["FORGE_CELLS"];
26 let dataDir = "";
27 let app: App;
28 let http: ReturnType<typeof forgeHttp>;
29 const users = {} as Record<"boss" | "gina" | "bot", User>;
30
31 beforeAll(async () => {
32 process.env["FORGE_CELLS"] = "off"; // env-restored: afterAll
33 dataDir = await mkdtemp(join(tmpdir(), "forge-infra-may-"));
34 app = createApp({ dataDir, port: 0, host: HOST });
35 for (const name of ["boss", "gina"] as const) {
36 const made = await createUser(app.db, {
37 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
38 password: "a-good-passphrase", adminIfFirst: name === "boss",
39 });
40 if (!made.ok) throw new Error(String(made.error));
41 users[name] = made.value;
42 }
43 promote(app.db, users.boss, users.gina); // a member, not a guest: she reaches the admin gate itself
44 const bot = await createAgent(app, users.boss, { username: "infrabot", brief: "x" });
45 if (!bot.ok) throw new Error(String(bot.error));
46 users.bot = bot.value.user;
47 http = forgeHttp(app);
48 });
49
50 afterAll(async () => {
51 if (cellsBefore === undefined) delete process.env["FORGE_CELLS"];
52 else process.env["FORGE_CELLS"] = cellsBefore;
53 app.close();
54 await rm(dataDir, { recursive: true, force: true });
55 });
56
57 beforeEach(() => app.db.run("DELETE FROM access_disagreement"));
58
59 const rows = () => app.db.query("SELECT door, action, principal, may FROM access_disagreement ORDER BY door").all();
60 const session = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` });
61 const bearer = (u: User, scope: "ro" | "rw" | "admin" = "rw") => ({ authorization: `Bearer ${createToken(app.db, u.id, scope, scope).token}` });
62
63 async function status(path: string, headers: Record<string, string>): Promise<number> {
64 const res = await http.handle(new Request(`http://${HOST}${path}`, { headers }));
65 await res.body?.cancel();
66 return res.status;
67 }
68
69 /**
70 * Admin-marked pages: an everyday account meets `admin_gate`'s 403 before the handler, as before.
71 */
72 const PAGES = ["/infra/build", "/infra/live?part=running"];
73
74 test("an admin is let in, an everyday person is not, and may agrees: no row", async () => {
75 for (const p of PAGES) {
76 expect(await status(p, session(users.boss))).toBeLessThan(400);
77 expect(await status(p, session(users.gina))).toBe(403);
78 }
79 expect(await status("/api/v1/cloud/accounts", bearer(users.boss, "admin"))).toBe(200);
80 expect(await status("/api/v1/cloud/accounts", bearer(users.gina))).toBe(403);
81 expect(await status("/api/v1/places", bearer(users.gina))).toBe(200);
82 expect(rows()).toEqual([]);
83 });
84
85 test("an agent's token, not an admin, is turned away as before: no row", async () => {
86 expect(await status("/api/v1/cloud/accounts", bearer(users.bot))).toBe(404);
87 expect(await status("/infra/build", bearer(users.bot))).toBe(404);
88 expect(rows()).toEqual([]);
89 });
90
91 test("an anonymous visitor is sent to sign in, or told to authenticate, as before: no row", async () => {
92 expect(await status("/infra/build", {})).toBe(303);
93 expect(await status("/infra/live?part=running", {})).toBe(404);
94 expect(await status("/api/v1/cloud/accounts", {})).toBe(401);
95 expect(rows()).toEqual([]);
96 });
97
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.
101 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 }]);
103 });
104
outdated

This test greps source text, so it passes even if the call is dead. Replace it with real requests to /api/v1/places (admin rw, admin ro, agent token) asserting status and rows, plus a forced-disagreement row under infra places refresh or infra cloud accounts, or a direct mayBeside test with those door names.

105 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 () => {
106 expect(await status("/api/v1/places", bearer(users.boss, "rw"))).toBe(200);
107 expect(await status("/api/v1/places", bearer(users.bot, "rw"))).toBe(200);
108 // An ro token skips the refresh, and may refuses it forge.administer too: they agree.
109 expect(await status("/api/v1/places", bearer(users.boss, "ro"))).toBe(200);
110 expect(rows()).toEqual([]);
111 });
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