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

A forge running as an app says its self-probes are refused by its own egress instead of trying its own host again and again #16127

Merged opened this

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

Merged

mason/forge:mason/16123-a-forge-running-as-an-app-says-its-self → main 0 commits fork

  • Merged. mason/16123-a-forge-running-as-an-app-says-its-self was merged into main as 7516ef5.

Review

Sign in to review this change.
5 files changed +189 −8
docs/features/v1-proven.md +5
@@ -25,6 +25,11 @@ A weekly maintenance duty, `v1-proven` (#12989), runs the production probes of `
2525 - **Cannot reach.** Probes whose read got no HTTP answer at all fold into one line, `cannot reach <origin>: <k> of <n>
2626 probes got no answer`; when that is the only failure the title is `Defect of the production proof: cannot reach
2727 <origin>`. An unreachable forge files one line, not one per probe.
28 - **Refused by its own gate.** A forge hosted as an app reaches out through its parent's egress gate, which refuses the
29 forge's own host (#16123). The host differs per preview, so it is never added to `forge.json` `egress`. The first read
30 goes out alone. When it comes back `403` with `X-Forge-Egress: refused`, the run sends no other read and files no
31 defect, and it records one line: `skipped: refused by this forge: <host> is not in this app's forge.json egress`.
32 Outside a cell nothing is refused and every probe reads as before.
2833 - **A repeat failure.** The open defect is found by its `Probe key:` line, so renaming the title loses nothing. While it
2934 is open, a run that fails again (a second run the same day, or next week's) adds one comment ("Still failing on
3035 <date>") listing that run's failing lines, and no second issue. Once it is closed, a new failure opens a new one. A
src/maintain/duties/v1_proven.ts +11 −5
@@ -1,15 +1,18 @@
11 /**
22 * v1.0.0 stays proven (#12989): the weekly read-only probe of the forge's public origin;
3 * see `../proven.ts`.
3 * see `../proven.ts`. A forge hosted as an app has its own host refused by its parent's egress
4 * gate (#16123): the first read that comes back refused ends the run as one skip line, no read
5 * of that host is sent again in the run, and no defect is filed (`../refused_once.ts`).
46 */
57
68 import { getRepo } from "../../core/repos.ts";
7 import type { Proof } from "../../core/v1_proof.ts";
9 import type { Fetch } from "../../core/v1_proof.ts";
810 import { publicOrigin } from "../../core/public_origin.ts";
911 import type { Duty, Finding } from "../duty.ts";
10 import { recordLines, reportResults, weeklyProof } from "../proven.ts";
12 import { recordLines, reportResults, weeklyProof, type WeeklyProof } from "../proven.ts";
13 import { refusedOnce } from "../refused_once.ts";
1114
12 export function v1Proven(proof: Proof = weeklyProof): Duty {
15 export function v1Proven(proof: WeeklyProof = weeklyProof, fetcher: Fetch = fetch): Duty {
1316 return {
1417 name: "v1-proven",
1518 intervalMs: 7 * 86_400_000,
@@ -17,7 +20,10 @@ export function v1Proven(proof: Proof = weeklyProof): Duty {
1720 async run({ db, now, app }) {
1821 const url = app?.config.url;
1922 if (url === undefined || url === "") return { findings: [], actions: ["skipped: this forge does not know its public origin (FORGE_URL)"] };
20 const results = await proof(publicOrigin(url, ""));
23 const once = refusedOnce(fetcher);
24 const results = await proof(publicOrigin(url, ""), once.fetch);
25 const refused = once.refused();
26 if (refused !== undefined) return { findings: [], actions: [`skipped: ${refused}`] };
2127 const findings: Finding[] = results
2228 .filter((r) => r.status === "fail")
2329 .map((r) => ({
src/maintain/proven.ts +5 −3
@@ -10,14 +10,16 @@
1010
1111 import type { Database } from "bun:sqlite";
1212 import { addComment, createIssue, listComments } from "../core/issues.ts";
13 import { line, prove, readsWords, type Proof, type Result } from "../core/v1_proof.ts";
13 import { line, prove, readsWords, type Fetch, type Result } from "../core/v1_proof.ts";
1414 import { watcherId } from "../rules/bot.ts";
1515 import { evidenceBlock } from "./evidence.ts";
1616
1717 const DEFECT_PREFIX = "Defect of the production proof: ";
1818
19 /** The proof a week runs: the probes over fetch, at the forge's own origin and no other host. */
20 export const weeklyProof: Proof = (base) => prove(base, fetch);
19 /** The proof a week runs: the probes over the fetcher the duty hands it (`fetch`, wrapped by
20 * `refused_once.ts`), at the forge's own origin and no other host. */
21 export type WeeklyProof = (base: string, fetcher: Fetch) => Promise<Result[]>;
22 export const weeklyProof: WeeklyProof = (base, fetcher) => prove(base, fetcher);
2123
2224 /** The stable key a run's defect carries in its body; the title may be edited, this line is not. */
2325 const RUN_KEY = "Probe key: v1-proven/run";
src/maintain/refused_once.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * A read of the forge's own origin that its egress gate refused, asked once per run (#16123).
3 *
4 * A forge hosted as an app reaches out through its parent's gate, and the gate refuses the
5 * forge's own public host (it is not in `forge.json` `egress`, and it differs per preview, so it
6 * is never added there). The refusal is the gate's no, not the forge's answer: a duty that reads
7 * its own origin wraps its fetcher in `refusedOnce`, so the first read of a host goes out alone,
8 * and once the gate has refused it every later read of that host in the run fails at once with
9 * the gate's words and is never sent. The duty asks `refused()` and records one skip line.
10 *
11 * Outside a cell nothing is refused: every read is sent as before, the first of each host simply
12 * ahead of the rest. Plain data in, plain data out.
13 */
14
15 import type { Fetch } from "../core/v1_proof.ts";
16 import { GateRefusedError } from "../kernel/outbound.ts";
17
18 /** What the gate says, in its own words: `refused by this forge: <host> is not in …`. */
19 export const refusedWords = (host: string): string => `refused by this forge: ${host} is not in this app's forge.json egress`;
20
21 /** A read the gate refused, or one not sent because the gate refused its host before. */
22 export class EgressRefused extends Error {
23 constructor(readonly host: string) {
24 super(refusedWords(host));
25 }
26 }
27
28 /** The gate's answer to a read: `403` marked `X-Forge-Egress: refused`. */
29 const refusedAnswer = (res: Response): boolean => res.status === 403 && res.headers.get("x-forge-egress") === "refused";
30
31 /** The gate's refusal as a throw: Bun's tunnel error, the outbound client's, or the words. */
32 function refusedThrow(e: unknown): boolean {
33 if (e instanceof GateRefusedError || e instanceof EgressRefused) return true;
34 const o = (typeof e === "object" && e !== null ? e : {}) as { code?: unknown; status?: unknown; message?: unknown };
35 if (o.code === "ERR_PROXY_TUNNEL" && o.status === 403) return true;
36 return typeof o.message === "string" && o.message.includes("refused by this forge");
37 }
38
39 export interface RefusedOnce {
40 readonly fetch: Fetch;
41 /** The gate's words for the first host it refused in this run; undefined when none was. */
42 readonly refused: () => string | undefined;
43 }
44
45 export function refusedOnce(fetcher: Fetch): RefusedOnce {
46 // Per host: the first read, settled once its answer (or throw) is known to be the gate's or not.
47 const first = new Map<string, Promise<boolean>>();
48 let said: string | undefined;
49 const fetchOnce: Fetch = async (url, init) => {
50 const host = new URL(url).host;
51 const seen = first.get(host);
52 if (seen !== undefined) {
53 if (await seen) throw new EgressRefused(host);
54 return fetcher(url, init);
55 }
56 let settle: (refused: boolean) => void = () => {};
57 first.set(host, new Promise<boolean>((done) => (settle = done)));
58 const refuse = (): never => {
59 said ??= refusedWords(host);
60 settle(true);
61 throw new EgressRefused(host);
62 };
63 let res: Response;
64 try {
65 res = await fetcher(url, init);
66 } catch (e) {
67 if (refusedThrow(e)) return refuse();
68 settle(false);
69 throw e;
70 }
71 if (refusedAnswer(res)) {
72 await res.body?.cancel().catch(() => {});
73 return refuse();
74 }
75 settle(false);
76 return res;
77 };
78 return { fetch: fetchOnce, refused: () => said };
79 }
test/maintain-v1-proven-refused.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * A forge hosted as an app has its own host refused by its parent's egress gate (#16123): the
3 * weekly proof's first read comes back `403` `X-Forge-Egress: refused`, the run records one skip
4 * line in the gate's words, sends no second read and files no `Defect of the production proof`.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/core/repos.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { v1Proven } from "../src/maintain/duties/v1_proven.ts";
14 import { refusedOnce } from "../src/maintain/refused_once.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18 let dir = "", app: App, repoId = "";
19 const NOW = new Date("2026-11-23T12:00:00Z");
20 const HOST = "lab--forge-trevato-apps.open-platform.sh";
21
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "forge-v1-refused-"));
24 app = createApp({ dataDir: dir, port: 0 });
25 const owner = await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
26 if (!owner.ok) throw new Error("user");
27 const made = await createRepo(app.db, app.reposRoot, { ownerId: owner.value.id, name: "forge", visibility: "public", description: "f" });
28 if (!made.ok) throw new Error("repo");
29 repoId = made.value.id;
30 });
31 afterAll(async () => {
32 app.close();
33 await rm(dir, { recursive: true, force: true });
34 });
35
36 const defects = () => app.db.query<{ n: number }, [string]>("SELECT count(*) AS n FROM issue WHERE repo_id = ?1 AND title LIKE 'Defect of the production proof%'").get(repoId)!.n;
37 const run = (fetcher: (url: string, init?: RequestInit) => Promise<Response>) =>
38 v1Proven(undefined, fetcher).run({ db: app.db, bus: app.bus, now: NOW, app: { config: { url: `https://${HOST}/`, forgeRepo: "boss/forge" } } as unknown as App });
39
40 const gate = () => new Response(`refused by this forge: ${HOST}:443 is not in this app's forge.json egress\n`, { status: 403, headers: { "x-forge-egress": "refused" } });
41
42 test("the gate refuses the forge's own host: one request, one skip line in its words, no defect", async () => {
43 const asked: string[] = [];
44 const r = await run(async (url) => {
45 asked.push(url);
46 return gate();
47 });
48 expect(asked).toHaveLength(1);
49 expect(r.findings).toEqual([]);
50 expect(r.actions).toEqual([`skipped: refused by this forge: ${HOST} is not in this app's forge.json egress`]);
51 expect(defects()).toBe(0);
52 });
53
54 test("a Bun tunnel refusal thrown by the proxy is the gate's no too: one request, skipped", async () => {
55 let asked = 0;
56 const r = await run(async () => {
57 asked++;
58 throw Object.assign(new Error("Proxy tunnel failed"), { code: "ERR_PROXY_TUNNEL", status: 403 });
59 });
60 expect(asked).toBe(1);
61 expect(r.actions).toEqual([`skipped: refused by this forge: ${HOST} is not in this app's forge.json egress`]);
62 expect(defects()).toBe(0);
63 });
64
65 test("a 403 that is not the gate's is the forge's answer: every probe reads, and the run files its defect as before", async () => {
66 let asked = 0;
67 const r = await run(async () => {
68 asked++;
69 return new Response("no", { status: 403 });
70 });
71 expect(asked).toBeGreaterThan(1);
72 expect(r.findings.length).toBeGreaterThan(0);
73 expect(r.actions.some((a) => a.startsWith("skipped"))).toBe(false);
74 expect(defects()).toBe(1);
75 });
76
77 test("refusedOnce: another host is still read, and a host that answers is never held back", async () => {
78 const asked: string[] = [];
79 const once = refusedOnce(async (url) => {
80 asked.push(url);
81 return new URL(url).host === "own.example" ? gate() : new Response("ok");
82 });
83 const own = await Promise.allSettled([once.fetch("https://own.example/a"), once.fetch("https://own.example/b")]);
84 expect(own.map((s) => s.status)).toEqual(["rejected", "rejected"]);
85 expect((await once.fetch("https://other.example/x")).status).toBe(200);
86 expect((await once.fetch("https://other.example/y")).status).toBe(200);
87 expect(asked).toEqual(["https://own.example/a", "https://other.example/x", "https://other.example/y"]);
88 expect(once.refused()).toBe("refused by this forge: own.example is not in this app's forge.json egress");
89 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs