Public: anyone can read this; the crew can change it.
A stranger's outbound private-address fetch is refused and tested at every fetch in src/http #15606
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/15596-a-stranger-s-outbound-private-address-fe → main 0 commits fork 1 thread · 1 unresolved
2 files
changed +344
−0
docs/SECURITY-RUNBOOK.md +10
| @@ -185,6 +185,16 @@ An error (status 400 or above) on a public path stays `same-origin`. | ||
| 185 | 185 | |
| 186 | 186 | **A link preview or feed reader breaks:** check the header with `curl -sI https://<forge>/og/site.png | grep -i cross-origin-resource`. It should say `cross-origin`. If a new public path needs it, add it to `src/http/corp.ts` and to `test/corp.test.ts`. |
| 187 | 187 | |
| 188 | ## Someone points the forge at an internal address | |
| 189 | ||
| 190 | A webhook, a notify URL, an origin, a model gateway, a custom domain, a pack source or a migration all make the forge fetch a URL a person typed. Each one goes through the same guard (`src/kernel/outbound.ts`). The guard resolves the name and refuses the request if any answer is loopback, unspecified, private (10/8, 172.16/12, 192.168/16), shared (100.64/10), link-local, the cloud metadata address (169.254.169.254), or an IPv6 local or wrapped form of one of them. The request then goes to the address that was judged, so a second DNS answer can't change it. Redirects are never followed blindly: a 302 is passed back as an answer, and discovery checks each hop with the guard before it follows it. | |
| 191 | ||
| 192 | **What a person sees:** the webhook delivery fails with `refused: private address`, the origin form says the host is private, and the gateway answers 502 `the forge would not reach this gateway`. Nothing is retried, because a private address does not fix itself. | |
| 193 | ||
| 194 | **An origin on your own network should be reachable** (your own Forgejo, for example): an admin adds its name to the trusted hosts on `/settings/origins`, or the operator sets `FORGE_OUTBOUND_TRUSTED_HOSTS`. Trust is given by name, never by address, and it covers origins only. Webhooks and notify URLs are never trusted this way. **Undo:** remove the name. | |
| 195 | ||
| 196 | **Checking it:** `test/outbound-guard.test.ts` lists every site and runs each address class through it. A new site fails that test until it has a row there. | |
| 197 | ||
| 188 | 198 | ## After any of these |
| 189 | 199 | |
| 190 | 200 | Write down what happened, when and what you changed, in an issue on the forge once it's calm. Then check Settings → Security again. Each section shows when it was last checked. |
test/outbound-guard.test.ts added +334
| @@ -0,0 +1,334 @@ | ||
| 1 | /** | |
| 2 | * Every place the forge fetches a URL a person supplied, held to the one guard | |
| 3 | * (`kernel/outbound.ts`, #15596). The table below lists each site by the file that holds it and how | |
| 4 | * it is reached; each is asked for every address class (loopback, unspecified, private, shared, | |
| 5 | * link-local, the metadata address, IPv6 local and wrapped forms), once as a literal and once as a | |
| 6 | * name whose DNS answer is that address, and once more for an answer that mixes a public address | |
| 7 | * with a private one. | |
| 8 | * | |
| 9 | * `fetch` is watched for the whole file and dials nothing: a site that skipped the guard would hand | |
| 10 | * the private URL to `fetch`, and the watcher's list fails the row. Each fetching site also has a | |
| 11 | * control: a public answer reaches the watcher (so the row proves something), and its 302 to the | |
| 12 | * metadata address is never followed. The last test fails when a new file calls the guard without a | |
| 13 | * row here, so a site added later is in the table before it lands. | |
| 14 | * | |
| 15 | * The sites in `src/http/` fetch only this forge's own socket and loopback port, and the parent | |
| 16 | * issuer from configuration (`test/outbound-sweep.test.ts` names each and why): none takes a URL | |
| 17 | * from a request, so none is a row. | |
| 18 | */ | |
| 19 | ||
| 20 | import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; | |
| 21 | import { Glob } from "bun"; | |
| 22 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 23 | import { tmpdir } from "node:os"; | |
| 24 | import { join } from "node:path"; | |
| 25 | import { createApp, type App } from "../src/app.ts"; | |
| 26 | import { vetClone } from "../src/actions/migrate.ts"; | |
| 27 | import { probeCertificate } from "../src/apps/certificate.ts"; | |
| 28 | import { statusOf } from "../src/apps/parity_probe.ts"; | |
| 29 | import { createRepo } from "../src/core/repos.ts"; | |
| 30 | import { createUser, type User } from "../src/core/users.ts"; | |
| 31 | import { createWebhook, deliverDue, pingWebhook } from "../src/core/webhooks.ts"; | |
| 32 | import { openGatewayDoor } from "../src/crew/gateway_door.ts"; | |
| 33 | import { post } from "../src/crew/notify.ts"; | |
| 34 | import { REFUSED_SENTENCE, type Resolve } from "../src/kernel/outbound.ts"; | |
| 35 | import { discover } from "../src/origins/discover.ts"; | |
| 36 | import { MIRROR_REFUSED, vettedEnv } from "../src/origins/git-mirror.ts"; | |
| 37 | import { lookupLineage } from "../src/origins/lineage.ts"; | |
| 38 | import { originFetch } from "../src/origins/origin_fetch.ts"; | |
| 39 | import { sourceOf } from "../src/packs/pack.ts"; | |
| 40 | import { guardSource } from "../src/packs/source_guard.ts"; | |
| 41 | import { mirrorOutbound, quietLogs } from "./helpers/globals.ts"; | |
| 42 | ||
| 43 | quietLogs(); | |
| 44 | ||
| 45 | /** Each address class, by one address a public service would never have. */ | |
| 46 | const CLASSES: readonly { readonly name: string; readonly address: string }[] = [ | |
| 47 | { name: "loopback", address: "127.0.0.1" }, | |
| 48 | { name: "loopback, IPv6", address: "::1" }, | |
| 49 | { name: "unspecified", address: "0.0.0.0" }, | |
| 50 | { name: "private 10/8", address: "10.0.0.1" }, | |
| 51 | { name: "private 172.16/12", address: "172.16.0.1" }, | |
| 52 | { name: "private 192.168/16", address: "192.168.1.1" }, | |
| 53 | { name: "shared 100.64/10", address: "100.64.0.1" }, | |
| 54 | { name: "link-local", address: "169.254.1.1" }, | |
| 55 | { name: "metadata", address: "169.254.169.254" }, | |
| 56 | { name: "metadata, IPv4-mapped", address: "::ffff:169.254.169.254" }, | |
| 57 | { name: "metadata, NAT64", address: "64:ff9b::a9fe:a9fe" }, | |
| 58 | { name: "link-local, IPv6", address: "fe80::1" }, | |
| 59 | { name: "unique-local, IPv6", address: "fd00::1" }, | |
| 60 | ]; | |
| 61 | ||
| 62 | /** An address a public host would have: what the controls resolve to. */ | |
| 63 | const PUBLIC = "93.184.216.34"; | |
| 64 | /** The name every named form asks for; its answer is the injected resolver's. */ | |
| 65 | const NAME = "internal.example.net"; | |
| 66 | const METADATA = "169.254.169.254"; | |
| 67 | ||
| 68 | /** One way a site is asked: the host as a URL writes it, as a bare host, and what DNS answers. */ | |
| 69 | interface Target { | |
| 70 | readonly host: string; | |
| 71 | readonly bare: string; | |
| 72 | readonly resolve: Resolve; | |
| 73 | } | |
| 74 | ||
| 75 | const literal = (address: string): Target => ({ | |
| 76 | host: address.includes(":") ? `[${address}]` : address, | |
| 77 | bare: address, | |
| 78 | resolve: () => Promise.reject(new Error(`a literal was resolved: ${address}`)), | |
| 79 | }); | |
| 80 | const named = (...answers: string[]): Target => ({ host: NAME, bare: NAME, resolve: () => Promise.resolve(answers) }); | |
| 81 | ||
| 82 | /** | |
| 83 | * A site that takes a person's URL. `refused` asks it for `target` and says whether the site itself | |
| 84 | * reported a refusal; `names` is false where the site has no resolver seam (it calls the guard with | |
| 85 | * the system resolver), so only literals are asked here and the guard's own test covers names. | |
| 86 | */ | |
| 87 | interface Site { | |
| 88 | readonly file: string; | |
| 89 | readonly what: string; | |
| 90 | readonly fetches: boolean; | |
| 91 | readonly names: boolean; | |
| 92 | /** | |
| 93 | * The site follows a redirect itself, judging each hop with the guard: its control is refused, | |
| 94 | * because the public host's 302 points at the metadata address, and that hop is never dialled. | |
| 95 | */ | |
| 96 | readonly judgesRedirects?: true; | |
| 97 | refused(target: Target): Promise<boolean>; | |
| 98 | } | |
| 99 | ||
| 100 | let dir: string; | |
| 101 | let app: App; | |
| 102 | let member: User; | |
| 103 | let repoId = ""; | |
| 104 | let hooks = 0; | |
| 105 | ||
| 106 | const SITES: readonly Site[] = [ | |
| 107 | { | |
| 108 | file: "src/core/webhooks.ts", | |
| 109 | what: "a repository's webhook, delivered", | |
| 110 | fetches: true, | |
| 111 | names: true, | |
| 112 | async refused(t) { | |
| 113 | const made = createWebhook(app.db, { repoId, url: `https://${t.host}/hook-${++hooks}` }); | |
| 114 | if (!made.ok) throw new Error("webhook"); | |
| 115 | const ping = pingWebhook(app.db, "guardowner/r", made.value.webhook); | |
| 116 | if (!ping.ok) throw new Error("ping"); | |
| 117 | await deliverDue(app.db, app.log, new Date(), { resolve: t.resolve }); | |
| 118 | const row = app.db.query<{ last_error: string | null }, [string]>("SELECT last_error FROM webhook_ping WHERE id = ?1").get(ping.value.id); | |
| 119 | return row?.last_error === REFUSED_SENTENCE; | |
| 120 | }, | |
| 121 | }, | |
| 122 | { | |
| 123 | file: "src/crew/notify.ts", | |
| 124 | what: "a person's notify URL", | |
| 125 | fetches: true, | |
| 126 | names: false, | |
| 127 | // A refusal and a 302 are both "not sent": the refusal is the one that asked `fetch` nothing. | |
| 128 | refused: (t) => unasked(async () => !(await post(`https://${t.host}/notify`, "hello", {}))), | |
| 129 | }, | |
| 130 | { | |
| 131 | file: "src/apps/parity_probe.ts", | |
| 132 | what: "the parity probe's two bases", | |
| 133 | fetches: true, | |
| 134 | names: false, | |
| 135 | refused: async (t) => (await statusOf(`https://${t.host}/`)) === null, | |
| 136 | }, | |
| 137 | { | |
| 138 | file: "src/origins/origin_fetch.ts", | |
| 139 | what: "an origin a member named (and `origins/oauth.ts`, `origins/providers/http.ts` through it)", | |
| 140 | fetches: true, | |
| 141 | names: false, | |
| 142 | refused: async (t) => (await originFetch(`https://${t.host}/api/v1/version`, {}, { FORGE_DEV: "0" }).then(() => false, () => true)), | |
| 143 | }, | |
| 144 | { | |
| 145 | file: "src/origins/discover.ts", | |
| 146 | what: "a host typed on the connect-an-origin form", | |
| 147 | fetches: true, | |
| 148 | names: true, | |
| 149 | judgesRedirects: true, | |
| 150 | async refused(t) { | |
| 151 | const found = await discover({ host: `https://${t.host}`, kind: "forgejo" }, {}, { resolve: t.resolve }); | |
| 152 | return !found.ok && (found.error === "private_host" || found.error === "unknown_host"); | |
| 153 | }, | |
| 154 | }, | |
| 155 | { | |
| 156 | file: "src/origins/lineage.ts", | |
| 157 | what: "the fork chain of a repository a person migrates", | |
| 158 | fetches: true, | |
| 159 | names: true, | |
| 160 | // No fork chain is the answer to a refusal and to a 302 alike: the refusal asked `fetch` | |
| 161 | // nothing. | |
| 162 | refused: (t) => unasked(async () => (await lookupLineage(`https://${t.host}/owner/name`, { resolve: t.resolve })).length === 0), | |
| 163 | }, | |
| 164 | { | |
| 165 | file: "src/crew/gateway_door.ts", | |
| 166 | what: "a member's model gateway, carried through the door", | |
| 167 | fetches: true, | |
| 168 | names: true, | |
| 169 | async refused(t) { | |
| 170 | const door = openGatewayDoor(`https://${t.host}`, { resolve: t.resolve }); | |
| 171 | try { | |
| 172 | const answer = await realFetch(`${door.base}/v1/messages`, { method: "POST", body: "{}", redirect: "manual" }); | |
| 173 | const said = await answer.text(); | |
| 174 | return answer.status === 502 && said.includes("would not reach"); | |
| 175 | } finally { | |
| 176 | door.close(); | |
| 177 | } | |
| 178 | }, | |
| 179 | }, | |
| 180 | { | |
| 181 | file: "src/apps/certificate.ts", | |
| 182 | what: "an app's custom domain, its certificate probed", | |
| 183 | fetches: false, | |
| 184 | names: true, | |
| 185 | refused: async (t) => { | |
| 186 | const said = await probeCertificate(t.bare, { resolve: t.resolve }); | |
| 187 | return "error" in said && said.error.includes("private address"); | |
| 188 | }, | |
| 189 | }, | |
| 190 | { | |
| 191 | file: "src/packs/source_guard.ts", | |
| 192 | what: "a pack's source, cloned", | |
| 193 | fetches: false, | |
| 194 | names: true, | |
| 195 | async refused(t) { | |
| 196 | const env = await guardSource(`https://${t.host}/owner/name`, {}, { resolve: t.resolve }); | |
| 197 | return !env.ok && env.error.includes("internal address"); | |
| 198 | }, | |
| 199 | }, | |
| 200 | { | |
| 201 | file: "src/packs/pack.ts", | |
| 202 | what: "a pack's source, read from its manifest", | |
| 203 | fetches: false, | |
| 204 | names: false, | |
| 205 | refused: async (t) => sourceOf(`https://${t.host}/owner/name`) === undefined, | |
| 206 | }, | |
| 207 | { | |
| 208 | file: "src/origins/git-mirror.ts", | |
| 209 | what: "a mirror's clone URL", | |
| 210 | fetches: false, | |
| 211 | names: true, | |
| 212 | async refused(t) { | |
| 213 | mirrorResolve = t.resolve; | |
| 214 | const env = await vettedEnv(`https://${t.host}/owner/name.git`, {}); | |
| 215 | return !env.ok && env.error.message === MIRROR_REFUSED; | |
| 216 | }, | |
| 217 | }, | |
| 218 | { | |
| 219 | file: "src/actions/migrate.ts", | |
| 220 | what: "a repository a member migrates in", | |
| 221 | fetches: false, | |
| 222 | names: true, | |
| 223 | async refused(t) { | |
| 224 | const vetted = await vetClone(app, member, `https://${t.host}/owner/name.git`, t.resolve); | |
| 225 | return !vetted.ok && vetted.error === "private_host"; | |
| 226 | }, | |
| 227 | }, | |
| 228 | ]; | |
| 229 | ||
| 230 | /** Files that reach the guard only through a row's file, and which one. */ | |
| 231 | const THROUGH: Record<string, string> = { | |
| 232 | "src/origins/oauth.ts": "src/origins/origin_fetch.ts", | |
| 233 | "src/origins/providers/http.ts": "src/origins/origin_fetch.ts", | |
| 234 | }; | |
| 235 | ||
| 236 | /** The mirror's resolver, swapped per row: `vettedEnv` reads its options from a module seam. */ | |
| 237 | let mirrorResolve: Resolve = () => Promise.resolve([PUBLIC]); | |
| 238 | mirrorOutbound({ resolve: (host) => mirrorResolve(host) }); | |
| 239 | ||
| 240 | const realFetch = globalThis.fetch; | |
| 241 | /** Every URL `fetch` was handed while a row ran; nothing is dialled. */ | |
| 242 | let asked: string[] = []; | |
| 243 | ||
| 244 | beforeEach(() => { | |
| 245 | asked = []; | |
| 246 | globalThis.fetch = Object.assign( | |
| 247 | (input: string | URL | Request) => { | |
| 248 | const url = input instanceof Request ? input.url : String(input); | |
| 249 | asked.push(url); | |
| 250 | // A public host answers with a redirect to the metadata address: following it would show | |
| 251 | // here. | |
| 252 | const location = new URL(url).hostname === PUBLIC ? `https://${METADATA}/latest/meta-data/` : undefined; | |
| 253 | return Promise.resolve(new Response("{}", { status: location ? 302 : 200, headers: location ? { location } : {} })); | |
| 254 | }, | |
| 255 | realFetch, | |
| 256 | ); | |
| 257 | }); | |
| 258 | afterEach(() => { | |
| 259 | globalThis.fetch = realFetch; | |
| 260 | }); | |
| 261 | ||
| 262 | beforeAll(async () => { | |
| 263 | dir = await mkdtemp(join(tmpdir(), "forge-outbound-guard-")); | |
| 264 | app = createApp({ dataDir: dir, port: 0 }); | |
| 265 | const owner = await createUser(app.db, { origin: "seed", trusted: true, username: "guardowner", email: "[email protected]", password: "guarded-owner-pass" }); | |
| 266 | if (!owner.ok) throw new Error("owner"); | |
| 267 | const other = await createUser(app.db, { origin: "seed", trusted: true, username: "guardmember", email: "[email protected]", password: "guarded-member-pass" }); | |
| 268 | if (!other.ok) throw new Error("member"); | |
| 269 | member = other.value; | |
| 270 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: owner.value.id, name: "r" }); | |
| 271 | if (!repo.ok) throw new Error("repo"); | |
| 272 | repoId = repo.value.id; | |
| 273 | }); | |
| 274 | afterAll(async () => { | |
| 275 | app.db.close(); | |
| 276 | await rm(dir, { recursive: true, force: true }); | |
| 277 | }); | |
| 278 | ||
| 279 | /** `fn` said yes and asked `fetch` for nothing while it ran. */ | |
| 280 | async function unasked(fn: () => Promise<boolean>): Promise<boolean> { | |
| 281 | const before = asked.length; | |
| 282 | return (await fn()) && asked.length === before; | |
| 283 | } | |
| 284 | ||
| 285 | /** The hosts in what `fetch` was asked for that a public service would never have. */ | |
| 286 | const privateAsked = (): string[] => | |
| 287 | asked.filter((url) => { | |
| 288 | const host = new URL(url).hostname.replace(/^\[|\]$/g, ""); | |
| 289 | return host !== PUBLIC && host !== NAME; | |
| 290 | }); | |
| 291 | ||
| 292 | for (const site of SITES) | |
| 293 | describe(`${site.file}: ${site.what}`, () => { | |
| 294 | test("the member is not an admin, so migrate judges the address", () => expect(member.isAdmin).toBe(false)); | |
| 295 | ||
| 296 | for (const { name, address } of CLASSES) | |
| 297 | test(`refuses ${name} (${address})${site.names ? ", as a literal and as a DNS answer" : ", as a literal"}`, async () => { | |
| 298 | expect([address, "literal", await site.refused(literal(address))]).toEqual([address, "literal", true]); | |
| 299 | if (site.names) expect([address, "named", await site.refused(named(address))]).toEqual([address, "named", true]); | |
| 300 | expect(privateAsked()).toEqual([]); | |
| 301 | }); | |
| 302 | ||
| 303 | if (site.names) | |
| 304 | test("refuses a name when any one of its answers is private", async () => { | |
| 305 | expect(await site.refused(named(PUBLIC, METADATA))).toBe(true); | |
| 306 | expect(privateAsked()).toEqual([]); | |
| 307 | }); | |
| 308 | ||
| 309 | test("lets a public host through, and never follows its redirect to the metadata address", async () => { | |
| 310 | expect(await site.refused(site.names ? named(PUBLIC) : literal(PUBLIC))).toBe(site.judgesRedirects === true); | |
| 311 | if (site.fetches) { | |
| 312 | expect(asked.length).toBeGreaterThan(0); | |
| 313 | expect([...new Set(asked.map((url) => new URL(url).hostname))]).toEqual([PUBLIC]); | |
| 314 | } | |
| 315 | expect(privateAsked()).toEqual([]); | |
| 316 | }); | |
| 317 | }); | |
| 318 | ||
| 319 | test("every file that calls the guard has its row here", async () => { | |
| 320 | const CALL = /\b(?:outboundFetch|vetHost|originFetch|isRefusedAddress)\(/; | |
| 321 | const rows = new Set(SITES.map((s) => s.file)); | |
| 322 | const missing: string[] = []; | |
| 323 | for (const file of new Glob("src/**/*.ts").scanSync(".")) { | |
| 324 | if (file === "src/kernel/outbound.ts") continue; | |
| 325 | const code = (await Bun.file(file).text()).split("\n").filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line)).join("\n"); | |
| 326 | if (!CALL.test(code)) continue; | |
| 327 | if (!rows.has(file) && !(file in THROUGH)) missing.push(file); | |
| 328 | } | |
| 329 | expect(missing).toEqual([]); | |
| 330 | for (const [file, via] of Object.entries(THROUGH)) { | |
| 331 | expect([file, rows.has(via)]).toEqual([file, true]); | |
| 332 | expect([file, (await Bun.file(file).text()).includes("originFetch(")]).toEqual([file, true]); | |
| 333 | } | |
| 334 | }); |
new above
offline
This assertion is identical for every site. Move it into one test, or into beforeAll, so a failure names one cause instead of 12.