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

A private app's page and its preview answer a signed-out visitor with the same 404, never a hint it exists #13695

Merged opened this

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

Merged

scout/forge:scout/13678-a-private-app-s-page-and-its-preview-ans → main 5 commits fork

  • Merged. scout/13678-a-private-app-s-page-and-its-preview-ans was merged into main as ec2635d.

Review

Sign in to review this change.
4 files changed +184 −35
src/apps/proxy.ts +45 −32
@@ -885,27 +885,8 @@ function admit(
885885 // grant, and otherwise gives the answer a private repository gives.
886886 // Anything that is not a person navigating — a script, an API call —
887887 // gets that answer here.
888 const url = new URL(request.url);
889 const navigating =
890 bearer?.hint === undefined &&
891 // A caller that presented a token is a script, not a person at a
892 // link: it is answered, not sent to sign in.
893 !(request.headers.get("authorization") ?? "").startsWith("Bearer ") &&
894 (request.method === "GET" || request.method === "HEAD") &&
895 (request.headers.get("accept") ?? "").includes("text/html") &&
896 !url.pathname.startsWith("/__forge/");
897 if (navigating) {
898 const host = request.headers.get("host") ?? "";
899 const open = new URL("/apps/open", runtime.options.forgeUrl);
900 open.searchParams.set("host", host);
901 open.searchParams.set("to", url.pathname + url.search);
902 return err(
903 new Response(null, {
904 status: 303,
905 headers: { location: open.toString(), "cache-control": "no-store" },
906 }),
907 );
908 }
888 if (bearer?.hint === undefined && navigating(request))
889 return err(toSignIn(runtime, request));
909890 return err(
910891 new Response(bearer?.hint ?? "not found", {
911892 status: 404,
@@ -987,6 +968,47 @@ export function discoveryLinks(runtime: AppsRuntime, target: AppTarget): string[
987968 const isHtml = (headers: Headers): boolean =>
988969 (headers.get("content-type") ?? "").toLowerCase().startsWith("text/html");
989970
971 /**
972 * A person at a link, not a script: a GET for a page, carrying no token,
973 * outside the forge's own `/__forge/` paths.
974 */
975 function navigating(request: Request): boolean {
976 return (
977 // A caller that presented a token is a script, not a person at a link:
978 // it is answered, not sent to sign in.
979 !(request.headers.get("authorization") ?? "").startsWith("Bearer ") &&
980 (request.method === "GET" || request.method === "HEAD") &&
981 (request.headers.get("accept") ?? "").includes("text/html") &&
982 !new URL(request.url).pathname.startsWith("/__forge/")
983 );
984 }
985
986 /** Off to the forge to sign in, and back to the same path after. */
987 function toSignIn(runtime: AppsRuntime, request: Request, to?: string): Response {
988 const url = new URL(request.url);
989 const open = new URL("/apps/open", runtime.options.forgeUrl);
990 open.searchParams.set("host", request.headers.get("host") ?? "");
991 open.searchParams.set("to", to ?? url.pathname + url.search);
992 return new Response(null, {
993 status: 303,
994 headers: { location: open.toString(), "cache-control": "no-store" },
995 });
996 }
997
998 /**
999 * A hostname shaped like an app's that names none. It answers exactly as a
1000 * private app answers a signed-out visitor — a person navigating is sent to
1001 * sign in, anything else gets the bare 404 — so no one learns from the
1002 * answer whether a private app by that name exists (#13678).
1003 */
1004 export function unknownApp(runtime: AppsRuntime, request: Request): Response {
1005 const url = new URL(request.url);
1006 if (url.pathname === "/__forge/signin")
1007 return securityFloor(toSignIn(runtime, request, safePath(url.searchParams.get("to"))));
1008 if (navigating(request)) return securityFloor(toSignIn(runtime, request));
1009 return securityFloor(new Response("not found", { status: 404 }));
1010 }
1011
9901012 /**
9911013 * Serve a request addressed to an app. `undefined` means the request became
9921014 * a websocket: the response was the handshake, and `appWebSocket` now owns
@@ -1052,17 +1074,8 @@ export async function proxyApp(
10521074 // The two doors an app links to: sign in sends the visitor to the forge,
10531075 // which vouches for them and sends them back named; sign out drops the
10541076 // grant so the app hears nobody again.
1055 if (url.pathname === "/__forge/signin" && !target.nested) {
1056 const open = new URL("/apps/open", runtime.options.forgeUrl);
1057 open.searchParams.set("host", request.headers.get("host") ?? "");
1058 open.searchParams.set("to", safePath(url.searchParams.get("to")));
1059 return securityFloor(
1060 new Response(null, {
1061 status: 303,
1062 headers: { location: open.toString(), "cache-control": "no-store" },
1063 }),
1064 );
1065 }
1077 if (url.pathname === "/__forge/signin" && !target.nested)
1078 return securityFloor(toSignIn(runtime, request, safePath(url.searchParams.get("to"))));
10661079 if (url.pathname === "/__forge/signout" && !target.nested) {
10671080 const secure = proxySecure(request, url, runtime.options.forgeUrl);
10681081 return securityFloor(
src/http/server.ts +2 −2
@@ -664,6 +664,7 @@ import {
664664 isWebSocketHandshake,
665665 proxyApp,
666666 resolveAppHost,
667 unknownApp,
667668 } from "../apps/proxy.ts";
668669
669670 import { stopCellChildren } from "../spawn/cell.ts";
@@ -3040,8 +3041,7 @@ export async function serve(app: App): Promise<Servers> {
30403041 return withHeader(response, "connection", "close");
30413042 }
30423043 }
3043 if (ownUnknown)
3044 return securityFloor(new Response("not found", { status: 404 }));
3044 if (ownUnknown && runtime !== undefined) return securityFloor(unknownApp(runtime, request));
30453045 notePeer(request, server.requestIP(request)?.address, trust);
30463046 // A writer's shell into a machine: decided here, before any route,
30473047 // because an upgrade is answered by the socket, not a response.
src/web/pages/apps.ts +4 −1
@@ -826,9 +826,12 @@ function appsOpenResponse(ctx: Ctx): Response {
826826 const path =
827827 wanted.startsWith("/") && !wanted.startsWith("//") ? wanted : "/";
828828 if (runtime === undefined || !isHostPort(host)) return notFoundPage(ctx);
829 // Signed out, every app-shaped host is sent to sign in before it is looked
830 // up: a private app and a name nobody holds answer alike (#13678).
829831 const target = resolveAppHostname(ctx.app, runtime.options.domain, host);
830 if (target === undefined || target === "unknown") return notFoundPage(ctx);
832 if (target === undefined) return notFoundPage(ctx);
831833 if (!ctx.auth.user) return signInFirst(ctx);
834 if (target === "unknown") return notFoundPage(ctx);
832835 const repo = getRepoById(ctx.app.db, target.app.repoId);
833836 if (!repo) return notFoundPage(ctx);
834837 const link = openEnvUrl(ctx.app, ctx.auth.user, repo, target.env, path, host);
test/private-404.test.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * A private app is not there to a signed-out visitor (#13678): its page on
3 * the forge, its API, its production and preview hosts, a file on them and
4 * the sign-in hand-off answer exactly as a name nobody holds does — the same
5 * status, the same kind of body, a size that differs only by the name's own
6 * length. Its owner, signed in, still reaches each of them.
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 { newApp } from "../src/actions/apps.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { AppsRuntime } from "../src/apps/runtime.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 // The same length as "ledger", so a body that names the app is the same size.
24 const PRIVATE = "ledger";
25 const MISSING = "nobody";
26
27 describe("a private app answers a signed-out visitor as a missing one", () => {
28 let dataDir: string;
29 let app: App;
30 let servers: Servers;
31 let runtime: AppsRuntime;
32 let owner = "";
33
34 beforeAll(async () => {
35 dataDir = await mkdtemp(join(tmpdir(), "forge-private-404-"));
36 app = createApp({ dataDir, port: 0, host: "forge.test" });
37 servers = await serve(app);
38 runtime = new AppsRuntime(app, {
39 domain: DOMAIN,
40 scheme: "http",
41 publicPort: servers.port,
42 forgeUrl: servers.url,
43 concurrency: 1,
44 });
45 await runtime.start();
46 const alice = await createUser(app.db, { origin: "seed", trusted: true,
47 username: "alice",
48 email: "[email protected]",
49 password: "a-good-passphrase",
50 adminIfFirst: true,
51 });
52 if (!alice.ok) throw new Error(alice.error);
53 const made = await newApp(app, alice.value, { name: PRIVATE, description: "Books", visibility: "private" });
54 if (!made.ok) throw new Error(String(made.error));
55 expect(made.value.app.access).toBe("private");
56 const signin = await fetch(`${servers.url}/signin`, {
57 method: "POST",
58 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
59 redirect: "manual",
60 });
61 owner = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
62 }, 120_000);
63
64 afterAll(async () => {
65 await runtime.stop();
66 servers.stop();
67 app.close();
68 await rm(dataDir, { recursive: true, force: true });
69 });
70
71 /** `[path, app host or undefined for the forge's own]`, N standing for the name. */
72 const PLACES: readonly (readonly [string, string | undefined])[] = [
73 ["/", `N.${DOMAIN}`],
74 ["/assets/report.pdf", `N.${DOMAIN}`],
75 ["/", `N--3.${DOMAIN}`],
76 ["/notes/a.txt", `N--3.${DOMAIN}`],
77 ["/__forge/", `N.${DOMAIN}`],
78 ["/__forge/signin?to=%2F", `N.${DOMAIN}`],
79 ["/alice/N", undefined],
80 ["/alice/N/app", undefined],
81 ["/alice/N/blob/main/README.md", undefined],
82 ["/api/v1/repos/alice/N", undefined],
83 ["/api/v1/repos/alice/N/app", undefined],
84 [`/apps/open?host=N.${DOMAIN}&to=%2F`, undefined],
85 [`/apps/open?host=N--3.${DOMAIN}&to=%2F`, undefined],
86 ];
87 const ACCEPTS = ["text/html", "application/json", "*/*"];
88
89 const ask = async (name: string, path: string, host: string | undefined, accept: string, cookie = "") => {
90 const res = await fetch(`${servers.url}${path.replaceAll("N", name)}`, {
91 headers: {
92 accept,
93 ...(host === undefined ? {} : { host: host.replace("N", name) }),
94 ...(cookie ? { cookie } : {}),
95 },
96 redirect: "manual",
97 });
98 const body = await res.text();
99 const location = res.headers.get("location");
100 return {
101 status: res.status,
102 type: res.headers.get("content-type"),
103 // Only the order of magnitude: a page that names what was asked for
104 // differs by those bytes alone.
105 size: body.length === 0 ? 0 : Math.round(Math.log10(body.length)),
106 location: location?.replaceAll(name, "N") ?? null,
107 };
108 };
109
110 for (const accept of ACCEPTS)
111 for (const [path, host] of PLACES)
112 test(`${host ?? "forge"} ${path} (${accept})`, async () => {
113 const hidden = await ask(PRIVATE, path, host, accept);
114 const missing = await ask(MISSING, path, host, accept);
115 expect(hidden).toEqual(missing);
116 // Never an answer that is the app's own: refused, sent to sign in.
117 expect([303, 404]).toContain(hidden.status);
118 });
119
120 test("the signed-in owner still reaches the app's page, API and hand-off", async () => {
121 for (const path of ["/alice/N", "/api/v1/repos/alice/N", "/api/v1/repos/alice/N/app"]) {
122 const res = await ask(PRIVATE, path, undefined, "text/html", owner);
123 expect({ path, status: res.status, location: res.location }).toEqual({ path, status: 200, location: null });
124 }
125 for (const host of [`N.${DOMAIN}`, `N--3.${DOMAIN}`]) {
126 const res = await ask(PRIVATE, `/apps/open?host=${host}&to=%2F`, undefined, "text/html", owner);
127 expect(res.status).toBe(302);
128 expect(new URL(res.location!).pathname).toBe("/__forge/grant");
129 // A name nobody holds stays a 404 to the owner too.
130 expect((await ask(MISSING, `/apps/open?host=${host}&to=%2F`, undefined, "text/html", owner)).status).toBe(404);
131 }
132 });
133 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs