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

The Talk pane's frame draws the app: the forge's own origin may frame an app, no one else #16318

Merged opened this

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

Merged

talk/look-6-preview-frames → main 0 commits

  • Merged. talk/look-6-preview-frames was merged into main as fc0ecb8.

Review

Sign in to review this change.
7 files changed +474 −13
docs/features/talk.md +6
@@ -222,3 +222,9 @@ Its buttons belong to the composer's form and post to the confirm's own address
222222 Beside a conversation that builds or changes an app, the pane's **Code** tab is the repository's files at the conversation's branch from the first moment: the files this conversation changed come first under "Changed here", each with what it added and removed, and are marked in the tree; the tree is the repository page's own explorer, and a file opens in the pane from the blob page's own view, with **Files** to go back. **Diff** is the change itself, inline: the forge's diff with its highlighting, each file folded open, for everything the branch changed against the default branch, or one version's own change when its chip is chosen (All, v1, v2, …). The pull is a quiet link in the head with its checks in words ("Pull #2 · checks passing"). Both are read only when their tab is opened, and a tab swaps the pane in place from the page's own fragment (`?pane=code&fragment=pane`), so nothing is a page in a frame. A preview that has not loaded in ten seconds says so in words, and one not there yet says why, never a blank box. Proof: `test/talk-steps.test.ts`, `test/talk-page.test.ts`.
223223
224224 **In the terminal** the pane (`p`) lists what the conversation's branch changed, each file with its +/− counts, then the diff itself, read through the same `branchDiff`.
225
226 ## The pane's preview frame (#15734)
227
228 The pane's Preview tab frames the app the conversation builds, on the app's own host. An app's answer says who may frame it; the proxy (`admitForgeFrame`, `src/apps/frame_policy.ts`) adds the forge's own origin, and only that origin, to a `frame-ancestors` that restricts framing (`'none'` becomes the forge, `'self'` or a list keeps its sources and gains the forge). A policy that frames freely (`*`, or none) is the app's choice and stays as it is. An `X-Frame-Options: DENY` or `SAMEORIGIN` becomes `frame-ancestors <forge>`. Any other site that frames the app is refused by the browser, as before.
229
230 A private preview signs the person in inside the frame through their own grant. That grant's cookie is set inside the frame as `SameSite=None; Secure; Partitioned`, so it is kept per embedding site, is sent only while the forge is the framing page, and lives half an hour. A frame that is not signed in gets one sentence and a link that opens the preview on its own, never a redirect it cannot follow. A preview that is not serving shows the forge's own sentence inside the frame, with its links opening beside it. Proof: `test/apps-frame-policy.test.ts`, `test/talk-preview-frame.test.ts` (a real Chromium).
src/apps/frame_policy.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * Who may frame an app. An app's answer says who may put it in a frame
3 * (`frame-ancestors` in its own policy, or `X-Frame-Options`); the template's
4 * own policy says `'none'`, and the forge's holding pages say the same. The
5 * Talk pane frames the app it is building, so the forge's own origin is
6 * admitted there, and only the forge's own origin: an app stays unframeable
7 * by every other site. The forge's pages never frame an app any other way
8 * than through the person's own grant (`apps/grants.ts`), and a framed app
9 * is a different origin from the forge, so it can neither read the forge's
10 * session nor script the parent.
11 *
12 * What changes, and what does not:
13 * - a policy that restricts framing (`'none'`, `'self'`, or an origin list)
14 * keeps its restriction and gains the forge's origin; `'none'` is replaced
15 * by it. A policy that frames freely (`*`, or no `frame-ancestors`) is the
16 * app's own choice and is left alone;
17 * - `X-Frame-Options` is dropped only when the answer has been given a
18 * `frame-ancestors` that says the same, with the forge added, so a browser
19 * that reads both reads one rule;
20 * - an answer with neither is untouched: the forge adds no restriction an
21 * app did not ask for.
22 */
23
24 const originOf = (url: string): string | undefined => {
25 try {
26 const u = new URL(url);
27 return u.protocol === "http:" || u.protocol === "https:" ? u.origin : undefined;
28 } catch {
29 return undefined;
30 }
31 };
32
33 /** One policy (a `;`-separated list of directives) with the forge admitted to `frame-ancestors`, or the same text. */
34 function admitOne(policy: string, forge: string): { text: string; restricts: boolean } {
35 const directives = policy.split(";").map((d) => d.trim()).filter((d) => d !== "");
36 let restricts = false;
37 const next = directives.map((d) => {
38 const [name = "", ...sources] = d.split(/\s+/);
39 if (name.toLowerCase() !== "frame-ancestors") return d;
40 if (sources.some((s) => s === "*")) return d;
41 restricts = true;
42 const kept = sources.filter((s) => s.toLowerCase() !== "'none'");
43 return ["frame-ancestors", ...kept, ...(kept.includes(forge) ? [] : [forge])].join(" ");
44 });
45 return { text: next.join("; "), restricts };
46 }
47
48 /** `headers` of an answer to a request for an app, with the forge's own origin admitted as a framer. */
49 export function admitForgeFrame(headers: Headers, forgeUrl: string): void {
50 const forge = originOf(forgeUrl);
51 if (forge === undefined) return;
52 const csp = headers.get("content-security-policy");
53 let admitted = false;
54 if (csp !== null) {
55 const policies = csp.split(",").map((p) => admitOne(p, forge));
56 admitted = policies.some((p) => p.restricts);
57 if (admitted) headers.set("content-security-policy", policies.map((p) => p.text).join(", "));
58 }
59 const xfo = headers.get("x-frame-options");
60 if (xfo === null) return;
61 if (admitted) {
62 headers.delete("x-frame-options");
63 } else if (/^\s*(deny|sameorigin)\s*$/i.test(xfo)) {
64 // The app asked not to be framed by the web at large and said it with the older header only.
65 headers.delete("x-frame-options");
66 const own = csp === null || csp.trim() === "" ? "" : `${csp}, `;
67 headers.set("content-security-policy", `${own}frame-ancestors ${forge}`);
68 }
69 }
src/apps/proxy.ts +70 −9
@@ -67,6 +67,7 @@ import { openPulls } from "./door_pulls.ts";
6767 import { notePhase, startedAt, takePhases, timePhase } from "../core/route_timing.ts";
6868 import { readServing } from "./serving.ts";
6969 import { notFound, securityFloor } from "../http/respond.ts";
70 import { admitForgeFrame } from "./frame_policy.ts";
7071 import { UPSTREAM_WAIT_MS, slowAnswer } from "./upstream_wait.ts";
7172 import { appMeasure } from "./measure.ts";
7273 import { holdPortRequest, holdPortSocket } from "./handoff.ts";
@@ -266,6 +267,8 @@ export function originFor(
266267 const grantCookieName = (target: AppTarget): string =>
267268 `forge_grant_${target.app.id.slice(-8)}`;
268269 const GRANT_COOKIE_TTL_MS = 12 * 60 * 60_000;
270 /** A grant cookie set inside another site's frame lives half an hour: the pane asks again. */
271 const GRANT_FRAME_TTL_MS = 30 * 60_000;
269272
270273 /**
271274 * The forge's and the edge's credentials never reach tenant code: every
@@ -911,12 +914,32 @@ function toSignIn(runtime: AppsRuntime, request: Request, to?: string): Response
911914 const open = new URL("/apps/open", runtime.options.forgeUrl);
912915 open.searchParams.set("host", request.headers.get("host") ?? "");
913916 open.searchParams.set("to", to ?? url.pathname + url.search);
917 // Inside the Talk pane's frame a redirect to the forge would only be refused and draw nothing:
918 // say in words what is wrong, and where to go.
919 if (request.headers.get("sec-fetch-dest") === "iframe") return needsSignIn(open.toString());
914920 return new Response(null, {
915921 status: 303,
916922 headers: { location: open.toString(), "cache-control": "no-store" },
917923 });
918924 }
919925
926 /** What a frame is told instead of a sign-in redirect it cannot follow: one sentence and a link out. */
927 function needsSignIn(href: string): Response {
928 const html = `<!doctype html>
929 <meta charset="utf-8">
930 <meta name="viewport" content="width=device-width, initial-scale=1">
931 <title>Sign in to see this</title>
932 <style>:root{color-scheme:light dark;font:16px/1.5 system-ui,sans-serif}body{max-width:30rem;margin:18vh auto;padding:0 1.5rem}</style>
933 <p>This preview is private, and this frame cannot show who you are. <a href="${escape(href)}" target="_blank" rel="noopener">Open it on its own</a>.</p>
934 `;
935 return securityFloor(
936 new Response(html, {
937 status: 403,
938 headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": HOLDING_POLICY },
939 }),
940 );
941 }
942
920943 /**
921944 * A hostname shaped like an app's that names none. It answers exactly as a
922945 * private app answers a signed-out visitor — a person navigating is sent to
@@ -941,6 +964,36 @@ export async function proxyApp(
941964 request: Request,
942965 target: AppTarget,
943966 server: Bun.Server<AppSocket>,
967 ): Promise<Response | undefined> {
968 const answer = await proxyAppAnswer(runtime, request, target, server);
969 const framedHolding = answer?.headers.has(HOLDING_MARK) === true;
970 if (framedHolding) answer!.headers.delete(HOLDING_MARK);
971 // The forge's own origin may frame what any app host answers (the Talk pane); nobody else may. A
972 // bare not-found is left byte for byte as a name nobody holds gets, so a private app's existence
973 // never shows in its headers; the forge's own sentence pages (a preview that is gone) are framed.
974 // The forge's own `/__forge/` answers (the panel, the grant) are never framed: they keep the floor.
975 const forgeOwn = new URL(request.url).pathname.startsWith("/__forge/");
976 if (answer !== undefined && !forgeOwn && (answer.status !== 404 || framedHolding)) {
977 try {
978 admitForgeFrame(answer.headers, runtime.options.forgeUrl);
979 } catch {
980 // headers the forge is only carrying cannot be changed; they keep what they came with
981 }
982 }
983 // The forge's sentence in the pane's frame: its links open beside it, since the forge's own pages
984 // cannot be framed and a link followed inside the frame would draw nothing.
985 if (framedHolding && request.headers.get("sec-fetch-dest") === "iframe" && answer !== undefined) {
986 const page = (await answer.text()).replace("<meta charset=\"utf-8\">", '<meta charset="utf-8">\n<base target="_blank">');
987 return new Response(page, { status: answer.status, headers: answer.headers });
988 }
989 return answer;
990 }
991
992 async function proxyAppAnswer(
993 runtime: AppsRuntime,
994 request: Request,
995 target: AppTarget,
996 server: Bun.Server<AppSocket>,
944997 ): Promise<Response | undefined> {
945998 const entered = performance.now();
946999 const url = new URL(request.url);
@@ -1520,7 +1573,9 @@ export async function proxyApp(
15201573 export function proofWanted(request: Request): boolean {
15211574 const dest = request.headers.get("sec-fetch-dest");
15221575 if (dest === null || dest === "document") return true;
1523 return dest === "iframe" && request.headers.get("sec-fetch-site") === "cross-site";
1576 // A frame from another site or a sibling host (the Talk pane on the forge's own host) is proved;
1577 // a frame of the app's own origin is the app framing itself, and never is.
1578 return dest === "iframe" && request.headers.get("sec-fetch-site") !== "same-origin";
15241579 }
15251580
15261581 /**
@@ -1830,13 +1885,13 @@ function grant(
18301885 if (vouched === undefined) {
18311886 return new Response("not found", { status: 404 });
18321887 }
1833 const cookie = signGrant(
1834 runtime.app.config.dataDir,
1835 target,
1836 GRANT_COOKIE_TTL_MS,
1837 Date.now(),
1838 vouched.who,
1839 );
1888 // The pane's frame. On another site than the app's host (a custom domain, a forge on its own
1889 // domain, a local `localhost`) a Lax cookie is not sent back into it, and a browser may call even
1890 // a sibling host another site, so the cookie is kept per embedding site instead (partitioned),
1891 // and lives half an hour.
1892 const framed = request.headers.get("sec-fetch-dest") === "iframe";
1893 const ttl = framed ? GRANT_FRAME_TTL_MS : GRANT_COOKIE_TTL_MS;
1894 const cookie = signGrant(runtime.app.config.dataDir, target, ttl, Date.now(), vouched.who);
18401895 const path = safePath(url.searchParams.get("to"));
18411896 const proof = url.searchParams.get("plain") ?? "";
18421897 const expected = Buffer.from(plainProof(runtime.app.config.dataDir, token));
@@ -1846,11 +1901,13 @@ function grant(
18461901 given.length === expected.length &&
18471902 timingSafeEqual(given, expected);
18481903 const secure = !plain && proxySecure(request, url, runtime.options.forgeUrl);
1904 // The grant is consumed here: the redirect names a path of the app and never the token, so the app
1905 // (its address bar, its logs, its Referer) never sees it.
18491906 return new Response(null, {
18501907 status: 303,
18511908 headers: {
18521909 location: path,
1853 "set-cookie": setCookie(grantCookieName(target), cookie, { maxAge: Math.floor(GRANT_COOKIE_TTL_MS / 1000), secure }),
1910 "set-cookie": setCookie(grantCookieName(target), cookie, { maxAge: Math.floor(ttl / 1000), secure, ...(framed ? { framed } : {}) }),
18541911 "cache-control": "no-store",
18551912 },
18561913 });
@@ -2001,6 +2058,7 @@ ${report ? '<p><a href="/__forge/report">Report a problem</a> to the people who
20012058 "content-type": "text/html; charset=utf-8",
20022059 "cache-control": "no-store",
20032060 "content-security-policy": HOLDING_POLICY,
2061 [HOLDING_MARK]: "1",
20042062 ...(deploying ? { "retry-after": "3" } : {}),
20052063 ...(report ? { link: links.join(", ") } : {}),
20062064 },
@@ -2008,6 +2066,9 @@ ${report ? '<p><a href="/__forge/report">Report a problem</a> to the people who
20082066 );
20092067 }
20102068
2069 /** Set on the forge's own sentence-pages so the proxy can tell them from an app's answer; never sent. */
2070 const HOLDING_MARK = "x-forge-holding";
2071
20112072 /** The policy of the forge's own holding pages: their inline style, nothing that runs. */
20122073 const HOLDING_POLICY =
20132074 "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; " +
src/auth/cookies.ts +12 −2
@@ -1,6 +1,7 @@
11 /**
22 * The one place a cookie line is spelled (#12314). Every cookie the forge
3 * sets is HttpOnly and SameSite=Lax, and Secure when `secure` says the
3 * sets is HttpOnly and SameSite=Lax (but an app's grant set inside the Talk
4 * pane's frame, which is SameSite=None, Secure and Partitioned), and Secure when `secure` says the
45 * request or the forge's own address is https (see `secureFor` in
56 * src/http/cookie_secure.ts). Nothing here can switch a flag off: a cookie
67 * that needs to drop one has to change this file, and test/cookie-flags.test.ts
@@ -23,6 +24,12 @@ export interface CookieOptions {
2324 expires?: Date;
2425 /** `secureFor(url, forgeUrl)`: the request or the forge is https. */
2526 secure: boolean;
27 /**
28 * For a cookie set inside another site's frame: `SameSite=None; Secure; Partitioned`. The cookie is
29 * then kept apart per embedding site (CHIPS), so it is sent only when the forge's page is the one
30 * framing, never to a request another site makes to the app. Always `Secure`.
31 */
32 framed?: boolean;
2633 }
2734
2835 /** A cookie name: an RFC 6265 token, which every forge name is a subset of. */
@@ -42,12 +49,15 @@ export function setCookie(name: string, value: string, o: CookieOptions): string
4249 const path = o.path ?? "/";
4350 if (!PATH.test(path)) throw new Error(`cookie ${name}'s path ${JSON.stringify(path)} is not an absolute path`);
4451 const parts = [`${name}=${value}`, `Path=${path}`, "HttpOnly", "SameSite=Lax"];
52 // An app's grant set inside the Talk pane's frame is the one cookie that is not Lax (see `framed`).
53 if (o.framed === true) parts[3] = "SameSite=None";
4554 if (o.maxAge !== undefined) {
4655 if (!Number.isInteger(o.maxAge) || o.maxAge < 0) throw new Error(`cookie ${name}'s max-age ${o.maxAge} is not a whole number of seconds`);
4756 parts.push(`Max-Age=${o.maxAge}`);
4857 }
4958 if (o.expires !== undefined) parts.push(`Expires=${o.expires.toUTCString()}`);
50 if (o.secure) parts.push("Secure");
59 if (o.secure || o.framed === true) parts.push("Secure");
60 if (o.framed === true) parts.push("Partitioned");
5161 return parts.join("; ");
5262 }
5363
test/apps-frame-policy.test.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * Who may frame an app (`src/apps/frame_policy.ts`): the forge's own origin, for the Talk pane,
3 * and nobody else. An app that restricts framing keeps the restriction and gains the forge; an app
4 * that frames freely, or says nothing, is not touched.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { admitForgeFrame } from "../src/apps/frame_policy.ts";
8
9 const FORGE = "https://forge.example";
10 const admit = (headers: Record<string, string>): Headers => {
11 const h = new Headers(headers);
12 admitForgeFrame(h, `${FORGE}/talk?x=1`);
13 return h;
14 };
15
16 describe("admitForgeFrame", () => {
17 test("'none' becomes the forge's origin alone", () => {
18 const h = admit({ "content-security-policy": "default-src 'none'; frame-ancestors 'none'; base-uri 'none'" });
19 expect(h.get("content-security-policy")).toBe(`default-src 'none'; frame-ancestors ${FORGE}; base-uri 'none'`);
20 });
21
22 test("'self' and a list keep what they named and gain the forge", () => {
23 expect(admit({ "content-security-policy": "frame-ancestors 'self'" }).get("content-security-policy")).toBe(`frame-ancestors 'self' ${FORGE}`);
24 expect(admit({ "content-security-policy": "frame-ancestors https://a.example" }).get("content-security-policy")).toBe(`frame-ancestors https://a.example ${FORGE}`);
25 });
26
27 test("every policy of a comma list is admitted", () => {
28 const h = admit({ "content-security-policy": "frame-ancestors 'none', default-src 'self'; frame-ancestors 'none'" });
29 expect(h.get("content-security-policy")).toBe(`frame-ancestors ${FORGE}, default-src 'self'; frame-ancestors ${FORGE}`);
30 });
31
32 test("an app that frames freely, or says nothing, is left alone", () => {
33 expect(admit({ "content-security-policy": "frame-ancestors *" }).get("content-security-policy")).toBe("frame-ancestors *");
34 expect(admit({ "content-security-policy": "default-src 'self'" }).get("content-security-policy")).toBe("default-src 'self'");
35 expect(admit({}).get("content-security-policy")).toBeNull();
36 });
37
38 test("X-Frame-Options goes only when a frame-ancestors now says the same with the forge added", () => {
39 const both = admit({ "x-frame-options": "DENY", "content-security-policy": "frame-ancestors 'none'" });
40 expect(both.get("x-frame-options")).toBeNull();
41 expect(both.get("content-security-policy")).toBe(`frame-ancestors ${FORGE}`);
42 const only = admit({ "x-frame-options": "SAMEORIGIN" });
43 expect(only.get("x-frame-options")).toBeNull();
44 expect(only.get("content-security-policy")).toBe(`frame-ancestors ${FORGE}`);
45 // an option the forge does not read (ALLOW-FROM, long gone) is not its to drop
46 expect(admit({ "x-frame-options": "ALLOW-FROM https://a.example" }).get("x-frame-options")).toBe("ALLOW-FROM https://a.example");
47 });
48
49 test("never a blanket: the result never carries * or 'none' beside the forge", () => {
50 const text = admit({ "content-security-policy": "frame-ancestors 'none'" }).get("content-security-policy")!;
51 expect(text).not.toContain("*");
52 expect(text).not.toContain("'none'");
53 });
54
55 test("a forge url that is not http(s) changes nothing", () => {
56 const h = new Headers({ "content-security-policy": "frame-ancestors 'none'" });
57 admitForgeFrame(h, "javascript:alert(1)");
58 expect(h.get("content-security-policy")).toBe("frame-ancestors 'none'");
59 });
60 });
test/helpers/chrome.ts +72 −2
@@ -14,8 +14,8 @@ import { join } from "node:path";
1414 import { browserCommand, browserRefusal } from "../../src/looks/chromium.ts";
1515
1616 /** Start a browser on `profile` with its DevTools port open, as every helper here does. */
17 function start(binary: string, profile: string) {
18 const { argv, env, cwd } = browserCommand(binary, { profile, flags: ["--remote-debugging-port=0"] });
17 function start(binary: string, profile: string, flags: readonly string[] = []) {
18 const { argv, env, cwd } = browserCommand(binary, { profile, flags: ["--remote-debugging-port=0", ...flags] });
1919 return Bun.spawn(argv, { env, cwd, stdin: "ignore", stdout: "ignore", stderr: "pipe" });
2020 }
2121
@@ -552,3 +552,73 @@ export async function observeNavigations(
552552 rmSync(profile, { recursive: true, force: true });
553553 }
554554 }
555
556 /** A frame of a loaded page: where it ended up, and whether it ended on the browser's own error page. */
557 export interface LoadedFrame {
558 url: string;
559 refused: boolean;
560 }
561
562 /**
563 * Load `url` in headless Chromium (with `flags`, for a test's own host names), then wait for every
564 * child frame the page has to stop loading, however it ends, and report them. A frame
565 * the browser refused (a frame policy, a blocked redirect) reports `refused`: it ended on
566 * `chrome-error://`, which a page cannot read across origins but the browser's own tree says.
567 * Waits on the browser's own signals, never a clock.
568 */
569 export async function framesLoaded(
570 binary: string,
571 url: string,
572 cookies: { name: string; value: string; url: string }[],
573 flags: readonly string[],
574 ): Promise<LoadedFrame[]> {
575 const profile = mkdtempSync(join(tmpdir(), "forge-frames-"));
576 const proc = start(binary, profile, flags);
577 let ws: WebSocket | undefined;
578 try {
579 const browserWsUrl = await within(10_000, "printing its devtools address", readDebuggerUrl(proc.stderr));
580 const page = await findPageTarget(browserWsUrl);
581 ws = new WebSocket(page.webSocketDebuggerUrl);
582 await within(5_000, "opening the devtools socket", new Promise<void>((resolve, reject) => {
583 ws!.addEventListener("open", () => resolve());
584 ws!.addEventListener("error", () => reject(new Error("chromium's devtools socket refused the connection")));
585 }));
586 const cdp = new Cdp(ws);
587 await cdp.send("Page.enable");
588 await cdp.send("Network.enable");
589 for (const cookie of cookies) await cdp.send("Network.setCookie", cookie);
590 const stopped = new Set<string>();
591 let wake: (() => void) | undefined;
592 cdp.on("Page.frameStoppedLoading", (params: { frameId: string }) => {
593 stopped.add(params.frameId);
594 wake?.();
595 });
596 const loaded = cdp.once("Page.loadEventFired");
597 await cdp.send("Page.navigate", { url });
598 await within(15_000, `loading ${url}`, loaded);
599 const children = async (): Promise<{ id: string; url: string; unreachable: string | undefined }[]> => {
600 const { frameTree } = await cdp.send("Page.getFrameTree");
601 return ((frameTree.childFrames ?? []) as { frame: { id: string; url: string; unreachableUrl?: string } }[]).map((c) => ({ id: c.frame.id, url: c.frame.url, unreachable: c.frame.unreachableUrl }));
602 };
603 // The frame stops loading on its own signal; wait until every child present has.
604 const settled = within(30_000, "the child frames finishing", (async () => {
605 for (;;) {
606 // Armed before the look, so a frame that stops while the tree is being read still wakes it.
607 const next = new Promise<void>((resolve) => {
608 wake = resolve;
609 });
610 const now = await children();
611 // A frame in the markup is in the tree by the load event; none by then means none.
612 if (now.every((c) => stopped.has(c.id))) return;
613 await next;
614 }
615 })());
616 await settled;
617 return (await children()).map((c) => ({ url: c.unreachable ?? c.url, refused: c.url.startsWith("chrome-error:") }));
618 } finally {
619 ws?.close();
620 proc.kill("SIGKILL");
621 await proc.exited.catch(() => {});
622 rmSync(profile, { recursive: true, force: true });
623 }
624 }
test/talk-preview-frame.test.ts added +185
@@ -0,0 +1,185 @@
1 /**
2 * The Talk pane's frame draws the app it is building (#11009), in a real Chromium: a public app, a
3 * private app for its owner, and nothing at all for a person who may not read the repository. The
4 * app is framed only by the forge's own origin: its answer names that origin in `frame-ancestors`
5 * and nothing else. A private app asked without a grant, from inside a frame, says so in words
6 * instead of redirecting to a page the frame cannot show. Skipped, and says so, where no Chromium
7 * starts. The forge and its apps share a registrable name (`apps.test`, as production's forge and
8 * its app hosts share one), so the grant cookie is first-party in the frame; two hosts are mapped
9 * to loopback for the browser.
10 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { newApp } from "../src/actions/apps.ts";
16 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
17 import { AppsRuntime } from "../src/apps/runtime.ts";
18 import { getAppByRepo } from "../src/core/apps.ts";
19 import { getRepo } from "../src/core/repos.ts";
20 import { createApp, type App } from "../src/app.ts";
21 import { appendTurn, openConversation } from "../src/core/conversations.ts";
22 import { createSession } from "../src/core/sessions.ts";
23 import { createUser, type User } from "../src/core/users.ts";
24 import { findChromium } from "../src/looks/capture.ts";
25 import { serve, type Servers } from "../src/http/server.ts";
26 import { setSsh } from "../src/settings/ssh.ts";
27 import { deploySettled, fetchAsHost } from "./helpers/apps-forge.ts";
28 import { chromiumRuns, framesLoaded } from "./helpers/chrome.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30 import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts";
31 import { promote } from "./helpers/members.ts";
32 import "./helpers/roomy-disk.ts";
33
34 quietLogs();
35
36 const found = findChromium();
37 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
38 if (chromium === undefined) console.log("SKIPPING: no chromium that starts on this machine, so the pane's frame is not drawn");
39
40 const DOMAIN = "apps.test";
41 let dir: string;
42 let app: App;
43 let servers: Servers;
44 let runtime: AppsRuntime;
45 let origin: string;
46 let alice: User;
47 let bob: User;
48 const cookies: Record<string, string> = {};
49
50 const talkFor = (userId: string, repo: string): void => {
51 const chat = openConversation(app.db, userId);
52 appendTurn(app.db, userId, chat.id, { role: "person", text: "show me the app" });
53 appendTurn(app.db, userId, chat.id, { role: "tool", text: `read_file ${JSON.stringify({ repo, path: "README.md" })}` });
54 appendTurn(app.db, userId, chat.id, { role: "agent", text: "Here it is." });
55 };
56
57 beforeAll(async () => {
58 dir = await mkdtemp(join(tmpdir(), "forge-pane-frame-"));
59 app = createApp({ dataDir: dir, port: 0, trustedProxies: LOOPBACK_PROXIES });
60 setSsh(app.db, true, "test");
61 servers = await serve(app);
62 origin = `http://${DOMAIN}:${servers.port}`;
63 runtime = new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: origin, concurrency: 2 });
64 await runtime.start();
65 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
66 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
67 if (!a.ok || !b.ok) throw new Error("users");
68 alice = a.value;
69 bob = b.value;
70 promote(app.db, alice, bob);
71 for (const [name, visibility] of [["pub", "public"], ["priv", "private"]] as const) {
72 const made = await newApp(app, alice, { name, description: name, visibility });
73 if (!made.ok) throw new Error(String(made.error));
74 const run = await deploySettled(app, made.value.repo.id, (r) => r.env === "production");
75 if (run.state !== "ok") throw new Error(`${name} did not deploy: ${run.summary}`);
76 }
77 cookies["alice"] = createSession(app.db, alice.id).token;
78 cookies["bob"] = createSession(app.db, bob.id).token;
79 }, 120_000);
80
81 afterAll(async () => {
82 await runtime.stop();
83 servers.stop();
84 app.close();
85 await rm(dir, { recursive: true, force: true });
86 });
87
88 // The check runs in a cell whose proxy (in the environment) is for the world: this browser only
89 // visits the forge's own listener, directly, as a look's browser does (`lookFlags`).
90 const FLAGS = ["--no-proxy-server", `--host-resolver-rules=MAP ${DOMAIN} 127.0.0.1, MAP *.${DOMAIN} 127.0.0.1`];
91 const talk = (as: "alice" | "bob") => framesLoaded(chromium!, `${origin}/talk`, [{ name: "forge_session", value: cookies[as]!, url: origin }], FLAGS);
92
93 describe("an app's answer", () => {
94 test("is framed by the forge's own origin and no other", async () => {
95 const answer = await fetchAsHost(servers, `pub.${DOMAIN}:${servers.port}`, "/", { headers: { accept: "text/html" } });
96 expect(answer.status).toBe(200);
97 const csp = answer.headers.get("content-security-policy") ?? "";
98 const ancestors = csp.split(";").map((d) => d.trim()).find((d) => d.startsWith("frame-ancestors"));
99 expect(ancestors).toBe(`frame-ancestors ${origin}`);
100 expect(answer.headers.get("x-frame-options")).toBeNull();
101 });
102
103 test("a private app asked from inside a frame, with no grant, says so in words and does not redirect", async () => {
104 const answer = await fetchAsHost(servers, `priv.${DOMAIN}:${servers.port}`, "/", { headers: { accept: "text/html", "sec-fetch-dest": "iframe" } });
105 expect(answer.status).toBe(403);
106 expect(await answer.text()).toContain("Open it on its own");
107 expect(answer.headers.get("location")).toBeNull();
108 // the same request as a page of its own is still sent to sign in
109 const page = await fetchAsHost(servers, `priv.${DOMAIN}:${servers.port}`, "/", { headers: { accept: "text/html", "sec-fetch-dest": "document" } });
110 expect(page.status).toBe(303);
111 });
112 });
113
114 describe("a preview that is not serving, in the pane's frame", () => {
115 test("says so in words, links open beside the frame, and the mark is never sent", async () => {
116 const host = `pub--7.${DOMAIN}:${servers.port}`;
117 const framed = await fetchAsHost(servers, host, "/", { headers: { accept: "text/html", "sec-fetch-dest": "iframe" } });
118 const page = await framed.text();
119 expect(page).toContain("is gone");
120 expect(page).toContain('<base target="_blank">');
121 expect(framed.headers.get("x-forge-holding")).toBeNull();
122 const ancestors = (framed.headers.get("content-security-policy") ?? "").split(";").map((d) => d.trim()).find((d) => d.startsWith("frame-ancestors"));
123 expect(ancestors).toBe(`frame-ancestors ${origin}`);
124 // opened on its own the same page keeps its links in place
125 const own = await fetchAsHost(servers, host, "/", { headers: { accept: "text/html", "sec-fetch-dest": "document" } });
126 expect(await own.text()).not.toContain("<base");
127 });
128 });
129
130 describe("the grant in the frame's address", () => {
131 const targetOf = (name: string): AppTarget => ({ app: getAppByRepo(app.db, getRepo(app.db, "alice", name)!.id)!, env: "production" });
132 const who = () => ({ id: alice.id, name: alice.username, role: "admin" as const });
133 const grantAt = (host: string, token: string, dest = "iframe") =>
134 fetchAsHost(servers, `${host}.${DOMAIN}:${servers.port}`, `/__forge/grant?t=${encodeURIComponent(token)}&to=%2F`, { headers: { accept: "text/html", "sec-fetch-dest": dest } });
135
136 test("is spent at the door: the redirect names a path of the app and never the grant", async () => {
137 const token = signGrant(app.config.dataDir, targetOf("priv"), 60_000, Date.now(), who());
138 const answer = await grantAt("priv", token);
139 expect(answer.status).toBe(303);
140 expect(answer.headers.get("location")).toBe("/");
141 expect(JSON.stringify([...answer.headers])).not.toContain(token);
142 });
143
144 test("an expired grant, and one signed for another app, are refused", async () => {
145 const expired = signGrant(app.config.dataDir, targetOf("priv"), -1_000, Date.now(), who());
146 expect((await grantAt("priv", expired)).status).toBe(404);
147 const other = signGrant(app.config.dataDir, targetOf("pub"), 60_000, Date.now(), who());
148 expect((await grantAt("priv", other)).status).toBe(404);
149 });
150
151 test("in a frame its cookie is kept per embedding site; opened on its own it stays Lax", async () => {
152 const token = signGrant(app.config.dataDir, targetOf("priv"), 60_000, Date.now(), who());
153 const framed = (await grantAt("priv", token, "iframe")).headers.get("set-cookie") ?? "";
154 expect(framed).toContain("SameSite=None");
155 expect(framed).toContain("Secure");
156 expect(framed).toContain("Partitioned");
157 expect(framed).toContain("Max-Age=1800");
158 const own = (await grantAt("priv", token, "document")).headers.get("set-cookie") ?? "";
159 expect(own).toContain("SameSite=Lax");
160 expect(own).not.toContain("Partitioned");
161 });
162 });
163
164 describe("the pane's frame", () => {
165 test.skipIf(chromium === undefined)("draws a public app", async () => {
166 talkFor(alice.id, "alice/pub");
167 const frames = await talk("alice");
168 expect(frames).toHaveLength(1);
169 expect(frames[0]!.refused).toBe(false);
170 expect(frames[0]!.url).toContain(`pub.${DOMAIN}`);
171 }, 60_000);
172
173 test.skipIf(chromium === undefined)("draws a private app for its owner", async () => {
174 talkFor(alice.id, "alice/priv");
175 const frames = await talk("alice");
176 expect(frames).toHaveLength(1);
177 expect(frames[0]!.refused).toBe(false);
178 expect(frames[0]!.url).toContain(`priv.${DOMAIN}`);
179 }, 60_000);
180
181 test.skipIf(chromium === undefined)("draws nothing for a person who may not read the repository", async () => {
182 talkFor(bob.id, "alice/priv");
183 expect(await talk("bob")).toHaveLength(0);
184 }, 60_000);
185 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs