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

Roles, part 3a: a member is refused admin settings and releases, with a 403 on the API and a plain line on the page #2396

Parked opened this
Closed without merging

scout/forge:scout/2384-roles-part-3a-a-member-is-refused-admin → main 1 commit fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +171 −0
docs/ROLES.md +7
@@ -15,6 +15,13 @@ verify, a suspended one is refused, an agent and a stranger to a private
1515 repository meet their own reasons first. A comment from a guest is still a
1616 comment; it just starts no run. Agents and organizations are not guests.
1717
18 Part 3a (#2384) enforces "Administer the forge" for admin settings and
19 releases: every `/admin/*` page, `/api/v1/admin/*` call, and the `/releases`
20 page with its rollback refuse a member or guest with a 403 and "only an admin
21 can change the forge's settings or its releases" (`not_admin` in the API).
22 `src/http/admin_gate.ts` is the one gate, ahead of every handler;
23 `/releases.json` stays public. Token scopes are a later part.
24
1825 The Capacity setting `guard_guests` (`FORGE_GUARD_GUESTS`, default `on`) is the
1926 switch: `off` leaves the usual permissions. The test suite boots with it `off`
2027 and `test/guests.test.ts` turns it on.
src/core/roles.ts +3
@@ -49,6 +49,9 @@ export function rolesTable(): string {
4949 /** The words a guest is refused with, on every surface. */
5050 export const NOT_A_MEMBER = "the owner has not made this account a member";
5151
52 /** The words a member (or guest) is refused admin settings and releases with. */
53 export const NOT_AN_ADMIN = "only an admin can change the forge's settings or its releases";
54
5255 /**
5356 * Whether the table withholds `ability` from this account. Only a person
5457 * can be a guest: agents and organizations are not accounts the owner
src/http/admin_gate.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * The one gate in front of admin settings and releases: `/admin/*`,
3 * `/api/v1/admin/*` and the `/releases` page with its rollback. A signed-in
4 * person whose role lacks `administer` (`core/roles.ts`) is refused with a
5 * 403 and one plain sentence, as JSON for the API and as a page for a
6 * browser, before any handler runs. Anyone else meets the handler's own
7 * rules, so an admin is unchanged. `/releases.json` stays public.
8 */
9
10 import type { App } from "../app.ts";
11 import { lacks, NOT_AN_ADMIN } from "../core/roles.ts";
12 import { empty } from "../web/ui.ts";
13 import { html } from "../web/html.ts";
14 import { page } from "../web/layout.ts";
15 import type { Auth, Ctx } from "./context.ts";
16 import { json } from "./respond.ts";
17
18 const under = (path: string, root: string): boolean => path === root || path.startsWith(`${root}/`);
19
20 /** Whether this path is one the `administer` ability guards. */
21 export function isAdminPath(path: string): boolean {
22 return under(path, "/admin") || under(path, "/api/v1/admin") || under(path, "/releases");
23 }
24
25 /** The refusal for a person who may not administer, or undefined to carry on. */
26 export function adminGate(app: App, request: Request, url: URL, auth: Auth): Response | undefined {
27 if (auth.user === undefined || !isAdminPath(url.pathname)) return undefined;
28 if (!lacks(app.db, auth.user, "administer")) return undefined;
29 if (url.pathname.startsWith("/api/")) return json({ error: "not_admin", message: NOT_AN_ADMIN }, 403);
30 const ctx: Ctx = { app, request, url, params: {}, auth, theme: undefined };

Nit: theme: undefined ignores the viewer's forge_theme cookie. This viewer is signed in, so a member on a dark theme gets the 403 page in the default theme. cookieValue(request, "forge_theme") plus isThemeName, as server.ts does for the not-found page, would keep it consistent.

31 return page(
32 {
33 ctx,
34 title: "Not allowed",
35 body: html`<div class="page-head"><h1>403</h1></div>
36 ${empty({ icon: "lock", title: "Not allowed", note: NOT_AN_ADMIN })}`,
37 },
38 403,
39 );
40 }
src/http/server.ts +5
@@ -430,6 +430,7 @@ import { targetForShortCode } from "../origins/oauth.ts";
430430 import { apiRoutes } from "./api.ts";
431431 import { inNamespace } from "../core/proposal_token.ts";
432432 import { proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts";
433 import { adminGate } from "./admin_gate.ts";
433434 import { proposalGate } from "./proposal_gate.ts";
434435 import { feedRoutes } from "./feed.ts";
435436 import type { Database } from "bun:sqlite";
@@ -2300,6 +2301,10 @@ async function answerGet(
23002301 const proposalRefusal = proposalGate(app, request, url, auth);
23012302 if (proposalRefusal !== undefined) return proposalRefusal;
23022303
2304 // Admin settings and releases are an admin's; a member is told so.
2305 const adminRefusal = adminGate(app, request, url, auth);
2306 if (adminRefusal !== undefined) return adminRefusal;
2307
23032308 // The two things standing between one runaway agent and everybody
23042309 // else's latency, applied before a handler runs and after auth is
23052310 // known — a limit needs an identity, and a replay needs a credential.
test/admin_refused.test.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * Roles, part 3a (#2384): a member is refused admin settings and releases
3 * with a 403 and one plain sentence, on the API and on the page; an admin is
4 * unchanged.
5 */
6
7 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
12 import { changeCapacity } from "../src/actions/capacity.ts";
13 import { NOT_AN_ADMIN, setMember } from "../src/core/roles.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 describe("a member is refused admin settings and releases", () => {
23 let dataDir = "";
24 let app: App;
25 let servers: Servers;
26 let alice: User;
27 let carol: User; // member
28
29 const token = (u: User) => createToken(app.db, u.id, "admin", "admin").token;
30 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
31 const call = (method: string, path: string, u: User, body?: unknown) =>
32 fetch(`${servers.url}${path}`, {
33 method,
34 headers: { "content-type": "application/json", authorization: `Bearer ${token(u)}` },
35 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
36 });
37 const visit = (method: string, path: string, u: User) =>
38 fetch(`${servers.url}${path}`, {
39 method,
40 headers: { cookie: cookie(u), origin: servers.url, accept: "text/html" },
41 ...(method === "POST" ? { body: new URLSearchParams({}) } : {}),
42 redirect: "manual",
43 });
44 const mk = async (username: string, admin = false) => {
45 const r = await createUser(app.db, {
46 trusted: true,
47 username,
48 email: `${username}@forge.local`,
49 password: "a-good-passphrase",
50 ...(admin ? { adminIfFirst: true } : {}),
51 });
52 if (!r.ok) throw new Error(r.error);
53 return r.value;
54 };
55
56 beforeAll(async () => {
57 dataDir = await mkdtemp(join(tmpdir(), "forge-admin-refused-"));
58 app = createApp({ dataDir, port: 0 });
59 servers = await serve(app);
60 alice = await mk("alice", true);
61 carol = await mk("carol");
62 setMember(app.db, carol.id, true, alice.id, new Date());
63 expect(changeCapacity(app, alice, "guard_guests", "on").ok).toBe(true);
64 }, 60_000);
65
66 afterAll(async () => {
67 servers.stop();
68 app.close();
69 await rm(dataDir, { recursive: true, force: true });
70 });
71
72 const apiActs: [string, string, unknown?][] = [
73 ["GET", "/api/v1/admin/capacity"],
74 ["PUT", "/api/v1/admin/capacity/guard_guests", { value: "on" }],
75 ["GET", "/api/v1/admin/limits"],
76 ["GET", "/api/v1/admin/settings"],
77 ["GET", "/api/v1/admin/invites"],
78 ["POST", "/api/v1/admin/invites", {}],
79 ["GET", "/api/v1/admin/accounts"],
80 ["GET", "/api/v1/admin/people"],
81 ["POST", "/api/v1/admin/accounts/alice/suspend", {}],
82 ];
83
84 test("every admin API act: 403 and the sentence for a member, success for an admin", async () => {
85 for (const [method, path, body] of apiActs) {
86 const refused = await call(method, path, carol, body);
87 expect(refused.status, `${method} ${path}`).toBe(403);
88 expect(await refused.json()).toMatchObject({ error: "not_admin", message: NOT_AN_ADMIN });
89 }
90 for (const path of ["/api/v1/admin/capacity", "/api/v1/admin/limits", "/api/v1/admin/people"])
91 expect((await call("GET", path, alice)).status, path).toBe(200);
92 });
93
94 test("admin pages and releases: a plain 403 line for a member, the page for an admin", async () => {
95 const pages: [string, string][] = [
96 ["GET", "/admin/limits"],
97 ["POST", "/admin/limits"],
98 ["POST", "/admin/quotas"],
99 ["POST", "/admin/signup"],
100 ["GET", "/releases"],
101 ["POST", `/releases/${"a".repeat(40)}/rollback`],
102 ];
103 for (const [method, path] of pages) {
104 const refused = await visit(method, path, carol);
105 expect(refused.status, `${method} ${path}`).toBe(403);
106 expect(await refused.text()).toContain(NOT_AN_ADMIN.replace("'", "&#39;"));
107 }
108 expect((await visit("GET", "/admin/limits", alice)).status).toBe(200);
109 expect((await visit("GET", "/releases", alice)).status).toBe(200);
110 });
111
112 test("the public release list stays public, and a signed-out caller meets the old rules", async () => {
113 expect((await fetch(`${servers.url}/releases.json`)).status).toBe(200);
114 expect((await fetch(`${servers.url}/api/v1/admin/capacity`)).status).not.toBe(403);
115 });
116 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs