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

A forge toolbar still draws and tells under an app's own strict Content-Security-Policy #15778

Merged opened this

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

Merged

mason/forge:mason/15765-a-forge-toolbar-still-draws-and-tells-un → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/15765-a-forge-toolbar-still-draws-and-tells-un was merged into main as d45c7a7.

Review

Sign in to review this change.
5 files changed +318 −2
docs/features/strict-app-policy.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: Your apps
3 row: A strict Content-Security-Policy no longer hides the forge toolbar or blocks its tell
4 ---
5 # A strict app policy and the toolbar
6
7 An app may send its own `Content-Security-Policy`, even `default-src 'none'`. The forge toolbar is a same-origin script that posts the tell to relative `/__forge/…` paths on the app's own host, so the forge adds the least that lets it run, only where the policy lacks it:
8
9 - **A nonce** on the directive that governs script tags: `script-src-elem` if the policy has one, else `script-src` (built from `default-src` when absent). The toolbar's tag carries the same nonce, on every policy of a comma-separated header.
10 - **`'unsafe-inline'`** is the exception. Browsers ignore it once a nonce is present, which would switch the app's own inline scripts off. There the forge adds `'self'` instead and no nonce.
11 - **`connect-src 'self'`** where the policy does not admit it. This is unavoidable: CSP has no source narrower than an origin, and the tell is posted to the app's own origin. It is the only change to `connect-src`.
12
13 Everything else the app set is left as it was. `Content-Security-Policy-Report-Only` blocks nothing and is passed through unchanged. A policy that already admits the toolbar (`'self'`, `*`, its own nonce) is not touched.
src/apps/proxy.ts +4 −1
@@ -77,6 +77,7 @@ import { stepsOf } from "../core/review_steps.ts";
7777 import { TOUR_ASSET_PATH, tourResponse } from "./tour.ts";
7878 import { behindDefault } from "./pill_behind.ts";
7979 import { repoDir } from "../git/repos.ts";
80 import { admitToolbar } from "./toolbar_csp.ts";
8081 import { cspNonce, HIDE_COOKIE, HIDE_PATH, HIDE_SECONDS, htmlAnswer, readPage, rewritable, TOOLBAR_ASSET_PATH, TOOLBAR_ASSET_PREFIX, toolbarResponse, withToolbar, type PillWhere } from "./toolbar.ts";
8182 import { COMMENT_ASSET_PATH, commentResponse } from "./toolbar_comment.ts";
8283 import { signYoursGo } from "./yours_go.ts";
@@ -1428,13 +1429,15 @@ export async function proxyApp(
14281429 const dismissed = cookieValue(request, HIDE_COOKIE) === "1";
14291430 // Dismissed or not, the page differs by the cookie, so every copy says so.
14301431 out.append("vary", "cookie");
1432 const admitted = admitToolbar(out.get("content-security-policy"));
1433 if (admitted.policy !== null) out.set("content-security-policy", admitted.policy);
14311434 const page = timePhase(request, "rewrite", () =>
14321435 withToolbar(
14331436 bytes,
14341437 runtime.options.forgeUrl,
14351438 { ...pillWhere(runtime, target, vouched?.who), ...(dismissed ? { hidden: true } : {}) },
14361439 proof,
1437 cspNonce(out.get("content-security-policy")),
1440 admitted.nonce,
14381441 ),
14391442 );
14401443 let sent = page;
src/apps/toolbar.ts +1 −1
@@ -833,7 +833,7 @@ export function cspNonce(policy: string | null): string | undefined {
833833 for (const one of policy.split(",")) {
834834 const directives = one.split(";").map((d) => d.trim().split(/\s+/));
835835 const names = (n: string) => directives.find((d) => d[0]?.toLowerCase() === n);
836 const chosen = names("script-src") ?? names("default-src");
836 const chosen = names("script-src-elem") ?? names("script-src") ?? names("default-src");
837837 for (const source of chosen?.slice(1) ?? []) {
838838 const m = /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/i.exec(source);
839839 if (m) return m[1];
src/apps/toolbar_csp.ts added +99
@@ -0,0 +1,99 @@
1 /**
2 * An app's own Content-Security-Policy and the forge's toolbar (#15765). The toolbar is a
3 * same-origin script that posts the tell to the app's own host, so a policy like
4 * `default-src 'none'` would drop both. The forge adds the least that lets it run: a nonce it mints
5 * on `script-src`, and `'self'` on `connect-src`, each only where the policy does not already admit
6 * it. Every other directive is the app's, untouched; a directive the policy lacked is created from
7 * `default-src`, so what the app's own content may do does not change.
8 */
9
10 import { cspNonce } from "./toolbar.ts";
11
12 /**
13 * What the page is served with: the policy header (or none) and the nonce the toolbar's tag
14 * carries.
15 */
16 export type ToolbarPolicy = { policy: string | null; nonce: string | undefined };
17
18 type Directive = string[];
19
20 const has = (sources: Directive, ...wanted: string[]) =>
21 sources.slice(1).some((s) => wanted.includes(s.toLowerCase()));
22
23 /** The directive named `n`, or undefined. */
24 const find = (ds: Directive[], n: string) => ds.find((d) => d[0]?.toLowerCase() === n);
25
26 /**
27 * Add `source` to directive `n`, building it from `fallback` (or `default-src`) when absent; no
28 * change when unconstrained.
29 */
30 function add(ds: Directive[], n: string, source: string, fallback?: string): void {
31 const own = find(ds, n);

A nonce added next to 'unsafe-inline' switches inline scripts off in browsers. Skip adding it, or handle it explicitly, when the directive has 'unsafe-inline' and no 'self'. Also extend script-src-elem when the policy has one.

32 const base = own ?? (fallback ? find(ds, fallback) : undefined) ?? find(ds, "default-src");
33 if (base === undefined) return; // no restriction on it
34 const kept = base.slice(1).filter((s) => s.toLowerCase() !== "'none'");
35 const next = [n, ...kept, source];
36 if (own) own.splice(0, own.length, ...next);
37 else ds.push(next);
38 }
39
40 /**
41 * The directive that governs a `<script src>` tag: `script-src-elem` outranks `script-src`, which
42 * outranks `default-src`. Its name is what the forge extends.
43 */
44 const scriptOf = (ds: Directive[]) => find(ds, "script-src-elem") ?? find(ds, "script-src") ?? find(ds, "default-src");
45 const connectOf = (ds: Directive[]) => find(ds, "connect-src") ?? find(ds, "default-src");
46
47 /**
48 * How one policy must change for the toolbar's script tag: `nonce` where the policy is closed,
49 * `self` where it is closed but spells `'unsafe-inline'` (a browser ignores `'unsafe-inline'` once
50 * a nonce is present, so a nonce would switch the app's own inline scripts off; same-origin scripts
51 * are admitted instead, which breaks nothing), `none` where the toolbar already runs.
52 */
53 function scriptNeed(ds: Directive[]): "nonce" | "self" | "none" {
outdated

scriptOf ignores script-src-elem, which takes precedence over script-src for <script> tags. The toolbar stays blocked when that directive is closed.

54 const s = scriptOf(ds);
55 if (s === undefined || has(s, "'self'", "*")) return "none";
56 if (s.some((x) => /^'nonce-/i.test(x))) return "none";
57 return has(s, "'unsafe-inline'") && !has(s, "'strict-dynamic'") ? "self" : "nonce";
58 }
59
60 /**
61 * The policy with the toolbar admitted, and the nonce for its tag. A policy that already admits the
62 * toolbar (no policy, `'self'`, `*`, an existing nonce) is returned as it was.
63 *
64 * `connect-src 'self'` is the narrowest the tell allows: the toolbar posts to relative `/__forge/…`
65 * paths, which are the app's own origin (the forge proxies them), and CSP has no source narrower
66 * than an origin. It widens what the app's own scripts may fetch to that one origin, and nothing
67 * else in `connect-src` changes. Only the enforcing `Content-Security-Policy` is passed here; a
68 * `-Report-Only` header blocks nothing, so it is left as the app sent it.
69 */
70 export function admitToolbar(policy: string | null): ToolbarPolicy {
71 const existing = cspNonce(policy);
72 if (policy === null || policy.trim() === "") return { policy, nonce: existing };
73 const parsed = policy.split(",").map((one) =>
74 one
75 .split(";")
76 .map((d) => d.trim().split(/\s+/).filter(Boolean))
77 .filter((d) => d.length > 0),
78 );
79 const minted = parsed.some((ds) => scriptNeed(ds) === "nonce")
80 ? Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64")
81 : undefined;
82 let changed = false;
83 for (const ds of parsed) {
84 const need = scriptNeed(ds);
85 if (need !== "none") {
86 const name = find(ds, "script-src-elem") ? "script-src-elem" : "script-src";
87 add(ds, name, need === "nonce" ? `'nonce-${minted}'` : "'self'");
88 changed = true;
89 }
90 const c = connectOf(ds);
91 if (c !== undefined && !has(c, "'self'", "*")) {
92 add(ds, "connect-src", "'self'");
93 changed = true;
94 }
95 }
96 if (!changed) return { policy, nonce: existing };
97 const text = parsed.map((ds) => ds.map((d) => d.join(" ")).join("; ")).join(", ");
98 return { policy: text, nonce: minted ?? existing };
99 }
test/toolbar-strict-csp.test.ts added +201
@@ -0,0 +1,201 @@
1 /**
2 * A strict app policy (#15765): the forge admits the toolbar and its tell, and the app's own
3 * content stays as strict as it was.
4 */
5
6 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { newApp } from "../src/actions/apps.ts";
12 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { admitToolbar } from "../src/apps/toolbar_csp.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const DOMAIN = "apps.test";
21 let reached = 0;
22
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let runtime: AppsRuntime;
27 let backend: ReturnType<typeof Bun.serve>;
28 let status: ReturnType<typeof spyOn>;
29
30 beforeAll(async () => {
31 backend = Bun.serve({
32 port: 0,
33 fetch: (req) => {
34 reached++;
35 const path = new URL(req.url).pathname;
36 const policies: Record<string, string> = {
37 "/lax": "default-src 'self'",
38 "/multi": "default-src 'none', script-src 'sha256-abc'; img-src 'self'",
39 "/inline": "script-src 'unsafe-inline'",
40 "/elem": "script-src 'self'; script-src-elem 'none'",
41 "/report": "default-src 'self'",
42 };
43 const policy = policies[path] ?? "default-src 'none'; img-src 'self'; form-action 'self'";
44 if (path === "/report") {
45 return new Response(`<html><body>x</body></html>`, {
46 headers: {
47 "content-type": "text/html",
48 "content-security-policy": policy,
49 "content-security-policy-report-only": "default-src 'none'",
50 },
51 });
52 }
53 // The request's own words never reach the tag.
54 return new Response(`<html><body><h1>hi</h1><i>nonce="evil"</i></body></html>`, {
55 headers: { "content-type": "text/html", "content-security-policy": policy },
56 });
57 },
58 });
59 dataDir = await mkdtemp(join(tmpdir(), "forge-toolbar-nonce-"));
60 app = createApp({ dataDir, port: 0, host: "forge.test" });
61 servers = await serve(app);
62 runtime = new AppsRuntime(app, {
63 domain: DOMAIN,
64 scheme: "http",
65 publicPort: servers.port,
66 forgeUrl: servers.url,
67 concurrency: 1,
68 });
69 await runtime.start();
70 status = spyOn(AppsRuntime.prototype, "envStatus").mockImplementation(
71 () =>
72 ({
73 env: "production",
74 state: "running",
75 port: backend.port,
76 commitOid: "a".repeat(40),
77 }) as EnvStatus,
78 );
79 const a = await createUser(app.db, {
80 origin: "seed",
81 trusted: true,
82 username: "alice",
83 email: "[email protected]",
84 password: "a-good-passphrase",
85 adminIfFirst: true,
86 });
87 if (!a.ok) throw new Error(a.error);
88 const made = await newApp(app, a.value, {
89 name: "notes",
90 description: "A place for words",
91 visibility: "public",
92 });
93 if (!made.ok) throw new Error(String(made.error));
94 }, 120_000);
95
96 afterAll(async () => {
97 status.mockRestore();
98 await runtime.stop();
99 servers.stop();
100 backend.stop(true);
101 app.close();
102 await rm(dataDir, { recursive: true, force: true });
103 });
104
105 const get = (path: string) =>
106 fetch(`${servers.url}${path}`, { headers: { host: `notes.${DOMAIN}`, accept: "text/html" }, redirect: "manual" });
107
108 test("under default-src 'none' the toolbar is injected with a nonce the policy admits", async () => {
109 const res = await get("/");
110 const policy = res.headers.get("content-security-policy")!;
111 const html = await res.text();
112 const nonce = /<script src="[^"]+" nonce="([^"]+)"/.exec(html)?.[1];
113 expect(nonce).toBeDefined();
114 expect(policy).toContain(`script-src 'nonce-${nonce}'`);
115 });
116
117 test("the tell's same-origin post is allowed and the rest of the app's policy is as it set it", async () => {
118 const policy = (await get("/")).headers.get("content-security-policy")!;
119 expect(policy).toContain("connect-src 'self'");
120 expect(policy).toContain("default-src 'none'");
121 expect(policy).toContain("img-src 'self'");
122 expect(policy).toContain("form-action 'self'");
123 expect(policy).not.toMatch(/'unsafe-|\*/);
124 });
125
126 test("a policy that already admits the toolbar is left alone", async () => {
127 const res = await get("/lax");
128 expect(res.headers.get("content-security-policy")).toBe("default-src 'self'");
129 expect(await res.text()).toContain("__forge/toolbar-");
130 });
131
132 test("admitToolbar keeps the app's own scripts out and its own nonce in", () => {
133 const a = admitToolbar("default-src 'none'");
134 expect(a.policy).toMatch(/^default-src 'none'; script-src 'nonce-[^']+'; connect-src 'self'$/);
135 const b = admitToolbar("default-src 'self'; script-src 'self' 'nonce-abc'");
136 expect(b).toEqual({ policy: "default-src 'self'; script-src 'self' 'nonce-abc'", nonce: "abc" });
137 const c = admitToolbar("script-src 'nonce-abc'");
138 expect(c).toEqual({ policy: "script-src 'nonce-abc'", nonce: "abc" });
139 const d = admitToolbar("script-src 'sha256-xx'; connect-src https://api.example");
140 expect(d.policy).toMatch(/^script-src 'sha256-xx' 'nonce-[^']+'; connect-src https:\/\/api.example 'self'$/);
141 expect(admitToolbar(null)).toEqual({ policy: null, nonce: undefined });
142 expect(admitToolbar("img-src 'none'").policy).toBe("img-src 'none'");
143 });
144
145 const tagNonce = (html: string) => /<script src="[^"]+" nonce="([^"]+)"/.exec(html)?.[1];
146
147 test("a comma-separated header: every policy carries the nonce the tag carries", async () => {
148 const res = await get("/multi");
149 const policy = res.headers.get("content-security-policy")!;
150 const nonce = tagNonce(await res.text());
151 expect(nonce).toBeDefined();
152 const [first, second] = policy.split(", ");
153 expect(first).toContain(`script-src 'nonce-${nonce}'`);
154 expect(second).toContain(`script-src 'sha256-abc' 'nonce-${nonce}'`);
155 });
156
157 test("'unsafe-inline' keeps the app's inline scripts: 'self' is added, no nonce", async () => {
158 const res = await get("/inline");
159 expect(res.headers.get("content-security-policy")).toBe("script-src 'unsafe-inline' 'self'");
160 const html = await res.text();
161 expect(html).toContain("__forge/toolbar-");
162 expect(tagNonce(html)).toBeUndefined();
163 });
164
165 test("script-src-elem is the directive extended when the policy has one", async () => {
166 const res = await get("/elem");
167 const policy = res.headers.get("content-security-policy")!;
168 const nonce = tagNonce(await res.text());
169 expect(nonce).toBeDefined();
170 expect(policy).toBe(`script-src 'self'; script-src-elem 'nonce-${nonce}'`);
171 });
172
173 test("a Report-Only header is passed through as the app sent it", async () => {
174 const res = await get("/report");
175 expect(res.headers.get("content-security-policy-report-only")).toBe("default-src 'none'");
176 expect(res.headers.get("content-security-policy")).toBe("default-src 'self'");
177 });
178
179 test("the only change to connect-src is the added 'self'", () => {
180 const p = admitToolbar("script-src 'self'; connect-src https://api.example wss://x.example").policy;
181 expect(p).toBe("script-src 'self'; connect-src https://api.example wss://x.example 'self'");
182 });
183
184 test("the tell's target is the app's own origin: every toolbar call is a relative /__forge/ path", async () => {
185 const src = await Bun.file(join(import.meta.dir, "../src/apps/toolbar.ts")).text();
186 const calls = [...src.matchAll(/\b(?:call|fetch)\(\s*"([^"]+)"/g)].map((m) => m[1]!);
187 expect(calls.length).toBeGreaterThan(0);
188 for (const c of calls) expect(c.startsWith("/__forge/")).toBe(true);
189 const policy = (await get("/")).headers.get("content-security-policy")!;
190 expect(policy).toContain("connect-src 'self'");
191 });
192
193 test("admitToolbar: unit cases for 'unsafe-inline' and script-src-elem", () => {
194 expect(admitToolbar("default-src 'unsafe-inline'").policy).toBe(
195 "default-src 'unsafe-inline'; script-src 'unsafe-inline' 'self'; connect-src 'unsafe-inline' 'self'",
196 );
197 expect(admitToolbar("script-src 'unsafe-inline' 'strict-dynamic'").policy).toMatch(/'nonce-[^']+'$/);
198 expect(admitToolbar("default-src 'none'; script-src-elem 'none'").policy).toMatch(
199 /^default-src 'none'; script-src-elem 'nonce-[^']+'; connect-src 'self'$/,
200 );
201 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs