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 #2401
scout/forge:scout/2386-roles-part-3c-a-token-a-member-mints-car → main 1 commit fork
10 files
changed +190
−11
docs/ROLES.md +8
| @@ -33,3 +33,11 @@ back on the account's page. | ||
| 33 | 33 | | Run a crew on a model allowance | no | yes | yes | |
| 34 | 34 | | Administer the forge | no | no | yes | |
| 35 | 35 | <!-- /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( | ||
| 191 | 191 | actor: User | undefined, |
| 192 | 192 | name: string, |
| 193 | 193 | scope: TokenScope, |
| 194 | ): Result<{ id: string; token: string }, "unauthorized"> { | |
| 194 | ): Result<{ id: string; token: string }, "unauthorized" | "too_wide"> { | |
| 195 | 195 | const user = requireUser(actor); |
| 196 | 196 | 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 }); | |
| 198 | 202 | app.bus.append({ |
| 199 | 203 | kind: "token.created", |
| 200 | 204 | actorId: user.value.id, |
| @@ -350,3 +354,7 @@ export function setPreference( | ||
| 350 | 354 | setUserSetting(app.db, user.value.id, key, value); |
| 351 | 355 | return ok(); |
| 352 | 356 | } |
| 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( | ||
| 39 | 39 | userId: string, |
| 40 | 40 | name: string, |
| 41 | 41 | scope: TokenScope, |
| 42 | options: { expiresAt?: string } = {}, | |
| 42 | options: { expiresAt?: string; ownOnly?: boolean } = {}, | |
| 43 | 43 | ): { id: string; token: string } { |
| 44 | 44 | const tokenId = id(); |
| 45 | 45 | const token = `forge_${secret()}`; |
| 46 | 46 | 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); | |
| 49 | 49 | return { id: tokenId, token }; |
| 50 | 50 | } |
| 51 | 51 | |
| @@ -67,7 +67,7 @@ export function verifyToken( | ||
| 67 | 67 | db: Database, |
| 68 | 68 | presented: string, |
| 69 | 69 | ): Result< |
| 70 | { user: User; scope: TokenScope; proposal?: Proposal }, | |
| 70 | { user: User; scope: TokenScope; proposal?: Proposal; ownOnly?: true }, | |
| 71 | 71 | "invalid_token" |
| 72 | 72 | > { |
| 73 | 73 | const row = db |
| @@ -78,13 +78,14 @@ export function verifyToken( | ||
| 78 | 78 | scope: TokenScope; |
| 79 | 79 | last_used_at: string | null; |
| 80 | 80 | expires_at: string | null; |
| 81 | own_only: number; | |
| 81 | 82 | p_repo: string | null; |
| 82 | 83 | p_child: string | null; |
| 83 | 84 | p_origin: string | null; |
| 84 | 85 | }, |
| 85 | 86 | [string] |
| 86 | 87 | >( |
| 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, | |
| 88 | 89 | p.repo_id AS p_repo, p.child AS p_child, p.origin AS p_origin |
| 89 | 90 | FROM token t LEFT JOIN proposal_token p ON p.token_id = t.id |
| 90 | 91 | WHERE t.token_hash = ?1`, |
| @@ -119,7 +120,7 @@ export function verifyToken( | ||
| 119 | 120 | origin: row.p_origin!, |
| 120 | 121 | }, |
| 121 | 122 | }); |
| 122 | return ok({ user, scope: row.scope }); | |
| 123 | return ok({ user, scope: row.scope, ...(row.own_only === 1 ? { ownOnly: true as const } : {}) }); | |
| 123 | 124 | } |
| 124 | 125 | |
| 125 | 126 | export function listTokens(db: Database, userId: string): TokenInfo[] { |
src/http/api.ts +5 −1
| @@ -155,6 +155,7 @@ import { | ||
| 155 | 155 | deleteToken, |
| 156 | 156 | HUMAN_CHECK_MESSAGE, |
| 157 | 157 | PASSKEY_REQUIRED_MESSAGE, |
| 158 | TOO_WIDE_WORDS, | |
| 158 | 159 | signUp, |
| 159 | 160 | SIGNUP_CLOSED_MESSAGE, |
| 160 | 161 | updateProfile, |
| @@ -1823,7 +1824,10 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1823 | 1824 | str(input.name) || "unnamed", |
| 1824 | 1825 | scope, |
| 1825 | 1826 | ); |
| 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(); | |
| 1827 | 1831 | return json(minted.value, 201); |
| 1828 | 1832 | }); |
| 1829 | 1833 |
src/http/context.ts +2
| @@ -21,6 +21,8 @@ export interface Auth { | ||
| 21 | 21 | readonly sessionId?: string; |
| 22 | 22 | /** Set for a proposal token: all it may do (`http/proposal_gate.ts`). */ |
| 23 | 23 | 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; | |
| 24 | 26 | } |
| 25 | 27 | |
| 26 | 28 | 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"; | ||
| 430 | 430 | import { apiRoutes } from "./api.ts"; |
| 431 | 431 | import { inNamespace } from "../core/proposal_token.ts"; |
| 432 | 432 | import { proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal-tokens.ts"; |
| 433 | import { ownGate } from "./own_gate.ts"; | |
| 433 | 434 | import { proposalGate } from "./proposal_gate.ts"; |
| 434 | 435 | import { feedRoutes } from "./feed.ts"; |
| 435 | 436 | import type { Database } from "bun:sqlite"; |
| @@ -539,6 +540,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 539 | 540 | scope: verified.value.scope, |
| 540 | 541 | via: "token", |
| 541 | 542 | ...(verified.value.proposal ? { proposal: verified.value.proposal } : {}), |
| 543 | ...(verified.value.ownOnly ? { ownOnly: true as const } : {}), | |
| 542 | 544 | }; |
| 543 | 545 | } |
| 544 | 546 | return NO_AUTH; |
| @@ -564,6 +566,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 564 | 566 | ...(verified.value.proposal |
| 565 | 567 | ? { proposal: verified.value.proposal } |
| 566 | 568 | : {}), |
| 569 | ...(verified.value.ownOnly ? { ownOnly: true as const } : {}), | |
| 567 | 570 | }; |
| 568 | 571 | } |
| 569 | 572 | return NO_AUTH; |
| @@ -2299,6 +2302,8 @@ async function answerGet( | ||
| 2299 | 2302 | // request it makes ends here, before the limiter or any handler. |
| 2300 | 2303 | const proposalRefusal = proposalGate(app, request, url, auth); |
| 2301 | 2304 | if (proposalRefusal !== undefined) return proposalRefusal; |
| 2305 | const ownRefusal = ownGate(url, auth); | |
| 2306 | if (ownRefusal !== undefined) return ownRefusal; | |
| 2302 | 2307 | |
| 2303 | 2308 | // The two things standing between one runaway agent and everybody |
| 2304 | 2309 | // else's latency, applied before a handler runs and after auth is |
src/web/pages/account.ts +7 −2
| @@ -18,6 +18,7 @@ import { | ||
| 18 | 18 | deleteSshKey, |
| 19 | 19 | deleteToken, |
| 20 | 20 | updateProfile, |
| 21 | TOO_WIDE_WORDS, | |
| 21 | 22 | } from "../../actions/users.ts"; |
| 22 | 23 | import { |
| 23 | 24 | NOTIFY_ERRORS, |
| @@ -532,9 +533,11 @@ function tokensView(ctx: Ctx): Html { | ||
| 532 | 533 | options: [ |
| 533 | 534 | { value: "rw", label: "read + write — clone, push, open issues" }, |
| 534 | 535 | { 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 | : []), | |
| 536 | 539 | ], |
| 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.", | |
| 538 | 541 | })} |
| 539 | 542 | ${ctx.auth.user?.isAdmin |
| 540 | 543 | ? html`<div class="field" id="ai-admin"> |
| @@ -587,6 +590,8 @@ export async function tokenCreate(ctx: Ctx): Promise<Response> { | ||
| 587 | 590 | field(form, "name").trim() || "token", |
| 588 | 591 | chosen, |
| 589 | 592 | ); |
| 593 | if (!minted.ok && minted.error === "too_wide") | |
| 594 | return flashTo(ctx, "/settings/tokens", { tone: "danger", message: TOO_WIDE_WORDS }); | |
| 590 | 595 | if (!minted.ok) return signInFirst(ctx); |
| 591 | 596 | // Post-redirect-get: the secret rides a one-shot flash, so a refresh shows |
| 592 | 597 | // 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 | }); |
new above
offline