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

An agent's bearer token is refused on a mutation from a browser origin that is not the forge's, with a test per method #15864

Merged opened this

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

Merged

scout/forge:scout/15852-an-agent-s-bearer-token-is-refused-on-a → main 0 commits fork

  • Merged. scout/15852-an-agent-s-bearer-token-is-refused-on-a was merged into main as 8910327.

Review

Sign in to review this change.
1 file changed +104 −0
test/origin-mutations.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * One representative route per mutating method (#15852): POST, PATCH, PUT and
3 * DELETE, each sent from a browser origin that is not the forge's. With a
4 * session cookie the gate (`src/http/origin_gate.ts`) refuses it with 403 and
5 * nothing changes; with an agent's bearer token and no cookie the same request
6 * is accepted and does its work, because no browser attaches a token by
7 * itself.
8 *
9 * `test/origin-every-mutation.test.ts` walks every route for the refusal; this
10 * file proves the acceptance half end to end, method by method, by reading the
11 * state each request was meant to change.
12 */
13 import { afterAll, beforeAll, expect, test } from "bun:test";
14 import { mkdtemp, rm } from "node:fs/promises";
15 import { tmpdir } from "node:os";
16 import { join } from "node:path";
17 import { createApp, type App } from "../src/app.ts";
18 import { createRepo } from "../src/actions/repos.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createToken } from "../src/core/tokens.ts";
21 import { forgeHttp } from "../src/http/server.ts";
22 import { seedAdmin } from "./helpers/admin.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const FOREIGN = "https://evil.example";
28 let dataDir = "", app: App, cookie = "", bearer = "", userId = "", repoId = "";
29 let http: ReturnType<typeof forgeHttp>;
30 const cells = process.env["FORGE_CELLS"];
31
32 beforeAll(async () => {
33 process.env["FORGE_CELLS"] = "off";
34 dataDir = await mkdtemp(join(tmpdir(), "forge-origin-methods-"));
35 app = createApp({ dataDir, port: 0 });
36 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
37 if (!admin.ok) throw new Error(admin.error);
38 userId = admin.value.id;
39 const repo = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" });
40 if (!repo.ok) throw new Error(String(repo.error));
41 repoId = repo.value.id;
42 cookie = `forge_session=${createSession(app.db, userId).token}`;
43 bearer = `Bearer ${createToken(app.db, userId, "agent", "admin").token}`;
44 http = forgeHttp(app);
45 });
46
47 afterAll(async () => {
48 app.close();
49 await rm(dataDir, { recursive: true, force: true });
50 if (cells === undefined) delete process.env["FORGE_CELLS"];
51 else process.env["FORGE_CELLS"] = cells;
52 });
53
54 async function send(method: string, path: string, auth: Record<string, string>, body?: unknown): Promise<number> {
55 const headers: Record<string, string> = { origin: FOREIGN, "content-type": "application/json", ...auth };
56 const res = await http.handle(
57 new Request(`http://forge.test${path}`, {
58 method,
59 headers,
60 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
61 }),
62 );
63 await res.body?.cancel();
64 return res.status;
65 }
66
67 const issues = (): number =>
68 (app.db.query("select count(*) as n from issue where repo_id = ?").get(repoId) as { n: number }).n;
69 const description = (): string =>
70 (app.db.query("select description from repo where id = ?").get(repoId) as { description: string }).description;
71 const pinned = async (): Promise<boolean> => {
72 const res = await http.handle(new Request("http://forge.test/api/v1/user/pins", { headers: { authorization: bearer } }));
73 const page = (await res.json()) as { items: { name: string }[] };
74 return page.items.some((p) => p.name === "notes");
75 };
76
77 /**
78 * Each case: the route, its body, what to read before and after, and the
79 * status the bearer is answered with. Run in order: DELETE takes off the pin
80 * PUT made.
81 */
82 const CASES: {
83 method: string;
84 path: string;
85 body?: unknown;
86 read: () => unknown;
87 accepted: number;
88 }[] = [
89 { method: "POST", path: "/api/v1/repos/alice/notes/issues", body: { title: "from an agent", body: "" }, read: issues, accepted: 201 },
90 { method: "PATCH", path: "/api/v1/repos/alice/notes", body: { description: "set by an agent" }, read: description, accepted: 200 },
91 { method: "PUT", path: "/api/v1/user/pins/alice/notes", read: pinned, accepted: 200 },
92 { method: "DELETE", path: "/api/v1/user/pins/alice/notes", read: pinned, accepted: 204 },
93 ];
94
95 test.each(CASES.map((c) => [c.method, c] as const))(
96 "%s from a foreign origin: a session cookie is refused with 403, an agent's bearer token is accepted",
97 async (_, c) => {
98 const before = await c.read();
99 expect(await send(c.method, c.path, { cookie }, c.body)).toBe(403);
100 expect(await c.read()).toEqual(before);
101 expect(await send(c.method, c.path, { authorization: bearer }, c.body)).toBe(c.accepted);
102 expect(await c.read()).not.toEqual(before);
103 },
104 );

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs