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

Apps see the visitor's scheme: x-forwarded-proto is forwarded, not this hop's (Glint's fix, muse/forge#1) #13720

Merged opened this in answer to

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

Merged

scout/forge:scout/13711-apps-see-the-visitor-s-scheme-x-forwarde → main 2 commits fork

  • Merged. scout/13711-apps-see-the-visitor-s-scheme-x-forwarde was merged into main as e71223b.

Review

Sign in to review this change.
2 files changed +121 −1
src/apps/proxy.ts +18 −1
@@ -79,6 +79,23 @@ const proxySecure = (request: Request, url: URL, forgeUrl: string): boolean =>
7979 secureFor(url, forgeUrl) ||
8080 request.headers.get("x-forwarded-proto") === "https";
8181
82 /**
83 * The scheme the visitor used, not this hop's: the edge ends TLS and speaks
84 * http to the forge, so an app reading the URL's scheme would see `http` and
85 * refuse its own https Origin. It is `https` when this request is https or
86 * the hop in front says so (`x-forwarded-proto`, first value); anything else
87 * is `http`. The forge's own address is deliberately not consulted: an https
88 * forge also answers http visitors, and labelling them https would lie.
89 * The incoming header is writable by a client that reaches the forge
90 * directly, but it can only change the scheme its own request is labelled
91 * with; the app sees what that client claimed, as with any proxy header.
92 */
93 export const forwardedProto = (request: Request, url: URL): "http" | "https" =>
94 url.protocol === "https:" ||
95 request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase() === "https"
96 ? "https"
97 : "http";
98
8299 export interface AppTarget {
83100 readonly app: AppRecord;
84101 readonly env: EnvName;
@@ -1300,7 +1317,7 @@ export async function proxyApp(
13001317 for (const name of IDENTITY_HEADERS) headers.delete(name);
13011318 stripForgeCredentials(headers, grantCookieName(target));
13021319 headers.set("x-forwarded-host", request.headers.get("host") ?? "");
1303 headers.set("x-forwarded-proto", url.protocol.replace(":", ""));
1320 headers.set("x-forwarded-proto", forwardedProto(request, url));
13041321 for (const [name, value] of Object.entries(
13051322 identityHeaders(runtime.app.config.dataDir, target.app.id, vouched),
13061323 ))
test/apps-proxy-forwarded-proto.test.ts added +103
@@ -0,0 +1,103 @@
1 /** The app behind the proxy receives the visitor's scheme in x-forwarded-proto (#13711). */
2
3 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { newApp } from "../src/actions/apps.ts";
9 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
10 import { forwardedProto } from "../src/apps/proxy.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 const DOMAIN = "apps.test";
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 let runtime: AppsRuntime;
22 let backend: ReturnType<typeof Bun.serve>;
23 let status: ReturnType<typeof spyOn>;
24
25 beforeAll(async () => {
26 // The app: answers with the scheme header it received.
27 backend = Bun.serve({
28 port: 0,
29 fetch: (req) =>
30 new Response(req.headers.get("x-forwarded-proto") ?? "none", {
31 headers: { "content-type": "text/plain" },
32 }),
33 });
34 dataDir = await mkdtemp(join(tmpdir(), "forge-proxy-proto-"));
35 app = createApp({ dataDir, port: 0, host: "forge.test" });
36 servers = await serve(app);
37 // The forge's own address is https, as behind the edge: it must not
38 // relabel an http visitor.
39 runtime = new AppsRuntime(app, {
40 domain: DOMAIN,
41 scheme: "http",
42 publicPort: servers.port,
43 forgeUrl: "https://forge.test",
44 concurrency: 1,
45 });
46 await runtime.start();
47 status = spyOn(AppsRuntime.prototype, "envStatus").mockImplementation(
48 () =>
49 ({
50 env: "production",
51 state: "running",
52 port: backend.port,
53 commitOid: "a".repeat(40),
54 }) as EnvStatus,
55 );
56 const u = await createUser(app.db, {
57 origin: "seed", trusted: true, username: "alice",
58 email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true,
59 });
60 if (!u.ok) throw new Error(u.error);
61 const made = await newApp(app, u.value, { name: "notes", description: "x", visibility: "public" });
62 if (!made.ok) throw new Error(String(made.error));
63 }, 120_000);
64
65 afterAll(async () => {
66 status.mockRestore();
67 await runtime.stop();
68 servers.stop();
69 backend.stop(true);
70 app.close();
71 await rm(dataDir, { recursive: true, force: true });
72 });
73
74 const seen = async (extra: Record<string, string> = {}) => {
75 const r = await fetch(`${servers.url}/`, {
76 headers: { host: `notes.${DOMAIN}`, ...extra },
77 redirect: "manual",
78 });
79 expect(r.status).toBe(200);
80 return r.text();
81 };
82
83 test("a visitor the edge says came over https reaches the app as https", async () => {
84 expect(await seen({ "x-forwarded-proto": "https" })).toBe("https");
85 });
86
87 test("a plain http request reaches the app as http, even with an https forge address", async () => {
88 expect(await seen()).toBe("http");
89 });
90
91 test("a junk incoming value reaches the app as http, never echoed", async () => {
92 expect(await seen({ "x-forwarded-proto": "gopher" })).toBe("http");
93 });
94
95 test("forwardedProto: https request url, first list value, and nothing else", () => {
96 const ask = (url: string, h: Record<string, string> = {}) => {
97 const r = new Request(url, { headers: h });
98 return forwardedProto(r, new URL(r.url));
99 };
100 expect(ask("https://a.test/")).toBe("https");
101 expect(ask("http://a.test/", { "x-forwarded-proto": "HTTPS, http" })).toBe("https");
102 expect(ask("http://a.test/", { "x-forwarded-proto": "http, https" })).toBe("http");
103 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs