Public: anyone can read this; the crew can change it.
Access 3, infrastructure and clouds: the admin-only routes ask may() in shadow #18409
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
3 files
changed +155
−17
src/http/api/cloud.ts +8 −2
| @@ -16,6 +16,7 @@ import { pinPlace, placesCatalog } from "../../actions/places.ts"; | ||
| 16 | 16 | import { refreshIfDue } from "../../actions/places_refresh.ts"; |
| 17 | 17 | import { MAX_ID } from "../../cloud/places_read.ts"; |
| 18 | 18 | import { accountAdmin } from "./admin.ts"; |
| 19 | import { mayBeside } from "../may_beside.ts"; | |
| 19 | 20 | import { apiError, body, json, notFound, str, unauthorized } from "../respond.ts"; |
| 20 | 21 | import type { Router } from "../router.ts"; |
| 21 | 22 | |
| @@ -26,7 +27,10 @@ export function cloudRoutes(router: Router<Handler>): void { | ||
| 26 | 27 | if (!user || ctx.auth.scope === undefined) return unauthorized(); |
| 27 | 28 | if (!scopeAllows(ctx.auth.scope, "rw")) |
| 28 | 29 | 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(); | |
| 30 | 34 | const uses = await usesByVendor(ctx.app.db, ctx.app.reposRoot, user).catch( |
| 31 | 35 | () => new Map<string, VendorUse[]>(), |
| 32 | 36 | ); |
| @@ -48,7 +52,9 @@ export function cloudRoutes(router: Router<Handler>): void { | ||
| 48 | 52 | if (!user || ctx.auth.scope === undefined) return unauthorized(); |
| 49 | 53 | // An admin's look refreshes a stale catalog first; a failed read leaves the last good one |
| 50 | 54 | // 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); | |
| 52 | 58 | const url = new URL(ctx.request.url); |
| 53 | 59 | const q = (k: string) => url.searchParams.get(k) ?? undefined; |
| 54 | 60 | 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 | ||
| 27 | 27 | import { filesByNode } from "../cloud/declared_read.ts"; |
| 28 | 28 | import { logsOfContainer } from "../cloud/containers.ts"; |
| 29 | 29 | import { nodeAt, tabOf, type CloudNode, type CloudView } from "../cloud/tree.ts"; |
| 30 | import { mayBeside } from "./may_beside.ts"; | |
| 30 | 31 | import { pinnedBlock } from "./pinned_routes.ts"; |
| 31 | 32 | import { containerConsole } from "../web/pages/games.ts"; |
| 32 | 33 | import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts"; |
| @@ -87,7 +88,7 @@ function placeOf(pathname: string): string[] | undefined { | ||
| 87 | 88 | // GET /infra/-/<cloud>/<account>/<project>/<id>, or any level above it: the tree with that open |
| 88 | 89 | // beside it. `?fragment=1` is what opens alone, `?fragment=explorer` a branch's rows. |
| 89 | 90 | async function infraResource(ctx: Ctx): Promise<Response> { |
| 90 | const denied = guard(ctx); | |
| 91 | const denied = guard(ctx, "resource"); | |
| 91 | 92 | if (denied) return denied; |
| 92 | 93 | const path = placeOf(ctx.url.pathname) ?? []; |
| 93 | 94 | const tree = timePhase(ctx.request, "tree", () => treeOf(ctx)); |
| @@ -137,8 +138,15 @@ async function render( | ||
| 137 | 138 | /** To the build's tray, which says what is happening better than a flash could. */ |
| 138 | 139 | const toBuild = (planId: string): Response => new Response(null, { status: 303, headers: { location: `/infra/build?plan=${planId}` } }); |
| 139 | 140 | |
| 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 { | |
| 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 | } | |
| 142 | 150 | |
| 143 | 151 | /** What the forge runs, with what each provider says of it as kept: no page waits on a provider. */ |
| 144 | 152 | function runningNow(ctx: Ctx): Html | undefined { |
| @@ -161,7 +169,7 @@ const endsOf = (ctx: Ctx) => { | ||
| 161 | 169 | }; |
| 162 | 170 | |
| 163 | 171 | function infraGet(ctx: Ctx): Response { |
| 164 | const denied = guard(ctx); | |
| 172 | const denied = guard(ctx, "overview"); | |
| 165 | 173 | if (denied) return denied; |
| 166 | 174 | // A build's old address, kept for the links a talk already holds. |
| 167 | 175 | const planId = ctx.url.searchParams.get("plan"); |
| @@ -177,7 +185,7 @@ function infraGet(ctx: Ctx): Response { | ||
| 177 | 185 | // GET /infra/build, /infra/build?app=owner/name from an app's page, and ?plan=<id> for a build's |
| 178 | 186 | // progress. |
| 179 | 187 | function infraBuild(ctx: Ctx): Promise<Response> | Response { |
| 180 | const denied = guard(ctx); | |
| 188 | const denied = guard(ctx, "build"); | |
| 181 | 189 | if (denied) return denied; |
| 182 | 190 | const planId = ctx.url.searchParams.get("plan") ?? undefined; |
| 183 | 191 | return render(ctx, undefined, planId === undefined ? { app: ctx.url.searchParams.get("app") ?? "" } : { planId }); |
| @@ -185,6 +193,7 @@ function infraBuild(ctx: Ctx): Promise<Response> | Response { | ||
| 185 | 193 | |
| 186 | 194 | // GET /infra/live?part=running | ?plan=<id>: a live region alone, refetched on an event. |
| 187 | 195 | function infraLive(ctx: Ctx): Response { |
| 196 | mayBeside(ctx, "infra live", "forge.administer", ctx.auth.user?.isAdmin === true); | |
| 188 | 197 | if (!ctx.auth.user?.isAdmin) return fragment(html``, { status: 404 }); |
| 189 | 198 | const planId = ctx.url.searchParams.get("plan"); |
| 190 | 199 | if (planId !== null) { |
| @@ -211,7 +220,7 @@ function infraLive(ctx: Ctx): Response { | ||
| 211 | 220 | // POST /infra/plan: the tray for what the form says now (a fragment for the page's script), or the |
| 212 | 221 | // whole page with it for a browser without one. |
| 213 | 222 | async function infraPlan(ctx: Ctx): Promise<Response> { |
| 214 | const denied = guard(ctx); | |
| 223 | const denied = guard(ctx, "plan"); | |
| 215 | 224 | if (denied) return denied; |
| 216 | 225 | const form = await readForm(ctx, "admin"); |
| 217 | 226 | if (form instanceof Response) return form; |
| @@ -223,7 +232,7 @@ async function infraPlan(ctx: Ctx): Promise<Response> { | ||
| 223 | 232 | |
| 224 | 233 | // POST /infra/apply: build what the form says, if it is the plan the person was shown. |
| 225 | 234 | async function infraApply(ctx: Ctx): Promise<Response> { |
| 226 | const denied = guard(ctx); | |
| 235 | const denied = guard(ctx, "apply"); | |
| 227 | 236 | if (denied) return denied; |
| 228 | 237 | const form = await readForm(ctx, "admin"); |
| 229 | 238 | if (form instanceof Response) return form; |
| @@ -249,7 +258,7 @@ async function infraApply(ctx: Ctx): Promise<Response> { | ||
| 249 | 258 | // POST /infra/record: plan the DNS record the form says and start it; a record costs nothing, so |
| 250 | 259 | // this one press is the Build. Every refusal comes back as a flash. |
| 251 | 260 | async function infraRecord(ctx: Ctx): Promise<Response> { |
| 252 | const denied = guard(ctx); | |
| 261 | const denied = guard(ctx, "record"); | |
| 253 | 262 | if (denied) return denied; |
| 254 | 263 | const form = await readForm(ctx, "admin"); |
| 255 | 264 | if (form instanceof Response) return form; |
| @@ -270,7 +279,7 @@ async function infraRecord(ctx: Ctx): Promise<Response> { | ||
| 270 | 279 | |
| 271 | 280 | // POST /infra/rebuild: the same wants again, after a build stopped. |
| 272 | 281 | async function infraRebuild(ctx: Ctx): Promise<Response> { |
| 273 | const denied = guard(ctx); | |
| 282 | const denied = guard(ctx, "rebuild"); | |
| 274 | 283 | if (denied) return denied; |
| 275 | 284 | const form = await readForm(ctx, "admin"); |
| 276 | 285 | if (form instanceof Response) return form; |
| @@ -282,7 +291,7 @@ async function infraRebuild(ctx: Ctx): Promise<Response> { | ||
| 282 | 291 | |
| 283 | 292 | // POST /infra/projects: read every account into its projects now (GETs only), then back to them. |
| 284 | 293 | async function infraProjects(ctx: Ctx): Promise<Response> { |
| 285 | const denied = guard(ctx); | |
| 294 | const denied = guard(ctx, "projects"); | |
| 286 | 295 | if (denied) return denied; |
| 287 | 296 | const form = await readForm(ctx, "admin"); |
| 288 | 297 | if (form instanceof Response) return form; |
| @@ -299,7 +308,7 @@ async function infraProjects(ctx: Ctx): Promise<Response> { | ||
| 299 | 308 | |
| 300 | 309 | // POST /infra/:name/keep and /infra/:name/end (End now arrives from the confirm page). |
| 301 | 310 | async function infraMachine(ctx: Ctx): Promise<Response> { |
| 302 | const denied = guard(ctx); | |
| 311 | const denied = guard(ctx, "machine"); | |
| 303 | 312 | if (denied) return denied; |
| 304 | 313 | const form = await readForm(ctx, "admin"); |
| 305 | 314 | if (form instanceof Response) return form; |
| @@ -352,7 +361,7 @@ async function infraMachine(ctx: Ctx): Promise<Response> { | ||
| 352 | 361 | |
| 353 | 362 | // GET /infra/:name/ending: the offer to snapshot before End. |
| 354 | 363 | function infraEnding(ctx: Ctx): Response { |
| 355 | const denied = guard(ctx); | |
| 364 | const denied = guard(ctx, "ending"); | |
| 356 | 365 | if (denied) return denied; |
| 357 | 366 | const m = machineOf(ctx.app, ctx.auth.user, ctx.params.name ?? ""); |
| 358 | 367 | if (!m.ok || m.value === undefined || !m.value.atProvider || m.value.offer === "") return notFoundPage(ctx); |
| @@ -361,7 +370,7 @@ function infraEnding(ctx: Ctx): Response { | ||
| 361 | 370 | |
| 362 | 371 | // GET /infra/:name/cloud: what the provider's API says of the machine, read on open. |
| 363 | 372 | async function infraCloud(ctx: Ctx): Promise<Response> { |
| 364 | const denied = guard(ctx); | |
| 373 | const denied = guard(ctx, "cloud"); | |
| 365 | 374 | if (denied) return denied; |
| 366 | 375 | const name = ctx.params.name ?? ""; |
| 367 | 376 | const seen = await machineView(ctx.app, ctx.auth.user, name); |
| @@ -371,7 +380,7 @@ async function infraCloud(ctx: Ctx): Promise<Response> { | ||
| 371 | 380 | // POST /infra/snapshot/:id/restore (a new forge's name) and /delete (arrives from the confirm |
| 372 | 381 | // page). |
| 373 | 382 | async function infraSnapshot(ctx: Ctx): Promise<Response> { |
| 374 | const denied = guard(ctx); | |
| 383 | const denied = guard(ctx, "snapshot"); | |
| 375 | 384 | if (denied) return denied; |
| 376 | 385 | const form = await readForm(ctx, "admin"); |
| 377 | 386 | if (form instanceof Response) return form; |
| @@ -390,7 +399,7 @@ async function infraSnapshot(ctx: Ctx): Promise<Response> { | ||
| 390 | 399 | |
| 391 | 400 | // GET /infra/end/:act/<path>: the plan of a stop or a delete. POST: the confirm. |
| 392 | 401 | async function infraEnd(ctx: Ctx): Promise<Response> { |
| 393 | const denied = guard(ctx); | |
| 402 | const denied = guard(ctx, "end"); | |
| 394 | 403 | if (denied) return denied; |
| 395 | 404 | const act = endActOf(ctx.params.act); |
| 396 | 405 | 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 | ||
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 |
||
| 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 | }); |
new above
offline
This wrapper only calls mayBeside and returns
old. Call mayBeside directly in guard and infraLive.