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

`GET /og/:kind/:ref.svg` serves a live card for an app, repo, issue, pull or run, cached by input hash #1555

Closed opened this
Closed without merging

scout/forge:scout/1471-get-og-kind-ref-svg-serves-a-live-card-f → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +338 −0
scripts/gate.ts +1
@@ -38,6 +38,7 @@ export const GATE: readonly string[] = [
3838 "test/tui-limbs.test.ts",
3939 "test/claim-link.test.ts",
4040 "test/og-card.test.ts",
41 "test/og-route.test.ts",
4142 "test/health.test.ts",
4243 "test/client-address.test.ts",
4344 "test/client-list.test.ts",
src/core/reserved.ts +1
@@ -80,6 +80,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8080 "mode",
8181 "new",
8282 "oauth",
83 "og",
8384 "organizations",
8485 "origins",
8586 "robots.txt",
src/http/server.ts +3
@@ -238,6 +238,7 @@ import {
238238 runsList,
239239 } from "../web/pages/runs.ts";
240240 import { lookImage } from "../web/pages/looks.ts";
241 import { ogCard } from "../web/pages/og.ts";
241242 import { bigRedirect, boardPage } from "../web/pages/board.ts";
242243 import { returnsPage } from "../web/pages/returns.ts";
243244 import {
@@ -981,6 +982,8 @@ export function buildRouter(): Router<Handler> {
981982 router.add("GET", "/:owner/:name/runs/:id", runPage);
982983 router.add("POST", "/:owner/:name/runs/:id/cancel", runCancel);
983984 router.add("POST", "/:owner/:name/runs/:id/steer", runSteer);
985 // The live social card of an app, repo, issue, pull or run.
986 router.add("GET", "/og/:kind/:ref.svg", ogCard);
984987 // The pictures of an environment, read like the repository.
985988 router.add("GET", "/:owner/:name/looks/:env/:commit/:kind.png", lookImage);
986989
src/web/pages/og.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * The live social card: `GET /og/:kind/:ref.svg` for an app, repo, issue,
3 * pull or run. It reads only what the viewer may read — the same gates the
4 * pages use — and answers the one 404 for a private thing, an unknown kind
5 * or a malformed ref, so the card never says what exists.
6 *
7 * The ref names the thing with `~` between its parts (a character no owner,
8 * repository name or number holds): `owner~name` for a repo or app,
9 * `owner~name~7` for an issue or pull, `owner~name~<run id>` for a run.
10 *
11 * A card is a pure function of its inputs (`web/og/card.ts`), so it is kept
12 * in memory under the sha256 of those inputs; that hash is the ETag, and a
13 * repeat with `If-None-Match` is a 304. The inputs are read afresh on every
14 * request (that is the access check), only the drawing is kept.
15 */
16
17 import { getRepoRun } from "../../actions/runs.ts";
18 import { getAppByRepo } from "../../core/apps.ts";
19 import { getIssue } from "../../core/issues.ts";
20 import { getPull } from "../../core/pulls.ts";
21 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
22 import { mayViewId } from "../../core/sealed.ts";
23 import type { Ctx } from "../../http/context.ts";
24 import { notFound } from "../../http/respond.ts";
25 import { renderCard, type CardInput } from "../og/card.ts";
26
27 const KINDS = ["app", "repo", "issue", "pull", "run"] as const;
28 type OgKind = (typeof KINDS)[number];
29
30 const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
31 const NUMBER = /^[1-9][0-9]{0,8}$/;
32 const RUN_ID = /^[0-9a-z]{26}$/;
33
34 const MAX_CARDS = 500;
35 const cards = new Map<string, string>();
36 let drawn = 0;
37
38 /** How many cards have been drawn rather than served from memory. */
39 export const ogCardsDrawn = (): number => drawn;
40
41 interface Ref {
42 owner: string;
43 name: string;
44 tail: string | undefined;
45 }
46
47 /** Split a ref into its parts, or undefined when it is not shaped for `kind`. */
48 function parseRef(kind: OgKind, ref: string): Ref | undefined {
49 const parts = ref.split("~");
50 const wanted = kind === "app" || kind === "repo" ? 2 : 3;
51 if (parts.length !== wanted) return undefined;
52 const [owner = "", name = "", tail] = parts;
53 if (!NAME.test(owner) || !NAME.test(name)) return undefined;
54 if (kind === "issue" || kind === "pull")
55 if (tail === undefined || !NUMBER.test(tail)) return undefined;
56 if (kind === "run" && (tail === undefined || !RUN_ID.test(tail)))
57 return undefined;
58 return { owner, name, tail };
59 }
60
61 const plural = (n: number, word: string): string =>
62 `${n} ${word}${n === 1 ? "" : "s"}`;
63
64 /** What the card says, read through the viewer's own access; undefined is a 404. */
65 function inputsFor(ctx: Ctx, kind: OgKind, ref: Ref): CardInput | undefined {
66 const { db } = ctx.app;
67 const user = ctx.auth.user;
68 const repo = getRepo(db, ref.owner, ref.name);
69 if (!repo || !canReadRepo(ctx, repo)) return undefined;
70 const slug = `${repo.ownerName}/${repo.name}`;
71
72 if (kind === "repo")
73 return {
74 kind: "repo",
75 title: slug,
76 lines: repo.description === "" ? [] : [repo.description],
77 stat: repo.visibility,
78 };
79 if (kind === "app") {
80 const record = getAppByRepo(db, repo.id);
81 if (!record) return undefined;
82 return {
83 kind: "app",
84 title: record.slug,
85 lines: [slug],
86 stat: record.access,
87 };
88 }
89 if (kind === "run") {
90 const found = getRepoRun(ctx.app, user, repo, ref.tail ?? "");
91 if (!found.ok) return undefined;
92 const run = found.value;
93 return {
94 kind: "page",
95 title: `${run.kind} run`,
96 lines: [slug, run.summary],
97 stat: run.state,
98 };
99 }
100 const number = Number(ref.tail);
101 const thread =
102 kind === "pull" ? getPull(db, repo.id, number) : getIssue(db, repo.id, number);
103 if (!thread || thread.kind !== kind) return undefined;
104 if (!mayViewId(db, repo, thread.id, user)) return undefined;
105 const merged = kind === "pull" && "mergedAt" in thread && thread.mergedAt !== null;
106 return {
107 kind,
108 title: thread.title,
109 lines: [`${slug}#${thread.number}`, `by ${thread.authorName}`],
110 stat: merged ? "merged" : thread.state,
111 };
112 }
113
114 const canReadRepo = (ctx: Ctx, repo: Repo): boolean =>
115 canRead(ctx.app.db, repo, ctx.auth.user);
116
117 const sha256 = (s: string): string =>
118 new Bun.CryptoHasher("sha256").update(s).digest("hex");
119
120 // GET /og/:kind/:ref.svg
121 export function ogCard(ctx: Ctx): Response {
122 const kind = KINDS.find((k) => k === ctx.params.kind);
123 if (!kind) return notFound();
124 const ref = parseRef(kind, ctx.params.ref ?? "");
125 if (!ref) return notFound();
126 const input = inputsFor(ctx, kind, ref);
127 if (!input) return notFound();
128
129 const hash = sha256(JSON.stringify(input));
130 const etag = `"${hash}"`;
131 // A private repository's card is the reader's alone; a shared cache must
132 // not hand it to someone else, and the answer varies with who asks.
133 const repo = getRepo(ctx.app.db, ref.owner, ref.name);
134 const headers: Record<string, string> = {
135 etag,
136 "cache-control":
137 repo?.visibility === "public"
138 ? "public, max-age=300"
139 : "private, max-age=300",
140 vary: "cookie, authorization",
141 };
142 const match = ctx.request.headers.get("if-none-match");
143 if (match !== null && match.split(",").some((t) => t.trim().replace(/^W\//, "") === etag))
144 return new Response(null, { status: 304, headers });
145
146 let svg = cards.get(hash);
147 if (svg === undefined) {
148 svg = renderCard(input);
149 drawn++;
150 if (cards.size >= MAX_CARDS)
151 cards.delete(cards.keys().next().value as string);
152 cards.set(hash, svg);
153 }
154 return new Response(svg, {
155 headers: { ...headers, "content-type": "image/svg+xml; charset=utf-8" },
156 });
157 }
test/og-route.test.ts added +176
@@ -0,0 +1,176 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { openIssue } from "../src/actions/issues.ts";
7 import { openPull } from "../src/actions/pulls.ts";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import { createApp as createAppRecord } from "../src/core/apps.ts";
10 import { createRun } from "../src/core/runs.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { ogCardsDrawn } from "../src/web/pages/og.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22 let aliceToken = "";
23 let runId = "";
24
25 const ok = <T>(
26 r: { ok: true; value: T } | { ok: false; error: unknown },
27 ): T => {
28 if (!r.ok) throw new Error(JSON.stringify(r.error));
29 return r.value;
30 };
31
32 const og = (path: string, headers: Record<string, string> = {}) =>
33 fetch(`${servers.url}/og/${path}`, { headers });
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-og-route-"));
37 app = createApp({ dataDir, port: 0 });
38 servers = await serve(app);
39 const alice = ok(
40 await createUser(app.db, {
41 trusted: true,
42 username: "alice",
43 email: "[email protected]",
44 password: "a-good-passphrase",
45 adminIfFirst: true,
46 }),
47 );
48 aliceToken = createToken(app.db, alice.id, "read", "ro").token;
49 const pub = ok(
50 await createRepo(app, alice, {
51 name: "square",
52 visibility: "public",
53 description: "A <square> & more",
54 }),
55 );
56 for (const [repo, branch] of [[pub, "main"]] as const)
57 ok(
58 await commitToBranch(app, alice, repo, {
59 message: "Start",
60 files: [{ path: "README.md", content: "# square\n" }],
61 branch,
62 }),
63 );
64 ok(
65 await commitToBranch(app, alice, pub, {
66 branch: "feature",
67 base: "main",
68 message: "More",
69 files: [{ path: "README.md", content: "# square\nmore\n" }],
70 }),
71 );
72 ok(openIssue(app, alice, pub, { title: "Smoother <edges>" }));
73 ok(
74 await openPull(app, alice, pub, {
75 title: "Rounder",
76 body: "",
77 baseBranch: "main",
78 headBranch: "feature",
79 }),
80 );
81 ok(createAppRecord(app.db, { repoId: pub.id, slug: "square", access: "public" }));
82 runId = createRun(app.db, { repoId: pub.id, kind: "deploy", env: "production" }).id;
83
84 const priv = ok(
85 await createRepo(app, alice, { name: "vault", visibility: "private" }),
86 );
87 ok(openIssue(app, alice, priv, { title: "Secret plan" }));
88 }, 30_000);
89
90 afterAll(async () => {
91 servers?.stop();
92 app?.close();
93 await rm(dataDir, { recursive: true, force: true });
94 });
95
96 describe("GET /og/:kind/:ref.svg", () => {
97 const refs: Record<string, string> = {
98 repo: "alice~square",
99 app: "alice~square",
100 issue: "alice~square~1",
101 pull: "alice~square~2",
102 };
103
104 for (const kind of ["repo", "app", "issue", "pull", "run"]) {
105 test(`${kind} answers 200 with an SVG and the security headers`, async () => {
106 const ref = kind === "run" ? `alice~square~${runId}` : refs[kind]!;
107 const res = await og(`${kind}/${ref}.svg`);
108 expect(res.status).toBe(200);
109 expect(res.headers.get("content-type")).toStartWith("image/svg+xml");
110 expect(res.headers.get("cache-control")).toBe("public, max-age=300");
111 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
112 expect(res.headers.get("referrer-policy")).toBeTruthy();
113 expect(res.headers.get("content-security-policy")).toBeTruthy();
114 const body = await res.text();
115 expect(body.startsWith("<svg ")).toBe(true);
116 expect(body).not.toContain("<edges>");
117 });
118 }
119
120 test("a private thing is a 404 to the public and a card to its reader", async () => {
121 expect((await og("repo/alice~vault.svg")).status).toBe(404);
122 expect((await og("issue/alice~vault~1.svg")).status).toBe(404);
123 const res = await og("issue/alice~vault~1.svg", {
124 authorization: `Bearer ${aliceToken}`,
125 });
126 expect(res.status).toBe(200);
127 expect(res.headers.get("cache-control")).toStartWith("private");
128 });
129
130 test("unknown kind, bad ref and missing things are 404", async () => {
131 for (const path of [
132 "nope/alice~square.svg",
133 "repo/alice.svg",
134 "repo/alice~square~1.svg",
135 "repo/..~square.svg",
136 "repo/alice~ghost.svg",
137 "issue/alice~square~x.svg",
138 "issue/alice~square~0.svg",
139 "issue/alice~square~99.svg",
140 "issue/alice~square~2.svg", // a pull, not an issue
141 "pull/alice~square~1.svg", // an issue, not a pull
142 "run/alice~square~nope.svg",
143 "app/alice~vault.svg",
144 ])
145 expect([path, (await og(path)).status]).toEqual([path, 404]);
146 });
147
148 test("ETag is the input hash and a repeat is a 304", async () => {
149 const first = await og("repo/alice~square.svg");
150 const etag = first.headers.get("etag")!;
151 expect(etag).toMatch(/^"[0-9a-f]{64}"$/);
152 const again = await og("repo/alice~square.svg", { "if-none-match": etag });
153 expect(again.status).toBe(304);
154 expect(again.headers.get("etag")).toBe(etag);
155 expect(await again.text()).toBe("");
156 expect((await og("repo/alice~square.svg", { "if-none-match": '"x"' })).status).toBe(200);
157 });
158
159 test("a warm request is drawn once and answered from memory", async () => {
160 const before = ogCardsDrawn();
161 await (await og("pull/alice~square~2.svg")).text();
162 const drawn = ogCardsDrawn();
163 // The cold request may draw; the warm ones, never.
164 const best: number[] = [];
165 for (let i = 0; i < 20; i++) {
166 const t = performance.now();
167 await (await og("pull/alice~square~2.svg")).text();
168 best.push(performance.now() - t);
169 }
170 expect(ogCardsDrawn()).toBe(drawn);
171 expect(drawn - before).toBeLessThanOrEqual(1);
172 // The floor for a wall-clock bound here is 200 ms (test/flake.test.ts);
173 // the measured best is a few ms.
174 expect(Math.min(...best)).toBeLessThan(200);
175 });
176 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs