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

A private app's /__forge/* doors answer a stranger exactly as a name nobody holds #15208

Merged opened this

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

Merged

torque/forge:torque/15200-a-private-app-s-forge-doors-answer-a-str → main 2 commits fork

  • Merged. torque/15200-a-private-app-s-forge-doors-answer-a-str was merged into main as 1b87279.

Review

Sign in to review this change.
6 files changed +226 −41
src/apps/proxy.ts +46 −16
@@ -846,17 +846,26 @@ function bearerAdmission(
846846 : { hint: NOT_ENTITLED_WORDS };
847847 }
848848
849 /** Whether this app answers only those it admits: a private app, or a sealed pull's preview. */
850 function guardedTarget(runtime: AppsRuntime, target: AppTarget): boolean {
851 // Only a pull's preview can be sealed; production is asked nothing of the database.
852 return (
853 target.app.access === "private" ||
854 (target.env.startsWith("pull-") && sealedPull(runtime, target) !== undefined)
855 );
856 }
857
849858 /**
850 * What a request addressed to an app must pass before anything is served:
851 * a private app's grant, then a live port. One gate for both the request
852 * that is fetched and the one that becomes a socket — the answer when a
853 * gate refuses is the response to send instead.
859 * Who a request comes as, asked before anything else of a guarded app: the
860 * grant it carries, if it still names someone who may enter. A stranger is
861 * answered exactly as a name nobody holds (`unknownApp`), so no door, no
862 * wake and no preview tells them the app is there (#15200).
854863 */
855 function admit(
864 function vouch(
856865 runtime: AppsRuntime,
857866 request: Request,
858867 target: AppTarget,
859 ): Result<{ status: EnvStatus; port: number; grant?: Grant }, Response> {
868 ): Result<Grant | undefined, Response> {
860869 const cookie = cookieValue(request, grantCookieName(target));
861870 const cookieGrant =
862871 cookie === undefined
@@ -906,9 +915,7 @@ function admit(
906915 : getUserById(runtime.app.db, signed.who.id);
907916 // A sealed pull's preview is held like a private app's, whatever the
908917 // app's own access: asked on every request.
909 const guarded =
910 target.app.access === "private" ||
911 sealedPull(runtime, target) !== undefined;
918 const guarded = guardedTarget(runtime, target);
912919 const lapsed =
913920 signed !== undefined &&
914921 ((guarded && !stillEntitled(runtime, target, signed)) ||
@@ -920,19 +927,34 @@ function admit(
920927 // for them if they may enter the app and sends them back with the
921928 // grant, and otherwise gives the answer a private repository gives.
922929 // Anything that is not a person navigating — a script, an API call —
923 // gets that answer here.
924 if (bearer?.hint === undefined && navigating(request))
925 return err(toSignIn(runtime, request));
930 // gets that answer here. A reader's token that may not enter is told
931 // why: its holder already knows the app is there.
932 if (bearer?.hint === undefined) return err(unknownApp(runtime, request));
926933 return err(
927 new Response(bearer?.hint ?? "not found", {
934 new Response(bearer.hint, {
928935 status: 404,
929 ...(bearer?.hint === undefined
930 ? {}
931 : { headers: { "content-type": "text/plain; charset=utf-8" } }),
936 headers: { "content-type": "text/plain; charset=utf-8" },
932937 }),
933938 );
934939 }
935940 }
941 return ok(grant);
942 }
943
944 /**
945 * What a request addressed to an app must pass before anything is served:
946 * a private app's grant, then a live port. One gate for both the request
947 * that is fetched and the one that becomes a socket — the answer when a
948 * gate refuses is the response to send instead.
949 */
950 function admit(
951 runtime: AppsRuntime,
952 request: Request,
953 target: AppTarget,
954 ): Result<{ status: EnvStatus; port: number; grant?: Grant }, Response> {
955 const vouched = vouch(runtime, request, target);
956 if (!vouched.ok) return vouched;
957 const grant = vouched.value;
936958 // An archived repository's app is put away: stopped, its data kept, and
937959 // never woken by a visit.
938960 const repo = getRepoById(runtime.app.db, target.app.repoId);
@@ -1065,6 +1087,14 @@ export async function proxyApp(
10651087 ): Promise<Response | undefined> {
10661088 const entered = performance.now();
10671089 const url = new URL(request.url);
1090 // A private app or a sealed preview asks who is there before any door,
1091 // any relay and any wake: a stranger gets the answer a name nobody holds
1092 // gets, byte for byte. The grant door is how one comes to be admitted;
1093 // a token it cannot read is that same 404 already.
1094 if (url.pathname !== "/__forge/grant" && guardedTarget(runtime, target)) {
1095 const vouched = vouch(runtime, request, target);
1096 if (!vouched.ok) return securityFloor(vouched.error);
1097 }
10681098 // A webhook for a pull's preview, sent to production's stable address.
10691099 if (url.pathname.startsWith(HOOK_PREFIX) && !target.nested && target.env === "production") {
10701100 const hook = hookPath(url.pathname);
test/apps-crew-side.test.ts +15 −12
@@ -81,7 +81,7 @@ afterAll(async () => {
8181 await rm(dataDir, { recursive: true, force: true });
8282 });
8383
84 const crew = async (host: string, as?: { id: string; name: string }) => {
84 const crew = async (host: string, as?: { id: string; name: string }, status = 200) => {
8585 const cookie =
8686 as === undefined
8787 ? undefined
@@ -95,8 +95,9 @@ const crew = async (host: string, as?: { id: string; name: string }) => {
9595 const res = await fetch(`${servers.url}/__forge/crew`, {
9696 headers: { host, ...(cookie === undefined ? {} : { cookie }) },
9797 });
98 expect(res.status).toBe(200);
98 expect(res.status).toBe(status);
9999 const text = await res.text();
100 if (status !== 200) return { text, json: {} as { side?: { label: string; url: string } } };
100101 return { text, json: JSON.parse(text) as { side?: { label: string; url: string } } };
101102 };
102103
@@ -116,18 +117,20 @@ test("a preview names production to a reader", async () => {
116117 expect(json.side).toEqual({ label: "Open on production", url: runtime.urlFor(vault, "production") });
117118 });
118119
120 /**
121 * A private app's crew door to someone it does not admit: the bare 404 a missing name gets
122 * (#15200).
123 */
124 const refused = async (host: string, as?: { id: string; name: string }) => {
125 const res = await crew(host, as, 404);
126 expect(res.text).toBe("not found");
127 expect(res.text).not.toContain("secret plan");
128 };
129
119130 test("a guest of a private app gets no side, and no pull title", async () => {
120 for (const host of [prod, pre()]) {
121 const { text, json } = await crew(host);
122 expect(json.side).toBeUndefined();
123 expect(text).not.toContain("secret plan");
124 }
131 for (const host of [prod, pre()]) await refused(host);
125132 });
126133
127134 test("a signed-in stranger of a private app gets no side, and no pull title", async () => {
128 for (const host of [prod, pre()]) {
129 const { text, json } = await crew(host, { id: bob, name: "bob" });
130 expect(json.side).toBeUndefined();
131 expect(text).not.toContain("secret plan");
132 }
135 for (const host of [prod, pre()]) await refused(host, { id: bob, name: "bob" });
133136 });
test/apps-proxy-doors.test.ts +12 −1
@@ -7,7 +7,8 @@
77
88 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
99 import { newApp } from "../src/actions/apps.ts";
10 import { safePath } from "../src/apps/proxy.ts";
10 import { safePath, signGrant, type AppTarget } from "../src/apps/proxy.ts";
11 import { getAppByRepo } from "../src/core/apps.ts";
1112 import type { Repo } from "../src/core/repos.ts";
1213 import { mintRunToken } from "../src/core/run_token.ts";
1314 import { createToken } from "../src/core/tokens.ts";
@@ -60,12 +61,21 @@ describe("an app host's doors", () => {
6061 });
6162
6263 test("sign out's `to` keeps a deep link and drops an escape", async () => {
64 // Only someone the private app admits is answered by its doors (#15200).
65 const target = { app: getAppByRepo(forge.app.db, repo.id)!, env: "production" } as AppTarget;
66 const grant = signGrant(forge.app.config.dataDir, target, 60_000, Date.now(), {
67 id: forge.alice.id,
68 name: forge.alice.username,
69 role: "admin",
70 });
71 const headers = { cookie: `forge_grant_${target.app.id.slice(-8)}=${grant}` };
6372 const where = async (to: string) =>
6473 (
6574 await fetchAsHost(
6675 forge.servers,
6776 host(),
6877 `/__forge/signout?to=${encodeURIComponent(to)}`,
78 { headers },
6979 )
7080 ).headers.get("location");
7181 expect(await where("/a?b")).toBe("/a?b");
@@ -76,6 +86,7 @@ describe("an app host's doors", () => {
7686 forge.servers,
7787 host(),
7888 "/__forge/signout?to=/%09/evil.example",
89 { headers },
7990 );
8091 expect(raw.headers.get("location")).toBe("/");
8192 });
test/apps-toolbar-yours.test.ts +15 −6
@@ -7,7 +7,7 @@ import { join } from "node:path";
77 import { createApp, type App } from "../src/app.ts";
88 import { newApp } from "../src/actions/apps.ts";
99 import { yoursLink } from "../src/apps/crew.ts";
10 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
10 import { signGrant, type AppTarget, type GrantWho } from "../src/apps/proxy.ts";
1111 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
1212 import { toolbarJs } from "../src/apps/toolbar.ts";
1313 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
@@ -120,9 +120,9 @@ test("a private app is offered nothing", () => {
120120 test("the endpoint takes who the reader is from the grant, never the client", async () => {
121121 const target = { app: pub, env: "production" } as AppTarget;
122122 const cookie = `forge_grant_${pub.id.slice(-8)}`;
123 const ask = async (who: { id: string; name: string; role: string }) =>
123 const ask = async (who: GrantWho) =>
124124 (await fetch(`${servers.url}/__forge/crew`, {
125 headers: { host: `pubapp.${DOMAIN}`, cookie: `${cookie}=${signGrant(dataDir, target, 60_000, Date.now(), who as never)}` },
125 headers: { host: `pubapp.${DOMAIN}`, cookie: `${cookie}=${signGrant(dataDir, target, 60_000, Date.now(), who)}` },
126126 })).json() as Promise<{ yours?: string }>;
127127 expect((await ask({ id: bob, name: "bob", role: "user" })).yours).toBe(`${servers.url}/alice/pubapp/make-it-yours`);
128128 expect((await ask({ id: alice, name: "alice", role: "admin" })).yours).toBeUndefined();
@@ -140,14 +140,23 @@ test("a read-only member of a public repository is offered the link; a suspended
140140
141141 const crewAt = async (host: string, who?: string, env = "production") => {
142142 const target = { app: pub, env } as AppTarget;
143 const cookie = who === undefined ? {} : { cookie: `forge_grant_${pub.id.slice(-8)}=${signGrant(dataDir, target, 60_000, Date.now(), { id: who, name: "x", role: "user" } as never)}` };
143 const cookie = who === undefined ? {} : { cookie: `forge_grant_${pub.id.slice(-8)}=${signGrant(dataDir, target, 60_000, Date.now(), { id: who, name: "x", role: "user" })}` };
144144 return (await fetch(`${servers.url}/__forge/crew`, { headers: { host, ...cookie } })).json() as Promise<{ yours?: string }>;
145145 };
146146
147147 test("through the proxy, a preview of a sealed pull offers no link; an open pull's does", async () => {
148148 expect((await crewAt(`pubapp--${openPull}.${DOMAIN}`, bob, `pull-${openPull}`)).yours).toBe(`${servers.url}/alice/pubapp/make-it-yours`);
149 expect((await crewAt(`pubapp--${sealedPullNo}.${DOMAIN}`, bob, `pull-${sealedPullNo}`)).yours).toBeUndefined();
150 expect((await crewAt(`pubapp--${sealedPullNo}.${DOMAIN}`)).yours).toBeUndefined();
149 // Someone who may not see the sealed pull, signed in or not, is not answered by its preview's
150 // crew door at all (#15200).
151 const sealedTarget = { app: pub, env: `pull-${sealedPullNo}` } as AppTarget;
152 const bobs = `forge_grant_${pub.id.slice(-8)}=${signGrant(dataDir, sealedTarget, 60_000, Date.now(), { id: bob, name: "x", role: "user" })}`;
153 for (const cookie of [bobs, undefined]) {
154 const stranger = await fetch(`${servers.url}/__forge/crew`, {
155 headers: { host: `pubapp--${sealedPullNo}.${DOMAIN}`, ...(cookie === undefined ? {} : { cookie }) },
156 });
157 expect(stranger.status).toBe(404);
158 expect(await stranger.text()).toBe("not found");
159 }
151160 expect((await crewAt(`pubapp.${DOMAIN}`, gone)).yours).toBeUndefined();
152161 });
153162
test/private-404.test.ts +128 −1
@@ -4,6 +4,11 @@
44 * the sign-in hand-off answer exactly as a name nobody holds does — the same
55 * status, the same kind of body, a size that differs only by the name's own
66 * length. Its owner, signed in, still reaches each of them.
7 *
8 * The forge's own doors on the app's host (`/__forge/*`) answer a stranger
9 * byte for byte as the same path on a name nobody holds, a preview's hook
10 * says nothing of whether the preview exists, and nothing a stranger asks
11 * wakes the app (#15200).
712 */
813
914 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
@@ -12,7 +17,11 @@ import { tmpdir } from "node:os";
1217 import { join } from "node:path";
1318 import { newApp } from "../src/actions/apps.ts";
1419 import { createApp, type App } from "../src/app.ts";
15 import { AppsRuntime } from "../src/apps/runtime.ts";
20 import { HOOK_PREFIX } from "../src/apps/hook_relay.ts";
21 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
22 import { HIDE_PATH, TOOLBAR_ASSET_PATH } from "../src/apps/toolbar.ts";
23 import { COMMENT_ASSET_PATH } from "../src/apps/toolbar_comment.ts";
24 import { TOUR_ASSET_PATH } from "../src/apps/tour.ts";
1625 import { createUser } from "../src/core/users.ts";
1726 import { serve, type Servers } from "../src/http/server.ts";
1827 import { quietLogs } from "./helpers/globals.ts";
@@ -117,6 +126,124 @@ describe("a private app answers a signed-out visitor as a missing one", () => {
117126 expect([303, 404]).toContain(hidden.status);
118127 });
119128
129 /** `[method, path]` of each forge door on the app's own host. */
130 const DOORS: readonly (readonly [string, string])[] = [
131 ["GET", "/__forge/crew"],
132 ["GET", "/__forge/signout?to=%2F"],
133 ["GET", TOOLBAR_ASSET_PATH],
134 ["GET", TOUR_ASSET_PATH],
135 ["GET", COMMENT_ASSET_PATH],
136 ["GET", "/__forge/toolbar-nothing.js"],
137 ["GET", "/__forge/report?from=%2F"],
138 ["GET", "/__forge/notes"],
139 ["POST", "/__forge/note"],
140 ["POST", "/__forge/note/picture?note=x"],
141 ["GET", "/__forge/note/moderate"],
142 ["POST", "/__forge/comment"],
143 ["POST", "/__forge/measure"],
144 ["POST", `${HIDE_PATH}?on=1`],
145 ["GET", "/__forge/notebook"],
146 ["GET", `${HOOK_PREFIX}3/x`],
147 ["POST", `${HOOK_PREFIX}3/x`],
148 ["POST", `${HOOK_PREFIX}4/x`],
149 ];
150
151 /** The whole answer, with the name put back and only the date left out. */
152 const exact = async (name: string, method: string, path: string, cookie = "") => {
153 const res = await fetch(`${servers.url}${path}`, {
154 method,
155 headers: {
156 host: `${name}.${DOMAIN}`,
157 accept: "*/*",
158 origin: `http://${name}.${DOMAIN}`,
159 "sec-fetch-site": "same-origin",
160 ...(method === "POST" ? { "content-type": "application/json" } : {}),
161 ...(cookie ? { cookie } : {}),
162 },
163 ...(method === "POST" ? { body: "{}" } : {}),
164 redirect: "manual",
165 });
166 const headers = [...res.headers]
167 .filter(([k]) => k !== "date")
168 .map(([k, v]) => `${k}: ${v.replaceAll(name, "N")}`)
169 .sort();
170 return { status: res.status, headers, body: (await res.text()).replaceAll(name, "N") };
171 };
172
173 /** Pull 3 has a preview on the private app; production is asleep. Records each wake. */
174 const staged = () => {
175 const status = runtime.envStatus.bind(runtime);
176 const wake = runtime.wake.bind(runtime);
177 const woken: string[] = [];
178 runtime.envStatus = (record, env) =>
179 record.slug === PRIVATE && (env === "production" || env === "pull-3")
180 ? ({ env, state: env === "production" ? "asleep" : "running", port: 1 } as EnvStatus)
181 : status(record, env);
182 runtime.wake = async (record, env) => {
183 woken.push(`${record.slug}/${env}`);
184 return undefined;
185 };
186 return {
187 woken,
188 restore: () => {
189 runtime.envStatus = status;
190 runtime.wake = wake;
191 },
192 };
193 };
194
195 for (const [method, path] of DOORS)
196 test(`a stranger's ${method} ${path} is a missing name's, and wakes nothing`, async () => {
197 const stage = staged();
198 try {
199 const hidden = await exact(PRIVATE, method, path);
200 const missing = await exact(MISSING, method, path);
201 expect(hidden).toEqual(missing);
202 expect(stage.woken).toEqual([]);
203 } finally {
204 stage.restore();
205 }
206 });
207
208 test("a stranger's page on an asleep private app does not wake it", async () => {
209 const stage = staged();
210 try {
211 for (const accept of ACCEPTS) await ask(PRIVATE, "/", `N.${DOMAIN}`, accept);
212 expect(stage.woken).toEqual([]);
213 } finally {
214 stage.restore();
215 }
216 });
217
218 test("the admitted owner still opens the doors, and wakes the app", async () => {
219 const open = await fetch(`${servers.url}/apps/open?host=${PRIVATE}.${DOMAIN}&to=%2F`, {
220 headers: { cookie: owner },
221 redirect: "manual",
222 });
223 const to = new URL(open.headers.get("location")!);
224 const granted = await fetch(`${servers.url}${to.pathname}${to.search}`, {
225 headers: { host: `${PRIVATE}.${DOMAIN}` },
226 redirect: "manual",
227 });
228 expect(granted.status).toBe(303);
229 const grant = (granted.headers.get("set-cookie") ?? "").split(";")[0]!;
230 const stage = staged();
231 try {
232 expect((await exact(PRIVATE, "GET", "/__forge/crew", grant)).status).toBe(200);
233 expect((await exact(PRIVATE, "GET", TOOLBAR_ASSET_PATH, grant)).status).toBe(200);
234 // The note door answers for itself (here: no notes on this app), never the bare 404.
235 expect((await exact(PRIVATE, "GET", "/__forge/notes", grant)).body).toContain("not_found");
236 const out = await exact(PRIVATE, "GET", "/__forge/signout?to=%2F", grant);
237 expect(out.status).toBe(303);
238 // A hook for a pull with no preview is the forge's 404; the one with a preview is relayed.
239 expect((await exact(PRIVATE, "POST", `${HOOK_PREFIX}4/x`, grant)).status).toBe(404);
240 await exact(PRIVATE, "GET", "/", grant);
241 expect(stage.woken).toEqual([`${PRIVATE}/production`]);
242 } finally {
243 stage.restore();
244 }
245 });
246
120247 test("the signed-in owner still reaches the app's page, API and hand-off", async () => {
121248 for (const path of ["/alice/N", "/api/v1/repos/alice/N", "/api/v1/repos/alice/N/app"]) {
122249 const res = await ask(PRIVATE, path, undefined, "text/html", owner);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs