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

The crew's repository token reads the release keeper's newest beat on GET /api/v1/keeper, so a stopped release is diagnosed without the owner #15451

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15449-the-crew-s-repository-token-reads-the-re → main 0 commits fork

  • Merged. scout/15449-the-crew-s-repository-token-reads-the-re was merged into main as df22f2e.

Review

Sign in to review this change.
5 files changed +142 −4
scripts/v1-probe.ts +34 −2
@@ -6,6 +6,10 @@
66 * every request goes to `<base-url>`, apart from one GET of `--edition`, and reads only
77 * `--repo` (default `trevato/forge`). It never signs in, pays or writes.
88 *
9 * With `FORGE_TOKEN` set (the crew's token for the forge's repository is enough, #15449) it
10 * also GETs `/api/v1/keeper` with that token, and only there, and prints `keeper's last beat`:
11 * the release tick's newest outcome and reason, so a stopped release is named from a shell.
12 *
913 * `--edition` is a public page a scheduled app prints, such as the morning paper's latest
1014 * edition (#15388): its newest `<time datetime>` or `<updated>` is when the schedule last ran,
1115 * because an anonymous read of the schedules API answers 404.
@@ -156,7 +160,7 @@ function readOnlyCall(body: unknown): boolean {
156160 }
157161
158162 /** Runs every item against `base` and returns the lines in checklist order. */
159 export async function probe(base: string, repo: string, fetcher: Fetcher = fetch, now = Date.now(), edition?: string): Promise<Line[]> {
163 export async function probe(base: string, repo: string, fetcher: Fetcher = fetch, now = Date.now(), edition?: string, token?: string): Promise<Line[]> {
160164 const origin = new URL(base).origin;
161165 const get = async (path: string, init?: RequestInit): Promise<Seen | string> => {
162166 const url = new URL(path, origin);
@@ -298,9 +302,37 @@ export async function probe(base: string, repo: string, fetcher: Fetcher = fetch
298302 if (missing.length === 0) say(`security headers on ${path}`, "PASS", path, `CSP, nosniff, referrer-policy ${seen.headers.get("referrer-policy")}`);
299303 else say(`security headers on ${path}`, "FAIL", path, `missing ${missing.join(", ")}`);
300304 }
305
306 // 8. The release keeper's newest beat (#15449), only for a caller holding a token.
307 if (token) {
308 const keeper = await get("/api/v1/keeper", { headers: { authorization: `Bearer ${token}` } });
309 const beat = keeperBeat(typeof keeper === "string" ? undefined : json(keeper));
310 if (typeof keeper === "string") say(KEEPER_ITEM, "UNKNOWN", "/api/v1/keeper", keeper);
311 else if (keeper.status !== 200) say(KEEPER_ITEM, "UNKNOWN", "/api/v1/keeper", `${keeper.status}, this token may not read the release history`);
312 else if (beat === undefined) say(KEEPER_ITEM, "UNKNOWN", "/api/v1/keeper", "200 without a heartbeat: the release tick has not reported yet");
313 else {
314 const words = `${beat.outcome} at ${beat.at}${beat.silent ? " (silent for over an hour)" : ""}: ${beat.reason}`;
315 say(KEEPER_ITEM, beat.outcome === "failed" || beat.silent ? "FAIL" : "PASS", "/api/v1/keeper", words);
316 }
317 }
301318 return lines;
302319 }
303320
321 export const KEEPER_ITEM = "keeper's last beat";
322
323 /**
324 * The keeper answer's `heartbeat`, its words stripped of control characters; undefined when it has
325 * none.
326 */
327 export function keeperBeat(answer: unknown): { at: string; outcome: string; reason: string; silent: boolean } | undefined {
328 const h = (answer as { heartbeat?: unknown } | null | undefined)?.heartbeat as Record<string, unknown> | null | undefined;
329 if (h === null || typeof h !== "object") return undefined;
330 const { at, outcome, reason, silent } = h;
331 if (typeof at !== "string" || typeof outcome !== "string" || typeof reason !== "string") return undefined;
332 const plain = (t: string) => t.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 300);
333 return { at: plain(at), outcome: plain(outcome), reason: plain(reason), silent: silent === true };
334 }
335
304336 export const formatLine = (l: Line): string => `${l.verdict.padEnd(7)} ${l.item}: ${l.url} - ${l.evidence}`;
305337
306338 if (import.meta.main) {
@@ -309,7 +341,7 @@ if (import.meta.main) {
309341 console.error(parsed.error);
310342 process.exit(2);
311343 }
312 const lines = await probe(parsed.base, parsed.repo, fetch, Date.now(), parsed.edition);
344 const lines = await probe(parsed.base, parsed.repo, fetch, Date.now(), parsed.edition, process.env["FORGE_TOKEN"] || undefined);
313345 for (const l of lines) console.log(formatLine(l));
314346 const pass = lines.every((l) => l.verdict === "PASS");
315347 console.log(pass ? "every line PASS: v1.0.0 may be tagged" : "not every line is PASS: do not tag v1.0.0");
src/http/run_gate.ts +5
@@ -24,6 +24,7 @@
2424
2525 import type { App } from "../app.ts";
2626 import { getRepoById, type Repo } from "../core/repos.ts";
27 import { forgeRepoOf } from "../release/gate.ts";
2728 import type { Auth } from "./context.ts";
2829 import { movedTarget } from "./moved.ts";
2930 import { apiError } from "./respond.ts";
@@ -116,6 +117,10 @@ export function runGate(
116117 const method = request.method;
117118
118119 if ((method === "GET" || method === "HEAD") && FORGE_READS.has(path)) return undefined;
120 // A crew run on the forge's own repository reads why releases stopped (#15449): the keeper's
121 // answer, which its handler still gives only to `mayRead`. An app preview's token never does.
122 if ((method === "GET" || method === "HEAD") && path === "/api/v1/keeper" && scope.app !== true && forgeRepoOf(app)?.id === repo.id)
123 return undefined;
119124
120125 for (const own of [repo, fork]) {
121126 const api = under(path, "/api/v1/repos", own);
src/release/gate.ts +1 −1
@@ -22,7 +22,7 @@ import { beginSwap, endSwap, handover } from "./swap.ts";
2222 export const BOOTED = new Date().toISOString();
2323
2424 /** The forge's own code repository, when this forge names one. */
25 function forgeRepoOf(app: App): Repo | undefined {
25 export function forgeRepoOf(app: App): Repo | undefined {
2626 const named = app.config.forgeRepo;
2727 if (named === undefined) return undefined;
2828 const [owner, name] = named.split("/");
test/keeper-crew-reads.test.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The crew's run token on the forge's own repository reads the release keeper's newest beat on
3 * `GET /api/v1/keeper` (#15449): a stopped release is diagnosed without the owner. The run gate
4 * opens that one read for that one repository; `mayRead` still decides. Anonymous, a run on
5 * another repository, and an app preview's token stay refused.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { mintAppToken } from "../src/apps/token.ts";
14 import { createApp as insertApp } from "../src/core/apps.ts";
15 import { addCrew, createAgentRow } from "../src/core/agents.ts";
16 import { mintRunToken } from "../src/core/run_token.ts";
17 import { createUser } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { recordBeat } from "../src/keeper/beat.ts";
20
21 describe("GET /api/v1/keeper with the crew's run token", () => {
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25 let crew: string;
26 let elsewhere: string;
27 let preview: string;
28 const get = (token?: string) =>
29 fetch(`${servers.url}/api/v1/keeper`, token ? { headers: { authorization: `Bearer ${token}` } } : {});
30 const until = new Date(Date.now() + 3_600_000).toISOString();
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-keeper-crew-"));
34 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge" });
35 servers = await serve(app);
36 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
37 if (!a.ok) throw new Error(a.error);
38 const forge = await createRepo(app, a.value, { name: "forge", visibility: "private" });
39 const other = await createRepo(app, a.value, { name: "notes", visibility: "private" });
40 if (!forge.ok || !other.ok) throw new Error("repo");
41 const s = await createUser(app.db, { origin: "seed", username: "scout", email: "[email protected]", agent: true });
42 if (!s.ok) throw new Error("agent");
43 createAgentRow(app.db, { userId: s.value.id, brief: "build", createdBy: a.value.id });
44 for (const r of [forge.value, other.value]) addCrew(app.db, r.id, s.value.id, a.value.id);
45 const mint = (repoId: string) => mintRunToken(app.db, s.value.id, `run${Math.random()}`, { repoId, forkId: repoId }, until);
46 crew = mint(forge.value.id).token;
47 elsewhere = mint(other.value.id).token;
48 insertApp(app.db, { repoId: forge.value.id, slug: "alice-forge", access: "private" });
49 preview = mintAppToken(app.db, a.value.id, "alice-forge", "pull-1").token;
50 recordBeat(app.db, "skipped", "main is held: the check on main is red");
51 }, 30_000);
52
53 afterAll(async () => {
54 servers.stop();
55 app.close();
56 await rm(dataDir, { recursive: true, force: true });
57 });
58
59 test("the crew's token on the forge repository reads the newest beat", async () => {
60 const res = await get(crew);
61 expect(res.status).toBe(200);
62 const body: any = await res.json();
63 expect(body.heartbeat).toMatchObject({ outcome: "skipped", reason: "main is held: the check on main is red" });
64 expect(typeof body.heartbeat.at).toBe("string");
65 });
66
67 test("an anonymous read is refused with today's words", async () => {
68 const res = await get();
69 expect(res.status).toBe(403);
70 expect(((await res.json()) as any).message).toBe("the release history is for the forge's administrators and its repository's readers");
71 });
72
73 test("a run on another repository and an app preview's token are not let through", async () => {
74 for (const token of [elsewhere, preview]) expect((await get(token)).status).toBe(404);
75 });
76 });
test/v1-probe.test.ts +26 −1
@@ -4,7 +4,7 @@
44 */
55
66 import { afterAll, describe, expect, test } from "bun:test";
7 import { editionDate, formatLine, parseArgs, probe, type Line } from "../scripts/v1-probe.ts";
7 import { editionDate, formatLine, KEEPER_ITEM, parseArgs, probe, type Line } from "../scripts/v1-probe.ts";
88
99 const NOW = Date.parse("2026-11-21T12:00:00Z");
1010 const COMMIT = "c".repeat(40);
@@ -18,6 +18,8 @@ interface World {
1818 headers: boolean;
1919 /** What the token-free `releases` tool lists; null when it does not answer. */
2020 releases: { repo: string; version: string; commit: string }[] | null;
21 /** The keeper's heartbeat, served only to `Bearer t` (#15449). */
22 beat?: { at: string; outcome: string; reason: string; silent: boolean } | null;
2123 }
2224 const green = (): World => ({
2325 version: "1.0.0",
@@ -61,6 +63,9 @@ const server = Bun.serve({
6163 return json({ jsonrpc: "2.0", id: 1, result: { serverInfo: { name: "forge", version: world.version } } });
6264 case `/api/v1/repos/o/r/commits/${COMMIT}/check`:
6365 return world.checkState === null ? html("Just a moment...", 403) : json({ state: world.checkState, runId: "run1" });
66 case "/api/v1/keeper":
67 if (req.headers.get("authorization") !== "Bearer t") return json({ error: "forbidden" }, 403);
68 return json({ blocked: null, releases: [], holds: [], heartbeat: world.beat ?? null });
6469 case "/api/v1/repos/o/r/schedules":
6570 return world.runs === null ? json({ error: "not_found" }, 404) : json({ items: [], runs: world.runs });
6671 }
@@ -195,4 +200,24 @@ describe("v1 probe", () => {
195200 expect(parseArgs(["https://f.example", "--edition", "file:///etc/passwd"])).toHaveProperty("error");
196201 expect(parseArgs(["https://f.example", "--edition"])).toHaveProperty("error");
197202 });
203
204 test("with a token, one more line names the keeper's last beat; without, none and no keeper read", async () => {
205 const keeperLine = async (w: Partial<World>, token?: string) => {
206 world = { ...green(), ...w };
207 seen.length = 0;
208 const lines = await probe(base, "o/r", fetch, NOW, undefined, token);
209 return { line: lines.find((l) => l.item === KEEPER_ITEM), asked: seen.some((s) => s.path === "/api/v1/keeper") };
210 };
211 const beat = { at: "2026-11-22T10:00:00.000Z", outcome: "skipped", reason: "main is held\u001b[2J by #1", silent: false };
212 expect(await keeperLine({ beat })).toEqual({ line: undefined, asked: false });
213 const skipped = (await keeperLine({ beat }, "t")).line!;
214 expect(skipped.verdict).toBe("PASS");
215 expect(skipped.evidence).toBe("skipped at 2026-11-22T10:00:00.000Z: main is held [2J by #1");
216 const failed = (await keeperLine({ beat: { ...beat, outcome: "failed", reason: "tag push refused" } }, "t")).line!;
217 expect([failed.verdict, failed.evidence]).toEqual(["FAIL", "failed at 2026-11-22T10:00:00.000Z: tag push refused"]);
218 expect((await keeperLine({ beat: { ...beat, silent: true } }, "t")).line!.verdict).toBe("FAIL");
219 expect((await keeperLine({ beat: null }, "t")).line!.verdict).toBe("UNKNOWN");
220 const refused = (await keeperLine({ beat }, "wrong")).line!;
221 expect([refused.verdict, refused.evidence]).toEqual(["UNKNOWN", "403, this token may not read the release history"]);
222 });
198223 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs