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

Roles, part 3c: a token a member mints carries scopes only over that member's own repositories and apps #2405

Parked opened this
Closed without merging

scout/forge:scout/2386-roles-part-3c-a-token-a-member-mints-car → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +190 −11
docs/ROLES.md +8
@@ -33,3 +33,11 @@ back on the account's page.
3333 | Run a crew on a model allowance | no | yes | yes |
3434 | Administer the forge | no | no | yes |
3535 <!-- /roles-table -->
36
37 ## Tokens
38
39 A token a non-admin person mints carries `ro` or `rw` and reaches only that
40 person's own repositories and apps: a request that names another account's
41 repository (git or `/api/v1/repos/…`) is refused with a 403 (`http/own_gate.ts`),
42 and the `admin` scope is refused at minting, on the API and on the page. An
43 admin's minting is unchanged.
src/actions/users.ts +10 −2
@@ -191,10 +191,14 @@ export function createToken(
191191 actor: User | undefined,
192192 name: string,
193193 scope: TokenScope,
194 ): Result<{ id: string; token: string }, "unauthorized"> {
194 ): Result<{ id: string; token: string }, "unauthorized" | "too_wide"> {
195195 const user = requireUser(actor);
196196 if (!user.ok) return user;
197 const minted = mintToken(app.db, user.value.id, name, scope);
197 // A member's token reaches only their own repositories and apps, so it
198 // never carries `admin`; an admin's minting is unchanged (#2386).
199 const ownOnly = user.value.kind === "user" && !user.value.isAdmin;
200 if (ownOnly && scope === "admin") return err("too_wide");
201 const minted = mintToken(app.db, user.value.id, name, scope, { ownOnly });
198202 app.bus.append({
199203 kind: "token.created",
200204 actorId: user.value.id,
@@ -350,3 +354,7 @@ export function setPreference(
350354 setUserSetting(app.db, user.value.id, key, value);
351355 return ok();
352356 }
357
358 /** The plain words a member is refused a token scope wider than their own. */
359 export const TOO_WIDE_WORDS =
360 "a token you mint reaches only your own repositories and apps: choose read or read and write";
src/core/migrations/20261016210000-token-own-only.ts added +6
@@ -0,0 +1,6 @@
1 // A token a member mints reaches only that member's own repositories and apps
2 // (#2386). `own_only` is set when it is minted and read on every use;
3 // tokens already minted keep reaching what they did.
4 export default `
5 ALTER TABLE token ADD COLUMN own_only INTEGER NOT NULL DEFAULT 0;
6 `;
src/core/tokens.ts +7 −6
@@ -39,13 +39,13 @@ export function createToken(
3939 userId: string,
4040 name: string,
4141 scope: TokenScope,
42 options: { expiresAt?: string } = {},
42 options: { expiresAt?: string; ownOnly?: boolean } = {},
4343 ): { id: string; token: string } {
4444 const tokenId = id();
4545 const token = `forge_${secret()}`;
4646 db.query(
47 "INSERT INTO token (id, token_hash, user_id, name, scope, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
48 ).run(tokenId, sha256(token), userId, name, scope, options.expiresAt ?? null);
47 "INSERT INTO token (id, token_hash, user_id, name, scope, expires_at, own_only) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
48 ).run(tokenId, sha256(token), userId, name, scope, options.expiresAt ?? null, options.ownOnly ? 1 : 0);
4949 return { id: tokenId, token };
5050 }
5151
@@ -67,7 +67,7 @@ export function verifyToken(
6767 db: Database,
6868 presented: string,
6969 ): Result<
70 { user: User; scope: TokenScope; proposal?: Proposal },
70 { user: User; scope: TokenScope; proposal?: Proposal; ownOnly?: true },
7171 "invalid_token"
7272 > {
7373 const row = db
@@ -78,13 +78,14 @@ export function verifyToken(
7878 scope: TokenScope;
7979 last_used_at: string | null;
8080 expires_at: string | null;
81 own_only: number;
8182 p_repo: string | null;
8283 p_child: string | null;
8384 p_origin: string | null;
8485 },
8586 [string]
8687 >(
87 `SELECT t.id, t.user_id, t.scope, t.last_used_at, t.expires_at,
88 `SELECT t.id, t.user_id, t.scope, t.last_used_at, t.expires_at, t.own_only,
8889 p.repo_id AS p_repo, p.child AS p_child, p.origin AS p_origin
8990 FROM token t LEFT JOIN proposal_token p ON p.token_id = t.id
9091 WHERE t.token_hash = ?1`,
@@ -119,7 +120,7 @@ export function verifyToken(
119120 origin: row.p_origin!,
120121 },
121122 });
122 return ok({ user, scope: row.scope });
123 return ok({ user, scope: row.scope, ...(row.own_only === 1 ? { ownOnly: true as const } : {}) });
123124 }
124125
125126 export function listTokens(db: Database, userId: string): TokenInfo[] {
src/http/api.ts +5 −1
@@ -155,6 +155,7 @@ import {
155155 deleteToken,
156156 HUMAN_CHECK_MESSAGE,
157157 PASSKEY_REQUIRED_MESSAGE,
158 TOO_WIDE_WORDS,
158159 signUp,
159160 SIGNUP_CLOSED_MESSAGE,
160161 updateProfile,
@@ -1823,7 +1824,10 @@ export function apiRoutes(router: Router<Handler>): void {
18231824 str(input.name) || "unnamed",
18241825 scope,
18251826 );
1826 if (!minted.ok) return unauthorized();
1827 if (!minted.ok)
1828 return minted.error === "too_wide"
1829 ? apiError("forbidden", 403, TOO_WIDE_WORDS)
1830 : unauthorized();
18271831 return json(minted.value, 201);
18281832 });
18291833
src/http/context.ts +2
@@ -21,6 +21,8 @@ export interface Auth {
2121 readonly sessionId?: string;
2222 /** Set for a proposal token: all it may do (`http/proposal_gate.ts`). */
2323 readonly proposal?: Proposal;
24 /** Set for a token a member minted: it reaches only their own repositories (`http/own_gate.ts`). */
25 readonly ownOnly?: true;
2426 }
2527
2628 export interface Ctx {
src/http/own_gate.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * The gate a member's token passes: it reaches the member's own repositories
3 * and nothing named under another account. Paths that name no repository
4 * (the account's own tokens, keys, apps list) act as the member already, so
5 * they pass. Git (`/:owner/:name.git/…`) and the API
6 * (`/api/v1/repos/:owner/:name/…`) are the two ways a repository is named.
7 */
8
9 import type { Auth } from "./context.ts";
10 import { apiError } from "./respond.ts";
11
12 /** The account a path names a repository under, if it names one. */
13 export function ownerNamed(pathname: string): string | undefined {
14 const parts = pathname.split("/").filter((p) => p !== "");
15 if (parts[0] === "api" && parts[1] === "v1") return parts[2] === "repos" ? parts[3] : undefined;
16 return parts[1]?.endsWith(".git") ? parts[0] : undefined;
17 }
18
19 /** The refusal for this request, or undefined when it may proceed. */
20 export function ownGate(url: URL, auth: Auth): Response | undefined {
21 if (auth.ownOnly !== true || auth.user === undefined) return undefined;
22 let owner: string | undefined;
23 try {
24 owner = ownerNamed(decodeURIComponent(url.pathname));
25 } catch {
26 owner = "";
27 }
28 if (owner === undefined || owner.toLowerCase() === auth.user.username.toLowerCase()) return undefined;
29 return apiError("forbidden", 403, "this token was minted by a member: it reaches only that member's own repositories and apps");
30 }
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 { ownGate } from "./own_gate.ts";
433434 import { proposalGate } from "./proposal_gate.ts";
434435 import { feedRoutes } from "./feed.ts";
435436 import type { Database } from "bun:sqlite";
@@ -539,6 +540,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> {
539540 scope: verified.value.scope,
540541 via: "token",
541542 ...(verified.value.proposal ? { proposal: verified.value.proposal } : {}),
543 ...(verified.value.ownOnly ? { ownOnly: true as const } : {}),
542544 };
543545 }
544546 return NO_AUTH;
@@ -564,6 +566,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> {
564566 ...(verified.value.proposal
565567 ? { proposal: verified.value.proposal }
566568 : {}),
569 ...(verified.value.ownOnly ? { ownOnly: true as const } : {}),
567570 };
568571 }
569572 return NO_AUTH;
@@ -2299,6 +2302,8 @@ async function answerGet(
22992302 // request it makes ends here, before the limiter or any handler.
23002303 const proposalRefusal = proposalGate(app, request, url, auth);
23012304 if (proposalRefusal !== undefined) return proposalRefusal;
2305 const ownRefusal = ownGate(url, auth);
2306 if (ownRefusal !== undefined) return ownRefusal;
23022307
23032308 // The two things standing between one runaway agent and everybody
23042309 // else's latency, applied before a handler runs and after auth is
src/web/pages/account.ts +7 −2
@@ -18,6 +18,7 @@ import {
1818 deleteSshKey,
1919 deleteToken,
2020 updateProfile,
21 TOO_WIDE_WORDS,
2122 } from "../../actions/users.ts";
2223 import {
2324 NOTIFY_ERRORS,
@@ -532,9 +533,11 @@ function tokensView(ctx: Ctx): Html {
532533 options: [
533534 { value: "rw", label: "read + write — clone, push, open issues" },
534535 { value: "ro", label: "read only — clone and browse" },
535 { value: "admin", label: "admin — everything, including settings" },
536 ...(ctx.auth.user?.isAdmin
537 ? [{ value: "admin", label: "admin — everything, including settings" }]
538 : []),
536539 ],
537 hint: "A token can never mint another token, whatever its scope.",
540 hint: "A token you mint reaches only your own repositories and apps. It can never mint another token, whatever its scope.",
538541 })}
539542 ${ctx.auth.user?.isAdmin
540543 ? html`<div class="field" id="ai-admin">
@@ -587,6 +590,8 @@ export async function tokenCreate(ctx: Ctx): Promise<Response> {
587590 field(form, "name").trim() || "token",
588591 chosen,
589592 );
593 if (!minted.ok && minted.error === "too_wide")
594 return flashTo(ctx, "/settings/tokens", { tone: "danger", message: TOO_WIDE_WORDS });
590595 if (!minted.ok) return signInFirst(ctx);
591596 // Post-redirect-get: the secret rides a one-shot flash, so a refresh shows
592597 // the list rather than minting a second token.
test/token-own-only.test.ts added +110
@@ -0,0 +1,110 @@
1 /** Roles, part 3c (#2386): a token a member mints reaches only that member's own repositories and apps. */
2
3 import { afterAll, beforeAll, describe, 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 { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { setMember } from "../src/core/roles.ts";
10 import { createUser, getUserById } from "../src/core/users.ts";
11 import { ownerNamed } from "../src/http/own_gate.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 const PASS = "a-long-own-only-passphrase";
18
19 describe("a member's token", () => {
20 let dataDir = "";
21 let app: App;
22 let servers: Servers;
23
24 const mint = (username: string, body: Record<string, unknown>) =>
25 fetch(`${servers.url}/api/v1/tokens`, {
26 method: "POST",
27 headers: { "content-type": "application/json" },
28 body: JSON.stringify({ username, password: PASS, name: "t", ...body }),
29 });
30 const tokenOf = async (username: string, scope = "rw") =>
31 ((await (await mint(username, { scope, adminConfirm: true })).json()) as { token: string }).token;
32 const get = (token: string, path: string) =>
33 fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${token}` } });
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-own-only-"));
37 app = createApp({ dataDir, port: 0 });
38 servers = await serve(app);
39 for (const [username, isAdmin] of [["alice", true], ["bob", false], ["carol", false]] as const) {
40 const made = await createUser(app.db, { trusted: true, username, email: `${username}@x.test`, password: PASS, isAdmin });
41 if (!made.ok) throw new Error(username);
42 if (!isAdmin) setMember(app.db, made.value.id, true, made.value.id, new Date());
43 }
44 for (const [owner, name] of [["bob", "yard"], ["carol", "hers"]] as const) {
45 const user = app.db.query<{ id: string }, [string]>("SELECT id FROM user WHERE username = ?1").get(owner)!;
46 const made = await createRepo(app, getUserById(app.db, user.id)!, { name, visibility: "private" });
47 if (!made.ok) throw new Error(`${owner}/${name}: ${JSON.stringify(made.error)}`);
48 }
49 }, 30_000);
50
51 afterAll(async () => {
52 servers.stop();
53 app.close();
54 await rm(dataDir, { recursive: true, force: true });
55 });
56
57 test("works on the member's own repository", async () => {
58 const token = await tokenOf("bob");
59 expect((await get(token, "/api/v1/repos/bob/yard")).status).toBe(200);
60 });
61
62 test("cannot reach another account's repository, over the API or git", async () => {
63 const token = await tokenOf("bob");
64 const api = await get(token, "/api/v1/repos/carol/hers");
65 expect(api.status).toBe(403);
66 expect(await api.text()).toContain("only that member's own repositories");
67 expect((await get(token, "/carol/hers.git/info/refs?service=git-upload-pack")).status).toBe(403);
68 });
69
70 test("a scope wider than their own is refused with a plain error", async () => {
71 const res = await mint("bob", { scope: "admin" });
72 expect(res.status).toBe(403);
73 expect(await res.text()).toContain("only your own repositories and apps");
74 });
75
76 test("an admin's minting is unchanged: admin scope, any repository", async () => {
77 const token = await tokenOf("alice", "admin");
78 expect((await get(token, "/api/v1/repos/bob/yard")).status).toBe(200);
79 expect((await get(token, "/api/v1/repos/carol/hers")).status).toBe(200);
80 });
81
82 test("the page refuses a member the admin scope too", async () => {
83 const res = await fetch(`${servers.url}/signin`, {
84 method: "POST",
85 body: new URLSearchParams({ username: "bob", password: PASS }),
86 redirect: "manual",
87 });
88 const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
89 const page = await (await fetch(`${servers.url}/settings/tokens`, { headers: { cookie } })).text();
90 expect(page).not.toContain('value="admin"');
91 const posted = await fetch(`${servers.url}/settings/tokens`, {
92 method: "POST",
93 headers: { cookie, origin: servers.url },
94 body: new URLSearchParams({ name: "x", scope: "admin" }),
95 redirect: "manual",
96 });
97 expect(posted.status).toBe(303);
98 const list = await (await fetch(`${servers.url}/settings/tokens`, { headers: { cookie } })).text();
99 expect(list).not.toContain("<td>admin</td>");
100 });
101 });
102
103 describe("ownerNamed", () => {
104 test("reads the account a path names a repository under", () => {
105 expect(ownerNamed("/api/v1/repos/bob/yard/pulls")).toBe("bob");
106 expect(ownerNamed("/bob/yard.git/git-upload-pack")).toBe("bob");
107 expect(ownerNamed("/api/v1/tokens")).toBeUndefined();
108 expect(ownerNamed("/settings/tokens")).toBeUndefined();
109 });
110 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs