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

An app that is refused an outside host by the forge's gate says so in its own… #12185

opened this in answer to

Parked 18d 8h ago

torque/forge:torque/12182-an-app-that-is-refused-an-outside-host-b → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +109 −13
docs/features/blocked-hosts.md +4
@@ -8,3 +8,7 @@ When a production cell is refused a host, the forge says so: `apps/egress_refuse
88 - **Ignore:** keeps the row and its count, stops saying it.
99 - **No wildcards** are offered; an owner who wants `*.hf.co` writes it in `forge.json`.
1010 - **Private, LAN and tailnet** destinations are never allowed live: an owner who is not a site admin cannot allow one, and a site admin only gets it into `forge.json`; the grant (`core/egress_grants.ts`) stays the gate.
11
12 ## Said as the forge's own (#12182)
13
14 The gate answers a host `forge.json` `egress` does not list with `403 Refused by this forge`, the header `X-Forge-Egress: refused` and `X-Forge-Egress-Host: <host>`, and a body that starts `refused by this forge: <host> is not in this app's forge.json egress`. An app must not read that as the remote server's 403. The app template ships `src/egress.ts` (`refusedByForge`, `checkedFetch`) to recognise it, and `src/egress.test.ts`, which fails with one line when the app's code fetches a literal host (or one read from an env name ending `URL`, `HOST`, `ENDPOINT` or `BASE`) that `egress` does not declare. The crew's brief tells a builder to declare the host in the same change. The first refusal of a host is an event and a needs-you line on the app's settings page (Allow, live with no redeploy); the forge's log names the app and host once an hour.
src/apps/egress.ts +19 −4
@@ -410,6 +410,13 @@ export function isPublicAddress(address: string): boolean {
410410 return false;
411411 }
412412
413 /**
414 * What an app reads when the gate refuses it a host (#12182): the status
415 * reason and the body both start with this, so app code and a person tell
416 * the forge's refusal from the remote server's own 403.
417 */
418 export const REFUSED_BY_FORGE = "refused by this forge";
419
413420 export type Verdict =
414421 | { ok: true; address: string; undeclared: boolean }
415422 | { ok: false; why: string; policy?: { private: boolean } };
@@ -443,7 +450,7 @@ export async function decide(
443450 if (!declared && (policy.report === undefined || payment || !WEB_PORTS.includes(port)))
444451 return {
445452 ok: false,
446 why: `${name}:${port} is not in this repository's egress (forge.json "egress")`,
453 why: `${REFUSED_BY_FORGE}: ${port === 443 || port === 80 ? name : `${name}:${port}`} is not in this app's forge.json egress`,
447454 policy: { private: false },
448455 };
449456 // Inside a cell, the cell's proxy resolves and checks the name itself.
@@ -545,11 +552,11 @@ function flush(
545552 const encoder = new TextEncoder();
546553 const decoder = new TextDecoder();
547554
548 function refuse(client: Socket<Conn>, status: string, why: string): void {
555 function refuse(client: Socket<Conn>, status: string, why: string, host?: string): void {
549556 client.data.done = true;
550557 client.end(
551558 encoder.encode(
552 `HTTP/1.1 ${status}\r\nContent-Type: text/plain\r\nX-Forge-Egress: refused\r\nConnection: close\r\nContent-Length: ${encoder.encode(why).length + 1}\r\n\r\n${why}\n`,
559 `HTTP/1.1 ${status}\r\nContent-Type: text/plain\r\nX-Forge-Egress: refused\r\n${host === undefined || !/^[a-z0-9._:\[\]-]{1,255}$/.test(host) ? "" : `X-Forge-Egress-Host: ${host}\r\n`}Connection: close\r\nContent-Length: ${encoder.encode(why).length + 1}\r\n\r\n${why}\n`,
553560 ),
554561 );
555562 }
@@ -633,7 +640,15 @@ async function open(
633640 if (!verdict.ok) {
634641 log(`egress refused: ${verdict.why}`);
635642 if (verdict.policy !== undefined) policy.refused?.(host.toLowerCase(), port, verdict.policy.private);
636 refuse(client, "403 Forbidden", verdict.why);
643 // A policy refusal is said as the forge's own, never as a bare 403.
644 if (verdict.policy === undefined) refuse(client, "403 Forbidden", verdict.why);
645 else
646 refuse(
647 client,
648 "403 Refused by this forge",
649 verdict.why.startsWith(REFUSED_BY_FORGE) ? verdict.why : `${REFUSED_BY_FORGE}: ${verdict.why}`,
650 host.toLowerCase(),
651 );
637652 return;
638653 }
639654 if (client.data.done) return;
src/apps/egress_refused.ts +15
@@ -204,6 +204,18 @@ export function allowNow(dataDir: string, repoId: string, entry: string): void {
204204 cache.delete(file);
205205 }
206206
207 /** A refusal is logged once per app and host an hour (#12182); at most the rows kept per app. */
208 const SAID_MS = 3_600_000;
209 const said = new Map<string, number>();
210 function saidDue(repoId: string, host: string, port: number, at: number): boolean {
211 const key = `${repoId}:${host}:${port}`;
212 const last = said.get(key);
213 if (last !== undefined && at - last < SAID_MS) return false;
214 if (said.size >= 5_000) said.clear();
215 said.set(key, at);
216 return true;
217 }
218
207219 /**
208220 * What a cell of `env` is given to ask and tell: production alone. A preview
209221 * runs a pull's code (a fork's too), so it neither inherits the owner's yes
@@ -214,6 +226,8 @@ export function cellHooks(
214226 repoId: string,
215227 env: string,
216228 first: (host: string, port: number) => void,
229 say?: (host: string, port: number) => void,
230 now: () => number = Date.now,
217231 ): {
218232 allowed?: () => readonly string[];
219233 onRefused?: (host: string, port: number, isPrivate: boolean) => void;
@@ -223,6 +237,7 @@ export function cellHooks(
223237 allowed: () => allowedHosts(dataDir, repoId),
224238 onRefused: (host, port, isPrivate) => {
225239 if (noteRefused(dataDir, repoId, host, port, isPrivate)) first(host, port);
240 if (say !== undefined && saidDue(repoId, host, port, now())) say(host, port);
226241 },
227242 };
228243 }
src/apps/runtime.ts +1
@@ -1678,6 +1678,7 @@ export class AppsRuntime {
16781678 // Said once per host: the first refusal is an event, the rest a count.
16791679 ...cellHooks(dataDir, record.repoId, env, (host, port) =>
16801680 this.app.bus.append({ kind: "app.egress.refused", repoId: record.repoId, payload: { host, port } }),
1681 (host, port) => log.warn("app refused an outside host", { app: record.slug, host, port, fix: "add it to forge.json egress or Allow it on the app's settings page" }),
16811682 ),
16821683 // Asked at every start: an admin's grant reaches the next cell.
16831684 granted: grantsHere(this.app, () => grantedFor(this.app.db, record.repoId)),
src/crew/brief.ts +2 −1
@@ -1006,7 +1006,8 @@ export function ownAppLines(own: OwnApp | undefined): string[] {
10061006 (previews.length === 0
10071007 ? "; no pull has a preview yet."
10081008 : `, and the previews of the open pulls: ${previews.join(", ")}.`) +
1009 " Use them for checks that need the running app (end-to-end, screenshots, the public launch check).",
1009 " Use them for checks that need the running app (end-to-end, screenshots, the public launch check)." +
1010 " When your change makes the app call an outside host (a fetch to a literal or configured address), add that host to `forge.json` `egress` in the same change: the forge refuses any host not listed there with `403` \"refused by this forge: <host> is not in this app's forge.json egress\", and that is not the remote server's answer. The app's `src/egress.ts` (`refusedByForge`) recognises it, and its `bun test` fails when code names an undeclared host.",
10101011 ...(own.blocked === undefined
10111012 ? []
10121013 : [
templates/app-template.json +4 −2

Diff not shown — a line 15,877 characters wide (limit 2,000). +4 −2

View file
test/contain.test.ts +2 −2
@@ -256,7 +256,7 @@ bySocket("egress: the proxy forwards what is allowed, byte for byte, and refuses
256256 );
257257 expect(reply).toStartWith("HTTP/1.1 403");
258258 expect(reply).toContain(
259 `localhost:${port} is not in this repository's egress`,
259 `localhost:${port} is not in this app's forge.json egress`,
260260 );
261261 }
262262 });
@@ -315,7 +315,7 @@ bySocket("egress, reported: an undeclared public host goes through and is counte
315315 const reply = await head(`CONNECT example.com:${port} HTTP/1.1\r\n\r\n`);
316316 expect(reply).toStartWith("HTTP/1.1 403");
317317 expect(reply).toContain(
318 `example.com:${port} is not in this repository's egress`,
318 `example.com:${port} is not in this app's forge.json egress`,
319319 );
320320 }
321321 expect(seen).toEqual([]);
test/egress-refused.test.ts +59 −1
@@ -151,7 +151,7 @@ describe("refused hosts", () => {
151151 expect(blockedLines(app, cy)[0]!.items[0]).toBe(lines[0]!.items[0]);
152152 const own = { access: "public" as const, production: "https://x", previews: [], blocked: ["huggingface.co (4 tries, last just now)"] };
153153 expect(ownAppLines(own).join("\n")).toContain("huggingface.co");
154 expect(ownAppLines({ access: "public", production: "https://x", previews: [] }).join("\n")).not.toContain("refused");
154 expect(ownAppLines({ access: "public", production: "https://x", previews: [] }).join("\n")).not.toContain("cells were refused");
155155 });
156156
157157 test("a host that is not a hostname or an address is dropped, and long names too", () => {
@@ -302,3 +302,61 @@ describe("refused hosts", () => {
302302 expect(blockedHosts(dataDir, repo.id).map((r) => r.host)).not.toContain("term.example.org");
303303 });
304304 });
305
306 describe("the walk (#12182)", () => {
307 test("the walk: an app calls an undeclared host, is told it was the forge, the owner sees the line, Allow, the next call is not refused", async () => {
308 const told: string[] = [];
309 const said: string[] = [];
310 let clock = Date.now();
311 const hooks = cellHooks(dataDir, repo.id, "production", (h, p) => told.push(`${h}:${p}`), (h, p) => said.push(`${h}:${p}`), () => clock);
312 const probe = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } });
313 const port = probe.port;
314 probe.stop(true);
315 const proxy = startEgress({ tcp: port }, {
316 hosts: [],
317 origins: [],
318 allowed: hooks.allowed!,
319 refused: hooks.onRefused!,
320 });
321 const connect = async (target: string): Promise<string> => {
322 let reply = "";
323 await new Promise<void>((resolve) => {
324 void Bun.connect({
325 hostname: "127.0.0.1",
326 port,
327 socket: {
328 open: (s) => void s.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n\r\n`),
329 data: (s, d) => {
330 reply += new TextDecoder().decode(d);
331 s.end();
332 },
333 close: () => resolve(),
334 error: () => resolve(),
335 },
336 });
337 });
338 return reply;
339 };
340 const refusal = await connect("beta-bridge.simplefin.invalid:443");
341 expect(refusal).toStartWith("HTTP/1.1 403 Refused by this forge\r\n");
342 expect(refusal).toContain("X-Forge-Egress: refused");
343 expect(refusal).toContain("X-Forge-Egress-Host: beta-bridge.simplefin.invalid");
344 expect(refusal).toContain("refused by this forge: beta-bridge.simplefin.invalid is not in this app's forge.json egress");
345 // The owner is told once; the log says it once an hour.
346 await connect("beta-bridge.simplefin.invalid:443");
347 expect(told).toEqual(["beta-bridge.simplefin.invalid:443"]);
348 expect(said).toEqual(["beta-bridge.simplefin.invalid:443"]);
349 clock += 3_600_001;
350 await connect("beta-bridge.simplefin.invalid:443");
351 expect(said).toHaveLength(2);
352 expect(blockedLines(app, cy).map((l) => l.line).join()).toContain("game: Blocked: beta-bridge.simplefin.invalid");
353 // Allow: the running gate takes it at once, with no redeploy.
354 const done = await allowBlocked(app, cy, repo, "beta-bridge.simplefin.invalid:443");
355 expect(done.ok).toBe(true);
356 allowNow(dataDir, repo.id, "beta-bridge.simplefin.invalid");
357 const after = await connect("beta-bridge.simplefin.invalid:443");
358 expect(after).not.toContain("refused by this forge");
359 expect(blockedLines(app, cy).map((l) => l.line).join()).not.toContain("simplefin");
360 proxy.close();
361 });
362 });
test/egress-upstream.test.ts +2 −2
@@ -94,7 +94,7 @@ test("a host the inner policy allows but the outer cell refuses is refused, and
9494 // The inner policy still refuses on its own, before the outer is asked.
9595 const own = await through(innerPort, "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n");
9696 expect(own).toStartWith("HTTP/1.1 403");
97 expect(own).toContain("not in this repository's egress");
97 expect(own).toContain("not in this app's forge.json egress");
9898 } finally {
9999 inner.close();
100100 outer.close();
@@ -126,7 +126,7 @@ test("a payment host passes a child's inner proxy only when the app declares it,
126126 expect(await through(innerPort, connect)).toContain("not reachable from this forge's cell");
127127 const refused = await through(innerPort + 1, connect);
128128 expect(refused).toStartWith("HTTP/1.1 403");
129 expect(refused).toContain("not in this repository's egress");
129 expect(refused).toContain("not in this app's forge.json egress");
130130 expect(seen).toEqual([]);
131131 // Report mode still lets another undeclared public host reach the outer proxy.
132132 if (report) expect(await through(innerPort + 1, "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n")).toContain("not reachable from this forge's cell");
test/outbound-gate.test.ts +1 −1
@@ -65,7 +65,7 @@ const allowing = () =>
6565 ? { status: 403, why: "nowhere.example.test does not resolve" }
6666 : {
6767 status: 403,
68 why: `${host}:${port} is not in this repository's egress (forge.json "egress")`,
68 why: `${host}:${port} is not in this app's forge.json egress (forge.json "egress")`,
6969 },
7070 );
7171

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs