Public: anyone can read this; the crew can change it.
A contrib pull's own contribute token may read its check.txt; another pull's token is 403 #12504
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/12166-a-contrib-pull-s-own-contribute-token-ma → main 3 commits fork 2 threads · 2 unresolved
4 files
changed +65
−10
docs/features/contribute-token.md +2
| @@ -21,3 +21,5 @@ or the MCP `start` tool with `action: "contribute"` (same arguments). The answer | ||
| 21 | 21 | **What runs, and what it holds.** The code on a `contrib/` branch is an outside agent's, whoever opens the pull, so the pull is a guest's (`src/origins/guest.ts`). Its **check runs at once**, with nobody's permission: green or red in minutes, read at the `checks (plain text)` URL the push prints. That is safe for what a check is: a cell holding no variable, no token and no secret, reaching the registry and the hosts **main's** `forge.json` declares, within main's limits (the branch's own `egress` and `check.limits` are not used until the pull lands, as for every pull, and for this one the list is enforced whatever the forge's egress setting; `src/checks/held.ts`, `src/checks/outside.ts`). Its check is **queued behind every other check**: while the owner's or the crew's work is queued, that runs first (`src/checks/outside_lane.ts`, and once the pull is approved it is the repository's like any pull's). **No preview is deployed from its branch until a person who can write approves the pull** (the same once-per-pull approval a guest's fork takes); after the approval the preview deploys as for any pull, with the app's settings. The pull page says one line to a writer, "From an outside contributor: approve to deploy its preview, with this app's settings.", with **Approve**. A crew reviewer's approval of the pull records the same approval (`approveGuestPull`), so it releases the preview too. On a machine that cannot hold a cell, an unapproved outside pull's check fails with a sentence that says a writer approves the pull (Approve on its page) and then runs its checks again, rather than run a stranger's code beside the forge's own data. |
| 22 | 22 | |
| 23 | 23 | **The push opens the pull (#12013).** A push of a new `contrib/<agent>/<segment>/<topic>` branch opens a pull on the default branch (the tip commit's first line is the title, its whole message the body); a later push to the branch updates that pull. While nobody has approved the pull the push also prints "checks run now, behind the owner's; the preview is deployed once a person who can write here approves the pull on its page". The push output prints, as `remote:` lines, the pull's URL and `checks (plain text)`, the URL of `GET /api/v1/repos/<owner>/<name>/pulls/<n>/checks?format=text` (`state:`, `head:`, `required:`). Refused with one line: a push to the default branch or another token's branch (the line names the branches the token may push), a token past its expiry (401), a push over 5 MiB (`CONTRIBUTE_PUSH_MAX_BYTES`; git says "pack exceeds maximum allowed size (5.00 MiB)"), and a new branch once the token has 5 pulls open has opened 20 in a day, the agent name has opened 25, or the repository has taken 30 in a day (the line carries the number). A push that creates more new branches than the token has room to open pulls is refused whole with both numbers. Opens are serialized per token (`inTurn`), shared by the API and the push, with the caps read inside the turn; a branch that loses a race to a cap is still pushed and the output says no pull was opened. Code: `src/actions/contribute_push.ts`; test: `test/contribute-push.test.ts`. |
| 24 | ||
| 25 | **Reading its own check.** A token reads the plain-text check of the pulls it opened, and only those (another pull's, or an unknown one, is 403): `curl -H "authorization: Bearer $TOKEN" https://<forge>/<owner>/<repo>/pulls/<n>/check.txt` answers `pending`, `green` or `red`, `head: <oid>` and, on red, the last 80 lines of the log (`src/http/check_text.ts`). |
src/core/contribute_token.ts +11 −5
| @@ -186,17 +186,23 @@ export function allows(scope: ContributeScope, repo: { owner: string; name: stri | ||
| 186 | 186 | if (ask.method === "POST" && /^\/[^/]+\/[^/]+\.git\/git-upload-pack$/.test(path)) return true; |
| 187 | 187 | if (ask.method === "POST" && path === `${at}.git/git-receive-pack`) return true; |
| 188 | 188 | if (ask.method === "POST" && path === `${api}/pulls`) return true; |
| 189 | // The plain-text check of the token's own pull, and no other's. | |
| 190 | if (read && ask.ownPull === true && /^\/[^/]+\/[^/]+\/pulls\/[1-9][0-9]{0,8}\/check\.txt$/.test(path) && path.startsWith(`${at}/pulls/`)) | |
| 191 | return true; | |
| 189 | 192 | if ((ask.method === "PATCH" || ask.method === "POST") && ask.ownPull === true && path.startsWith(`${api}/pulls/`)) return true; |
| 190 | 193 | return false; |
| 191 | 194 | } |
| 192 | 195 | |
| 193 | /** The pull number a path names under `repo`'s pulls, or undefined. */ | |
| 196 | /** The pull number a path names under `repo`'s pulls (API or page path), or undefined. */ | |
| 194 | 197 | export function pullNumberIn(path: string, repo: { owner: string; name: string }): number | undefined { |
| 195 | const head = `/api/v1/repos/${repo.owner}/${repo.name}/pulls/`.toLowerCase(); | |
| 196 | 198 | const lower = path.toLowerCase(); |
| 197 | if (!lower.startsWith(head)) return undefined; | |
| 198 | const m = /^([1-9][0-9]{0,8})(?:\/|$)/.exec(lower.slice(head.length)); | |
| 199 | return m ? Number(m[1]) : undefined; | |
| 199 | const at = `/${repo.owner}/${repo.name}`.toLowerCase(); | |
| 200 | for (const head of [`/api/v1/repos${at}/pulls/`, `${at}/pulls/`]) { | |
| 201 | if (!lower.startsWith(head)) continue; | |
| 202 | const m = /^([1-9][0-9]{0,8})(?:\/|$)/.exec(lower.slice(head.length)); | |
| 203 | return m ? Number(m[1]) : undefined; | |
| 204 | } | |
| 205 | return undefined; | |
| 200 | 206 | } |
| 201 | 207 | |
| 202 | 208 | // ---- the rows ---- |
src/http/check_text.ts +13 −4
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | * only when the log door (`runLog`) would show that reader the log. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { runLog } from "../actions/runs.ts"; | |
| 8 | import { getRepoRun, runLog } from "../actions/runs.ts"; | |
| 9 | import { readRunLogTail } from "../runs/log.ts"; | |
| 9 | 10 | import { checkSummary } from "../core/runs.ts"; |
| 10 | 11 | import { loadPull } from "./api.ts"; |
| 11 | 12 | import type { Ctx } from "./context.ts"; |
| @@ -21,9 +22,17 @@ export function checkText(ctx: Ctx): Response { | ||
| 21 | 22 | const word = state === "ok" ? "green" : state === "failed" || state === "cancelled" ? "red" : "pending"; |
| 22 | 23 | let body = `${word}\nhead: ${pull.headOid}\n`; |
| 23 | 24 | if (word === "red" && run) { |
| 24 | const log = runLog(ctx.app, ctx.auth.user, repo, run.id, TAIL_MAX); | |
| 25 | if (log.ok && !log.value.logHidden && log.value.lines.length > 0) | |
| 26 | body += `\n${log.value.lines.slice(-TAIL_MAX).join("\n")}\n`; | |
| 25 | // A contribute token reaching here is the pull's own author (the gate): its log is its to read. | |
| 26 | const own = ctx.auth.contribute !== undefined && ctx.auth.user?.id === pull.authorId; | |
| 27 | const lines = own | |
| 28 | ? getRepoRun(ctx.app, ctx.auth.user, repo, run.id).ok | |
| 29 | ? readRunLogTail(ctx.app.config.dataDir, run.id, TAIL_MAX).lines | |
| 30 | : [] | |
| 31 | : (() => { | |
| 32 | const log = runLog(ctx.app, ctx.auth.user, repo, run.id, TAIL_MAX); | |
| 33 | return log.ok && !log.value.logHidden ? log.value.lines : []; | |
| 34 | })(); | |
| 35 | if (lines.length > 0) body += `\n${lines.slice(-TAIL_MAX).join("\n")}\n`; | |
| 27 | 36 | } |
| 28 | 37 | return securityFloor( |
| 29 | 38 | new Response(body, { |
test/contribute-check-text.test.ts +39 −1
| @@ -4,10 +4,13 @@ import { mkdtemp, rm } from "node:fs/promises"; | ||
| 4 | 4 | import { tmpdir } from "node:os"; |
| 5 | 5 | import { join } from "node:path"; |
| 6 | 6 | import { createApp, type App } from "../src/app.ts"; |
| 7 | import { mintContributeToken, setOutsideContributions } from "../src/actions/contribute_token.ts"; | |
| 7 | 8 | import { newApp } from "../src/actions/apps.ts"; |
| 8 | 9 | import { createIssue } from "../src/core/issues.ts"; |
| 9 | 10 | import { createSession } from "../src/core/sessions.ts"; |
| 10 | import { createUser } from "../src/core/users.ts"; | |
| 11 | import { getRepoById } from "../src/core/repos.ts"; | |
| 12 | import { verifyToken } from "../src/core/tokens.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | 14 | import { appendRunLog, flushRunLogs } from "../src/runs/log.ts"; |
| 12 | 15 | import { serve, type Servers } from "../src/http/server.ts"; |
| 13 | 16 | import { quietLogs } from "./helpers/globals.ts"; |
| @@ -106,3 +109,38 @@ test("a red check carries the last 80 lines of its log, only for a reader the lo | ||
| 106 | 109 | test("an unknown pull is 404", async () => { |
| 107 | 110 | expect((await get(9999)).status).toBe(404); |
| 108 | 111 | }, SLOW); |
| 112 | ||
| 113 | test("a contribute token reads the check of its own pull, tail included, and no other pull's", async () => { | |
| 114 | const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!; | |
| 115 | const repo = getRepoById(app.db, repoId)!; | |
outdated
Use a top-level import of getRepoById, not a dynamic import inside the test. |
||
| 116 | setOutsideContributions(app, { id: alice.id } as User, repo, true); | |
| 117 | const mint = async (agent: string, n: number) => { | |
| 118 | const m = await mintContributeToken(app, { agent, origin: "t", repo: "alice/notes" }, `203.0.113.${n}`, "https://forge.test"); | |
| 119 | if (!m.ok) throw new Error(JSON.stringify(m.error)); | |
| 120 | const v = verifyToken(app.db, m.value.token) as { ok: true; value: { user: User } }; | |
| 121 | return { token: m.value.token, userId: v.value.user.id }; | |
| 122 | }; | |
| 123 | const a = await mint("codex", 1); | |
| 124 | const b = await mint("jules", 2); | |
| 125 | const mine = createIssue(app.db, { repoId, authorId: a.userId, title: "mine", kind: "pull" }); | |
| 126 | if (!mine.ok) throw new Error(mine.error); | |
| 127 | app.db | |
| 128 | .query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?, 'main', 'h-c1', 'b', 'c1')") | |
| 129 | .run(mine.value.id); | |
| 130 | const id = run(mine.value.id, "c1", "failed"); | |
| 131 | for (let i = 1; i <= 100; i++) appendRunLog(dataDir, id, `line ${i}`); | |
| 132 | flushRunLogs(); | |
| 133 | const as = (n: number, t: string) => | |
| 134 | fetch(`${servers.url}/alice/notes/pulls/${n}/check.txt`, { headers: { authorization: `Bearer ${t}` } }); | |
| 135 | ||
| 136 | const own = await as(mine.value.number, a.token); | |
| 137 | expect(own.status).toBe(200); | |
| 138 | const text = await own.text(); | |
| 139 | expect(text.startsWith("red\nhead: c1\n\nline 21\n")).toBe(true); | |
| 140 | expect(text.endsWith("line 100\n")).toBe(true); | |
| 141 | ||
| 142 | expect((await as(mine.value.number, b.token)).status).toBe(403); // another token's pull | |
| 143 | expect((await as(9999, a.token)).status).toBe(403); // unknown pull | |
| 144 | const theirs = addPull("o1"); // the owner's pull | |
| 145 | expect((await as(theirs.number, a.token)).status).toBe(403); | |
| 146 | }, SLOW); |
new above
offline
Indent the else body (and its closing brace) like the rest of the file.