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

One acceptance test opens a board JSON, an STL, a PDF, a CSV and an mp4 on the blob page and each renders with its view switch #16825

Merged opened this

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

Merged

scout/forge:scout/16744-one-acceptance-test-opens-a-board-json-a → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16744-one-acceptance-test-opens-a-board-json-a was merged into main as 860d8a7.

Review

Sign in to review this change.
1 file changed +199 −0
test/files-render-acceptance.test.ts added +199
@@ -0,0 +1,199 @@
1 /**
2 * The acceptance pass of #7329, as a test anyone can rerun: a board JSON, an STL, a PDF, a CSV
3 * and an mp4 committed to a repository, each opened on its blob page. Each draws with its own
4 * renderer (never "Binary file"), keeps the Rendered | Source | Raw | Download switch, and has
5 * its bytes served by the media route under its sandbox policy and `nosniff`. Then the board is
6 * changed through the file form, as a writer would, and /boards shows the change.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { writeBoard } from "../src/actions/boards.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { boardSchema } from "../src/boards/schema.ts";
17 import { STARTING_BOARDS } from "../src/boards/starting.ts";
18 import { BOARDS_OWNER, BOARDS_REPO, parseBoard, readBoard } from "../src/boards/store.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { setCrawlClock } from "../src/http/crawl.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { MEDIA_POLICY, PDF_POLICY } from "../src/web/pages/media.ts";
23 import { seedAdmin } from "./helpers/admin.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
29
30 /** One triangle, as ASCII STL. */
31 const STL = "solid tri\nfacet normal 0 0 1\n outer loop\n vertex 0 0 0\n vertex 10 0 0\n vertex 0 10 0\n endloop\nendfacet\nendsolid tri\n";
32 /** One empty page, a cross-reference table and all: the smallest PDF a viewer opens. */
33 const PDF = "%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]>>endobj\ntrailer<</Root 1 0 R/Size 4>>\n%%EOF\n";
34 const CSV = "name,runs\nalpha,3\nbeta,5\n";
35 /** An `ftyp` box and nothing else: 32 bytes the container sniff takes for MPEG-4. */
36 const MP4 = (() => {
37 const b = new Uint8Array(32);
38 b.set(enc("\0\0\0\x20ftypisom"));
39 return b;
40 })();
41
42 const BOARD = STARTING_BOARDS.throughput!;
43 const SLUG = "acceptance";
44
45 type Kind = { path: string; type: string; has: string[]; policy: string };
46 const KINDS: Kind[] = [
47 { path: "boards/throughput.json", type: "application/octet-stream", has: ['class="card config-form"', "Edit as form"], policy: MEDIA_POLICY },
48 { path: "part.stl", type: "model/stl", has: ['class="model3d"', 'class="model3d-stage"'], policy: MEDIA_POLICY },
49 { path: "doc.pdf", type: "application/pdf", has: ['class="pdf-frame"'], policy: PDF_POLICY },
50 { path: "table.csv", type: "application/octet-stream", has: ['class="csv-scroll"', "<table"], policy: MEDIA_POLICY },
51 { path: "clip.mp4", type: "video/mp4", has: ['<video class="media-player"'], policy: MEDIA_POLICY },
52 ];
53
54 let dataDir = "";
55 let app: App;
56 let servers: Servers;
57 let base = "";
58 let cookie = "";
59
60 const get = (path: string): Promise<Response> => fetch(`${base}${path}`, { headers: { cookie } });
61
62 beforeAll(async () => {
63 dataDir = await mkdtemp(join(tmpdir(), "forge-files-acceptance-"));
64 app = createApp({ dataDir, port: 0 });
65 servers = await serve(app);
66 base = servers.url;
67 // The gate's load: the anonymous budget at its smallest, as in render-media.test.ts.
68 setCrawlClock(app, Date.now, true);
69 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-acceptance-passphrase" });
70 if (!a.ok) throw new Error("signup failed");
71 cookie = `forge_session=${createSession(app.db, a.value.id).token}`;
72 const repo = await createRepo(app, a.value, { name: "files", visibility: "public" });
73 if (!repo.ok) throw new Error("repo failed");
74 const made = await commitToBranch(app, a.value, repo.value, {
75 message: "one of each",
76 files: [
77 { path: "boards/throughput.json", content: `${JSON.stringify(BOARD, null, 2)}\n` },
78 { path: ".forge/schemas.json", content: '{"boards/*.json":"board.schema.json"}\n' },
79 { path: "board.schema.json", content: JSON.stringify(boardSchema()) },
80 { path: "part.stl", content: STL },
81 { path: "doc.pdf", content: PDF },
82 { path: "table.csv", content: CSV },
83 { path: "clip.mp4", content: MP4 },
84 ],
85 });
86 if (!made.ok) throw new Error("commit failed");
87 // The board the round trip changes lives where the forge reads boards from.
88 const board = await writeBoard(app, a.value, SLUG, BOARD);
89 if (!board.ok) throw new Error(`board failed: ${board.error}`);
90 }, 60_000);
91
92 afterAll(async () => {
93 await servers?.stop();
94 app?.close();
95 await rm(dataDir, { recursive: true, force: true });
96 });
97
98 describe("each kind opens drawn, with its switch, and its bytes come sandboxed", () => {
99 for (const k of KINDS) {
100 test(k.path, async () => {
101 const res = await get(`/alice/files/blob/main/${k.path}`);
102 const text = await res.text();
103 expect(res.status).toBe(200);
104 expect(text).not.toContain("Binary file");
105 for (const marker of k.has) expect(text).toContain(marker);
106 // The switch: Rendered | Source, then Raw and Download.
107 expect(text).toContain(`href="/alice/files/blob/main/${k.path}?view=source"`);
108 expect(text).toContain(">Rendered<");
109 expect(text).toContain(">Source<");
110 expect(text).toContain(`href="/alice/files/raw/main/${k.path}"`);
111 expect(text).toContain(`href="/alice/files/media/main/${k.path}?download=1"`);
112 expect(text).toContain(">Raw<");
113
114 const media = await get(`/alice/files/media/main/${k.path}`);
115 expect(media.status).toBe(200);
116 expect(media.headers.get("content-security-policy")).toBe(k.policy);
117 expect(media.headers.get("x-content-type-options")).toBe("nosniff");
118 expect(media.headers.get("content-type")).toBe(k.type);
119 });
120 }
121
122 test("only the PDF leaves without `sandbox`: Chrome's viewer will not run in one", () => {
123 expect(MEDIA_POLICY.startsWith("sandbox;")).toBe(true);
124 expect(PDF_POLICY).not.toContain("sandbox");
125 expect(PDF_POLICY).toContain("default-src 'none'");
126 });
127
128 test("the board is a form with the fields of the schema the repository maps it to", async () => {
129 const text = await (await get("/alice/files/blob/main/boards/throughput.json")).text();
130 expect(text).toContain('name="v/panels/0/title"');
131 expect(text).toContain("board.schema.json");
132 });
133
134 test("the source view still shows the file's text", async () => {

The round trip posts to forge/boards, not to the board JSON committed in the test repo above. Say in this comment that this is deliberate, because /boards/<slug> reads only from forge/boards. Otherwise a reader takes the two boards for one.

135 const res = await get("/alice/files/blob/main/table.csv?view=source");
136 expect(res.status).toBe(200);
137 expect(await res.text()).toContain("alpha,3");
138 });
139 });
140
141 // Deliberate: this round trip edits forge/boards, not the boards/throughput.json
142 // committed in the alice repository above. /boards/<slug> reads only from
143 // forge/boards, so that is the file whose edit /boards can show. The two boards
144 // are different files that share a shape.
145 describe("the board round trip through the file form", () => {
146 const path = `${SLUG}.json`;
147 const field = (html: string, name: string): string => {
148 const m = html.match(new RegExp(`name="${name}" value="([^"]*)"`));
149 if (!m) throw new Error(`no ${name} in the form`);
150 return m[1]!.replace(/&quot;/g, '"').replace(/&#39;|&#x27;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
151 };
152 /** One post of the form, carrying what the last page held, as the browser would. */
153 const post = (html: string, extra: Record<string, string>): Promise<Response> =>
154 fetch(`${base}/${BOARDS_OWNER}/${BOARDS_REPO}/config`, {
155 method: "POST",
156 redirect: "manual",
157 headers: { cookie, origin: base, "content-type": "application/x-www-form-urlencoded" },
158 body: new URLSearchParams({
159 ref: field(html, "ref"), path: field(html, "path"), base: field(html, "base"), doc: field(html, "doc"), from: "form", ...extra,
160 }),
161 });
162
163 test("add a panel, change bar to heat, reorder two; the file parses and /boards shows it", async () => {
164 let html = await (await get(`/${BOARDS_OWNER}/${BOARDS_REPO}/config/main/${path}`)).text();
165 expect(html).toContain('name="j/panels/1/chart"');
166 html = await (await post(html, { op: JSON.stringify(["down", "/panels/0"]) })).text();
167 html = await (await post(html, { op: JSON.stringify(["add", "/panels"]) })).text();
168 const last = (JSON.parse(field(html, "doc")) as { panels: unknown[] }).panels.length - 1;
169 const review = await post(html, {
170 step: "review",
171 "j/panels/0/chart": JSON.stringify("heat"),
172 [`v/panels/${last}/title`]: "Acceptance panel",
173 [`v/panels/${last}/query/source`]: "runs",
174 [`j/panels/${last}/chart`]: JSON.stringify("line"),
175 });
176 const reviewHtml = await review.text();
177 expect(review.status).toBe(200);
178 expect(reviewHtml).toContain("Commit to main");
179 const saved = await post(reviewHtml, { step: "save", message: "Acceptance round trip" });
180 expect(saved.status).toBe(303);
181
182 const read = await readBoard(app.reposRoot, SLUG);
183 expect(read).toBeDefined();
184 expect(parseBoard(read).ok).toBe(true);
185 expect(read!.panels).toHaveLength(BOARD.panels.length + 1);
186 // The two that swapped, in their new order, and the first one's chart now a heat strip.
187 expect(read!.panels[0]!.title).toBe(BOARD.panels[1]!.title);
188 expect(read!.panels[1]!.title).toBe(BOARD.panels[0]!.title);
189 expect(read!.panels[0]!.chart).toBe("heat");
190 expect(BOARD.panels[1]!.chart).toBe("bar");
191 expect(read!.panels.at(-1)!.title).toBe("Acceptance panel");
192
193 const page = await get(`/boards/${SLUG}`);
194 expect(page.status).toBe(200);
195 const shown = await page.text();
196 expect(shown).toContain("Acceptance panel");
197 expect(shown.indexOf(BOARD.panels[1]!.title)).toBeLessThan(shown.indexOf(BOARD.panels[0]!.title));
198 });
199 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs