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

Tab forge: a real-browser walk makes an app and edits a file without 'Failed to fetch' #18307

opened this

Merged 5h 16m ago, live in production

scout/forge:scout/18295-tab-forge-a-real-browser-walk-makes-an-a → main 0 commits fork

  • Merged. scout/18295-tab-forge-a-real-browser-walk-makes-an-a was merged into main as c343cd7.

Review

Sign in to review this change.
2 files changed +242 −0
test/helpers/chrome.ts +77
@@ -12,6 +12,7 @@ import { mkdtempSync, rmSync } from "node:fs";
1212 import { tmpdir } from "node:os";
1313 import { join } from "node:path";
1414 import { browserCommand, browserRefusal } from "../../src/looks/chromium.ts";
15 import { pollUntil } from "./poll.ts";
1516
1617 /** Start a browser on `profile` with its DevTools port open, as every helper here does. */
1718 function start(binary: string, profile: string, flags: readonly string[] = []) {
@@ -711,3 +712,79 @@ export async function framesLoaded(
711712 rmSync(profile, { recursive: true, force: true });
712713 }
713714 }
715
716 /**
717 * What `walkWithWorker` brings back: the walk's own answer, and what the worker and the page saw.
718 */
719 export interface WorkerWalk {
720 /** What `walk` returned (a JSON string). */
721 value: string;
722 /** What `read` returned in the service worker after the walk (a JSON string). */
723 worker: string;
724 /** Every POST the page sent, with the headers the browser put on it. */
725 posts: { url: string; headers: Record<string, string> }[];
726 }
727
728 /**
729 * Load `url` in a real headless Chromium, run `start` in the page (it must leave a service worker
730 * registered), then `walk` in the page, then `read` in that service worker. Each expression may return a promise; `walk` and `read` yield JSON strings. For a test
731 * that has to see what a real service worker was handed by a real form post, which a Request built
732 * by hand cannot show.
733 */
734 export async function walkWithWorker(
735 binary: string,
736 url: string,
737 steps: { start: string; walk: string; read: string },
738 ): Promise<WorkerWalk> {
739 const profile = mkdtempSync(join(tmpdir(), "forge-worker-"));
740 const proc = start(binary, profile);
741 const sockets: WebSocket[] = [];
742 const open = async (at: string): Promise<Cdp> => {
743 const ws = new WebSocket(at);
744 sockets.push(ws);
745 await within(5_000, "opening a devtools socket", new Promise<void>((resolve, reject) => {
746 ws.addEventListener("open", () => resolve());
747 ws.addEventListener("error", () => reject(new Error("chromium's devtools socket refused the connection")));
748 }));
749 return new Cdp(ws);
750 };
751 const run = async (cdp: Cdp, expression: string, what: string): Promise<unknown> => {
752 const { result, exceptionDetails } = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
753 if (exceptionDetails !== undefined) throw new Error(`${what}: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`);
754 return result.value;
755 };
756 try {
757 const browserWsUrl = await within(10_000, "printing its devtools address", readDebuggerUrl(proc.stderr));
758 const page = await open((await findPageTarget(browserWsUrl)).webSocketDebuggerUrl);
759 await page.send("Page.enable");
760 await page.send("Network.enable");
761 const posts: WorkerWalk["posts"] = [];
762 // One entry a request: DevTools may report one again (a redirect, a worker's answer).
763 const ids = new Set<string>();
764 page.on("Network.requestWillBeSent", (p: { requestId: string; request: { url: string; method: string; headers: Record<string, string> } }) => {
765 if (p.request.method !== "POST" || ids.has(p.requestId)) return;
766 ids.add(p.requestId);
767 posts.push({ url: p.request.url, headers: p.request.headers });
768 });
769 const loaded = page.once("Page.loadEventFired");
770 await page.send("Page.navigate", { url });
771 await within(15_000, `loading ${url}`, loaded);
772 await within(30_000, "starting", run(page, steps.start, "start"));
773 const httpBase = browserWsUrl.replace(/^ws:/, "http:").replace(/\/devtools\/browser\/.*$/, "");
774 let at: string | undefined;
775 await pollUntil(async () => {
776 const list = (await (await fetch(`${httpBase}/json/list`)).json()) as { type: string; webSocketDebuggerUrl?: string }[];
777 at = list.find((t) => t.type === "service_worker")?.webSocketDebuggerUrl;
778 return at !== undefined;
779 }, "the tab forge's service worker in the devtools list", 10_000);
780 const worker = await open(at!);
781 const value = String(await within(60_000, "the walk", run(page, steps.walk, "walk")));
782 return { value, worker: String(await run(worker, steps.read, "read")), posts };
783 } finally {
784 for (const ws of sockets) ws.close();
785 proc.kill("SIGKILL");
786 await proc.exited.catch(() => {});
787 rmSync(profile, { recursive: true, force: true });
788 }
789 }
790
test/tab-browser.test.ts added +165
@@ -0,0 +1,165 @@
1 /**
2 * The tab forge in a real browser (#18258, #18295): a headless Chromium opens /tab, starts the
3 * forge, and walks every write the tab forge has by real form posts through the real service
4 * worker — make an app, add an entry to it and see the app show it, file an issue, download the
5 * app file and import it back, remove the app — while DevTools records the Origin and Referer
6 * each post left the page with, the two things the worker's same-origin guard reads. The unit
7 * tests build their Headers by hand, which is how a page that sent `Origin: null` got past them.
8 *
9 * The record is taken in the page, not the worker: Chrome only runs the `fetch` listeners a
10 * worker adds while its script first runs, so one added later from DevTools never fires (the
11 * first check of #18295 saw 0 posts). Whether the guard let each post through is the walk itself:
12 * a refused post answers 403 where it was sent and never lands on the page its step expects.
13 *
14 * Nothing here calls `fetch` in a page: every forge page has CSP `default-src 'none'`, so a fetch
15 * from one fails with "TypeError: Failed to fetch" before it leaves the browser (#18295's red).
16 * The walk acts as a person does, by forms and links; the one file read is asked of the worker.
17 */
18 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
19 import { mkdtemp, rm } from "node:fs/promises";
20 import { tmpdir } from "node:os";
21 import { join } from "node:path";
22 import { createApp, type App } from "../src/app.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { findChromium } from "../src/looks/capture.ts";
25 import { makeSpec } from "../src/tab/spec.ts";
26 import { fromOwnPage } from "../src/tab/wire.ts";
27 import { chromiumRuns, walkWithWorker, type WorkerWalk } from "./helpers/chrome.ts";
28
29 const START = `(async () => {
30 document.getElementById("tab-start").click();
31 const end = Date.now() + 25000;
32 while (document.documentElement.dataset.running !== "1") {
33 if (Date.now() > end) throw new Error("the forge never started: " + document.getElementById("tab-status").textContent);
34 await new Promise((r) => requestAnimationFrame(r));
35 }
36 })()`;
37
38 // The download is asked of the worker the way a link would: a page of the forge has CSP
39 // `default-src 'none'`, so it cannot fetch the file itself, and the top page is outside the
40 // worker's scope.
41 const READ = `(async () => {
42 let reply;
43 const event = new FetchEvent("fetch", { request: new Request(self.location.origin + "/tab/f/app.json") });
44 event.respondWith = (r) => { reply = r; };
45 self.dispatchEvent(event);
46 const file = await reply;
47 return JSON.stringify({ file: { status: file.status, disposition: file.headers.get("content-disposition"), json: await file.text() } });
48 })()`;
49
50 const walkScript = (): string => `(async () => {
51 const frame = document.getElementById("tab-frame");
52 const doc = () => frame.contentDocument;
53 const frameDrawn = () => new Promise((r) => requestAnimationFrame(r));
54 const holds = async (ok, what) => {
55 const end = Date.now() + 15000;
56 for (;;) {
57 try { const v = ok(); if (v) return v; } catch {}
58 if (Date.now() > end) throw new Error("waited for " + what + " at " + frame.contentWindow.location.pathname);
59 await frameDrawn();
60 }
61 };
62 const landed = (path) => holds(() => doc().readyState === "complete" && path.test(frame.contentWindow.location.pathname) && doc().querySelector("main, body > *"), "a page at " + path);
63 const out = [];
64 const note = (step) => out.push({ step, path: frame.contentWindow.location.pathname, text: doc().body.innerText.slice(0, 400) });
65 const go = async (path) => { frame.src = path; await landed(new RegExp("^" + path + "$")); };
66 const post = async (step, action, fill, lands) => {
67 const form = await holds(() => [...doc().querySelectorAll("form")].find((f) => action.test(new URL(f.action).pathname)), "a form for " + step);
68 fill(form);
69 const before = doc();
70 form.requestSubmit();
71 await holds(() => doc() !== before, step + " to load a page");
72 await landed(lands);
73 note(step);
74 };
75 await landed(/^\\/tab\\/f\\/$/);
76 await post("make", /^\\/tab\\/f\\/apps$/, (f) => { f.elements.say.value = "Track my water"; }, /^\\/tab\\/f\\/apps\\/\\d+$/);
77 const app = frame.contentWindow.location.pathname;
78 await post("edit", /^\\/tab\\/f\\/apps\\/\\d+\\/\\d+\\/[a-z]+$/, (f) => {
79 for (const i of f.querySelectorAll("input:not([type=hidden])")) if (i.value === "") i.value = i.type === "number" ? "1" : "a glass";
80 }, new RegExp("^" + app + "$"));
81 await go("/tab/f/issues");
82 await post("issue", /^\\/tab\\/f\\/issues$/, (f) => { f.elements.title.value = "Filed from a real form"; f.elements.body.value = "by the browser test"; }, /^\\/tab\\/f\\/issues\\/\\d+$/);
83 await go("/tab/f/");
84 await post("import", /^\\/tab\\/f\\/import$/, (f) => { f.elements.spec.value = ${JSON.stringify(makeSpec("Imported back", undefined))}; }, /^\\/tab\\/f\\/$/);
85 await go(app);
86 await post("remove", /\\/delete$/, (f) => { f.elements.confirm.value = /“(.*)”/.exec(f.textContent)[1]; }, /^\\/tab\\/f\\/$/);
87 return JSON.stringify(out);
88 })()`;
89
90 interface Step { step: string; path?: string; text?: string; status?: number; disposition?: string | null }
91
92 // Runs everywhere, browser or not: a script the walk sends that does not parse fails in Chromium
93 // as "walk: SyntaxError", the second red #18267 met, and only where a browser starts.
94 describe("the scripts the walk sends to the browser", () => {
95 test("each parses as JavaScript", () => {
96 const parse = new Bun.Transpiler({ loader: "js" });
97 for (const script of [START, READ, walkScript()]) expect(() => parse.transformSync(script)).not.toThrow();
98 });
99
100 test("the pasted spec reaches the form as the exact text an import reads", () => {
101 const literal = /f\.elements\.spec\.value = (".*?"); \}/.exec(walkScript())![1]!;
102 expect(JSON.parse(literal)).toBe(makeSpec("Imported back", undefined));
103 });
104 });
105
106 const found = findChromium();
107 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
108
109 let dir: string;
110 let app: App;
111 let servers: Servers;
112 let walked: WorkerWalk;
113
114 describe.skipIf(chromium === undefined)("the tab forge in a real browser (#18258)", () => {
115 beforeAll(async () => {
116 dir = await mkdtemp(join(tmpdir(), "forge-tab-browser-"));
117 app = createApp({ dataDir: dir, port: 0 });
118 servers = await serve(app);
119 walked = await walkWithWorker(chromium!, `${servers.url}/tab`, { start: START, walk: walkScript(), read: READ });
120 // The record the review asked for: what the real browser sent, in the check's log.
121 console.log("tab forge, posts as the page sent them:", JSON.stringify(walked.posts));
122 }, 120_000);
123 afterAll(async () => {
124 servers?.stop();
125 app?.close();
126 await rm(dir, { recursive: true, force: true });
127 });
128
129 test("every write lands where it should, and none is refused", () => {
130 const steps = JSON.parse(walked.value) as Step[];
131 expect(steps.map((s) => s.step)).toEqual(["make", "edit", "issue", "import", "remove"]);
132 for (const s of steps) expect(s.text ?? "").not.toContain("Refused");
133 expect(steps.find((s) => s.step === "issue")!.text).toContain("Filed from a real form");
134 });
135
136 test("the app runs: the entry the edit added shows on the app's page", () => {
137 const steps = JSON.parse(walked.value) as Step[];
138 const made = steps.find((s) => s.step === "make")!;
139 const edited = steps.find((s) => s.step === "edit")!;
140 expect(edited.path).toBe(made.path);
141 expect(edited.text).not.toBe(made.text);
142 });
143
144 test("the app file downloads as an attachment, in the format an import reads", () => {
145 const { file } = JSON.parse(walked.worker) as { file: { status: number; disposition: string | null; json: string } };
146 expect(file.status).toBe(200);
147 expect(file.disposition).toContain('attachment; filename="app.json"');
148 expect(JSON.parse(file.json).format).toBe(JSON.parse(makeSpec("x", undefined)).format);
149 });
150
151 test("each post left the tab's own page, as the worker's guard reads it", () => {
152 const origin = new URL(servers.url).origin;
153 const header = (h: Record<string, string>, name: string): string | null =>
154 Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1] ?? null;
155 const seen = walked.posts.map((p) => ({ path: new URL(p.url).pathname, origin: header(p.headers, "origin"), referer: header(p.headers, "referer") ?? "" }));
156 const shapes = [/^\/tab\/f\/apps$/, /^\/tab\/f\/apps\/\d+\/\d+\/[a-z]+$/, /^\/tab\/f\/issues$/, /^\/tab\/f\/import$/, /^\/tab\/f\/apps\/\d+\/delete$/];
157 expect(seen.length).toBe(shapes.length);
158 shapes.forEach((shape, i) => expect(seen[i]!.path).toMatch(shape));
159 for (const s of seen) {
160 expect(fromOwnPage(s.origin, s.referer, origin)).toBe(true);
161 expect(s.referer).toStartWith(`${origin}/tab/f/`);
162 }
163 });
164 });
165

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

Keyboard shortcuts

Docs