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

A member cannot mint an admin-scope token; ro and rw tokens stay as they are #2414

Parked opened this
Closed without merging

scout/forge:scout/2409-a-member-cannot-mint-an-admin-scope-toke → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +126 −104
src/actions/users.ts +5 −1
@@ -53,6 +53,9 @@ export type SignUpError =
5353 | "signup_closed";
5454
5555 /** What anyone is told when the forge makes no new accounts. */
56 export const ADMIN_TOKEN_REFUSED =
57 "Only a forge admin can mint an admin-scope token; ro and rw are open to you.";
58
5659 export const SIGNUP_CLOSED_MESSAGE = "Signup is closed on this forge.";
5760
5861 /**
@@ -191,9 +194,10 @@ export function createToken(
191194 actor: User | undefined,
192195 name: string,
193196 scope: TokenScope,
194 ): Result<{ id: string; token: string }, "unauthorized"> {
197 ): Result<{ id: string; token: string }, "unauthorized" | "forbidden"> {
195198 const user = requireUser(actor);
196199 if (!user.ok) return user;
200 if (scope === "admin" && !user.value.isAdmin) return err("forbidden");
197201 const minted = mintToken(app.db, user.value.id, name, scope);
198202 app.bus.append({
199203 kind: "token.created",
src/http/api.ts +8 −1
@@ -150,6 +150,7 @@ import {
150150 import {
151151 addSshKey,
152152 changePassword,
153 ADMIN_TOKEN_REFUSED,
153154 createToken,
154155 deleteSshKey,
155156 deleteToken,
@@ -1830,7 +1831,13 @@ export function apiRoutes(router: Router<Handler>): void {
18301831 str(input.name) || "unnamed",
18311832 scope,
18321833 );
1833 if (!minted.ok) return unauthorized();
1834 if (!minted.ok)
1835 return minted.error === "forbidden"
1836 ? json(
1837 { error: "forbidden", message: ADMIN_TOKEN_REFUSED },
1838 403,
1839 )
1840 : unauthorized();
18341841 return json(minted.value, 201);
18351842 });
18361843
src/web/pages/account.ts +5 −1
@@ -14,6 +14,7 @@ import { emailVerified } from "../../core/verify.ts";
1414 import {
1515 addSshKey,
1616 changePassword,
17 ADMIN_TOKEN_REFUSED,
1718 createToken,
1819 deleteSshKey,
1920 deleteToken,
@@ -587,7 +588,10 @@ export async function tokenCreate(ctx: Ctx): Promise<Response> {
587588 field(form, "name").trim() || "token",
588589 chosen,
589590 );
590 if (!minted.ok) return signInFirst(ctx);
591 if (!minted.ok)
592 return minted.error === "forbidden"
593 ? new Response(ADMIN_TOKEN_REFUSED, { status: 403 })
594 : signInFirst(ctx);
591595 // Post-redirect-get: the secret rides a one-shot flash, so a refresh shows
592596 // the list rather than minting a second token.
593597 return flashTo(ctx, "/settings/tokens", {
test/apps-api.test.ts +2 −14
@@ -4,6 +4,7 @@
44 * text and as a live tail, and every floor holding.
55 */
66
7 import { adminScopeToken } from "./helpers/tokens.ts";
78 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
89 import { mkdtemp, rm } from "node:fs/promises";
910 import { tmpdir } from "node:os";
@@ -458,20 +459,7 @@ describe("apps, runs and the crew over the API", () => {
458459 },
459460 null,
460461 );
461 const mallory = (
462 (await (
463 await post(
464 "/api/v1/tokens",
465 {
466 username: "mallory",
467 password: "a-good-passphrase",
468 name: "admin",
469 scope: "admin",
470 },
471 null,
472 )
473 ).json()) as { token: string }
474 ).token;
462 const mallory = adminScopeToken(app.db, "mallory");
475463 expect((await api(env, { token: mallory })).status).toBe(404);
476464 expect((await put("GREETING", "x", mallory)).status).toBe(404);
477465 expect(
test/cross-repo-pull.test.ts +2 −12
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { adminScopeToken } from "./helpers/tokens.ts";
67 import { serve, type Servers } from "../src/http/server.ts";
78 import { gitClientEnv } from "./helpers/git-client.ts";
89 import { proveAll } from "./helpers/verified.ts";
@@ -56,18 +57,7 @@ describe("cross-repo pull requests (fork → upstream)", () => {
5657 redirect: "manual",
5758 });
5859 const cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
59 const token = await fetch(`${base}/api/v1/tokens`, {
60 method: "POST",
61 headers: { "content-type": "application/json" },
62 body: JSON.stringify({ adminConfirm: true,
63 username,
64 password: "cross-repo-pass",
65 name: "c",
66 scope: "admin",
67 }),
68 })
69 .then((r) => r.json())
70 .then((j) => (j as { token: string }).token);
60 const token = adminScopeToken(app.db, username);
7161 return { token, cookie };
7262 }
7363
test/fork-flow.test.ts +2 −13
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { adminScopeToken } from "./helpers/tokens.ts";
67 import { serve, type Servers } from "../src/http/server.ts";
78 import { listEvents } from "../src/core/events.ts";
89 import { firstFetchRetry } from "../src/origins/mirror.ts";
@@ -100,19 +101,7 @@ describe("the fork flow", () => {
100101 password: PASSWORD,
101102 }),
102103 });
103 const token = await read<{ token: string }>(
104 await fetch(`${server.url}/api/v1/tokens`, {
105 method: "POST",
106 headers: { "content-type": "application/json" },
107 body: JSON.stringify({ adminConfirm: true,
108 username,
109 password: PASSWORD,
110 name: "t",
111 scope: "admin",
112 }),
113 }),
114 );
115 return token.token;
104 return adminScopeToken(server === servers ? app.db : originApp.db, username);
116105 }
117106
118107 /** Seed a public repo on the upstream forge with one file on `main`. */
test/helpers/tokens.ts added +14
@@ -0,0 +1,14 @@
1 import type { Database } from "bun:sqlite";
2 import { createToken } from "../../src/core/tokens.ts";
3 import { getUserByName } from "../../src/core/users.ts";
4
5 /**
6 * An admin-scope token for any account, made below the API. Over the API only
7 * a forge admin may mint one (`test/token-admin-scope.test.ts`); suites that
8 * need a member holding one — to show it still opens nothing — make it here.
9 */
10 export function adminScopeToken(db: Database, username: string): string {
11 const user = getUserByName(db, username);
12 if (!user) throw new Error(`no such user ${username}`);
13 return createToken(db, user.id, "t", "admin").token;
14 }
test/orgs.test.ts +4 −12
@@ -3,6 +3,8 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { getUserByName } from "../src/core/users.ts";
7 import { adminScopeToken } from "./helpers/tokens.ts";
68 import {
79 accessAllows,
810 addTeamMember,
@@ -215,18 +217,8 @@ describe("orgs over HTTP", () => {
215217 password: "org-http-pass",
216218 }),
217219 });
218 return fetch(`${base}/api/v1/tokens`, {
219 method: "POST",
220 headers: { "content-type": "application/json" },
221 body: JSON.stringify({ adminConfirm: true,
222 username,
223 password: "org-http-pass",
224 name: "c",
225 scope: "admin",
226 }),
227 })
228 .then((r) => r.json())
229 .then((j) => (j as { token: string }).token);
220 // "nobody" is a reserved name: signup refuses it, so the stranger holds no token.
221 return getUserByName(app.db, username) ? adminScopeToken(app.db, username) : "";
230222 }
231223
232224 beforeAll(async () => {
test/parity.test.ts +2 −1
@@ -6,6 +6,7 @@
66 * an event for every mutation. Adversarial where authorization matters.
77 */
88
9 import { adminScopeToken } from "./helpers/tokens.ts";
910 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1011 import { existsSync } from "node:fs";
1112 import { mkdtemp, rm } from "node:fs/promises";
@@ -807,7 +808,7 @@ describe("parity: full control through actions and the API", () => {
807808 expect(
808809 (
809810 await call("DELETE", "/api/v1/orgs/acme/teams/ops", {
810 token: await mint("bob", "admin"),
811 token: adminScopeToken(app.db, "bob"),
811812 })
812813 ).status,
813814 ).toBe(404);
test/reviews-states.test.ts +2 −13
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { adminScopeToken } from "./helpers/tokens.ts";
67 import { serve, type Servers } from "../src/http/server.ts";
78 import { listEvents } from "../src/core/events.ts";
89
@@ -51,19 +52,7 @@ describe("review states, and the merge they gate", () => {
5152 password: PASSWORD,
5253 }),
5354 });
54 const token = await read<{ token: string }>(
55 await fetch(`${base}/api/v1/tokens`, {
56 method: "POST",
57 headers: { "content-type": "application/json" },
58 body: JSON.stringify({ adminConfirm: true,
59 username,
60 password: PASSWORD,
61 name: "t",
62 scope: "admin",
63 }),
64 }),
65 );
66 tokens[username] = token.token;
55 tokens[username] = adminScopeToken(app.db, username);
6756 }
6857
6958 /** The pull number of a fresh branch with one file changed on it. */
test/secret-store.test.ts +2 −14
@@ -9,6 +9,7 @@ import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
12 import { adminScopeToken } from "./helpers/tokens.ts";
1213 import { createRepo } from "../src/actions/repos.ts";
1314 import { createOrg } from "../src/core/orgs.ts";
1415 import {
@@ -50,20 +51,7 @@ describe("forge-level secrets", () => {
5051 },
5152 });
5253 const mint = async (username: string): Promise<string> =>
53 (
54 (await (
55 await fetch(`${servers.url}/api/v1/tokens`, {
56 method: "POST",
57 headers: { "content-type": "application/json" },
58 body: JSON.stringify({ adminConfirm: true,
59 username,
60 password: "a-good-passphrase",
61 name: "t",
62 scope: "admin",
63 }),
64 })
65 ).json()) as { token: string }
66 ).token;
54 adminScopeToken(app.db, username);
6755
6856 beforeAll(async () => {
6957 dataDir = await mkdtemp(join(tmpdir(), "forge-secret-store-"));
test/token-admin-scope.test.ts added +75
@@ -0,0 +1,75 @@
1 /** Only a forge admin may mint an admin-scope token; ro and rw stay open. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9
10 let dataDir: string;
11 let app: App;
12 let servers: Servers;
13 let base: string;
14
15 const json = { "content-type": "application/json" };
16
17 const signUp = (username: string, password: string) =>
18 fetch(`${base}/api/v1/users`, {
19 method: "POST",
20 headers: json,
21 body: JSON.stringify({ username, email: `${username}@forge.test`, password }),
22 });
23
24 const mint = (username: string, password: string, scope: string) =>
25 fetch(`${base}/api/v1/tokens`, {
26 method: "POST",
27 headers: json,
28 body: JSON.stringify({ adminConfirm: true, username, password, name: scope, scope }),
29 });
30
31 beforeAll(async () => {
32 dataDir = await mkdtemp(join(tmpdir(), "forge-token-admin-"));
33 app = createApp({ dataDir, port: 0 });
34 servers = await serve(app);
35 base = servers.url;
36 await signUp("alice", "alice-scope-secret");
37 await signUp("bob", "bob-scope-secret");
38 });
39
40 afterAll(async () => {
41 servers.stop();
42 app.close();
43 await rm(dataDir, { recursive: true, force: true });
44 });
45
46 test("a member is refused admin scope, gets rw and ro, and rw stays inside their rights", async () => {
47 const refused = await mint("bob", "bob-scope-secret", "admin");
48 expect(refused.status).toBe(403);
49 expect(((await refused.json()) as { message: string }).message).toContain(
50 "Only a forge admin",
51 );
52 expect((await mint("bob", "bob-scope-secret", "ro")).status).toBe(201);
53 const rw = await mint("bob", "bob-scope-secret", "rw");
54 expect(rw.status).toBe(201);
55 const token = ((await rw.json()) as { token: string }).token;
56
57 const made = await mint("alice", "alice-scope-secret", "rw");
58 const alice = ((await made.json()) as { token: string }).token;
59 const repo = await fetch(`${base}/api/v1/repos`, {
60 method: "POST",
61 headers: { ...json, authorization: `Bearer ${alice}` },
62 body: JSON.stringify({ name: "app", visibility: "public" }),
63 });
64 expect(repo.status).toBe(201);
65 const write = await fetch(`${base}/api/v1/repos/alice/app/branches`, {
66 method: "POST",
67 headers: { ...json, authorization: `Bearer ${token}` },
68 body: JSON.stringify({ name: "x" }),
69 });
70 expect(write.status).toBe(403);
71 });
72
73 test("an admin can still mint admin scope", async () => {
74 expect((await mint("alice", "alice-scope-secret", "admin")).status).toBe(201);
75 });
test/web-workflows.test.ts +3 −22
@@ -31,6 +31,7 @@ import { mkdtemp, rm } from "node:fs/promises";
3131 import { tmpdir } from "node:os";
3232 import { join } from "node:path";
3333 import { createApp, type App } from "../src/app.ts";
34 import { adminScopeToken } from "./helpers/tokens.ts";
3435 import { serve, type Servers } from "../src/http/server.ts";
3536 import { listOrigins, repoForkOf } from "../src/core/origins.ts";
3637 import { getRepo } from "../src/core/repos.ts";
@@ -140,17 +141,7 @@ describe("fork at the origin, and propose a change through it", () => {
140141 });
141142 proveAll(upApp);
142143 promote(upApp.db);
143 const made = await fetch(`${upServers.url}/api/v1/tokens`, {
144 method: "POST",
145 headers: { "content-type": "application/json" },
146 body: JSON.stringify({ adminConfirm: true,
147 username,
148 password: PASSWORD,
149 name: "t",
150 scope: "admin",
151 }),
152 });
153 return ((await made.json()) as { token: string }).token;
144 return adminScopeToken(upApp.db, username);
154145 }
155146
156147 const upstream = (
@@ -577,17 +568,7 @@ describe("verdicts, threads, and the gate they open", () => {
577568 cookies[username] = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
578569 proveAll(app);
579570 promote(app.db);
580 const token = await fetch(`${base}/api/v1/tokens`, {
581 method: "POST",
582 headers: { "content-type": "application/json" },
583 body: JSON.stringify({ adminConfirm: true,
584 username,
585 password: PASSWORD,
586 name: "t",
587 scope: "admin",
588 }),
589 });
590 tokens[username] = ((await token.json()) as { token: string }).token;
571 tokens[username] = adminScopeToken(app.db, username);
591572 }
592573
593574 /** The first line of the diff, as a review anchor form would name it. */

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs