Public: anyone can read this; the crew can change it.
Outbound fetches never reach private networks: webhooks, mirrors and migrate resolve and refuse private addresses #2979
scout/forge:scout/2921-outbound-fetches-never-reach-private-net → main 1 commit fork
8 files
changed +385
−133
README.md +6 −1
| @@ -1596,7 +1596,12 @@ work here. | ||
| 1596 | 1596 | say what the local client keeps cloned. |
| 1597 | 1597 | - **Automation** — a JSON API covering repos, issues, forks, and orgs (the |
| 1598 | 1598 | label-as-queue surface), a durable event outbox, and **webhooks** (HMAC-signed |
| 1599 | delivery with retry). | |
| 1599 | delivery with retry). Every address the forge dials on a user's say-so | |
| 1600 | (webhooks, discovery, migrate, mirrors) goes through `src/http/outbound.ts`: | |
| 1601 | the name is resolved and refused if any answer is loopback, private, | |
| 1602 | link-local or metadata; webhooks are https only; loopback is allowed only | |
| 1603 | with `FORGE_DEV=1` (or under `bun test`); `FORGE_ORIGIN_ALLOW` still names | |
| 1604 | trusted LAN hosts. The resolved IP is not pinned into the connection. | |
| 1600 | 1605 | - **Where an account came from** — `GET /api/v1/admin/accounts` lists each |
| 1601 | 1606 | account with `via` (`signup`, `edge`, or null) and `signsInThrough` |
| 1602 | 1607 | (`"open-platform.sh"` for an account the platform edge made, else null); |
src/actions/migrate.ts +8 −106
| @@ -39,6 +39,7 @@ import { | ||
| 39 | 39 | runningJob, |
| 40 | 40 | type MirrorJob, |
| 41 | 41 | } from "../origins/jobs.ts"; |
| 42 | import { gitRemoteEnv, vetUrl } from "../http/outbound.ts"; | |
| 42 | 43 | import { requireUser } from "./access.ts"; |
| 43 | 44 | import { enableApp } from "./apps.ts"; |
| 44 | 45 | import { addToCrew } from "./crew.ts"; |
| @@ -53,8 +54,6 @@ import { tell, toldWords } from "./tell.ts"; | ||
| 53 | 54 | /** The whole clone — the HEAD probe and the fetch — gets this long. */ |
| 54 | 55 | export const MIGRATE_TIMEOUT_MS = 120_000; |
| 55 | 56 | |
| 56 | /** The transports a migration will speak. Anything else is refused. */ | |
| 57 | const ALLOWED_PROTOCOL = "https:http:git"; | |
| 58 | 57 | |
| 59 | 58 | export type MigrateSource = |
| 60 | 59 | | { readonly originId: string; readonly fullName: string } |
| @@ -207,6 +206,8 @@ export function migrateMessage(error: MigrateError, limit = "at the repositories | ||
| 207 | 206 | } |
| 208 | 207 | } |
| 209 | 208 | |
| 209 | export { isPrivateHost } from "../http/outbound.ts"; | |
| 210 | ||
| 210 | 211 | /** |
| 211 | 212 | * A pasted address, made into one git may be handed — or `undefined`. |
| 212 | 213 | * `github.com/a/b` gets the `https://` a person meant; `file://`, `ssh://`, |
| @@ -232,103 +233,6 @@ export function migrateUrl(raw: string): string | undefined { | ||
| 232 | 233 | return safeRemoteUrl(parsed.toString()); |
| 233 | 234 | } |
| 234 | 235 | |
| 235 | /** | |
| 236 | * Whether a hostname names something inside the network rather than on the | |
| 237 | * open internet: loopback, link-local, the private ranges, `.localhost`, | |
| 238 | * and the unspecified address. Names are not resolved here — a public name | |
| 239 | * pointing at a private address is the network's own filter to catch. | |
| 240 | */ | |
| 241 | export function isPrivateHost(hostname: string): boolean { | |
| 242 | const h = hostname.toLowerCase().replace(/^\[|\]$/g, ""); | |
| 243 | if (h === "localhost" || h.endsWith(".localhost") || h === "0.0.0.0") | |
| 244 | return true; | |
| 245 | const v4 = privateV4(h); | |
| 246 | if (v4 !== undefined) return v4; | |
| 247 | const groups = expandV6(h); | |
| 248 | if (groups === undefined) return false; | |
| 249 | const [g0, g1, g2, g3, g4, g5, g6, g7] = groups; | |
| 250 | if (groups.every((g) => g === 0)) return true; // :: | |
| 251 | if ([g0, g1, g2, g3, g4].every((g) => g === 0)) { | |
| 252 | if (g5 === 0 && g6 === 0 && g7 === 1) return true; // ::1 | |
| 253 | // ::ffff:a.b.c.d — an IPv4 address in IPv6 clothes: judge the IPv4. | |
| 254 | if (g5 === 0xffff) | |
| 255 | return ( | |
| 256 | privateV4( | |
| 257 | `${(g6! >> 8) & 0xff}.${g6! & 0xff}.${(g7! >> 8) & 0xff}.${g7! & 0xff}`, | |
| 258 | ) === true | |
| 259 | ); | |
| 260 | } | |
| 261 | if ((g0! & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local | |
| 262 | if ((g0! & 0xffc0) === 0xfe80) return true; // fe80::/10 link local | |
| 263 | return false; | |
| 264 | } | |
| 265 | ||
| 266 | /** | |
| 267 | * Whatever the source's own git config says, a clone follows no redirect: | |
| 268 | * the address that was checked is the only address that is fetched. Added | |
| 269 | * after any entries the credential brought, at the next free index. | |
| 270 | */ | |
| 271 | function noRedirects(env: Record<string, string>): Record<string, string> { | |
| 272 | const n = Number(env["GIT_CONFIG_COUNT"] ?? "0"); | |
| 273 | return { | |
| 274 | ...env, | |
| 275 | GIT_CONFIG_COUNT: String(n + 1), | |
| 276 | [`GIT_CONFIG_KEY_${n}`]: "http.followRedirects", | |
| 277 | [`GIT_CONFIG_VALUE_${n}`]: "false", | |
| 278 | }; | |
| 279 | } | |
| 280 | ||
| 281 | /** Dotted IPv4 → inside the network?; `undefined` when not IPv4 at all. */ | |
| 282 | function privateV4(h: string): boolean | undefined { | |
| 283 | const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); | |
| 284 | if (v4 === null) return undefined; | |
| 285 | const [a, b] = [Number(v4[1]), Number(v4[2])]; | |
| 286 | return ( | |
| 287 | a === 127 || | |
| 288 | a === 10 || | |
| 289 | a === 0 || | |
| 290 | (a === 172 && b >= 16 && b <= 31) || | |
| 291 | (a === 192 && b === 168) || | |
| 292 | (a === 169 && b === 254) || | |
| 293 | (a === 100 && b >= 64 && b <= 127) | |
| 294 | ); | |
| 295 | } | |
| 296 | ||
| 297 | /** | |
| 298 | * An IPv6 literal as eight 16-bit groups, `::` expanded and a trailing | |
| 299 | * dotted IPv4 folded in; `undefined` when the text is not IPv6. | |
| 300 | */ | |
| 301 | function expandV6(h: string): number[] | undefined { | |
| 302 | if (!h.includes(":")) return undefined; | |
| 303 | let text = h; | |
| 304 | const dotted = /:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text); | |
| 305 | if (dotted !== null) { | |
| 306 | const p = dotted[1]!.split(".").map(Number); | |
| 307 | if (p.some((n) => n > 255)) return undefined; | |
| 308 | text = | |
| 309 | text.slice(0, dotted.index) + | |
| 310 | `:${((p[0]! << 8) | p[1]!).toString(16)}:${((p[2]! << 8) | p[3]!).toString(16)}`; | |
| 311 | } | |
| 312 | const halves = text.split("::"); | |
| 313 | if (halves.length > 2) return undefined; | |
| 314 | const parse = (part: string): number[] | undefined => { | |
| 315 | if (part === "") return []; | |
| 316 | const out: number[] = []; | |
| 317 | for (const g of part.split(":")) { | |
| 318 | if (!/^[0-9a-f]{1,4}$/.test(g)) return undefined; | |
| 319 | out.push(parseInt(g, 16)); | |
| 320 | } | |
| 321 | return out; | |
| 322 | }; | |
| 323 | const head = parse(halves[0]!); | |
| 324 | const tail = halves.length === 2 ? parse(halves[1]!) : []; | |
| 325 | if (head === undefined || tail === undefined) return undefined; | |
| 326 | if (halves.length === 1) return head.length === 8 ? head : undefined; | |
| 327 | const fill = 8 - head.length - tail.length; | |
| 328 | if (fill < 1) return undefined; | |
| 329 | return [...head, ...new Array<number>(fill).fill(0), ...tail]; | |
| 330 | } | |
| 331 | ||
| 332 | 236 | /** The last path segment without `.git`: what the repository was called. */ |
| 333 | 237 | function nameFromUrl(url: string): string { |
| 334 | 238 | const path = new URL(url).pathname.replace(/\/+$/, ""); |
| @@ -348,12 +252,10 @@ async function resolveSource( | ||
| 348 | 252 | // range — is not a public repository, and a pasted address must not |
| 349 | 253 | // become a way to knock on it. An admin may; a forge run for one person |
| 350 | 254 | // may say so once (`FORGE_MIGRATE_PRIVATE_HOSTS=1`). |
| 351 | if ( | |
| 352 | isPrivateHost(new URL(url).hostname) && | |
| 353 | !user.isAdmin && | |
| 354 | app.config.migrateFromPrivateHosts !== true | |
| 355 | ) | |
| 356 | return err("private_host"); | |
| 255 | if (!user.isAdmin && app.config.migrateFromPrivateHosts !== true) { | |
| 256 | const vetted = await vetUrl(url, { loopback: false }); | |
| 257 | if (!vetted.ok) return err("private_host"); | |
| 258 | } | |
| 357 | 259 | return ok({ |
| 358 | 260 | url, |
| 359 | 261 | label: url, |
| @@ -483,7 +385,7 @@ async function cloneInto( | ||
| 483 | 385 | const deadline = Date.now() + MIGRATE_TIMEOUT_MS; |
| 484 | 386 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 485 | 387 | const authEnv = await source.authEnv(); |
| 486 | const env = { ...noRedirects(authEnv), GIT_ALLOW_PROTOCOL: ALLOWED_PROTOCOL }; | |
| 388 | const env = gitRemoteEnv(authEnv); | |
| 487 | 389 | const said = (stderr: string, fallback: string): string => |
| 488 | 390 | redact(stderr.trim(), ...secretsIn(authEnv)) |
| 489 | 391 | .split("\n") |
src/core/webhooks.ts +13 −6
| @@ -15,6 +15,7 @@ import { id, secret as randomSecret } from "../kernel/id.ts"; | ||
| 15 | 15 | import type { Log } from "../kernel/log.ts"; |
| 16 | 16 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 17 | 17 | import type { ForgeEvent } from "./events.ts"; |
| 18 | import { guardedFetch, loopbackAllowed } from "../http/outbound.ts"; | |
| 18 | 19 | |
| 19 | 20 | const MAX_ATTEMPTS = 6; |
| 20 | 21 | const DELIVER_TIMEOUT_MS = 10_000; |
| @@ -68,8 +69,10 @@ export function createWebhook( | ||
| 68 | 69 | input: CreateWebhookInput, |
| 69 | 70 | ): Result<{ webhook: Webhook; secret: string }, CreateWebhookError> { |
| 70 | 71 | const url = input.url.trim(); |
| 71 | // Only http(s), and never a bare/relative URL — this value is fetched. | |
| 72 | if (!/^https?:\/\/.+/i.test(url)) return err("invalid_url"); | |
| 72 | // https only (http for a development instance), never a bare or relative | |
| 73 | // URL: this value is fetched. Where it points is judged at every delivery. | |
| 74 | const scheme = loopbackAllowed() ? /^https?:\/\/.+/i : /^https:\/\/.+/i; | |
| 75 | if (!scheme.test(url)) return err("invalid_url"); | |
| 73 | 76 | try { |
| 74 | 77 | // eslint-disable-next-line no-new |
| 75 | 78 | new URL(url); |
| @@ -263,7 +266,7 @@ async function deliverOne( | ||
| 263 | 266 | |
| 264 | 267 | let status = 0; |
| 265 | 268 | try { |
| 266 | const response = await fetch(row.url, { | |
| 269 | const sent = await guardedFetch(row.url, { | |
| 267 | 270 | method: "POST", |
| 268 | 271 | headers: { |
| 269 | 272 | "content-type": "application/json", |
| @@ -276,9 +279,13 @@ async function deliverOne( | ||
| 276 | 279 | }, |
| 277 | 280 | body, |
| 278 | 281 | signal: AbortSignal.timeout(DELIVER_TIMEOUT_MS), |
| 279 | redirect: "manual", | |
| 280 | }); | |
| 281 | status = response.status; | |
| 282 | }, { httpsOnly: true }); | |
| 283 | if (sent.ok) status = sent.value.status; | |
| 284 | else | |
| 285 | log.warn("webhook delivery refused", { | |
| 286 | delivery: row.id, | |
| 287 | error: sent.error, | |
| 288 | }); | |
| 282 | 289 | } catch (error) { |
| 283 | 290 | log.warn("webhook delivery error", { |
| 284 | 291 | delivery: row.id, |
src/http/outbound.ts added +201
| @@ -0,0 +1,201 @@ | ||
| 1 | /** | |
| 2 | * The one outbound guard: every address the forge dials on somebody's say-so | |
| 3 | * (webhooks, discovery, migrate, mirrors) is resolved first and refused when | |
| 4 | * any answer is loopback, private, link-local or the metadata address. No | |
| 5 | * redirect is followed here; callers walk hops by hand and vet each one. | |
| 6 | * | |
| 7 | * Residual: the vetted answer is not pinned into the connection (Bun's fetch | |
| 8 | * has no hook for it), so a resolver that changes its answer between the | |
| 9 | * check and the connect is not caught. The window is milliseconds. | |
| 10 | */ | |
| 11 | ||
| 12 | import { lookup } from "node:dns/promises"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | ||
| 15 | export const ALLOWED_PROTOCOL = "https:http:git"; | |
| 16 | ||
| 17 | /** Loopback is reachable only from a development instance or the test suite. */ | |
| 18 | export function loopbackAllowed( | |
| 19 | env: Record<string, string | undefined> = process.env, | |
| 20 | ): boolean { | |
| 21 | return env["FORGE_DEV"] === "1" || env["NODE_ENV"] === "test"; | |
| 22 | } | |
| 23 | ||
| 24 | export type Resolver = (host: string) => Promise<string[]>; | |
| 25 | ||
| 26 | const systemResolver: Resolver = async (host) => | |
| 27 | (await lookup(host, { all: true })).map((a) => a.address); | |
| 28 | ||
| 29 | export interface VetOptions { | |
| 30 | /** Webhooks: https only. */ | |
| 31 | httpsOnly?: boolean; | |
| 32 | /** Defaults to `loopbackAllowed()`. */ | |
| 33 | loopback?: boolean; | |
| 34 | /** Hosts the operator named (FORGE_ORIGIN_ALLOW): not judged. */ | |
| 35 | allowHosts?: ReadonlySet<string>; | |
| 36 | resolve?: Resolver; | |
| 37 | } | |
| 38 | ||
| 39 | export type VetError = "scheme" | "private" | "unresolved"; | |
| 40 | ||
| 41 | const isLoopbackAddress = (a: string): boolean => | |
| 42 | a === "::1" || a === "0:0:0:0:0:0:0:1" || /^127\./.test(a) || | |
| 43 | /^::ffff:(127\.|7f)/i.test(a.replace(/^\[|\]$/g, "")); | |
| 44 | ||
| 45 | /** Resolve the URL's host and judge every answer. */ | |
| 46 | export async function vetUrl( | |
| 47 | raw: string, | |
| 48 | options: VetOptions = {}, | |
| 49 | ): Promise<Result<URL, VetError>> { | |
| 50 | let url: URL; | |
| 51 | try { | |
| 52 | url = new URL(raw); | |
| 53 | } catch { | |
| 54 | return err("scheme"); | |
| 55 | } | |
| 56 | const loopback = options.loopback ?? loopbackAllowed(); | |
| 57 | const plain = url.protocol === "http:" && (!options.httpsOnly || loopback); | |
| 58 | if (url.protocol !== "https:" && !plain) | |
| 59 | return err("scheme"); | |
| 60 | const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase(); | |
| 61 | if ( | |
| 62 | options.allowHosts?.has(host) === true || | |
| 63 | options.allowHosts?.has(url.host.toLowerCase()) === true | |
| 64 | ) | |
| 65 | return ok(url); | |
| 66 | let addresses: string[]; | |
| 67 | if (/^[0-9.]+$/.test(host) || host.includes(":")) addresses = [host]; | |
| 68 | else { | |
| 69 | try { | |
| 70 | addresses = await (options.resolve ?? systemResolver)(host); | |
| 71 | } catch { | |
| 72 | return err("unresolved"); | |
| 73 | } | |
| 74 | } | |
| 75 | if (addresses.length === 0) return err("unresolved"); | |
| 76 | const named = host === "localhost" || host.endsWith(".localhost"); | |
| 77 | for (const a of named ? [host, ...addresses] : addresses) { | |
| 78 | if (!isPrivateHost(a)) continue; | |
| 79 | if (loopback && (named || isLoopbackAddress(a)) && addresses.every((x) => isLoopbackAddress(x) || named)) | |
| 80 | continue; | |
| 81 | return err("private"); | |
| 82 | } | |
| 83 | return ok(url); | |
| 84 | } | |
| 85 | ||
| 86 | /** Vet, then fetch without following redirects. */ | |
| 87 | export async function guardedFetch( | |
| 88 | raw: string, | |
| 89 | init: RequestInit, | |
| 90 | options: VetOptions = {}, | |
| 91 | ): Promise<Result<Response, VetError | "failed">> { | |
| 92 | const vetted = await vetUrl(raw, options); | |
| 93 | if (!vetted.ok) return vetted; | |
| 94 | try { | |
| 95 | return ok(await fetch(vetted.value, { ...init, redirect: "manual" })); | |
| 96 | } catch { | |
| 97 | return err("failed"); | |
| 98 | } | |
| 99 | } | |
| 100 | ||
| 101 | /** Git's environment for a remote the forge chose: pinned transports, no redirects. */ | |
| 102 | export function gitRemoteEnv(env: Record<string, string>): Record<string, string> { | |
| 103 | return { ...noRedirects(env), GIT_ALLOW_PROTOCOL: ALLOWED_PROTOCOL }; | |
| 104 | } | |
| 105 | ||
| 106 | /** | |
| 107 | * Whether a hostname names something inside the network rather than on the | |
| 108 | * open internet: loopback, link-local, the private ranges, `.localhost`, | |
| 109 | * and the unspecified address. Names are not resolved here — a public name | |
| 110 | * pointing at a private address is the network's own filter to catch. | |
| 111 | */ | |
| 112 | export function isPrivateHost(hostname: string): boolean { | |
| 113 | const h = hostname.toLowerCase().replace(/^\[|\]$/g, ""); | |
| 114 | if (h === "localhost" || h.endsWith(".localhost") || h === "0.0.0.0") | |
| 115 | return true; | |
| 116 | const v4 = privateV4(h); | |
| 117 | if (v4 !== undefined) return v4; | |
| 118 | const groups = expandV6(h); | |
| 119 | if (groups === undefined) return false; | |
| 120 | const [g0, g1, g2, g3, g4, g5, g6, g7] = groups; | |
| 121 | if (groups.every((g) => g === 0)) return true; // :: | |
| 122 | if ([g0, g1, g2, g3, g4].every((g) => g === 0)) { | |
| 123 | if (g5 === 0 && g6 === 0 && g7 === 1) return true; // ::1 | |
| 124 | // ::ffff:a.b.c.d — an IPv4 address in IPv6 clothes: judge the IPv4. | |
| 125 | if (g5 === 0xffff) | |
| 126 | return ( | |
| 127 | privateV4( | |
| 128 | `${(g6! >> 8) & 0xff}.${g6! & 0xff}.${(g7! >> 8) & 0xff}.${g7! & 0xff}`, | |
| 129 | ) === true | |
| 130 | ); | |
| 131 | } | |
| 132 | if ((g0! & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local | |
| 133 | if ((g0! & 0xffc0) === 0xfe80) return true; // fe80::/10 link local | |
| 134 | return false; | |
| 135 | } | |
| 136 | ||
| 137 | /** | |
| 138 | * Whatever the source's own git config says, a clone follows no redirect: | |
| 139 | * the address that was checked is the only address that is fetched. Added | |
| 140 | * after any entries the credential brought, at the next free index. | |
| 141 | */ | |
| 142 | export function noRedirects(env: Record<string, string>): Record<string, string> { | |
| 143 | const n = Number(env["GIT_CONFIG_COUNT"] ?? "0"); | |
| 144 | return { | |
| 145 | ...env, | |
| 146 | GIT_CONFIG_COUNT: String(n + 1), | |
| 147 | [`GIT_CONFIG_KEY_${n}`]: "http.followRedirects", | |
| 148 | [`GIT_CONFIG_VALUE_${n}`]: "false", | |
| 149 | }; | |
| 150 | } | |
| 151 | ||
| 152 | /** Dotted IPv4 → inside the network?; `undefined` when not IPv4 at all. */ | |
| 153 | function privateV4(h: string): boolean | undefined { | |
| 154 | const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); | |
| 155 | if (v4 === null) return undefined; | |
| 156 | const [a, b] = [Number(v4[1]), Number(v4[2])]; | |
| 157 | return ( | |
| 158 | a === 127 || | |
| 159 | a === 10 || | |
| 160 | a === 0 || | |
| 161 | (a === 172 && b >= 16 && b <= 31) || | |
| 162 | (a === 192 && b === 168) || | |
| 163 | (a === 169 && b === 254) || | |
| 164 | (a === 100 && b >= 64 && b <= 127) | |
| 165 | ); | |
| 166 | } | |
| 167 | ||
| 168 | /** | |
| 169 | * An IPv6 literal as eight 16-bit groups, `::` expanded and a trailing | |
| 170 | * dotted IPv4 folded in; `undefined` when the text is not IPv6. | |
| 171 | */ | |
| 172 | function expandV6(h: string): number[] | undefined { | |
| 173 | if (!h.includes(":")) return undefined; | |
| 174 | let text = h; | |
| 175 | const dotted = /:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text); | |
| 176 | if (dotted !== null) { | |
| 177 | const p = dotted[1]!.split(".").map(Number); | |
| 178 | if (p.some((n) => n > 255)) return undefined; | |
| 179 | text = | |
| 180 | text.slice(0, dotted.index) + | |
| 181 | `:${((p[0]! << 8) | p[1]!).toString(16)}:${((p[2]! << 8) | p[3]!).toString(16)}`; | |
| 182 | } | |
| 183 | const halves = text.split("::"); | |
| 184 | if (halves.length > 2) return undefined; | |
| 185 | const parse = (part: string): number[] | undefined => { | |
| 186 | if (part === "") return []; | |
| 187 | const out: number[] = []; | |
| 188 | for (const g of part.split(":")) { | |
| 189 | if (!/^[0-9a-f]{1,4}$/.test(g)) return undefined; | |
| 190 | out.push(parseInt(g, 16)); | |
| 191 | } | |
| 192 | return out; | |
| 193 | }; | |
| 194 | const head = parse(halves[0]!); | |
| 195 | const tail = halves.length === 2 ? parse(halves[1]!) : []; | |
| 196 | if (head === undefined || tail === undefined) return undefined; | |
| 197 | if (halves.length === 1) return head.length === 8 ? head : undefined; | |
| 198 | const fill = 8 - head.length - tail.length; | |
| 199 | if (fill < 1) return undefined; | |
| 200 | return [...head, ...new Array<number>(fill).fill(0), ...tail]; | |
| 201 | } |
src/origins/discover.ts +23 −12
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | * a redirect may never leave the host we asked. |
| 17 | 17 | */ |
| 18 | 18 | |
| 19 | import { guardedFetch, loopbackAllowed } from "../http/outbound.ts"; | |
| 19 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 20 | 21 | import { readCapped } from "./providers/http.ts"; |
| 21 | 22 | import type { Discovered, OriginKind } from "./types.ts"; |
| @@ -140,7 +141,7 @@ export function allowedOrigin( | ||
| 140 | 141 | allowed.has(url.host.toLowerCase()) || |
| 141 | 142 | allowed.has(url.hostname.toLowerCase()); |
| 142 | 143 | if (named) return url.origin; |
| 143 | if (isLoopback(url.hostname)) return url.origin; | |
| 144 | if (loopbackAllowed(env) && isLoopback(url.hostname)) return url.origin; | |
| 144 | 145 | if (url.protocol !== "https:") return undefined; |
| 145 | 146 | if (isPrivateLiteral(url.hostname)) return undefined; |
| 146 | 147 | return url.origin; |
| @@ -187,10 +188,10 @@ export async function discover( | ||
| 187 | 188 | } |
| 188 | 189 | |
| 189 | 190 | // One cheap look at the standard, then the probe that actually answers. |
| 190 | const node = await viaNodeInfo(web); | |
| 191 | const node = await viaNodeInfo(web, env); | |
| 191 | 192 | if (node) return ok(node); |
| 192 | 193 | |
| 193 | const version = await viaVersionEndpoint(web); | |
| 194 | const version = await viaVersionEndpoint(web, env); | |
| 194 | 195 | if (version) return ok(version); |
| 195 | 196 | |
| 196 | 197 | return err("unreachable"); |
| @@ -205,8 +206,9 @@ export async function discover( | ||
| 205 | 206 | */ |
| 206 | 207 | async function viaVersionEndpoint( |
| 207 | 208 | web: string, |
| 209 | env: Record<string, string | undefined>, | |
| 208 | 210 | ): Promise<Discovered | undefined> { |
| 209 | const doc = await getJson(`${web}/api/v1/version`, web); | |
| 211 | const doc = await getJson(`${web}/api/v1/version`, web, env); | |
| 210 | 212 | if (!doc.ok) return undefined; |
| 211 | 213 | const version = asString(field(doc.value, "version")); |
| 212 | 214 | if (version === "") return undefined; |
| @@ -220,8 +222,11 @@ async function viaVersionEndpoint( | ||
| 220 | 222 | }; |
| 221 | 223 | } |
| 222 | 224 | |
| 223 | async function viaNodeInfo(web: string): Promise<Discovered | undefined> { | |
| 224 | const index = await getJson(`${web}/.well-known/nodeinfo`, web); | |
| 225 | async function viaNodeInfo( | |
| 226 | web: string, | |
| 227 | env: Record<string, string | undefined>, | |
| 228 | ): Promise<Discovered | undefined> { | |
| 229 | const index = await getJson(`${web}/.well-known/nodeinfo`, web, env); | |
| 225 | 230 | if (!index.ok) return undefined; |
| 226 | 231 | const links = asArray(field(index.value, "links")); |
| 227 | 232 | // Prefer the newest schema the host offers; any of them carries `software`. |
| @@ -234,7 +239,7 @@ async function viaNodeInfo(web: string): Promise<Discovered | undefined> { | ||
| 234 | 239 | for (const href of hrefs.slice(0, 3)) { |
| 235 | 240 | // A NodeInfo document on another host is a redirect we did not consent to. |
| 236 | 241 | if (!sameOrigin(href, web)) continue; |
| 237 | const doc = await getJson(href, web); | |
| 242 | const doc = await getJson(href, web, env); | |
| 238 | 243 | if (!doc.ok) continue; |
| 239 | 244 | const name = asString(field(field(doc.value, "software"), "name")) |
| 240 | 245 | .trim() |
| @@ -271,17 +276,23 @@ function sameOrigin(href: string, web: string): boolean { | ||
| 271 | 276 | async function getJson( |
| 272 | 277 | url: string, |
| 273 | 278 | web: string, |
| 279 | env: Record<string, string | undefined>, | |
| 274 | 280 | ): Promise<Result<unknown, "failed">> { |
| 275 | 281 | let target = url; |
| 276 | 282 | for (let hop = 0; hop < MAX_HOPS; hop++) { |
| 277 | 283 | if (!sameOrigin(target, web)) return err("failed"); |
| 278 | 284 | let response: Response; |
| 279 | 285 | try { |
| 280 | response = await fetch(target, { | |
| 281 | headers: { accept: "application/json", "user-agent": "forge" }, | |
| 282 | redirect: "manual", | |
| 283 | signal: AbortSignal.timeout(TIMEOUT_MS), | |
| 284 | }); | |
| 286 | const sent = await guardedFetch( | |
| 287 | target, | |
| 288 | { | |
| 289 | headers: { accept: "application/json", "user-agent": "forge" }, | |
| 290 | signal: AbortSignal.timeout(TIMEOUT_MS), | |
| 291 | }, | |
| 292 | { allowHosts: allowedHosts(env) }, | |
| 293 | ); | |
| 294 | if (!sent.ok) return err("failed"); | |
| 295 | response = sent.value; | |
| 285 | 296 | } catch { |
| 286 | 297 | return err("failed"); |
| 287 | 298 | } |
src/origins/git-mirror.ts +26 −3
| @@ -23,6 +23,7 @@ import { isSafeOid, isSafeRef } from "../git/guard.ts"; | ||
| 23 | 23 | import { runGitCapture, type RunOptions } from "../git/env.ts"; |
| 24 | 24 | import { listRefs } from "../git/read.ts"; |
| 25 | 25 | import { ZERO_OID } from "../git/hooks.ts"; |
| 26 | import { gitRemoteEnv, vetUrl } from "../http/outbound.ts"; | |
| 26 | 27 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 27 | 28 | import { redact, safeRemoteUrl, secretsIn } from "./credentials.ts"; |
| 28 | 29 | |
| @@ -136,6 +137,24 @@ export async function configureMirror( | ||
| 136 | 137 | return ok(); |
| 137 | 138 | } |
| 138 | 139 | |
| 140 | /** | |
| 141 | * A remote's address comes from the remote's own API, so it is resolved and | |
| 142 | * judged before git dials it. Hosts the operator named (FORGE_ORIGIN_ALLOW) | |
| 143 | * are the origins they set up on purpose and are not judged. | |
| 144 | */ | |
| 145 | async function vetRemote(url: string): Promise<GitMirrorError | undefined> { | |
| 146 | const allow = new Set( | |
| 147 | (process.env["FORGE_ORIGIN_ALLOW"] ?? "") | |
| 148 | .split(",") | |
| 149 | .map((h) => h.trim().toLowerCase()) | |
| 150 | .filter((h) => h !== ""), | |
| 151 | ); | |
| 152 | const vetted = await vetUrl(url, { allowHosts: allow }); | |
| 153 | return vetted.ok | |
| 154 | ? undefined | |
| 155 | : { message: "refusing a remote that is not on the open internet" }; | |
| 156 | } | |
| 157 | ||
| 139 | 158 | export interface FetchResult { |
| 140 | 159 | readonly changes: readonly RefChange[]; |
| 141 | 160 | } |
| @@ -158,6 +177,8 @@ export async function fetchMirror( | ||
| 158 | 177 | const url = safeRemoteUrl(cloneUrl); |
| 159 | 178 | if (url === undefined) |
| 160 | 179 | return err({ message: "refusing an unusable clone URL" }); |
| 180 | const refused = await vetRemote(url); | |
| 181 | if (refused !== undefined) return err(refused); | |
| 161 | 182 | |
| 162 | 183 | const before = await snapshotRefs(dir); |
| 163 | 184 | const run = await runGitCapture( |
| @@ -170,7 +191,7 @@ export async function fetchMirror( | ||
| 170 | 191 | url, |
| 171 | 192 | ...MIRROR_REFSPECS, |
| 172 | 193 | ], |
| 173 | { cwd: dir, env: authEnv, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 194 | { cwd: dir, env: gitRemoteEnv(authEnv), timeoutMs: FETCH_TIMEOUT_MS }, | |
| 174 | 195 | ); |
| 175 | 196 | if (run.code !== 0) { |
| 176 | 197 | return err({ |
| @@ -206,6 +227,8 @@ export async function fetchRefFrom( | ||
| 206 | 227 | const url = safeRemoteUrl(cloneUrl); |
| 207 | 228 | if (url === undefined) |
| 208 | 229 | return err({ message: "refusing an unusable clone URL" }); |
| 230 | const refused = await vetRemote(url); | |
| 231 | if (refused !== undefined) return err(refused); | |
| 209 | 232 | if (!isSafeRef(srcRef)) |
| 210 | 233 | return err({ message: `refusing an unsafe ref: ${srcRef}` }); |
| 211 | 234 | |
| @@ -220,7 +243,7 @@ export async function fetchRefFrom( | ||
| 220 | 243 | // without any local ref moving. |
| 221 | 244 | srcRef, |
| 222 | 245 | ], |
| 223 | { cwd: dir, env: authEnv, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 246 | { cwd: dir, env: gitRemoteEnv(authEnv), timeoutMs: FETCH_TIMEOUT_MS }, | |
| 224 | 247 | ); |
| 225 | 248 | if (run.code !== 0) { |
| 226 | 249 | return err({ |
| @@ -293,7 +316,7 @@ export async function pushToOrigin( | ||
| 293 | 316 | |
| 294 | 317 | const run = await runGitCapture(args, { |
| 295 | 318 | ...options, |
| 296 | env: { ...authEnv, ...(options.env ?? {}) }, | |
| 319 | env: { ...gitRemoteEnv(authEnv), ...(options.env ?? {}) }, | |
| 297 | 320 | cwd: dir, |
| 298 | 321 | timeoutMs: options.timeoutMs ?? PUSH_TIMEOUT_MS, |
| 299 | 322 | }); |
test/origins-oauth.test.ts +6 −5
| @@ -625,14 +625,15 @@ describe("discovery will not dial anything it is asked to", () => { | ||
| 625 | 625 | ]) { |
| 626 | 626 | expect(allowedOrigin(refused, env())).toBeUndefined(); |
| 627 | 627 | } |
| 628 | // Public https hosts are fine, and so is loopback (this machine). | |
| 628 | // Public https hosts are fine; loopback (this machine) only in dev. | |
| 629 | 629 | expect(allowedOrigin("codeberg.org", env())).toBe("https://codeberg.org"); |
| 630 | expect(allowedOrigin("http://localhost:3000", env())).toBe( | |
| 630 | expect(allowedOrigin("http://localhost:3000", env())).toBeUndefined(); | |
| 631 | expect(allowedOrigin("http://127.0.0.1:9", env())).toBeUndefined(); | |
| 632 | const dev = { ...env(), FORGE_DEV: "1" }; | |
| 633 | expect(allowedOrigin("http://localhost:3000", dev)).toBe( | |
| 631 | 634 | "http://localhost:3000", |
| 632 | 635 | ); |
| 633 | expect(allowedOrigin("http://127.0.0.1:9", env())).toBe( | |
| 634 | "http://127.0.0.1:9", | |
| 635 | ); | |
| 636 | expect(allowedOrigin("http://127.0.0.1:9", dev)).toBe("http://127.0.0.1:9"); | |
| 636 | 637 | |
| 637 | 638 | // And discovery itself refuses the same input without making a request. |
| 638 | 639 | expect(await discover("file:///etc/passwd", env())).toEqual({ |
test/outbound.test.ts added +102
| @@ -0,0 +1,102 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { createWebhook } from "../src/core/webhooks.ts"; | |
| 3 | import { allowedOrigin } from "../src/origins/discover.ts"; | |
| 4 | import { gitRemoteEnv, guardedFetch, vetUrl } from "../src/http/outbound.ts"; | |
| 5 | ||
| 6 | const strict = { loopback: false }; | |
| 7 | const answers = | |
| 8 | (...a: string[]) => | |
| 9 | async () => | |
| 10 | a; | |
| 11 | ||
| 12 | describe("outbound guard", () => { | |
| 13 | test("refuses literal loopback, private and metadata addresses", async () => { | |
| 14 | for (const u of [ | |
| 15 | "https://127.0.0.1/", | |
| 16 | "https://10.1.2.3/", | |
| 17 | "https://169.254.169.254/latest/meta-data", | |
| 18 | "https://[::1]/", | |
| 19 | "https://[::ffff:169.254.169.254]/", | |
| 20 | ]) { | |
| 21 | const r = await vetUrl(u, strict); | |
| 22 | expect(r.ok).toBe(false); | |
| 23 | } | |
| 24 | }); | |
| 25 | ||
| 26 | test("refuses a public name that resolves to 127.0.0.1", async () => { | |
| 27 | const r = await vetUrl("https://example.com/", { | |
| 28 | ...strict, | |
| 29 | resolve: answers("93.184.216.34", "127.0.0.1"), | |
| 30 | }); | |
| 31 | expect(r).toEqual({ ok: false, error: "private" }); | |
| 32 | }); | |
| 33 | ||
| 34 | test("allows a public name, and refuses an unresolvable one", async () => { | |
| 35 | expect( | |
| 36 | (await vetUrl("https://example.com/", { ...strict, resolve: answers("93.184.216.34") })).ok, | |
| 37 | ).toBe(true); | |
| 38 | const r = await vetUrl("https://nope.invalid/", { | |
| 39 | ...strict, | |
| 40 | resolve: async () => { | |
| 41 | throw new Error("ENOTFOUND"); | |
| 42 | }, | |
| 43 | }); | |
| 44 | expect(r).toEqual({ ok: false, error: "unresolved" }); | |
| 45 | }); | |
| 46 | ||
| 47 | test("httpsOnly refuses plain http; loopback is only for dev", async () => { | |
| 48 | const pub = { resolve: answers("93.184.216.34") }; | |
| 49 | expect(await vetUrl("http://example.com/", { ...strict, ...pub, httpsOnly: true })).toEqual({ ok: false, error: "scheme" }); | |
| 50 | expect((await vetUrl("http://127.0.0.1:9/", { loopback: true, httpsOnly: true })).ok).toBe(true); | |
| 51 | expect((await vetUrl("http://127.0.0.1:9/", strict)).ok).toBe(false); | |
| 52 | }); | |
| 53 | ||
| 54 | test("an operator-named host is not judged", async () => { | |
| 55 | const r = await vetUrl("https://10.0.0.5/", { ...strict, allowHosts: new Set(["10.0.0.5"]) }); | |
| 56 | expect(r.ok).toBe(true); | |
| 57 | }); | |
| 58 | ||
| 59 | test("guardedFetch never reaches a private address", async () => { | |
| 60 | const r = await guardedFetch("https://127.0.0.1:1/", {}, strict); | |
| 61 | expect(r).toEqual({ ok: false, error: "private" }); | |
| 62 | }); | |
| 63 | ||
| 64 | test("a redirect to a private address is not followed, and its next hop is refused", async () => { | |
| 65 | const server = Bun.serve({ | |
| 66 | port: 0, | |
| 67 | hostname: "127.0.0.1", | |
| 68 | fetch: () => new Response(null, { status: 302, headers: { location: "http://169.254.169.254/" } }), | |
| 69 | }); | |
| 70 | try { | |
| 71 | const hop = await guardedFetch(`http://127.0.0.1:${server.port}/`, {}, { loopback: true }); | |
| 72 | if (!hop.ok) throw new Error("first hop should be reachable in dev"); | |
| 73 | expect(hop.value.status).toBe(302); | |
| 74 | const next = await vetUrl(hop.value.headers.get("location")!, { loopback: true }); | |
| 75 | expect(next).toEqual({ ok: false, error: "private" }); | |
| 76 | } finally { | |
| 77 | server.stop(true); | |
| 78 | } | |
| 79 | }); | |
| 80 | ||
| 81 | test("webhooks need https outside dev", () => { | |
| 82 | const prev = process.env["NODE_ENV"]; | |
| 83 | process.env["NODE_ENV"] = "production"; | |
| 84 | try { | |
| 85 | const db = {} as never; | |
| 86 | expect(createWebhook(db, { repoId: "r", url: "http://example.com/h" })).toEqual({ ok: false, error: "invalid_url" }); | |
| 87 | } finally { | |
| 88 | process.env["NODE_ENV"] = prev ?? "test"; | |
| 89 | } | |
| 90 | }); | |
| 91 | ||
| 92 | test("discovery allows loopback only in dev", () => { | |
| 93 | expect(allowedOrigin("http://127.0.0.1:3000", { FORGE_DEV: "1" })).toBe("http://127.0.0.1:3000"); | |
| 94 | expect(allowedOrigin("http://127.0.0.1:3000", {})).toBeUndefined(); | |
| 95 | }); | |
| 96 | ||
| 97 | test("git sees no redirects and only the pinned transports", () => { | |
| 98 | const env = gitRemoteEnv({}); | |
| 99 | expect(env["GIT_ALLOW_PROTOCOL"]).toBe("https:http:git"); | |
| 100 | expect(env["GIT_CONFIG_VALUE_0"]).toBe("false"); | |
| 101 | }); | |
| 102 | }); |
new above
offline