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

The forge pill shows on an app whose CSP allows only its own scripts: the proxy serves it from the app's host #8215

Parked opened this
Closed without merging

scout/forge:scout/8209-the-forge-pill-shows-on-an-app-whose-csp → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +151 −22
src/apps/proxy.ts +8 −1
@@ -53,7 +53,7 @@ import { notFound, securityFloor } from "../http/respond.ts";
5353 import { appMeasure } from "./measure.ts";
5454 import { holdPortRequest, holdPortSocket } from "./handoff.ts";
5555 import { secureFor } from "../http/cookie_secure.ts";
56 import { htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts";
56 import { APP_TOOLBAR_PATH, toolbarResponse, htmlAnswer, readPage, rewritable, withToolbar, type PillWhere } from "./toolbar.ts";
5757
5858 const proxySecure = (request: Request, url: URL, forgeUrl: string): boolean =>
5959 secureFor(url, forgeUrl) ||
@@ -816,6 +816,13 @@ export async function proxyApp(
816816 server: Bun.Server<AppSocket>,
817817 ): Promise<Response | undefined> {
818818 const url = new URL(request.url);
819 // The pill's script, from the app's own host so a page that allows only
820 // its own scripts still loads it. Public bytes, named by their hash.
821 if (
822 url.pathname === APP_TOOLBAR_PATH &&
823 (request.method === "GET" || request.method === "HEAD")
824 )
825 return securityFloor(toolbarResponse(request));
819826 // A grant with this forge's own token is answered here. On a nested
820827 // hostname a grant this forge did not sign is the guest forge's, and
821828 // goes through to it like any other request.
src/apps/toolbar.ts +11 −6
@@ -20,8 +20,10 @@ export const toolbarJs = `(function () {
2020 if (window.__forgeToolbar) return;
2121 window.__forgeToolbar = true;
2222 var me = document.currentScript;
23 // The forge's address: a data attribute when the script is the app's own, else where the script came from.
24 var forgeAt = (me.dataset && me.dataset.forge) || me.src;
2325 var home = "/";
24 try { home = new URL(me.src).origin + "/"; } catch (e) {}
26 try { home = new URL(forgeAt).origin + "/"; } catch (e) {}
2527 var host = document.createElement("div");
2628 host.id = "forge-toolbar";
2729 host.style.cssText = "all:initial;position:fixed;z-index:2147483647";
@@ -74,7 +76,7 @@ export const toolbarJs = `(function () {
7476 var pullHref = "";
7577 // The pull this preview shows, one tap away: built from the script's own origin, never from page text.
7678 if (d.env !== "production" && /^\\d{1,9}$/.test(d.pull || "") && /^[\\w.-]+\\/[\\w.-]+$/.test(d.repo || "")) {
77 try { pullHref = new URL("/" + d.repo + "/pulls/" + d.pull, me.src).href; } catch (e) {}
79 try { pullHref = new URL("/" + d.repo + "/pulls/" + d.pull, forgeAt).href; } catch (e) {}
7880 }
7981 if (d.env === "production") {}
8082 else if (pullHref) {
@@ -92,13 +94,13 @@ export const toolbarJs = `(function () {
9294 link.style.cssText = LS;
9395 try {
9496 var target = new URL(home);
95 if (target.origin === new URL(me.src).origin) link.href = target.href;
97 if (target.origin === new URL(forgeAt).origin) link.href = target.href;
9698 } catch (e) {}
9799 // Tell the builders: one box, one button, no account. The note goes to
98100 // this app's own host (same-origin, so the sender's cookie goes along) and
99101 // the answer is a live status the panel keeps fresh while it is open.
100102 var forgeOrigin = "";
101 try { forgeOrigin = new URL(me.src).origin; } catch (e) {}
103 try { forgeOrigin = new URL(forgeAt).origin; } catch (e) {}
102104 var tellBox = document.createElement("form");
103105 tellBox.setAttribute("aria-label", "Tell the builders");
104106 tellBox.style.cssText = "display:flex;flex-direction:column;gap:6px;margin:6px 0";
@@ -320,7 +322,7 @@ export const toolbarJs = `(function () {
320322 .then(function (r) { return r.ok ? r.json() : {}; })
321323 .then(function (c) {
322324 if (!c) return;
323 var forge = new URL(me.src).origin;
325 var forge = new URL(forgeAt).origin;
324326 // Signed in, the crew can be told from here. The form is the forge's
325327 // own page, on its own origin, with its own CSRF check: the app's
326328 // page only carries the address and the pull to it.
@@ -507,6 +509,8 @@ const name = `toolbar-${hash.slice(0, 16)}`;
507509 /** The path the script is served from on the forge, content-addressed. */
508510 export const TOOLBAR_PATH = `/assets/${name}.js`;
509511 export const TOOLBAR_NAME = name;
512 /** The same bytes on every app's own host, so a `script-src 'self'` page loads them. */
513 export const APP_TOOLBAR_PATH = `/__forge/${name}.js`;
510514
511515 /** The forge's answer for the script: immutable, because its name is its hash. */
512516 export function toolbarResponse(request: Request): Response {
@@ -586,7 +590,8 @@ export function toolbarTag(forgeUrl: string, where?: PillWhere, proof?: string):
586590 .map(([k, v]) => ` data-${k}="${escapeAttr(v)}"`)
587591 .join("");
588592 const token = proof === undefined ? "" : ` data-proof="${escapeAttr(proof)}"`;
589 return `<script src="${new URL(TOOLBAR_PATH, forgeUrl).href}"${data}${token} defer></script>`;
593 const forge = ` data-forge="${escapeAttr(new URL("/", forgeUrl).origin)}"`;
594 return `<script src="${APP_TOOLBAR_PATH}"${forge}${data}${token} defer></script>`;
590595 }
591596
592597 /**
test/apps-pill-where.test.ts +1 −1
@@ -168,6 +168,6 @@ describe("the pill's script", () => {
168168 test("puts text in with textContent and checks the home href against the forge origin", () => {
169169 expect(toolbarJs).toContain("textContent = text");
170170 expect(toolbarJs).not.toMatch(/innerHTML|outerHTML|insertAdjacentHTML|document\.write/);
171 expect(toolbarJs).toContain("target.origin === new URL(me.src).origin");
171 expect(toolbarJs).toContain("target.origin === new URL(forgeAt).origin");
172172 });
173173 });
test/apps-toolbar-same-origin.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * (never-lost setup reused) The Lost test (P6 Never lost): from production and from a preview, the
3 * pill says where you are and links home, to comment, and to tell the crew.
4 * One forge, one app serving one HTML page, asked through the app proxy as
5 * production and as the preview of an open pull, signed in and signed out.
6 */
7
8 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { newApp } from "../src/actions/apps.ts";
14 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
15 import { APP_TOOLBAR_PATH, toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const DOMAIN = "apps.test";
23 const HTML = "<html><body><h1>hi</h1></body></html>";
24
25 describe("the pill loads on an app whose CSP allows only its own scripts", () => {
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let runtime: AppsRuntime;
30 let backend: ReturnType<typeof Bun.serve>;
31 let status: ReturnType<typeof spyOn>;
32
33 beforeAll(async () => {
34 backend = Bun.serve({
35 port: 0,
36 fetch: () =>
37 new Response(HTML, {
38 headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'self'; script-src 'self'" },
39 }),
40 });
41 dataDir = await mkdtemp(join(tmpdir(), "forge-never-lost-"));
42 app = createApp({ dataDir, port: 0, host: "forge.test" });
43 servers = await serve(app);
44 runtime = new AppsRuntime(app, {
45 domain: DOMAIN,
46 scheme: "http",
47 publicPort: servers.port,
48 forgeUrl: servers.url,
49 concurrency: 1,
50 });
51 await runtime.start();
52 status = spyOn(AppsRuntime.prototype, "envStatus").mockImplementation(
53 (_app: unknown, env: string) =>
54 ({
55 env,
56 state: "running",
57 port: backend.port,
58 commitOid: "a".repeat(40),
59 }) as EnvStatus,
60 );
61 const u = await createUser(app.db, {
62 origin: "seed",
63 trusted: true,
64 username: "alice",
65 email: "[email protected]",
66 password: "a-good-passphrase",
67 adminIfFirst: true,
68 });
69 if (!u.ok) throw new Error(u.error);
70
71 const made = await newApp(app, u.value, { name: "notes", description: "x", visibility: "public" });
72 if (!made.ok) throw new Error(String(made.error));
73
74 }, 120_000);
75
76 afterAll(async () => {
77 status.mockRestore();
78 await runtime.stop();
79 servers.stop();
80 backend.stop(true);
81 app.close();
82 await rm(dataDir, { recursive: true, force: true });
83 });
84
85 const ask = (path: string) =>
86 fetch(`${servers.url}${path}`, { headers: { host: `notes.${DOMAIN}`, accept: "text/html" }, redirect: "manual" });
87
88 test("the tag's src is the app's own origin and the forge's address rides in data-forge", async () => {
89 const res = await ask("/");
90 expect(res.headers.get("content-security-policy")).toContain("script-src 'self'");
91 const html = await res.text();
92 const tag = /<script src="([^"]+)"([^>]*) defer><\/script>/.exec(html);
93 expect(tag).not.toBeNull();
94 expect(tag![1]).toBe(APP_TOOLBAR_PATH);
95 expect(tag![1]!.startsWith("/")).toBe(true);
96 expect(tag![2]).toContain(` data-forge="${servers.url}"`);
97 });
98
99 test("the app's host answers the pill's bytes, immutable, with the security headers", async () => {
100 const res = await ask(APP_TOOLBAR_PATH);
101 expect(res.status).toBe(200);
102 expect(res.headers.get("content-type")).toStartWith("text/javascript");
103 expect(res.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
104 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
105 expect(res.headers.get("referrer-policy")).not.toBeNull();
106 expect(res.headers.get("content-security-policy")).not.toBeNull();
107 expect(await res.text()).toBe(toolbarJs);
108 });
109
110 test("the script takes the forge's origin from data-forge, and the tag escapes it", () => {
111 expect(toolbarJs).toContain("me.dataset.forge");
112 const tag = toolbarTag("https://forge.example", { app: 'a"b', repo: "x/y", env: "production" });
113 expect(tag).toContain('src="/__forge/toolbar-');
114 expect(tag).toContain('data-forge="https://forge.example"');
115 expect(tag).toContain("data-app=\"a&quot;b\"");
116 });
117 });
test/apps-toolbar.test.ts +9 −9
@@ -17,7 +17,7 @@ import { getAppByRepo } from "../src/core/apps.ts";
1717 import { listRuns } from "../src/core/runs.ts";
1818 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1919 import { parseManifest } from "../src/apps/manifest.ts";
20 import { REWRITE_MAX, TOOLBAR_PATH, readPage, toolbarJs, withToolbar } from "../src/apps/toolbar.ts";
20 import { APP_TOOLBAR_PATH, REWRITE_MAX, TOOLBAR_PATH, readPage, toolbarJs, withToolbar } from "../src/apps/toolbar.ts";
2121 import { createUser } from "../src/core/users.ts";
2222 import { serve, type Servers } from "../src/http/server.ts";
2323 import { quietLogs } from "./helpers/globals.ts";
@@ -187,7 +187,7 @@ describe("the forge pill", () => {
187187 redirect: "manual",
188188 });
189189 const tag = () =>
190 `<script src="${servers.url}${TOOLBAR_PATH}" data-app="notes" data-repo="alice/notes" data-env="production" defer></script>`;
190 `<script src="${APP_TOOLBAR_PATH}" data-forge="${servers.url}" data-app="notes" data-repo="alice/notes" data-env="production" defer></script>`;
191191
192192 test("HTML gets one script tag before </body>, with its length fixed", async () => {
193193 toolbar = undefined;
@@ -227,7 +227,7 @@ describe("the forge pill", () => {
227227 const got = Buffer.from(await res.arrayBuffer()).toString();
228228 const piece = "<p>" + "b".repeat(1024 * 1024) + "</p>";
229229 expect(got).toBe("<html><body>" + piece.repeat(5) + "</body></html>");
230 expect(got).not.toContain(TOOLBAR_PATH);
230 expect(got).not.toContain(APP_TOOLBAR_PATH);
231231 });
232232
233233 test("a streamed page still open after the wait arrives whole with no pill", async () => {
@@ -273,7 +273,7 @@ describe("the forge pill", () => {
273273 });
274274 expect(plain.headers.get("content-encoding")).toBeNull();
275275 expect(plain.headers.get("vary")).toContain("accept-encoding");
276 expect(await plain.text()).toContain(TOOLBAR_PATH);
276 expect(await plain.text()).toContain(APP_TOOLBAR_PATH);
277277 });
278278
279279 test("a client that refuses gzip with q=0 gets the page plain", async () => {
@@ -284,7 +284,7 @@ describe("the forge pill", () => {
284284 } as RequestInit);
285285 expect(res.headers.get("content-encoding")).toBeNull();
286286 expect(res.headers.get("vary")).toContain("accept-encoding");
287 expect(await res.text()).toContain(TOOLBAR_PATH);
287 expect(await res.text()).toContain(APP_TOOLBAR_PATH);
288288 });
289289
290290 test("a client that accepts br is sent brotli", async () => {
@@ -309,7 +309,7 @@ describe("the forge pill", () => {
309309 } as RequestInit);
310310 expect(res.headers.get("content-encoding")).toBeNull();
311311 expect(res.headers.get("vary")).toContain("accept-encoding");
312 expect(await res.text()).toContain(TOOLBAR_PATH);
312 expect(await res.text()).toContain(APP_TOOLBAR_PATH);
313313 });
314314
315315 test("an app with the pill off is sent the client's encoding and its gzip passes through", async () => {
@@ -375,7 +375,7 @@ describe("the forge pill", () => {
375375 const out = new TextDecoder().decode(
376376 withToolbar(new TextEncoder().encode("<BODY>x</BODY>"), "http://f.test"),
377377 );
378 expect(out).toBe(`<BODY>x<script src="http://f.test${TOOLBAR_PATH}" defer></script></BODY>`);
378 expect(out).toBe(`<BODY>x<script src="${APP_TOOLBAR_PATH}" data-forge="http://f.test" defer></script></BODY>`);
379379 });
380380
381381 test("forge.json toolbar is validated", () => {
@@ -612,7 +612,7 @@ describe("the opt-out, from forge.json to the proxy", () => {
612612 // As created: the pill is on, so the page below has something to lose.
613613 expect((await settled()).state).toBe("ok");
614614 expect(runtime.envStatus(record, "production")?.toolbar).toBe(true);
615 expect(await page()).toContain(TOOLBAR_PATH);
615 expect(await page()).toContain(APP_TOOLBAR_PATH);
616616
617617 const off = await commitToBranch(app, a.value, repo, {
618618 message: "Turn the pill off",
@@ -628,7 +628,7 @@ describe("the opt-out, from forge.json to the proxy", () => {
628628 expect(runtime.envStatus(record, "production")?.toolbar).toBe(false);
629629 const html = await page();
630630 expect(html).toContain("<");
631 expect(html).not.toContain(TOOLBAR_PATH);
631 expect(html).not.toContain(APP_TOOLBAR_PATH);
632632 }, 180_000);
633633 });
634634
test/never-lost.test.ts +2 −2
@@ -13,7 +13,7 @@ import { createApp, type App } from "../src/app.ts";
1313 import { newApp } from "../src/actions/apps.ts";
1414 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
1515 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
16 import { TOOLBAR_PATH } from "../src/apps/toolbar.ts";
16 import { APP_TOOLBAR_PATH } from "../src/apps/toolbar.ts";
1717 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
1818 import { createIssue } from "../src/core/issues.ts";
1919 import { createToken } from "../src/core/tokens.ts";
@@ -119,7 +119,7 @@ describe("never lost: the pill from production and from a preview", () => {
119119 const html = await res.text();
120120 const tag = /<script src="([^"]+)"([^>]*) defer><\/script>/.exec(html);
121121 expect(tag).not.toBeNull();
122 expect(tag![1]).toBe(`${servers.url}${TOOLBAR_PATH}`);
122 expect(tag![1]).toBe(APP_TOOLBAR_PATH);
123123 expect(tag![2]).toContain(' data-app="notes"');
124124 expect(tag![2]).toContain(' data-repo="alice/notes"');
125125 expect(tag![2]).toContain(` data-env="${env()}"`);
test/toolbar-body-close.test.ts +1 −1
@@ -2,7 +2,7 @@
22 import { expect, test } from "bun:test";
33 import { withToolbar } from "../src/apps/toolbar.ts";
44
5 const TAG = `<script src="http://f.test/`;
5 const TAG = `<script src="/__forge/`;
66 const put = (html: string): string =>
77 new TextDecoder().decode(withToolbar(new TextEncoder().encode(html), "http://f.test"));
88 /** Where the tag landed, as the text before it. */
test/toolbar-keyboard.test.ts +2 −2
@@ -11,7 +11,7 @@ import { mkdtempSync, rmSync } from "node:fs";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { childEnv } from "../src/apps/process.ts";
14 import { TOOLBAR_PATH, toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
14 import { APP_TOOLBAR_PATH, toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
1515 import { findChromium } from "../src/looks/capture.ts";
1616 import { chromiumRuns } from "./helpers/chrome.ts";
1717
@@ -70,7 +70,7 @@ describe.skipIf(chromium === undefined)("the pill by keyboard", () => {
7070 hostname: "127.0.0.1",
7171 fetch(req) {
7272 const url = new URL(req.url);
73 if (url.pathname === TOOLBAR_PATH)
73 if (url.pathname === APP_TOOLBAR_PATH)
7474 return new Response(toolbarJs, { headers: { "content-type": "text/javascript" } });
7575 if (url.pathname === "/__forge/notes") return Response.json({ notes: [] });
7676 if (url.pathname === "/__forge/crew") return Response.json({});

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs