Public: anyone can read this; the crew can change it.
A Mac can take a repository's checks and report them on the pull #17915
Merged 7h 15m ago, live in production
scout/forge:scout/17910-a-mac-can-take-a-repository-s-checks-and → main 0 commits fork 3 threads · 3 unresolved
12 files
changed +474
−10
- docs/features/outside-checks.md
- src/checks/outside_checks.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/putApiV1ReposOwnerNamePullsNumberChecksCheck.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261203050000-outside-check.pin
- src/core/migrations/20261203050000-outside-check.ts
- src/core/runs.ts
- src/http/api.ts
- src/http/api/outside_checks.ts
- src/http/lazy_lists.ts
- test/outside-checks.test.ts
docs/features/outside-checks.md added +26
| @@ -0,0 +1,26 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Outside checks: a Mac reports a build on the pull | |
| 4 | --- | |
| 5 | # Outside checks | |
| 6 | ||
| 7 | A check does not have to run on the forge. A machine the forge does not run (a Mac that | |
| 8 | archives and uploads the Apple app) reports a named check on a pull's head, and | |
| 9 | `require_checks` counts it like any other. | |
| 10 | ||
| 11 | sh | |
| 12 | curl -X PUT -H "Authorization: Bearer " -H 'content-type: application/json' \ | |
| 13 | -d '{"state":"pending","summary":"archiving","oid":"<head sha>"}' \ | |
| 14 | /api/v1/repos/OWNER/NAME/pulls/N/checks/macos | |
| 15 | ||
| 16 | ||
| 17 | `state` is `pending`, `ok` or `failed`; `summary` is one line (200 characters); `url` an http(s) | |
| 18 | link, shown after the summary; `oid` is the commit built. A head that moved answers 409 | |
| 19 | `head_moved` and nothing is written. Reporting again under the same name replaces the report. | |
| 20 | ||
| 21 | The head is green only when every named report, and the forge's own check, is `ok`. The token is a | |
| 22 | person's `rw` token with write access; a crew member's is refused, so the crew cannot turn a check | |
| 23 | green. The terminal's pull screen (`src/tui/screens/pull.ts`) reads the same verdict. | |
| 24 | ||
| 25 | Not yet: the forge does not hand a repository's declared runs to a machine by label, and | |
| 26 | repository secrets for such a run are not read for one run only. |
src/checks/outside_checks.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | /** | |
| 2 | * A check a machine outside the forge reports on a pull's head (#17910): the Apple app builds | |
| 3 | * only on a Mac, which posts `pending`, then `ok` or `failed`, with a summary and a link. A report | |
| 4 | * is read as a check run of the head (`outsideRuns`, merged by `core/runs.ts` into the runs of a | |
| 5 | * head), so `require_checks` counts it with no second rule: the head is green only when every | |
| 6 | * named report is `ok`. It is a row here and never a queued run, so no scheduler touches it. | |
| 7 | * | |
| 8 | * Plain data in, plain data out; the route (`http/api/outside_checks.ts`) judges who may post. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { id } from "../kernel/id.ts"; | |
| 13 | import type { Run, RunState } from "../core/runs.ts"; | |
| 14 | ||
| 15 | export const OUTSIDE_STATES = ["pending", "ok", "failed"] as const; | |
| 16 | export type OutsideState = (typeof OUTSIDE_STATES)[number]; | |
| 17 | ||
| 18 | /** The env a report's run carries: `ext:<name>`, never a branch or a pull's own. */ | |
| 19 | const OUTSIDE_ENV = "ext:"; | |
| 20 | ||
| 21 | const NAME = /^[a-z0-9][a-z0-9._-]{0,39}$/; | |
| 22 | const SUMMARY_MAX = 200; | |
| 23 | const URL_MAX = 500; | |
| 24 | // Control characters, bidi overrides and line breaks never reach a card or a log. | |
| 25 | // eslint-disable-next-line no-control-regex | |
| 26 | const UNSAFE = /[\u0000-\u001f\u007f\u2028\u2029\u202a-\u202e\u2066-\u2069]/; | |
| 27 | ||
| 28 | export interface OutsideReport { | |
| 29 | readonly name: string; | |
| 30 | readonly state: OutsideState; | |
| 31 | readonly summary: string; | |
| 32 | readonly url: string; | |
| 33 | } | |
| 34 | ||
| 35 | /** What a body says, or the one reason it is refused. */ | |
| 36 | export function parseReport(name: string, input: Record<string, unknown>): OutsideReport | string { | |
| 37 | if (!NAME.test(name)) return "a check's name is 1 to 40 of a-z, 0-9, dot, dash and underscore"; | |
| 38 | const state = input.state; | |
| 39 | if (typeof state !== "string" || !(OUTSIDE_STATES as readonly string[]).includes(state)) | |
| 40 | return "state is pending, ok or failed"; | |
| 41 | const summary = input.summary ?? ""; | |
| 42 | if (typeof summary !== "string" || summary.length > SUMMARY_MAX || UNSAFE.test(summary)) | |
| 43 | return `summary is one line of at most ${SUMMARY_MAX} characters`; | |
| 44 | const url = input.url ?? ""; | |
| 45 | if (typeof url !== "string" || url.length > URL_MAX || UNSAFE.test(url)) return "url is an http(s) address"; | |
| 46 | if (url !== "") { | |
| 47 | let parsed: URL; | |
| 48 | try { | |
| 49 | parsed = new URL(url); | |
| 50 | } catch { | |
| 51 | return "url is an http(s) address"; | |
| 52 | } | |
| 53 | if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "url is an http(s) address"; | |
| 54 | } | |
| 55 | return { name, state: state as OutsideState, summary: summary.trim(), url }; | |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * Records the report on the head, replacing the machine's earlier one of that name, and drops the | |
| 60 | * pull's reports of any older head, so the rows stay as many as the head's names. | |
| 61 | */ | |
| 62 | export function recordReport( | |
| 63 | db: Database, | |
| 64 | at: { readonly repoId: string; readonly issueId: string; readonly oid: string }, | |
| 65 | report: OutsideReport, | |
| 66 | actorId: string, | |
| 67 | ): void { | |
| 68 | db.query("DELETE FROM outside_check WHERE issue_id = ?1 AND commit_oid <> ?2").run(at.issueId, at.oid); | |
| 69 | db.query( | |
| 70 | `INSERT INTO outside_check (id, repo_id, issue_id, commit_oid, name, state, summary, url, actor_id, created_at, updated_at) | |
| 71 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) | |
| 72 | ON CONFLICT (issue_id, commit_oid, name) DO UPDATE SET | |
| 73 | state = excluded.state, summary = excluded.summary, url = excluded.url, | |
| 74 | actor_id = excluded.actor_id, updated_at = excluded.updated_at`, | |
| 75 | ).run(id(), at.repoId, at.issueId, at.oid, report.name, report.state, report.summary, report.url, actorId); | |
| 76 | } | |
| 77 | ||
| 78 | interface Row { | |
| 79 | id: string; | |
| 80 | repo_id: string; | |
| 81 | issue_id: string; | |
| 82 | commit_oid: string; | |
| 83 | name: string; | |
| 84 | state: OutsideState; | |
| 85 | summary: string; | |
| 86 | url: string; | |
| 87 | actor_id: string | null; | |
| 88 | created_at: string; | |
| 89 | updated_at: string; | |
| 90 | } | |
| 91 | ||
| 92 | const NO_REPORT = { | |
| 93 | branch: "", reason: "outside", sessionId: "", costUsd: 0, notBefore: null, attempt: 0, interruptions: 0, | |
| 94 | heartbeatAt: null, turns: 0, contextTokens: 0, model: "", tokensIn: null, tokensOut: null, pushed: null, | |
| 95 | sandboxEnforced: null, sandboxNote: "", placement: "", node: "", start: "", setupMs: -1, checkDetail: null, | |
| 96 | checkPlan: "", feed: null, baseOid: "", combinedOid: "", variantGroup: null, sent: false, servingAt: null, | |
| 97 | } as const; | |
| 98 | ||
| 99 | function asRun(row: Row): Run { | |
| 100 | const state: RunState = row.state === "pending" ? "running" : row.state; | |
| 101 | const words = [row.summary, row.url].filter((s) => s !== "").join(" "); | |
| 102 | return { | |
| 103 | ...NO_REPORT, | |
| 104 | id: row.id, | |
| 105 | repoId: row.repo_id, | |
| 106 | kind: "check", | |
| 107 | issueId: row.issue_id, | |
| 108 | env: OUTSIDE_ENV + row.name, | |
| 109 | commitOid: row.commit_oid, | |
| 110 | state, | |
| 111 | summary: words, | |
| 112 | actorId: row.actor_id, | |
| 113 | createdAt: row.created_at, | |
| 114 | startedAt: row.created_at, | |
| 115 | finishedAt: state === "running" ? null : row.updated_at, | |
| 116 | }; | |
| 117 | } | |
| 118 | ||
| 119 | /** | |
| 120 | * The reports at each pull's own head, as runs, in one statement however many pulls; pulls with | |
| 121 | * none are absent. | |
| 122 | */ | |
| 123 | export function outsideRuns(db: Database, heads: ReadonlyMap<string, string>): Map<string, Run[]> { | |
| 124 | const out = new Map<string, Run[]>(); | |
| 125 | if (heads.size === 0) return out; | |
| 126 | const ids = [...heads.keys()]; | |
| 127 | const rows = db | |
| 128 | .query<Row, string[]>(`SELECT * FROM outside_check WHERE issue_id IN (${ids.map(() => "?").join(",")})`) | |
| 129 | .all(...ids); | |
| 130 | for (const row of rows) { | |
| 131 | if (heads.get(row.issue_id) !== row.commit_oid) continue; | |
| 132 | const list = out.get(row.issue_id) ?? []; | |
| 133 | list.push(asRun(row)); | |
| 134 | out.set(row.issue_id, list); | |
| 135 | } | |
| 136 | return out; | |
| 137 | } | |
| 138 | ||
| 139 | /** | |
| 140 | * The head's reports as one JSON text, a column that rides along in the statement that reads the | |
| 141 | * head's runs (`issue` and `oid` are SQL expressions for the pull and the commit): a page that | |
| 142 | * asks for a head many times pays no second statement for it. | |
| 143 | */ | |
| 144 | export const outsideAsJson = (issue: string, oid: string): string => `(SELECT json_group_array(json_object( | |
| 145 | 'id', id, 'repo_id', repo_id, 'issue_id', issue_id, 'commit_oid', commit_oid, 'name', name, | |
| 146 | 'state', state, 'summary', summary, 'url', url, 'actor_id', actor_id, | |
| 147 | 'created_at', created_at, 'updated_at', updated_at)) | |
| 148 | FROM outside_check WHERE issue_id = ${issue} AND commit_oid = ${oid})`; | |
| 149 | ||
| 150 | /** The runs `outsideAsJson` read; `null` when the column was not there. */ | |
| 151 | export function outsideFromJson(text: string | null): Run[] { | |
| 152 | if (text === null || text === "[]") return []; | |
| 153 | return (JSON.parse(text) as Row[]).map(asRun); | |
| 154 | } | |
| 155 | ||
| 156 | /** Runs newest first, the order every reader of a head's runs expects. */ | |
| 157 | export const newestFirst = (runs: readonly Run[]): Run[] => | |
| 158 | [...runs].sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)); |
src/contract/openapi/routes/index.ts +1
| @@ -553,6 +553,7 @@ export { route as putApiV1ReposOwnerNameIssuesNumberPlan } from "./putApiV1Repos | ||
| 553 | 553 | export { route as putApiV1ReposOwnerNameIssuesNumberTeams } from "./putApiV1ReposOwnerNameIssuesNumberTeams.ts"; |
| 554 | 554 | export { route as putApiV1ReposOwnerNameMilestonesNumberWatch } from "./putApiV1ReposOwnerNameMilestonesNumberWatch.ts"; |
| 555 | 555 | export { route as putApiV1ReposOwnerNamePullsNumberAssignee } from "./putApiV1ReposOwnerNamePullsNumberAssignee.ts"; |
| 556 | export { route as putApiV1ReposOwnerNamePullsNumberChecksCheck } from "./putApiV1ReposOwnerNamePullsNumberChecksCheck.ts"; | |
| 556 | 557 | export { route as putApiV1ReposOwnerNamePullsNumberHold } from "./putApiV1ReposOwnerNamePullsNumberHold.ts"; |
| 557 | 558 | export { route as putApiV1ReposOwnerNamePullsNumberLabels } from "./putApiV1ReposOwnerNamePullsNumberLabels.ts"; |
| 558 | 559 | export { route as putApiV1ReposOwnerNamePullsNumberReview } from "./putApiV1ReposOwnerNamePullsNumberReview.ts"; |
src/contract/openapi/routes/putApiV1ReposOwnerNamePullsNumberChecksCheck.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | import { REPO, type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "put", | |
| 5 | path: `${REPO}/pulls/{number}/checks/{check}`, | |
| 6 | summary: "A machine outside the forge reports a named check on a pull's head", | |
| 7 | detail: "Report a named check (`macos`, 1 to 40 of a-z, 0-9, dot, dash, underscore) on a pull's head, from a machine the forge does not run (a Mac that builds and uploads); `state` is pending, ok or failed, `summary` one line of at most 200 characters, `url` an http(s) link, `oid` the commit built (a head that moved is refused). `require_checks` counts it: the head is green only when every named report is ok. A person's rw token, never an agent's; answers { head, check, state }", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | body: { state: "string", summary: "string", url: "string", oid: "string" }, | |
| 11 | reply: { head: "string", check: "string", state: "string" }, | |
| 12 | refusals: { | |
| 13 | forbidden: "only a person who can write here reports a check (403)", | |
| 14 | not_open: "only an open pull is reported on (409)", | |
| 15 | head_moved: "the pull's head is not the `oid` built (409)", | |
| 16 | invalid: "the name, state, summary, url or oid is not as described (422)", | |
| 17 | }, | |
| 18 | refuses: [401, 404], | |
| 19 | }; |
src/core/event_audience.ts +1
src/core/migration-pins/20261203050000-outside-check.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d07501e7684a1b3996b2174176242f5f291d08db37a8a95d1448adffbc348f98 |
src/core/migrations/20261203050000-outside-check.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | // A check a machine outside the forge reports on a pull's head (#17910): a Mac that builds and | |
| 2 | // uploads, say. One row per pull, commit and name, replaced as the machine reports again. The | |
| 3 | // unique index is the read: a head's reports are one seek. | |
| 4 | export default ` | |
| 5 | CREATE TABLE outside_check ( | |
| 6 | id TEXT PRIMARY KEY, | |
| 7 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 8 | issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE, | |
| 9 | commit_oid TEXT NOT NULL, | |
| 10 | name TEXT NOT NULL, | |
| 11 | state TEXT NOT NULL CHECK (state IN ('pending','ok','failed')), | |
| 12 | summary TEXT NOT NULL DEFAULT '', | |
| 13 | url TEXT NOT NULL DEFAULT '', | |
| 14 | actor_id TEXT REFERENCES user(id) ON DELETE SET NULL, | |
| 15 | created_at TEXT NOT NULL, | |
| 16 | updated_at TEXT NOT NULL | |
| 17 | ); | |
| 18 | CREATE UNIQUE INDEX outside_check_head ON outside_check (issue_id, commit_oid, name); | |
| 19 | `; |
src/core/runs.ts +24 −9
| @@ -12,6 +12,7 @@ import type { Database } from "bun:sqlite"; | ||
| 12 | 12 | import { hostname } from "node:os"; |
| 13 | 13 | import { BUDGET_PREFIX } from "../kernel/budgets.ts"; |
| 14 | 14 | import { id } from "../kernel/id.ts"; |
| 15 | import { newestFirst, outsideAsJson, outsideFromJson } from "../checks/outside_checks.ts"; | |
| 15 | 16 | import { appendRun } from "./ledger.ts"; |
| 16 | 17 | import { meterOf } from "./run_compute.ts"; |
| 17 | 18 | import { parseFeed, type RunFeed } from "./run_feed.ts"; |
| @@ -1269,19 +1270,26 @@ export function checksForHeads( | ||
| 1269 | 1270 | // Only the runs at each pull's own head, through `run_head_checks`: all of a |
| 1270 | 1271 | // pull's runs at every commit were read and dropped here (55 ms to 0.1 ms for 8 pulls). |
| 1271 | 1272 | const rows = db |
| 1272 | .query<RunRow, string[]>( | |
| 1273 | .query<RunRow & { h_issue: string; ext: string | null }, string[]>( | |
| 1273 | 1274 | `WITH head (issue_id, oid) AS (VALUES ${batch.map((_, n) => `(?${2 * n + 1}, ?${2 * n + 2})`).join(",")}) |
| 1274 | SELECT run.* FROM run JOIN head ON head.issue_id = run.issue_id AND head.oid = run.commit_oid | |
| 1275 | WHERE run.kind IN ('deploy','check') | |
| 1275 | SELECT run.*, head.issue_id AS h_issue, ${outsideAsJson("head.issue_id", "head.oid")} AS ext | |
| 1276 | FROM head LEFT JOIN run ON head.issue_id = run.issue_id AND head.oid = run.commit_oid | |
| 1277 | AND run.kind IN ('deploy','check') | |
| 1276 | 1278 | ORDER BY run.id DESC`, |
| 1277 | 1279 | ) |
| 1278 | 1280 | .all(...batch.flatMap((id) => [id, heads.get(id)!])); |
| 1281 | // What a machine outside the forge reported on each head counts as a check of it (#17910); | |
| 1282 | // the reports ride in a column of the same rows, so they cost no statement of their own. | |
| 1283 | const reported = new Map<string, Run[]>(); | |
| 1279 | 1284 | for (const row of rows) { |
| 1280 | if (!row.issue_id || row.commit_oid !== heads.get(row.issue_id)) continue; | |
| 1285 | if (!reported.has(row.h_issue)) reported.set(row.h_issue, outsideFromJson(row.ext)); | |
| 1286 | if (row.id === null || !row.issue_id || row.commit_oid !== heads.get(row.issue_id)) continue; | |
| 1281 | 1287 | const list = out.get(row.issue_id) ?? []; |
| 1282 | 1288 | list.push(toRun(row)); |
| 1283 | 1289 | out.set(row.issue_id, list); |
| 1284 | 1290 | } |
| 1291 | for (const [issueId, more] of reported) | |
| 1292 | if (more.length > 0) out.set(issueId, newestFirst([...(out.get(issueId) ?? []), ...more])); | |
| 1285 | 1293 | } |
| 1286 | 1294 | return out; |
| 1287 | 1295 | } |
| @@ -1352,13 +1360,20 @@ export function checksForHead( | ||
| 1352 | 1360 | headOid: string, |
| 1353 | 1361 | limit = -1, |
| 1354 | 1362 | ): Run[] { |
| 1355 | return db | |
| 1363 | if (limit === 0) return []; | |
| 1364 | // One statement: the runs, and beside them what a machine outside the forge reported on this | |
| 1365 | // head, which counts as a check of it (#17910). The reports ride in a column of the same rows. | |
| 1366 | const rows = db | |
| 1356 | 1367 | .query< |
| 1357 | RunRow, | |
| 1368 | RunRow & { ext: string | null }, | |
| 1358 | 1369 | [string, string, number] |
| 1359 | >("SELECT * FROM run WHERE kind IN ('deploy','check') AND issue_id = ?1 AND commit_oid = ?2 ORDER BY id DESC LIMIT ?3") | |
| 1360 | .all(issueId, headOid, limit) | |
| 1361 | .map(toRun); | |
| 1370 | >(`SELECT r.*, o.ext FROM (SELECT ${outsideAsJson('?1', '?2')} AS ext) o | |
| 1371 | LEFT JOIN run r ON r.kind IN ('deploy','check') AND r.issue_id = ?1 AND r.commit_oid = ?2 | |
| 1372 | ORDER BY r.id DESC LIMIT ?3`) | |
| 1373 | .all(issueId, headOid, limit); | |
| 1374 | const runs = rows.filter((row) => row.id !== null).map(toRun); | |
| 1375 | const reported = outsideFromJson(rows[0]?.ext ?? null); | |
| 1376 | return reported.length === 0 ? runs : newestFirst([...runs, ...reported]).slice(0, limit < 0 ? undefined : limit); | |
| 1362 | 1377 | } |
| 1363 | 1378 | |
| 1364 | 1379 | /** |
src/http/api.ts +3 −1
| @@ -339,6 +339,7 @@ import { displayRoutes } from "./api/displays.ts"; | ||
| 339 | 339 | import { followingRoutes } from "./api/following.ts"; |
| 340 | 340 | import { familyRoutes } from "./api/family.ts"; |
| 341 | 341 | import { labelsRoutes } from "./api/labels.ts"; |
| 342 | import { outsideChecksRoutes } from "./api/outside_checks.ts"; | |
| 342 | 343 | import { deskRoutes } from "./api/desk.ts"; |
| 343 | 344 | import { dataRoutes } from "./api/data.ts"; |
| 344 | 345 | import { dropRoutes } from "./api/drop.ts"; |
| @@ -1109,7 +1110,7 @@ export function agentJson(agent: Agent) { | ||
| 1109 | 1110 | } |
| 1110 | 1111 | |
| 1111 | 1112 | /** The live head of a pull — the branch tip, or the snapshot for a fork's. */ |
| 1112 | async function pullHeadOid(ctx: Ctx, repo: Repo, pull: Pull): Promise<string> { | |
| 1113 | export async function pullHeadOid(ctx: Ctx, repo: Repo, pull: Pull): Promise<string> { | |
| 1113 | 1114 | const ref = pull.crossRepo |
| 1114 | 1115 | ? `refs/pull/${pull.number}/head` |
| 1115 | 1116 | : `refs/heads/${pull.headBranch}`; |
| @@ -2373,6 +2374,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2373 | 2374 | // ── labels ─────────────────────────────────────────────────────────── |
| 2374 | 2375 | |
| 2375 | 2376 | labelsRoutes(router); |
| 2377 | outsideChecksRoutes(router); | |
| 2376 | 2378 | deskRoutes(router); |
| 2377 | 2379 | visionRoutes(router); |
| 2378 | 2380 | dataRoutes(router); |
src/http/api/outside_checks.ts added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | /** | |
| 2 | * A machine outside the forge reports a named check on a pull's head (#17910): | |
| 3 | * `PUT /api/v1/repos/:owner/:name/pulls/:number/checks/:check` with | |
| 4 | * `{ state: pending|ok|failed, summary?, url?, oid? }`. The report is read as a check of the head | |
| 5 | * (`checks/outside_checks.ts`), so `require_checks` counts it. The rules: a writer's rw token and | |
| 6 | * never an agent's (the crew proposes, a person lands, so a crew member cannot turn a check | |
| 7 | * green), an open pull, and, when `oid` is given, the head the machine built: a report for an | |
| 8 | * older head is refused (409 `head_moved`), never put on the new one. | |
| 9 | */ | |
| 10 | ||
| 11 | import { parseReport, recordReport } from "../../checks/outside_checks.ts"; | |
| 12 | import { canWrite } from "../../core/repos.ts"; | |
| 13 | import { loadPull, pullHeadOid } from "../api.ts"; | |
| 14 | import type { Handler } from "../context.ts"; | |
| 15 | import { apiError, body, json, requireScope } from "../respond.ts"; | |
| 16 | import type { Router } from "../router.ts"; | |
| 17 | ||
| 18 | export function outsideChecksRoutes(router: Router<Handler>): void { | |
| 19 | router.add("PUT", "/api/v1/repos/:owner/:name/pulls/:number/checks/:check", async (ctx) => { | |
| 20 | const denied = requireScope(ctx, "rw"); | |
| 21 | if (denied) return denied; | |
| 22 | const found = loadPull(ctx); | |
| 23 | if ("error" in found) return found.error; | |
| 24 | const user = ctx.auth.user; | |
| 25 | if (!user || user.kind === "agent" || !canWrite(ctx.app.db, found.repo, user)) | |
| 26 | return apiError("forbidden", 403, "only a person who can write here reports a check"); | |
| 27 | if (found.pull.state !== "open") return apiError("not_open", 409, "only an open pull is reported on"); | |
| 28 | const input = await body(ctx.request); | |
| 29 | const report = parseReport(ctx.params.check!, input); | |
| 30 | if (typeof report === "string") return apiError("invalid", 422, report); | |
| 31 | if (input.oid !== undefined && (typeof input.oid !== "string" || !/^[0-9a-f]{40}$/.test(input.oid))) | |
| 32 | return apiError("invalid", 422, "oid is a full commit id"); | |
| 33 | const head = await pullHeadOid(ctx, found.repo, found.pull); | |
| 34 | if (input.oid !== undefined && input.oid !== head) | |
| 35 | return apiError("head_moved", 409, `the pull's head is now ${head}, not ${String(input.oid)}`); | |
| 36 | recordReport(ctx.app.db, { repoId: found.repo.id, issueId: found.pull.id, oid: head }, report, user.id); | |
| 37 | ctx.app.bus.append({ | |
| 38 | kind: "check.reported", | |
| 39 | repoId: found.repo.id, | |
| 40 | actorId: user.id, | |
| 41 | payload: { pull: found.pull.number, check: report.name, state: report.state, oid: head }, | |
| 42 | }); | |
| 43 | return json({ head, check: report.name, state: report.state }, 200); | |
| 44 | }); | |
| 45 | } |
src/http/lazy_lists.ts +1
| @@ -1405,6 +1405,7 @@ export const API_ROUTES = [ | ||
| 1405 | 1405 | ["POST", "/api/v1/repos/:owner/:name/labels"], |
| 1406 | 1406 | ["PATCH", "/api/v1/repos/:owner/:name/labels/:id"], |
| 1407 | 1407 | ["DELETE", "/api/v1/repos/:owner/:name/labels/:id"], |
| 1408 | ["PUT", "/api/v1/repos/:owner/:name/pulls/:number/checks/:check"], | |
| 1408 | 1409 | ["GET", "/api/v1/repos/:owner/:name/desk"], |
| 1409 | 1410 | ["POST", "/api/v1/repos/:owner/:name/desk"], |
| 1410 | 1411 | ["DELETE", "/api/v1/repos/:owner/:name/desk/:id"], |
test/outside-checks.test.ts added +176
| @@ -0,0 +1,176 @@ | ||
| 1 | /** | |
| 2 | * A machine outside the forge reports a named check on a pull's head, and the head's verdict counts | |
| 3 | * it (#17910). | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { openPull } from "../src/actions/pulls.ts"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { parseReport, recordReport } from "../src/checks/outside_checks.ts"; | |
| 13 | import { checkSummary } from "../src/core/runs.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createUser } from "../src/core/users.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | let dataDir: string; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let owner = ""; | |
| 25 | let stranger = ""; | |
| 26 | let number = 0; | |
| 27 | let pullId = ""; | |
| 28 | const cells = process.env["FORGE_CELLS"]; | |
| 29 | ||
| 30 | const person = async (username: string, first: boolean) => { | |
| 31 | const made = await createUser(app.db, { | |
| 32 | origin: "seed", trusted: true, username, email: `${username}@forge.local`, | |
| 33 | password: "a-good-passphrase", adminIfFirst: first, | |
| 34 | }); | |
| 35 | if (!made.ok) throw new Error(String(made.error)); | |
| 36 | return made.value; | |
| 37 | }; | |
| 38 | ||
| 39 | beforeAll(async () => { | |
| 40 | process.env["FORGE_CELLS"] = "off"; | |
| 41 | dataDir = await mkdtemp(join(tmpdir(), "forge-outside-checks-")); | |
| 42 | app = createApp({ dataDir, port: 0 }); | |
| 43 | servers = await serve(app); | |
| 44 | const alice = await person("alice", true); | |
| 45 | const bob = await person("bob", false); | |
| 46 | owner = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 47 | stranger = `forge_session=${createSession(app.db, bob.id).token}`; | |
| 48 | const repo = await createRepo(app, alice, { name: "r", visibility: "public" }); | |
| 49 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 50 | for (const [branch, file] of [[undefined, "forge.json"], ["topic", "t.txt"]] as const) { | |
| 51 | const done = await commitToBranch(app, alice, repo.value, { | |
| 52 | ...(branch === undefined ? {} : { branch }), | |
| 53 | message: "change", | |
| 54 | files: [{ path: file, content: file === "forge.json" ? "{}" : "x" }], | |
| 55 | }); | |
| 56 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 57 | } | |
| 58 | const pull = await openPull(app, alice, repo.value, { title: "t", body: "", baseBranch: "main", headBranch: "topic" }); | |
| 59 | if (!pull.ok) throw new Error(JSON.stringify(pull.error)); | |
| 60 | number = pull.value.number; | |
| 61 | pullId = pull.value.id; | |
| 62 | }); | |
| 63 | ||
| 64 | afterAll(async () => { | |
| 65 | await servers.stop(); | |
| 66 | app.close(); | |
| 67 | if (cells === undefined) delete process.env["FORGE_CELLS"]; | |
| 68 | else process.env["FORGE_CELLS"] = cells; | |
| 69 | await rm(dataDir, { recursive: true, force: true }); | |
| 70 | }); | |
| 71 | ||
| 72 | const url = (name = "macos") => `${servers.url}/api/v1/repos/alice/r/pulls/${number}/checks/${name}`; | |
| 73 | const put = (payload: unknown, cookie = owner, name = "macos") => | |
| 74 | fetch(url(name), { | |
| 75 | method: "PUT", | |
| 76 | headers: { cookie, origin: servers.url, "content-type": "application/json" }, | |
| 77 | body: JSON.stringify(payload), | |
| 78 | }); | |
| 79 | const head = async () => | |
| 80 | ((await (await fetch(`${servers.url}/api/v1/repos/alice/r/pulls/${number}/checks`, { headers: { cookie: owner } })).json()) as { head: string }).head; | |
| 81 | const state = async () => | |
| 82 | ((await (await fetch(`${servers.url}/api/v1/repos/alice/r/pulls/${number}/checks`, { headers: { cookie: owner } })).json()) as { state: string; run: { summary: string } | null }); | |
| 83 | ||
| 84 | test("a pending report holds the head, ok clears it, failed is red", async () => { | |
| 85 | expect((await put({ state: "pending", summary: "building" })).status).toBe(200); | |
| 86 | expect((await state()).state).toBe("running"); | |
| 87 | expect((await put({ state: "failed", summary: "archive failed", url: "https://ci.example/1" })).status).toBe(200); | |
| 88 | const red = await state(); | |
| 89 | expect(red.state).toBe("failed"); | |
| 90 | expect(red.run?.summary).toContain("archive failed"); | |
| 91 | expect((await put({ state: "ok", summary: "uploaded to TestFlight" })).status).toBe(200); | |
| 92 | expect(checkSummary(app.db, pullId, await head()).state).toBe("ok"); | |
| 93 | }); | |
| 94 | ||
| 95 | test("a second name must also be ok: every named report counts", async () => { | |
| 96 | await put({ state: "pending" }, owner, "lint"); | |
| 97 | expect(checkSummary(app.db, pullId, await head()).state).not.toBe("ok"); | |
| 98 | await put({ state: "ok" }, owner, "lint"); | |
| 99 | expect(checkSummary(app.db, pullId, await head()).state).toBe("ok"); | |
| 100 | }); | |
| 101 | ||
| 102 | test("a report for a head that moved is refused and writes nothing", async () => { | |
| 103 | const before = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM outside_check").get()!.n; | |
| 104 | const res = await put({ state: "ok", oid: "0".repeat(40) }); | |
| 105 | expect(res.status).toBe(409); | |
| 106 | expect(((await res.json()) as { error: string }).error).toBe("head_moved"); | |
| 107 | expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM outside_check").get()!.n).toBe(before); | |
| 108 | }); | |
| 109 | ||
| 110 | test("someone who cannot write, and a cross-origin session, are refused", async () => { | |
| 111 | expect((await put({ state: "ok" }, stranger)).status).toBe(403); | |
| 112 | const cross = await fetch(url(), { | |
| 113 | method: "PUT", | |
| 114 | headers: { cookie: owner, origin: "https://evil.example", "content-type": "application/json" }, | |
| 115 | body: JSON.stringify({ state: "ok" }), | |
| 116 | }); | |
| 117 | expect(cross.status).toBe(403); | |
| 118 | }); | |
| 119 | ||
| 120 | test("a bad name, state, summary or link is a 422", async () => { | |
| 121 | expect((await put({ state: "green" })).status).toBe(422); | |
| 122 | expect((await put({ state: "ok" }, owner, "Mac%20OS")).status).toBe(422); | |
| 123 | expect((await put({ state: "ok", url: "javascript:alert(1)" })).status).toBe(422); | |
| 124 | expect((await put({ state: "ok", summary: "a\nb" })).status).toBe(422); | |
| 125 | expect((await put({ state: "ok", oid: "nope" })).status).toBe(422); | |
| 126 | }); | |
| 127 | ||
| 128 | const rows = () => | |
| 129 | app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM outside_check WHERE issue_id = ?1 AND name = 'macos'").get(pullId)!.n; | |
| 130 | ||
| 131 | test("reporting again under a name replaces it, and announces each report", async () => { | |
| 132 | const events = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'check.reported'").get()!.n; | |
| 133 | const before = events(); | |
| 134 | await put({ state: "pending" }); | |
| 135 | await put({ state: "ok" }); | |
| 136 | expect(rows()).toBe(1); | |
| 137 | expect(events()).toBe(before + 2); | |
| 138 | const res = await put({ state: "ok" }); | |
| 139 | expect(Object.keys((await res.json()) as object).sort()).toEqual(["check", "head", "state"]); | |
| 140 | }); | |
| 141 | ||
| 142 | test("reports of a superseded head are dropped when the new head is reported", () => { | |
| 143 | const old = "1".repeat(40); | |
| 144 | const at = { repoId: "r", issueId: pullId, oid: old }; | |
| 145 | app.db.run("PRAGMA foreign_keys = OFF"); | |
| 146 | const repoId = app.db.query<{ repo_id: string }, [string]>("SELECT repo_id FROM issue WHERE id = ?1").get(pullId)!.repo_id; | |
| 147 | recordReport(app.db, { ...at, repoId }, { name: "stale", state: "ok", summary: "", url: "" }, "x"); | |
| 148 | app.db.run("PRAGMA foreign_keys = ON"); | |
| 149 | expect(app.db.query("SELECT 1 FROM outside_check WHERE commit_oid = ?1").all(old).length).toBe(1); | |
| 150 | return put({ state: "ok" }).then(() => { | |
| 151 | expect(app.db.query("SELECT 1 FROM outside_check WHERE commit_oid = ?1").all(old).length).toBe(0); | |
| 152 | }); | |
| 153 | }); | |
| 154 | ||
| 155 | test("an agent is refused even with write access, and writes nothing", async () => { | |
| 156 | const bot = await person("helper", false); | |
| 157 | app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(bot.id); | |
| 158 | const before = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM outside_check").get()!.n; | |
| 159 | const res = await put({ state: "ok" }, `forge_session=${createSession(app.db, bot.id).token}`); | |
| 160 | expect(res.status).toBe(403); | |
| 161 | expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM outside_check").get()!.n).toBe(before); | |
| 162 | }); | |
| 163 | ||
| 164 | test("a closed pull is not reported on (409 not_open)", async () => { | |
| 165 | app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(pullId); | |
| 166 | const res = await put({ state: "failed" }); | |
| 167 | app.db.query("UPDATE issue SET state = 'open' WHERE id = ?1").run(pullId); | |
| 168 | expect(res.status).toBe(409); | |
| 169 | expect(((await res.json()) as { error: string }).error).toBe("not_open"); | |
| 170 | expect((await state()).state).toBe("ok"); | |
| 171 | }); | |
| 172 | ||
| 173 | test("parseReport names its refusals", () => { | |
| 174 | expect(typeof parseReport("../x", { state: "ok" })).toBe("string"); | |
| 175 | expect(parseReport("macos", { state: "ok", summary: " built " })).toEqual({ name: "macos", state: "ok", summary: "built", url: "" }); | |
| 176 | }); |
new above
offline
The agent refusal is untested. Add a test with an agent's token (or an agent user) expecting 403 and no row written.