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

An outsider's report is answered with a receipt id and a public status URL they can poll without an account #15697

Merged opened this

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

Merged

torque/forge:torque/15682-an-outsider-s-report-is-answered-with-a → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/15682-an-outsider-s-report-is-answered-with-a was merged into main as 64937d5.

Review

Sign in to review this change.
10 files changed +299 −4
docs/features/report-status.md added +31
@@ -0,0 +1,31 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: Reading back what became of a report you filed
4 ---
5 # A report's status
6
7 Whoever files a report from outside is handed a receipt with an `id` and a `statusUrl`. The status URL needs no
8 account and says what became of the report in four words:
9
10 | status | meaning |
11 | --- | --- |
12 | `open` | received; no person has read it yet |
13 | `being worked` | a person took it up and its issue is open |
14 | `fixed` | its issue was closed as done |
15 | `declined` | a person dismissed it, or its issue was closed as dropped |
16
17 An issue closed for any other reason (split, parked, or a reason added later) reads as `being worked`: it was taken
18 up and is neither fixed nor turned down.
19
20 Only `{id, status, message}` leaves: no title, no author, no issue number. An unknown id, a malformed one, another
21 repository's and a private repository's all answer the same 404.
22
23 - **JSON:** `GET /api/v1/repos/:owner/:name/reports/:id/status`, the `statusUrl` of the receipt (also its `Location`).
24 - **Plain text receipt:** the receipt prints a `status:` line with that URL.
25
26 Try it: file with `curl -s -XPOST -H 'content-type: application/json' -d '{"title":"x"}' $FORGE_URL/api/v1/repos/alice/game/reports`,
27 then `curl -s` the `statusUrl`.
28
29 Not limited yet: the status route has no rate limit of its own; that is tracked in #14500.
30
31 Pinned by `test/report-status.test.ts`.
src/contract/openapi/routes/getApiV1ReposOwnerNameReportsIdStatus.ts added +12
@@ -0,0 +1,12 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/reports/{id}/status`,
6 summary: "What became of a report from outside, without an account",
7 detail:
8 "What became of a report from outside, without an account: the id and statusUrl come from the 202 that filed it (also in its Location header); answers { id, status, message } where status is open, being worked, fixed or declined, and nothing else about the report, its filer or the repository. An unknown id, another repository's id and a private repository all answer the same 404",
9 auth: false,
10 role: "anonymous",
11 refuses: [404],
12 };
src/contract/openapi/routes/index.ts +1
@@ -202,6 +202,7 @@ export { route as getApiV1ReposOwnerNameQueue } from "./getApiV1ReposOwnerNameQu
202202 export { route as getApiV1ReposOwnerNameQueueGates } from "./getApiV1ReposOwnerNameQueueGates.ts";
203203 export { route as getApiV1ReposOwnerNameReleases } from "./getApiV1ReposOwnerNameReleases.ts";
204204 export { route as getApiV1ReposOwnerNameReports } from "./getApiV1ReposOwnerNameReports.ts";
205 export { route as getApiV1ReposOwnerNameReportsIdStatus } from "./getApiV1ReposOwnerNameReportsIdStatus.ts";
205206 export { route as getApiV1ReposOwnerNameRoadmap } from "./getApiV1ReposOwnerNameRoadmap.ts";
206207 export { route as getApiV1ReposOwnerNameRuns } from "./getApiV1ReposOwnerNameRuns.ts";
207208 export { route as getApiV1ReposOwnerNameRunsId } from "./getApiV1ReposOwnerNameRunsId.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameReports.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Report a problem in a public repository, without an account",
88 detail:
9 "Report a problem in a public repository, without an account; answers 202 { id, state, filedBy, message }. With a token the report carries that account (filedBy { how: \"signed\", name }); without one, agent is kept as a claim (how \"claimed\"); with neither, how is \"anonymous\" and name null",
9 "Report a problem in a public repository, without an account; answers 202 { id, state, filedBy, url, statusUrl, message, next } and a Location header: statusUrl is the public GET that says open, being worked, fixed or declined. With a token the report carries that account (filedBy { how: \"signed\", name }); without one, agent is kept as a claim (how \"claimed\"); with neither, how is \"anonymous\" and name null",
1010 auth: false,
1111 role: "anonymous",
1212 body: { title: "string", body: "string", page: "string", agent: "string" },
src/core/reports.ts +79
@@ -368,3 +368,82 @@ export function reportStanding(db: Database, repoId: string, reportId: string):
368368 .get(repoId, reportId) as ReportStanding | null;
369369 return row ?? undefined;
370370 }
371
372 /* ---- What became of a report, for the one who filed it ---- */
373
374 /**
375 * What became of a report from outside, in four plain words for the one who
376 * filed it: open, being worked, fixed, declined. Read from the report and
377 * the issue a person made from it, and nothing else leaves: no author, no
378 * title, no issue number, no repository but the one the URL names.
379 *
380 * waiting for a person -> open
381 * accepted, its issue open -> being worked
382 * accepted, its issue closed
383 * as done -> fixed
384 * as dropped -> declined
385 * dismissed -> declined
386 */
387 export type PublicStatus = "open" | "being worked" | "fixed" | "declined";
388
389 export const STATUS_WORDS: Readonly<Record<PublicStatus, string>> = {
390 open: "Received. A person who maintains this repository has not read it yet.",
391 "being worked": "A person read it and took it up. It is being worked on.",
392 fixed: "It was taken up and is fixed.",
393 declined: "A person read it and decided not to act on it.",
394 };
395
396 export interface ReportStatus {
397 readonly id: string;
398 readonly status: PublicStatus;
399 readonly message: string;
400 }
401
402 /** The shape a receipt id has: what `id()` makes. Anything else is not looked up. */
403 export const RECEIPT_ID = /^[0-9a-hjkmnp-tv-z]{26}$/;
404
405 /** One read: the report's state and, once adopted, its issue's state and close reason. */
406 interface Row {
407 readonly id: string;
408 readonly state: string;
409 readonly issue_number: number | null;
410 readonly issue_state: string | null;
411 readonly close_reason: string | null;
412 readonly parked: number | null;
413 }
414
415 export function reportStatus(db: Database, repoId: string, reportId: string): ReportStatus | undefined {
416 if (!RECEIPT_ID.test(reportId)) return undefined;
417 const row = db
418 .query(
419 `SELECT report.id, report.state, report.issue_number,
420 issue.state AS issue_state, issue.close_reason, issue.parked
421 FROM report LEFT JOIN issue ON issue.repo_id = report.repo_id AND issue.number = report.issue_number
422 WHERE report.repo_id = ?1 AND report.id = ?2`,
423 )
424 .get(repoId, reportId) as Row | null;
425 if (row === null) return undefined;
426 const status = statusOf(row);
427 return { id: row.id, status, message: STATUS_WORDS[status] };
428 }
429
430 /**
431 * An issue closed for any reason other than done or dropped (split, parked, or
432 * a reason added later) reads as "being worked": it was taken up and has not
433 * been fixed or turned down. A closed issue with no reason reads as fixed.
434 */
435 function statusOf(row: Row): PublicStatus {
436 if (row.state === "pending") return "open";
437 if (row.state === "dismissed") return "declined";
438 if (row.issue_state !== "closed") return "being worked";
439 if (row.parked === 1) return "being worked";
440 switch (row.close_reason) {
441 case null:
442 case "done":
443 return "fixed";
444 case "dropped":
445 return "declined";
446 default:
447 return "being worked";
448 }
449 }
src/http/api/reports.ts +19 −3
@@ -15,7 +15,8 @@ import {
1515 reportViews,
1616 waitingReports,
1717 } from "../../actions/reports.ts";
18 import { BODY_MAX, REQUEST_MAX, TITLE_MAX, byFiler } from "../../core/reports.ts";
18 import { canRead } from "../../core/repos.ts";
19 import { BODY_MAX, REQUEST_MAX, TITLE_MAX, byFiler, reportStatus } from "../../core/reports.ts";
1920 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
2021 import { keyedPage, keyedWindow, loadRepo, originAware, withLabels } from "../api.ts";
2122 import type { Handler } from "../context.ts";
@@ -81,9 +82,24 @@ export function reportRoutes(router: Router<Handler>): void {
8182 if (wantsText(ctx))
8283 return new Response(receiptText(receipt), {
8384 status: 202,
84 headers: { "content-type": "text/plain; charset=utf-8" },
85 headers: { "content-type": "text/plain; charset=utf-8", location: receipt.statusUrl },
8586 });
86 return json(receipt, 202);
87 const res = json(receipt, 202);
88 res.headers.set("location", receipt.statusUrl);
89 return res;
90 });
91
92 // What became of one report, for the one who filed it: no account, and
93 // only the state in words. An unknown id, another repository's id and a
94 // private repository all answer the same 404.
95 router.add("GET", "/api/v1/repos/:owner/:name/reports/:id/status", (ctx) => {
96 const repo = loadRepo(ctx);
97 if (!repo || !canRead(ctx.app.db, repo, undefined)) return notFound();
98 const found = reportStatus(ctx.app.db, repo.id, ctx.params.id ?? "");
99 if (found === undefined) return notFound();
100 const res = json(found);
101 res.headers.set("cache-control", "no-store");
102 return res;
87103 });
88104
89105 // Reading the words is a writer's act, so a read-only token — the one an
src/http/report_filer.ts +8
@@ -38,6 +38,8 @@ export interface Receipt {
3838 /** The issue's number, the same as `issue`: null until a writer adopts the report. */
3939 readonly number: number | null;
4040 readonly url: string;
41 /** Public, no account: GET answers open / being worked / fixed / declined. */
42 readonly statusUrl: string;
4143 readonly message: string;
4244 readonly next: string;
4345 }
@@ -52,6 +54,10 @@ export function publicOrigin(ctx: { app: { config: { url?: string | undefined }
5254 return configured !== undefined ? new URL(configured).origin : ctx.url.origin;
5355 }
5456
57 /** Where a filer polls what became of a report: the id in it is the receipt. */
58 export const statusUrlOf = (origin: string, repo: Repo, reportId: string): string =>
59 `${origin}/api/v1/repos/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/reports/${reportId}/status`;
60
5561 export function receiptOf(ctx: Ctx, repo: Repo, report: Report): Receipt {
5662 return {
5763 id: report.id,
@@ -60,6 +66,7 @@ export function receiptOf(ctx: Ctx, repo: Repo, report: Report): Receipt {
6066 issue: null,
6167 number: null,
6268 url: `${publicOrigin(ctx)}/${encodeURIComponent(repo.ownerName)}/${encodeURIComponent(repo.name)}/report?sent=${report.id}`,
69 statusUrl: statusUrlOf(publicOrigin(ctx), repo, report.id),
6370 message: REPORT_RECEIVED,
6471 next: REPORT_NEXT_STEP,
6572 };
@@ -71,6 +78,7 @@ export function receiptText(r: Receipt): string {
7178 `report: ${r.id}`,
7279 `issue: ${r.issue === null ? "none yet" : `#${r.issue}`}`,
7380 `url: ${r.url}`,
81 `status: ${r.statusUrl}`,
7482 `state: ${r.state}`,
7583 r.message,
7684 r.next,
test/pages-budget.test.ts +5
@@ -17,6 +17,7 @@
1717 * so no reading answers here while the pages are asked, and a page that waits
1818 * for one is over `AFTER_IDLE_MS` by construction, on any machine.
1919 */
20 import { fileReport } from "../src/actions/reports.ts";
2021 import { commitLog } from "../src/git/read.ts";
2122 import { repoDir } from "../src/git/repos.ts";
2223 import { afterAll, beforeAll, expect, setSystemTime, test } from "bun:test";
@@ -180,6 +181,10 @@ beforeAll(async () => {
180181 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'topic', '', 'h')", [pull.value.id]);
181182 // An offer's receipt, for `/api/v1/offers/:receipt`: random, so the fixture reads it back.
182183 FIXTURE["/api/v1/offers/:receipt"] = `/api/v1/offers/${issueReceipt(app.db, pull.value.id)}`;
184 // A report filed from outside, for its receipt's status route (#15682): its id is random.
185 const filed = fileReport(app, forge, { title: "It breaks", body: "", page: "", agent: "" }, "fixture");
186 if (!filed.ok) throw new Error(JSON.stringify(filed.error));
187 FIXTURE["/api/v1/repos/:owner/:name/reports/:id/status"] = `/api/v1/repos/alice/forge/reports/${filed.value.id}/status`;
183188 // A fork's offer upstream, for its receipt page (#14156): random, so the fixture reads it back.
184189 FIXTURE["/offers/:id"] = `/offers/${recordForkOffer(app.db, pull.value.id, bob.id)}`;
185190 // A conversation that builds, with a version on its branch, for the two build reads.
test/report-status.test.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * An outsider's receipt (#15682): filing answers an id and a status URL; the
3 * URL needs no account and says open / being worked / fixed / declined.
4 */
5 import { afterAll, beforeAll, describe, 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 { createRepo } from "../src/actions/repos.ts";
10 import { acceptReport, dismissReport } from "../src/actions/reports.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { openapi } from "../src/contract/openapi.ts";
13 import { setIssueState } from "../src/core/issues.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 describe("report status", () => {
20 quietLogs();
21 let dir: string;
22 let app: App;
23 let servers: Servers;
24 let alice: any;
25 let repo: any;
26 let n = 0;
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "forge-report-status-"));
30 app = createApp({ dataDir: dir, port: 0, trustedProxies: LOOPBACK_PROXIES });
31 servers = await serve(app);
32 const u = await createUser(app.db, {
33 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
34 password: "a-good-passphrase", adminIfFirst: true,
35 });
36 if (!u.ok) throw new Error(u.error);
37 alice = u.value;
38 const made = await createRepo(app, alice, { name: "game", visibility: "public" });
39 if (!made.ok) throw new Error(String(made.error));
40 repo = made.value;
41 const priv = await createRepo(app, alice, { name: "secret", visibility: "private" });
42 if (!priv.ok) throw new Error(String(priv.error));
43 });
44 afterAll(async () => {
45 servers.stop();
46 app.close();
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 const send = (payload: Record<string, string>, ip: string) =>
51 fetch(`${servers.url}/api/v1/repos/alice/game/reports`, {
52 method: "POST",
53 headers: { "content-type": "application/json", "x-forwarded-for": ip },
54 body: JSON.stringify(payload),
55 });
56 const file = async () => {
57 n += 1;
58 const res = await send({ title: `broken ${n}`, body: "it breaks" }, `10.0.0.${n}`);
59 return { res, body: (await res.json()) as any };
60 };
61 const status = async (url: string) => {
62 const res = await fetch(url);
63 return { res, body: (await res.json()) as any };
64 };
65
66 test("filing returns an id, a status URL and a Location header", async () => {
67 const { res, body } = await file();
68 expect(res.status).toBe(202);
69 expect(body.statusUrl).toContain(`/api/v1/repos/alice/game/reports/${body.id}/status`);
70 expect(res.headers.get("location")).toBe(body.statusUrl);
71 expect(body.id).toMatch(/^[0-9a-z]{26}$/);
72 });
73
74 test("open, then being worked, then fixed — in words, and nothing else", async () => {
75 const { body } = await file();
76 let s = await status(body.statusUrl);
77 expect(s.res.status).toBe(200);
78 expect(s.body.status).toBe("open");
79 expect(Object.keys(s.body).sort()).toEqual(["id", "message", "status"]);
80
81 const accepted = await acceptReport(app, alice, repo, body.id);
82 if (!accepted.ok) throw new Error(String(accepted.error));
83 s = await status(body.statusUrl);
84 expect(s.body.status).toBe("being worked");
85 const text = JSON.stringify(s.body);
86 expect(text).not.toContain("alice");
87 expect(text).not.toContain("broken");
88
89 setIssueState(app.db, accepted.value.id, "closed", "done");
90 s = await status(body.statusUrl);
91 expect(s.body.status).toBe("fixed");
92 });
93
94 test("a dismissed report and a dropped issue are declined", async () => {
95 const a = await file();
96 expect(dismissReport(app, alice, repo, a.body.id).ok).toBe(true);
97 expect((await status(a.body.statusUrl)).body.status).toBe("declined");
98
99 const b = await file();
100 const accepted = await acceptReport(app, alice, repo, b.body.id);
101 if (!accepted.ok) throw new Error(String(accepted.error));
102 setIssueState(app.db, accepted.value.id, "closed", "dropped");
103 expect((await status(b.body.statusUrl)).body.status).toBe("declined");
104 });
105
106 test("an issue closed as split or parked, or a closed one with no reason, reads as the close says", async () => {
107 for (const [reason, want] of [["split", "being worked"], ["parked", "being worked"]] as const) {
108 const a = await file();
109 if (a.res.status !== 202) throw new Error(JSON.stringify(a.body));
110 const accepted = await acceptReport(app, alice, repo, a.body.id);
111 if (!accepted.ok) throw new Error(String(accepted.error));
112 setIssueState(app.db, accepted.value.id, "closed", reason);
113 expect((await status(a.body.statusUrl)).body.status, reason).toBe(want);
114 }
115 });
116
117 test("an unknown, malformed or mismatched id, or a private repository, is the same 404", async () => {
118 const { body } = await file();
119 const base = `${servers.url}/api/v1/repos/alice`;
120 const urls = [
121 `${base}/game/reports/${"0".repeat(26)}/status`,
122 `${base}/game/reports/nope/status`,
123 `${base}/secret/reports/${body.id}/status`,
124 `${base}/missing/reports/${body.id}/status`,
125 ];
126 const seen: string[] = [];
127 for (const u of urls) {
128 const res = await fetch(u);
129 expect(res.status, u).toBe(404);
130 seen.push(await res.text());
131 }
132 expect(new Set(seen).size).toBe(1);
133 });
134
135 test("the route is in the contract", () => {
136 const doc = openapi("https://f.test", "1", "anonymous") as any;
137 const op = doc.paths["/api/v1/repos/{owner}/{name}/reports/{id}/status"]?.get;
138 expect(op).toBeDefined();
139 expect(op.security ?? []).toEqual([]);
140 });
141 });
test/security-floor-routes.test.ts +2
@@ -64,6 +64,7 @@ const GATE = "needs a kept gate log, written only when a full gate runs on land"
6464 const BET = "needs a bet, which the seed does not propose";
6565 const TALK = "needs a conversation of the signed-in person; the seed starts none";
6666 const HOOK = "needs a webhook, which the seed does not register";
67 const REPORT = "needs a report an outsider filed; the seed has none";
6768
6869 /** GET patterns the seed cannot fill → why. Requested with a placeholder all the same. */
6970 const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothing";
@@ -107,6 +108,7 @@ const UNSEEDED: Record<string, string> = {
107108 "/api/v1/repos/:owner/:name/builds/:label/shots/looks": SHOT,
108109 "/api/v1/repos/:owner/:name/gates/:id/log": GATE,
109110 "/api/v1/repos/:owner/:name/hooks/:id/deliveries": HOOK,
111 "/api/v1/repos/:owner/:name/reports/:id/status": REPORT,
110112 "/api/v1/repos/:owner/:name/waves/:version": WAVE,
111113 "/api/v1/secrets/:scope": SECRET,
112114 "/api/v1/user/origins/:id/browse/:owner/:name": ORIGIN,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs