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 #2946
mason/forge:mason/2921-outbound-fetches-never-reach-private-net → main 2 commits fork 1 thread · 1 unresolved
15 files
changed +800
−228
README.md +3 −1
| @@ -400,7 +400,9 @@ routers learn it is going, so a roll refuses nobody (`docs/ops/ROLL.md`). | ||
| 400 | 400 | Connecting origins |
| 401 | 401 | adds `FORGE_URL` (the canonical public base URL, needed for OAuth callbacks), |
| 402 | 402 | `FORGE_GITHUB_CLIENT_ID` / `FORGE_GITHUB_CLIENT_SECRET`, and |
| 403 | `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Behind a | |
| 403 | `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Webhooks, | |
| 404 | discovery, mirrors and migrations never reach this machine or a private | |
| 405 | address; `FORGE_DEV=1` lets a development forge reach `localhost`. Behind a | |
| 404 | 406 | platform edge that signs people in for every app it serves, `FORGE_EDGE_TOKEN` |
| 405 | 407 | is the edge's secret: a request carrying it and `X-Plat-User` is that person, |
| 406 | 408 | signed in by the platform if an account of that name exists. An unknown login |
docs/ORIGINS.md +6 −2
| @@ -111,8 +111,12 @@ publishes neither, so the user names it (`kind: "github"` with a host → | ||
| 111 | 111 | `/api/v3`). `whoami()` then validates the credential and fixes `login`. |
| 112 | 112 | |
| 113 | 113 | Discovery fetches a host a stranger named, so it is https-only, refuses |
| 114 | private address literals and non-http schemes, follows no redirect off-host, | |
| 115 | caps the body at 64 KB and times out in 5 s. An operator can vouch for a LAN | |
| 114 | non-http schemes and any name that resolves to a private, loopback or | |
| 115 | link-local address, connects to the address it judged, follows no redirect | |
| 116 | off-host, caps the body at 64 KB and times out in 5 s. A mirror's git fetch | |
| 117 | and push are held to the same rule (`kernel/outbound.ts`), pinned with | |
| 118 | `http.curloptResolve` and `http.followRedirects=false`. This machine is a | |
| 119 | destination only in development (`FORGE_DEV=1`) and under `bun test`. An operator can vouch for a LAN | |
| 116 | 120 | or plaintext host with `FORGE_ORIGIN_ALLOW=host[,host…]`; there is no |
| 117 | 121 | per-user toggle, because the risk it accepts belongs to the server. |
| 118 | 122 |
docs/THREATS.md +6
| @@ -62,6 +62,12 @@ trusts: a package, a model provider, a hosting provider, an origin it syncs from | ||
| 62 | 62 | repository declared and refuses names that resolve to private, loopback or |
| 63 | 63 | metadata addresses. |
| 64 | 64 | Test: `test/apps-adversarial.test.ts` |
| 65 | - Every address a person types that the forge then fetches — a webhook, an | |
| 66 | origin it discovers, a repository it mirrors or migrates — is resolved, | |
| 67 | refused when any answer is loopback, private, link-local or metadata, and | |
| 68 | connected to at the address that was judged (`kernel/outbound.ts`). No | |
| 69 | redirect is followed. This machine is reachable only with `FORGE_DEV=1`. | |
| 70 | Test: `test/outbound.test.ts` | |
| 65 | 71 | - A connected origin's replies are validated at the boundary and not trusted for |
| 66 | 72 | identity. |
| 67 | 73 | Test: `test/origins-security-provider.test.ts` |
src/actions/migrate.ts +29 −108
| @@ -28,6 +28,7 @@ import type { User } from "../core/users.ts"; | ||
| 28 | 28 | import { runGitCapture } from "../git/env.ts"; |
| 29 | 29 | import { isSafeRef } from "../git/guard.ts"; |
| 30 | 30 | import { repoDir } from "../git/repos.ts"; |
| 31 | import { pinnedGitEnv, resolveTarget } from "../kernel/outbound.ts"; | |
| 31 | 32 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 32 | 33 | import { providerForOrigin } from "../origins/credential.ts"; |
| 33 | 34 | import { redact, safeRemoteUrl, secretsIn } from "../origins/credentials.ts"; |
| @@ -96,6 +97,8 @@ interface Resolved { | ||
| 96 | 97 | readonly name: string; |
| 97 | 98 | readonly description: string; |
| 98 | 99 | readonly authEnv: () => Promise<Record<string, string>>; |
| 100 | /** The address the URL's name was judged at: the only one git connects to. */ | |
| 101 | readonly address: string; | |
| 99 | 102 | } |
| 100 | 103 | |
| 101 | 104 | /** |
| @@ -232,103 +235,6 @@ export function migrateUrl(raw: string): string | undefined { | ||
| 232 | 235 | return safeRemoteUrl(parsed.toString()); |
| 233 | 236 | } |
| 234 | 237 | |
| 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 | 238 | /** The last path segment without `.git`: what the repository was called. */ |
| 333 | 239 | function nameFromUrl(url: string): string { |
| 334 | 240 | const path = new URL(url).pathname.replace(/\/+$/, ""); |
| @@ -344,16 +250,8 @@ async function resolveSource( | ||
| 344 | 250 | if ("url" in source) { |
| 345 | 251 | const url = migrateUrl(source.url); |
| 346 | 252 | if (url === undefined) return err("invalid_url"); |
| 347 | // A host inside the network — this machine, the cluster, a private | |
| 348 | // range — is not a public repository, and a pasted address must not | |
| 349 | // become a way to knock on it. An admin may; a forge run for one person | |
| 350 | // 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"); | |
| 253 | const address = await judged(app, user, url); | |
| 254 | if (!address.ok) return address; | |
| 357 | 255 | return ok({ |
| 358 | 256 | url, |
| 359 | 257 | label: url, |
| @@ -361,6 +259,7 @@ async function resolveSource( | ||
| 361 | 259 | name: nameFromUrl(url), |
| 362 | 260 | description: "", |
| 363 | 261 | authEnv: () => Promise.resolve({}), |
| 262 | address: address.value, | |
| 364 | 263 | }); |
| 365 | 264 | } |
| 366 | 265 | const origin = getOriginFor(app.db, user.id, source.originId); |
| @@ -374,6 +273,9 @@ async function resolveSource( | ||
| 374 | 273 | ); |
| 375 | 274 | const url = safeRemoteUrl(remote.value.cloneUrl); |
| 376 | 275 | if (url === undefined) return err("unreachable"); |
| 276 | // The clone URL is the origin's word, not the person's: judged the same. | |
| 277 | const address = await judged(app, user, url); | |
| 278 | if (!address.ok) return address; | |
| 377 | 279 | return ok({ |
| 378 | 280 | url, |
| 379 | 281 | label: remote.value.fullName, |
| @@ -383,9 +285,28 @@ async function resolveSource( | ||
| 383 | 285 | // Only the header: the origin's credential reaches this one git |
| 384 | 286 | // invocation scoped to its host, and the repository never learns it. |
| 385 | 287 | authEnv: () => provider.value.gitAuthEnv(url), |
| 288 | address: address.value, | |
| 386 | 289 | }); |
| 387 | 290 | } |
| 388 | 291 | |
| 292 | /** | |
| 293 | * The address a clone of `url` connects to. A host inside the network — | |
| 294 | * this machine, the cluster, a private range, or a public name resolving | |
| 295 | * into one — is not a public repository, and a pasted address must not | |
| 296 | * become a way to knock on it. An admin may; a forge run for one person | |
| 297 | * may say so once (`FORGE_MIGRATE_PRIVATE_HOSTS=1`). | |
| 298 | */ | |
| 299 | async function judged( | |
| 300 | app: App, | |
| 301 | user: User, | |
| 302 | url: string, | |
| 303 | ): Promise<Result<string, "private_host" | "unreachable">> { | |
| 304 | const anywhere = user.isAdmin || app.config.migrateFromPrivateHosts === true; | |
| 305 | const target = await resolveTarget(url, { loopback: false, anywhere }); | |
| 306 | if (target.ok) return target; | |
| 307 | return err(target.error === "private_address" ? "private_host" : "unreachable"); | |
| 308 | } | |
| 309 | ||
| 389 | 310 | /** The job itself. Nothing here throws out: a detached promise must not. */ |
| 390 | 311 | async function runMigration( |
| 391 | 312 | app: App, |
| @@ -483,7 +404,7 @@ async function cloneInto( | ||
| 483 | 404 | const deadline = Date.now() + MIGRATE_TIMEOUT_MS; |
| 484 | 405 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 485 | 406 | const authEnv = await source.authEnv(); |
| 486 | const env = { ...noRedirects(authEnv), GIT_ALLOW_PROTOCOL: ALLOWED_PROTOCOL }; | |
| 407 | const env = pinnedGitEnv(authEnv, source.url, source.address, ALLOWED_PROTOCOL); | |
| 487 | 408 | const said = (stderr: string, fallback: string): string => |
| 488 | 409 | redact(stderr.trim(), ...secretsIn(authEnv)) |
| 489 | 410 | .split("\n") |
src/actions/upstream.ts +3 −1
| @@ -230,9 +230,11 @@ export async function proposeToParentForge( | ||
| 230 | 230 | const auth = gitAuthEnv(cred.url, basicHeader(cred.child, cred.token)); |
| 231 | 231 | const ref = `refs/heads/${head}`; |
| 232 | 232 | const push = (oldOid: string) => |
| 233 | // The parent is the operator's address, not a user's: any address it | |
| 234 | // resolves to is reached, still pinned and following no redirect. | |
| 233 | 235 | pushToOrigin(dir, `${cred.url}/${cred.repo}.git`, [{ ref, oldOid, newOid: tip }], auth, { |
| 234 | 236 | timeoutMs: PUSH_TIMEOUT_MS, |
| 235 | }); | |
| 237 | }, { loopback: true, anywhere: true }); | |
| 236 | 238 | let pushed = await push("0".repeat(40)); |
| 237 | 239 | // An earlier press may have landed the branch and then lost the pull: the |
| 238 | 240 | // branch is at this very tip, so pushing it again expecting it there is a |
src/core/webhooks.ts +48 −12
| @@ -13,6 +13,13 @@ import type { Database } from "bun:sqlite"; | ||
| 13 | 13 | import { defect } from "../kernel/error.ts"; |
| 14 | 14 | import { id, secret as randomSecret } from "../kernel/id.ts"; |
| 15 | 15 | import type { Log } from "../kernel/log.ts"; |
| 16 | import { | |
| 17 | isLoopbackHost, | |
| 18 | isPrivateHost, | |
| 19 | outboundFetch, | |
| 20 | outboundPolicy, | |
| 21 | type OutboundPolicy, | |
| 22 | } from "../kernel/outbound.ts"; | |
| 16 | 23 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 17 | 24 | import type { ForgeEvent } from "./events.ts"; |
| 18 | 25 | |
| @@ -63,19 +70,36 @@ export interface CreateWebhookInput { | ||
| 63 | 70 | secret?: string; |
| 64 | 71 | } |
| 65 | 72 | |
| 73 | /** | |
| 74 | * Whether a hook may point here: https to a host outside the network. Plain | |
| 75 | * http and this machine are for a development forge and the test suite | |
| 76 | * only. A name is judged again, resolved, at every delivery. | |
| 77 | */ | |
| 78 | export function webhookUrlAllowed( | |
| 79 | url: string, | |
| 80 | policy: OutboundPolicy = outboundPolicy(), | |
| 81 | ): boolean { | |
| 82 | if (!/^https?:\/\/.+/i.test(url)) return false; | |
| 83 | let parsed: URL; | |
| 84 | try { | |
| 85 | parsed = new URL(url); | |
| 86 | } catch { | |
| 87 | return false; | |
| 88 | } | |
| 89 | if (parsed.username !== "" || parsed.password !== "") return false; | |
| 90 | const local = policy.loopback && isLoopbackHost(parsed.hostname); | |
| 91 | if (local) return true; | |
| 92 | return parsed.protocol === "https:" && !isPrivateHost(parsed.hostname); | |
| 93 | } | |
| 94 | ||
| 66 | 95 | export function createWebhook( |
| 67 | 96 | db: Database, |
| 68 | 97 | input: CreateWebhookInput, |
| 98 | policy: OutboundPolicy = outboundPolicy(), | |
| 69 | 99 | ): Result<{ webhook: Webhook; secret: string }, CreateWebhookError> { |
| 70 | 100 | 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"); | |
| 73 | try { | |
| 74 | // eslint-disable-next-line no-new | |
| 75 | new URL(url); | |
| 76 | } catch { | |
| 77 | return err("invalid_url"); | |
| 78 | } | |
| 101 | // Never a bare/relative URL, never inside the network — this value is fetched. | |
| 102 | if (!webhookUrlAllowed(url, policy)) return err("invalid_url"); | |
| 79 | 103 | |
| 80 | 104 | const webhookId = id(); |
| 81 | 105 | const secretValue = |
| @@ -190,6 +214,7 @@ export async function deliverDue( | ||
| 190 | 214 | db: Database, |
| 191 | 215 | log: Log, |
| 192 | 216 | now = new Date(), |
| 217 | policy: OutboundPolicy = outboundPolicy(), | |
| 193 | 218 | ): Promise<number> { |
| 194 | 219 | const nowIso = now.toISOString(); |
| 195 | 220 | const due = db |
| @@ -226,7 +251,7 @@ export async function deliverDue( | ||
| 226 | 251 | ); |
| 227 | 252 | if (claimed.changes !== 1) continue; |
| 228 | 253 | try { |
| 229 | await deliverOne(db, log, row, now); | |
| 254 | await deliverOne(db, log, row, now, policy); | |
| 230 | 255 | } catch (error) { |
| 231 | 256 | // One malformed delivery must not take the batch with it. Without |
| 232 | 257 | // this, a single unsendable row stops every delivery behind it — and |
| @@ -249,6 +274,7 @@ async function deliverOne( | ||
| 249 | 274 | log: Log, |
| 250 | 275 | row: DueRow, |
| 251 | 276 | now: Date, |
| 277 | policy: OutboundPolicy, | |
| 252 | 278 | ): Promise<void> { |
| 253 | 279 | const body = JSON.stringify({ |
| 254 | 280 | id: row.event_id, |
| @@ -263,7 +289,15 @@ async function deliverOne( | ||
| 263 | 289 | |
| 264 | 290 | let status = 0; |
| 265 | 291 | try { |
| 266 | const response = await fetch(row.url, { | |
| 292 | // A hook made before the rule, or a name that now resolves inside the | |
| 293 | // network, is an attempt that reached nothing: status 0, and the | |
| 294 | // backoff gives up on it like any dead endpoint. | |
| 295 | if (!webhookUrlAllowed(row.url, policy)) { | |
| 296 | log.warn("webhook refused", { delivery: row.id, reason: "url" }); | |
| 297 | backOff(db, log, row, 0, now); | |
| 298 | return; | |
| 299 | } | |
| 300 | const sent = await outboundFetch(row.url, { | |
| 267 | 301 | method: "POST", |
| 268 | 302 | headers: { |
| 269 | 303 | "content-type": "application/json", |
| @@ -277,8 +311,10 @@ async function deliverOne( | ||
| 277 | 311 | body, |
| 278 | 312 | signal: AbortSignal.timeout(DELIVER_TIMEOUT_MS), |
| 279 | 313 | redirect: "manual", |
| 280 | }); | |
| 281 | status = response.status; | |
| 314 | }, policy); | |
| 315 | if (sent.ok) status = sent.value.status; | |
| 316 | else | |
| 317 | log.warn("webhook refused", { delivery: row.id, reason: sent.error }); | |
| 282 | 318 | } catch (error) { |
| 283 | 319 | log.warn("webhook delivery error", { |
| 284 | 320 | delivery: row.id, |
src/crew/notify.ts +16 −15
| @@ -23,9 +23,8 @@ | ||
| 23 | 23 | import { newAccountLines } from "../actions/accounts.ts"; |
| 24 | 24 | import { mailCeilingLines } from "../actions/mail.ts"; |
| 25 | 25 | import type { Database } from "bun:sqlite"; |
| 26 | import { lookup } from "node:dns/promises"; | |
| 27 | 26 | import type { App } from "../app.ts"; |
| 28 | import { isPrivateHost } from "../actions/migrate.ts"; | |
| 27 | import { isPrivateHost, outboundFetch } from "../kernel/outbound.ts"; | |
| 29 | 28 | import { getUserSetting, setUserSetting } from "../core/settings.ts"; |
| 30 | 29 | import { getUserById, type User } from "../core/users.ts"; |
| 31 | 30 | import { landedLines } from "../core/watches.ts"; |
| @@ -141,20 +140,22 @@ export type Sender = ( | ||
| 141 | 140 | headers: Record<string, string>, |
| 142 | 141 | ) => Promise<boolean>; |
| 143 | 142 | |
| 144 | /** The real sender: the name is resolved and judged first, no redirect is followed. */ | |
| 143 | /** | |
| 144 | * The real sender: the name is resolved, judged and pinned, no redirect is | |
| 145 | * followed, and this machine is never a topic host — not even in development. | |
| 146 | */ | |
| 145 | 147 | const post: Sender = async (url, body, headers) => { |
| 146 | const host = new URL(url).hostname; | |
| 147 | const found = await lookup(host, { all: true }); | |
| 148 | if (found.length === 0 || found.some((a) => isPrivateHost(a.address))) | |
| 149 | return false; | |
| 150 | const res = await fetch(url, { | |
| 151 | method: "POST", | |
| 152 | body, | |
| 153 | headers: { "content-type": "text/plain; charset=utf-8", ...headers }, | |
| 154 | redirect: "manual", | |
| 155 | signal: AbortSignal.timeout(SEND_TIMEOUT_MS), | |
| 156 | }); | |
| 157 | return res.status >= 200 && res.status < 300; | |
| 148 | const res = await outboundFetch( | |
| 149 | url, | |
| 150 | { | |
| 151 | method: "POST", | |
| 152 | body, | |
| 153 | headers: { "content-type": "text/plain; charset=utf-8", ...headers }, | |
| 154 | signal: AbortSignal.timeout(SEND_TIMEOUT_MS), | |
| 155 | }, | |
| 156 | { loopback: false }, | |
| 157 | ); | |
| 158 | return res.ok && res.value.status >= 200 && res.value.status < 300; | |
| 158 | 159 | }; |
| 159 | 160 | |
| 160 | 161 | /** |
src/kernel/outbound.ts added +212
| @@ -0,0 +1,212 @@ | ||
| 1 | /** | |
| 2 | * Every request the forge makes to an address a person typed — a webhook, | |
| 3 | * an origin it discovers, a repository it mirrors or migrates — passes here. | |
| 4 | * The name is resolved, every address it resolves to is judged, and the | |
| 5 | * connection is pinned to the address that was judged: a name that answers | |
| 6 | * "203.0.113.7" to the check and "127.0.0.1" to the connect (DNS rebinding) | |
| 7 | * reaches nothing, because there is no second lookup. | |
| 8 | * | |
| 9 | * Refused: loopback, the private ranges, link-local (the cloud metadata | |
| 10 | * address among them), carrier-grade NAT, multicast and the reserved | |
| 11 | * blocks, in either IP family and in IPv4-in-IPv6 clothes. This machine is | |
| 12 | * reachable only in development (`FORGE_DEV=1`) and under `bun test`, where | |
| 13 | * every fake remote listens on 127.0.0.1. | |
| 14 | */ | |
| 15 | ||
| 16 | import { lookup as dnsLookup } from "node:dns/promises"; | |
| 17 | import { checkServerIdentity } from "node:tls"; | |
| 18 | import { defect } from "./error.ts"; | |
| 19 | import { addressBytes, inCidrs, parseCidrs } from "./cidr.ts"; | |
| 20 | import { err, ok, type Result } from "./result.ts"; | |
| 21 | ||
| 22 | const PRIVATE = parseCidrs( | |
| 23 | [ | |
| 24 | "0.0.0.0/8", | |
| 25 | "10.0.0.0/8", | |
| 26 | "100.64.0.0/10", | |
| 27 | "127.0.0.0/8", | |
| 28 | "169.254.0.0/16", | |
| 29 | "172.16.0.0/12", | |
| 30 | "192.0.0.0/24", | |
| 31 | "192.168.0.0/16", | |
| 32 | "198.18.0.0/15", | |
| 33 | "224.0.0.0/3", // multicast, reserved, broadcast | |
| 34 | "::/96", // unspecified, loopback, IPv4-compatible | |
| 35 | "64:ff9b::/96", // NAT64: an IPv4 address behind a translator | |
| 36 | "fc00::/7", | |
| 37 | "fe80::/10", | |
| 38 | "ff00::/8", | |
| 39 | ].join(","), | |
| 40 | ); | |
| 41 | if (!PRIVATE.ok) defect("outbound.range", PRIVATE.error); | |
| 42 | const PRIVATE_RANGES = PRIVATE.value; | |
| 43 | ||
| 44 | const LOOPBACK = parseCidrs("127.0.0.0/8,::1/128"); | |
| 45 | if (!LOOPBACK.ok) defect("outbound.range", LOOPBACK.error); | |
| 46 | const LOOPBACK_RANGES = LOOPBACK.value; | |
| 47 | ||
| 48 | const bare = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, ""); | |
| 49 | ||
| 50 | /** | |
| 51 | * Whether a hostname names something inside the network rather than on the | |
| 52 | * open internet: an address literal in a refused range, `localhost`, or a | |
| 53 | * `.localhost` name. Names are not resolved here — `resolveTarget` does that. | |
| 54 | */ | |
| 55 | export function isPrivateHost(hostname: string): boolean { | |
| 56 | const h = bare(hostname); | |
| 57 | if (h === "localhost" || h.endsWith(".localhost")) return true; | |
| 58 | return addressBytes(h) !== undefined && inCidrs(h, PRIVATE_RANGES); | |
| 59 | } | |
| 60 | ||
| 61 | /** This machine: `localhost`, 127/8 or ::1, in any spelling. */ | |
| 62 | export function isLoopbackHost(hostname: string): boolean { | |
| 63 | const h = bare(hostname); | |
| 64 | if (h === "localhost" || h.endsWith(".localhost")) return true; | |
| 65 | return addressBytes(h) !== undefined && inCidrs(h, LOOPBACK_RANGES); | |
| 66 | } | |
| 67 | ||
| 68 | /** A development forge or the test suite: the only places loopback is a destination. */ | |
| 69 | export function devLoopback( | |
| 70 | env: Record<string, string | undefined> = process.env, | |
| 71 | ): boolean { | |
| 72 | return env.FORGE_DEV === "1" || env.NODE_ENV === "test"; | |
| 73 | } | |
| 74 | ||
| 75 | export type Lookup = (hostname: string) => Promise<readonly string[]>; | |
| 76 | ||
| 77 | const systemLookup: Lookup = async (hostname) => | |
| 78 | (await dnsLookup(hostname, { all: true })).map((a) => a.address); | |
| 79 | ||
| 80 | export interface OutboundPolicy { | |
| 81 | /** Loopback is a destination: `devLoopback()`, never in production. */ | |
| 82 | readonly loopback: boolean; | |
| 83 | /** | |
| 84 | * Any address is a destination — an operator vouched for this host | |
| 85 | * (`FORGE_ORIGIN_ALLOW`), or an admin asked. The connection is still pinned. | |
| 86 | */ | |
| 87 | readonly anywhere?: boolean; | |
| 88 | /** Stand-in for DNS in tests. */ | |
| 89 | readonly lookup?: Lookup; | |
| 90 | } | |
| 91 | ||
| 92 | export const outboundPolicy = ( | |
| 93 | env: Record<string, string | undefined> = process.env, | |
| 94 | ): OutboundPolicy => ({ loopback: devLoopback(env) }); | |
| 95 | ||
| 96 | export type OutboundRefusal = "invalid_url" | "private_address" | "unresolved"; | |
| 97 | ||
| 98 | /** | |
| 99 | * The one address a request to `url` may connect to, or why there is none. | |
| 100 | * Every address the name resolves to must pass, not just the first: a name | |
| 101 | * with one public and one private answer is a coin toss at connect time. | |
| 102 | */ | |
| 103 | export async function resolveTarget( | |
| 104 | url: string | URL, | |
| 105 | policy: OutboundPolicy, | |
| 106 | ): Promise<Result<string, OutboundRefusal>> { | |
| 107 | let parsed: URL; | |
| 108 | try { | |
| 109 | parsed = typeof url === "string" ? new URL(url) : url; | |
| 110 | } catch { | |
| 111 | return err("invalid_url"); | |
| 112 | } | |
| 113 | const host = bare(parsed.hostname); | |
| 114 | if (host === "") return err("invalid_url"); | |
| 115 | let addresses: readonly string[]; | |
| 116 | if (addressBytes(host) !== undefined) addresses = [host]; | |
| 117 | else if (host === "localhost" || host.endsWith(".localhost")) | |
| 118 | addresses = ["127.0.0.1"]; | |
| 119 | else { | |
| 120 | try { | |
| 121 | addresses = await (policy.lookup ?? systemLookup)(host); | |
| 122 | } catch { | |
| 123 | return err("unresolved"); | |
| 124 | } | |
| 125 | } | |
| 126 | if (addresses.length === 0) return err("unresolved"); | |
| 127 | if (policy.anywhere !== true) { | |
| 128 | for (const address of addresses) { | |
| 129 | if (policy.loopback && inCidrs(address, LOOPBACK_RANGES)) continue; | |
| 130 | if (addressBytes(address) === undefined) return err("unresolved"); | |
| 131 | if (inCidrs(address, PRIVATE_RANGES)) return err("private_address"); | |
| 132 | } | |
| 133 | } | |
| 134 | return ok(addresses[0]!); | |
| 135 | } | |
| 136 | ||
| 137 | /** | |
| 138 | * `fetch`, to the address `resolveTarget` judged and nowhere else. The URL's | |
| 139 | * host is swapped for the address; the name still rides as `Host`, as the | |
| 140 | * TLS server name and as the name the certificate must carry. A redirect is | |
| 141 | * never followed: the caller sees it, and a hop is a new `outboundFetch`. | |
| 142 | */ | |
| 143 | export async function outboundFetch( | |
| 144 | url: string, | |
| 145 | init: RequestInit, | |
| 146 | policy: OutboundPolicy, | |
| 147 | ): Promise<Result<Response, OutboundRefusal>> { | |
| 148 | let parsed: URL; | |
| 149 | try { | |
| 150 | parsed = new URL(url); | |
| 151 | } catch { | |
| 152 | return err("invalid_url"); | |
| 153 | } | |
| 154 | if (parsed.protocol !== "https:" && parsed.protocol !== "http:") | |
| 155 | return err("invalid_url"); | |
| 156 | const target = await resolveTarget(parsed, policy); | |
| 157 | if (!target.ok) return target; | |
| 158 | const name = bare(parsed.hostname); | |
| 159 | const pinned = new URL(parsed); | |
| 160 | pinned.hostname = target.value.includes(":") | |
| 161 | ? `[${target.value}]` | |
| 162 | : target.value; | |
| 163 | const headers = new Headers(init.headers); | |
| 164 | headers.set("host", parsed.host); | |
| 165 | const response = await fetch(pinned, { | |
| 166 | ...init, | |
| 167 | headers, | |
| 168 | redirect: "manual", | |
| 169 | ...(parsed.protocol === "https:" | |
| 170 | ? { | |
| 171 | tls: { | |
| 172 | serverName: name, | |
| 173 | checkServerIdentity: (_: string, cert: never) => | |
| 174 | checkServerIdentity(name, cert), | |
| 175 | }, | |
| 176 | } | |
| 177 | : {}), | |
| 178 | } as RequestInit); | |
| 179 | return ok(response); | |
| 180 | } | |
| 181 | ||
| 182 | /** | |
| 183 | * The environment a git fetch or push to `url` runs with: connected to the | |
| 184 | * judged address (`http.curloptResolve`), following no redirect, and | |
| 185 | * speaking only the named transports. Entries are added after any the | |
| 186 | * credential brought, at the next free index. | |
| 187 | */ | |
| 188 | export function pinnedGitEnv( | |
| 189 | env: Record<string, string>, | |
| 190 | url: string, | |
| 191 | address: string, | |
| 192 | protocols = "https:http", | |
| 193 | ): Record<string, string> { | |
| 194 | const parsed = new URL(url); | |
| 195 | const port = | |
| 196 | parsed.port !== "" ? parsed.port : parsed.protocol === "http:" ? "80" : "443"; | |
| 197 | const at = address.includes(":") ? `[${address}]` : address; | |
| 198 | const config: [string, string][] = [["http.followRedirects", "false"]]; | |
| 199 | if (parsed.protocol === "https:" || parsed.protocol === "http:") | |
| 200 | config.push(["http.curloptResolve", `${bare(parsed.hostname)}:${port}:${at}`]); | |
| 201 | const n = Number(env["GIT_CONFIG_COUNT"] ?? "0"); | |
| 202 | const out: Record<string, string> = { | |
| 203 | ...env, | |
| 204 | GIT_CONFIG_COUNT: String(n + config.length), | |
| 205 | GIT_ALLOW_PROTOCOL: protocols, | |
| 206 | }; | |
| 207 | for (const [i, [key, value]] of config.entries()) { | |
| 208 | out[`GIT_CONFIG_KEY_${n + i}`] = key; | |
| 209 | out[`GIT_CONFIG_VALUE_${n + i}`] = value; | |
| 210 | } | |
| 211 | return out; | |
| 212 | } |
src/origins/discover.ts +69 −76
| @@ -12,11 +12,20 @@ | ||
| 12 | 12 | * it costs one request and would be the right answer if anyone shipped it. |
| 13 | 13 | * |
| 14 | 14 | * Everything here talks to a host the user just named, so it is written like |
| 15 | * a fetch of hostile input: short timeouts, a byte cap, and a hard rule that | |
| 16 | * a redirect may never leave the host we asked. | |
| 15 | * a fetch of hostile input: short timeouts, a byte cap, a hard rule that | |
| 16 | * a redirect may never leave the host we asked, and every request resolved, | |
| 17 | * judged and pinned by `kernel/outbound.ts`. | |
| 17 | 18 | */ |
| 18 | 19 | |
| 19 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 21 | import { | |
| 22 | devLoopback, | |
| 23 | isLoopbackHost, | |
| 24 | isPrivateHost, | |
| 25 | outboundFetch, | |
| 26 | type Lookup, | |
| 27 | type OutboundPolicy, | |
| 28 | } from "../kernel/outbound.ts"; | |
| 20 | 29 | import { readCapped } from "./providers/http.ts"; |
| 21 | 30 | import type { Discovered, OriginKind } from "./types.ts"; |
| 22 | 31 | |
| @@ -47,64 +56,33 @@ function allowedHosts(env: Record<string, string | undefined>): Set<string> { | ||
| 47 | 56 | ); |
| 48 | 57 | } |
| 49 | 58 | |
| 50 | /** Loopback is always reachable: it is this machine, and it is where a | |
| 51 | * development instance and the test suite live. */ | |
| 52 | function isLoopback(hostname: string): boolean { | |
| 53 | const host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); | |
| 54 | return ( | |
| 55 | host === "localhost" || | |
| 56 | host === "::1" || | |
| 57 | host === "0:0:0:0:0:0:0:1" || | |
| 58 | /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) | |
| 59 | ); | |
| 60 | } | |
| 61 | ||
| 62 | 59 | /** |
| 63 | * A literal address inside a range a server has no business dialling on a | |
| 64 | * user's say-so. Only literals are checked here: a name that *resolves* into | |
| 65 | * one of these ranges still gets through, and closing that would mean | |
| 66 | * resolving the host ourselves and connecting to the pinned address, which | |
| 67 | * Bun's fetch gives us no hook for. That residual DNS-rebinding risk is | |
| 68 | * stated rather than papered over; the allow-list is the mitigation. | |
| 60 | * How a request to an origin's `url` is judged: loopback in development | |
| 61 | * only, and anything at all for a host an operator vouched for. | |
| 69 | 62 | */ |
| 70 | function isPrivateV4(a: number, b: number): boolean { | |
| 71 | if (a === 10 || a === 0) return true; | |
| 72 | if (a === 172 && b >= 16 && b <= 31) return true; | |
| 73 | if (a === 192 && b === 168) return true; | |
| 74 | if (a === 169 && b === 254) return true; | |
| 75 | if (a === 100 && b >= 64 && b <= 127) return true; | |
| 76 | if (a === 127) return true; // loopback, reached via a mapped form | |
| 77 | return false; | |
| 63 | export function originPolicy( | |
| 64 | url: string, | |
| 65 | env: Record<string, string | undefined> = process.env, | |
| 66 | ): OutboundPolicy { | |
| 67 | let vouchedFor = false; | |
| 68 | try { | |
| 69 | vouchedFor = vouched(new URL(url), env); | |
| 70 | } catch { | |
| 71 | // an unparseable URL is refused by the request itself | |
| 72 | } | |
| 73 | return { loopback: devLoopback(env), anywhere: vouchedFor }; | |
| 78 | 74 | } |
| 79 | 75 | |
| 80 | function isPrivateLiteral(hostname: string): boolean { | |
| 81 | const host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); | |
| 82 | const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host); | |
| 83 | if (v4) return isPrivateV4(Number(v4[1]), Number(v4[2])); | |
| 84 | if ( | |
| 85 | host.startsWith("fe80:") || | |
| 86 | host.startsWith("fc") || | |
| 87 | host.startsWith("fd") | |
| 88 | ) | |
| 89 | return true; | |
| 90 | // WHATWG URL parsing folds an IPv4-mapped/compatible IPv6 literal — and the | |
| 91 | // IPv4 shorthands that feed one (`127.1`, hex, octal, decimal) — down to a | |
| 92 | // bare IPv6 address whose last two hextets are the IPv4 octet pairs: | |
| 93 | // `[::ffff:169.254.169.254]` becomes hostname `::ffff:a9fe:a9fe`. Left | |
| 94 | // unchecked that is a live bypass onto the cloud metadata address (and | |
| 95 | // every other private range above) through a form neither `isLoopback` nor | |
| 96 | // the dotted-quad branch above ever sees. Decode it back to octets and | |
| 97 | // check those. | |
| 98 | const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host); | |
| 99 | if (mapped) { | |
| 100 | const hi = Number.parseInt(mapped[1]!, 16); | |
| 101 | const lo = Number.parseInt(mapped[2]!, 16); | |
| 102 | return ( | |
| 103 | isPrivateV4((hi >> 8) & 0xff, hi & 0xff) || | |
| 104 | isPrivateV4((lo >> 8) & 0xff, lo & 0xff) | |
| 105 | ); | |
| 106 | } | |
| 107 | return false; | |
| 76 | /** Whether an operator vouched for the origin's host (`FORGE_ORIGIN_ALLOW`). */ | |
| 77 | function vouched( | |
| 78 | url: URL, | |
| 79 | env: Record<string, string | undefined>, | |
| 80 | ): boolean { | |
| 81 | const allowed = allowedHosts(env); | |
| 82 | return ( | |
| 83 | allowed.has(url.host.toLowerCase()) || | |
| 84 | allowed.has(url.hostname.toLowerCase()) | |
| 85 | ); | |
| 108 | 86 | } |
| 109 | 87 | |
| 110 | 88 | /** |
| @@ -112,8 +90,10 @@ function isPrivateLiteral(hostname: string): boolean { | ||
| 112 | 90 | * refused unless the forge is willing to make requests to it. |
| 113 | 91 | * |
| 114 | 92 | * The user names a host and the server fetches it, which is textbook SSRF. |
| 115 | * The policy: https only; plaintext http only for loopback or an | |
| 116 | * operator-allowed host; and no private address literal unless allowed. | |
| 93 | * The policy: https only; plaintext http only for an operator-allowed host, | |
| 94 | * or loopback in development; and no private address literal unless | |
| 95 | * allowed. A name is judged again, resolved, at every request | |
| 96 | * (`kernel/outbound.ts`). | |
| 117 | 97 | */ |
| 118 | 98 | export function allowedOrigin( |
| 119 | 99 | input: string, |
| @@ -135,20 +115,17 @@ export function allowedOrigin( | ||
| 135 | 115 | if (url.hostname === "") return undefined; |
| 136 | 116 | if (url.protocol !== "https:" && url.protocol !== "http:") return undefined; |
| 137 | 117 | |
| 138 | const allowed = allowedHosts(env); | |
| 139 | const named = | |
| 140 | allowed.has(url.host.toLowerCase()) || | |
| 141 | allowed.has(url.hostname.toLowerCase()); | |
| 142 | if (named) return url.origin; | |
| 143 | if (isLoopback(url.hostname)) return url.origin; | |
| 118 | if (vouched(url, env)) return url.origin; | |
| 119 | if (devLoopback(env) && isLoopbackHost(url.hostname)) return url.origin; | |
| 144 | 120 | if (url.protocol !== "https:") return undefined; |
| 145 | if (isPrivateLiteral(url.hostname)) return undefined; | |
| 121 | if (isPrivateHost(url.hostname)) return undefined; | |
| 146 | 122 | return url.origin; |
| 147 | 123 | } |
| 148 | 124 | |
| 149 | 125 | export async function discover( |
| 150 | 126 | input: string | DiscoverInput, |
| 151 | 127 | env: Record<string, string | undefined> = process.env, |
| 128 | lookup?: Lookup, | |
| 152 | 129 | ): Promise<Result<Discovered, DiscoverError>> { |
| 153 | 130 | const wanted: DiscoverInput = |
| 154 | 131 | typeof input === "string" ? { host: input } : input; |
| @@ -187,10 +164,14 @@ export async function discover( | ||
| 187 | 164 | } |
| 188 | 165 | |
| 189 | 166 | // One cheap look at the standard, then the probe that actually answers. |
| 190 | const node = await viaNodeInfo(web); | |
| 167 | const policy: OutboundPolicy = { | |
| 168 | ...originPolicy(web, env), | |
| 169 | ...(lookup === undefined ? {} : { lookup }), | |
| 170 | }; | |
| 171 | const node = await viaNodeInfo(web, policy); | |
| 191 | 172 | if (node) return ok(node); |
| 192 | 173 | |
| 193 | const version = await viaVersionEndpoint(web); | |
| 174 | const version = await viaVersionEndpoint(web, policy); | |
| 194 | 175 | if (version) return ok(version); |
| 195 | 176 | |
| 196 | 177 | return err("unreachable"); |
| @@ -205,8 +186,9 @@ export async function discover( | ||
| 205 | 186 | */ |
| 206 | 187 | async function viaVersionEndpoint( |
| 207 | 188 | web: string, |
| 189 | policy: OutboundPolicy, | |
| 208 | 190 | ): Promise<Discovered | undefined> { |
| 209 | const doc = await getJson(`${web}/api/v1/version`, web); | |
| 191 | const doc = await getJson(`${web}/api/v1/version`, web, policy); | |
| 210 | 192 | if (!doc.ok) return undefined; |
| 211 | 193 | const version = asString(field(doc.value, "version")); |
| 212 | 194 | if (version === "") return undefined; |
| @@ -220,8 +202,11 @@ async function viaVersionEndpoint( | ||
| 220 | 202 | }; |
| 221 | 203 | } |
| 222 | 204 | |
| 223 | async function viaNodeInfo(web: string): Promise<Discovered | undefined> { | |
| 224 | const index = await getJson(`${web}/.well-known/nodeinfo`, web); | |
| 205 | async function viaNodeInfo( | |
| 206 | web: string, | |
| 207 | policy: OutboundPolicy, | |
| 208 | ): Promise<Discovered | undefined> { | |
| 209 | const index = await getJson(`${web}/.well-known/nodeinfo`, web, policy); | |
| 225 | 210 | if (!index.ok) return undefined; |
| 226 | 211 | const links = asArray(field(index.value, "links")); |
| 227 | 212 | // Prefer the newest schema the host offers; any of them carries `software`. |
| @@ -234,7 +219,7 @@ async function viaNodeInfo(web: string): Promise<Discovered | undefined> { | ||
| 234 | 219 | for (const href of hrefs.slice(0, 3)) { |
| 235 | 220 | // A NodeInfo document on another host is a redirect we did not consent to. |
| 236 | 221 | if (!sameOrigin(href, web)) continue; |
| 237 | const doc = await getJson(href, web); | |
| 222 | const doc = await getJson(href, web, policy); | |
| 238 | 223 | if (!doc.ok) continue; |
| 239 | 224 | const name = asString(field(field(doc.value, "software"), "name")) |
| 240 | 225 | .trim() |
| @@ -271,17 +256,25 @@ function sameOrigin(href: string, web: string): boolean { | ||
| 271 | 256 | async function getJson( |
| 272 | 257 | url: string, |
| 273 | 258 | web: string, |
| 259 | policy: OutboundPolicy, | |
| 274 | 260 | ): Promise<Result<unknown, "failed">> { |
| 275 | 261 | let target = url; |
| 276 | 262 | for (let hop = 0; hop < MAX_HOPS; hop++) { |
| 277 | 263 | if (!sameOrigin(target, web)) return err("failed"); |
| 278 | 264 | let response: Response; |
| 279 | 265 | try { |
| 280 | response = await fetch(target, { | |
| 281 | headers: { accept: "application/json", "user-agent": "forge" }, | |
| 282 | redirect: "manual", | |
| 283 | signal: AbortSignal.timeout(TIMEOUT_MS), | |
| 284 | }); | |
| 266 | // Each hop resolved and judged afresh: a name that answered publicly | |
| 267 | // for the first request may not answer privately for the second. | |
| 268 | const sent = await outboundFetch( | |
| 269 | target, | |
| 270 | { | |
| 271 | headers: { accept: "application/json", "user-agent": "forge" }, | |
| 272 | signal: AbortSignal.timeout(TIMEOUT_MS), | |
| 273 | }, | |
| 274 | policy, | |
| 275 | ); | |
| 276 | if (!sent.ok) return err("failed"); | |
| 277 | response = sent.value; | |
| 285 | 278 | } catch { |
| 286 | 279 | return err("failed"); |
| 287 | 280 | } |
src/origins/git-mirror.ts +40 −3
| @@ -23,8 +23,14 @@ 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 { | |
| 27 | pinnedGitEnv, | |
| 28 | resolveTarget, | |
| 29 | type OutboundPolicy, | |
| 30 | } from "../kernel/outbound.ts"; | |
| 26 | 31 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 27 | 32 | import { redact, safeRemoteUrl, secretsIn } from "./credentials.ts"; |
| 33 | import { originPolicy } from "./discover.ts"; | |
| 28 | 34 | |
| 29 | 35 | /** A mirror fetch can be genuinely slow; Forgejo allows its own 300s. */ |
| 30 | 36 | const FETCH_TIMEOUT_MS = 300_000; |
| @@ -85,6 +91,27 @@ export interface GitMirrorError { | ||
| 85 | 91 | readonly message: string; |
| 86 | 92 | } |
| 87 | 93 | |
| 94 | /** | |
| 95 | * The environment a git command reaching `url` runs with: the credential, | |
| 96 | * pinned to the address the origin's name was judged at, following no | |
| 97 | * redirect, speaking only http(s). A clone URL is the origin's word, and an | |
| 98 | * origin that answers with one inside the network reaches nothing. | |
| 99 | */ | |
| 100 | async function remoteEnv( | |
| 101 | url: string, | |
| 102 | authEnv: Record<string, string>, | |
| 103 | policy: OutboundPolicy = originPolicy(url), | |
| 104 | ): Promise<Result<Record<string, string>, GitMirrorError>> { | |
| 105 | const target = await resolveTarget(url, policy); | |
| 106 | if (target.ok) return ok(pinnedGitEnv(authEnv, url, target.value)); | |
| 107 | return err({ | |
| 108 | message: | |
| 109 | target.error === "private_address" | |
| 110 | ? "refusing a clone URL inside the network" | |
| 111 | : "the origin's host could not be resolved", | |
| 112 | }); | |
| 113 | } | |
| 114 | ||
| 88 | 115 | /** |
| 89 | 116 | * Where this bare repo fetches from, as `configureMirror` wrote it, or "" |
| 90 | 117 | * for one that has no remote. What a detached mirror still knows of its |
| @@ -159,6 +186,8 @@ export async function fetchMirror( | ||
| 159 | 186 | if (url === undefined) |
| 160 | 187 | return err({ message: "refusing an unusable clone URL" }); |
| 161 | 188 | |
| 189 | const env = await remoteEnv(url, authEnv); | |
| 190 | if (!env.ok) return env; | |
| 162 | 191 | const before = await snapshotRefs(dir); |
| 163 | 192 | const run = await runGitCapture( |
| 164 | 193 | [ |
| @@ -170,7 +199,7 @@ export async function fetchMirror( | ||
| 170 | 199 | url, |
| 171 | 200 | ...MIRROR_REFSPECS, |
| 172 | 201 | ], |
| 173 | { cwd: dir, env: authEnv, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 202 | { cwd: dir, env: env.value, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 174 | 203 | ); |
| 175 | 204 | if (run.code !== 0) { |
| 176 | 205 | return err({ |
| @@ -208,6 +237,8 @@ export async function fetchRefFrom( | ||
| 208 | 237 | return err({ message: "refusing an unusable clone URL" }); |
| 209 | 238 | if (!isSafeRef(srcRef)) |
| 210 | 239 | return err({ message: `refusing an unsafe ref: ${srcRef}` }); |
| 240 | const env = await remoteEnv(url, authEnv); | |
| 241 | if (!env.ok) return env; | |
| 211 | 242 | |
| 212 | 243 | const run = await runGitCapture( |
| 213 | 244 | [ |
| @@ -220,7 +251,7 @@ export async function fetchRefFrom( | ||
| 220 | 251 | // without any local ref moving. |
| 221 | 252 | srcRef, |
| 222 | 253 | ], |
| 223 | { cwd: dir, env: authEnv, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 254 | { cwd: dir, env: env.value, timeoutMs: FETCH_TIMEOUT_MS }, | |
| 224 | 255 | ); |
| 225 | 256 | if (run.code !== 0) { |
| 226 | 257 | return err({ |
| @@ -252,6 +283,9 @@ export interface PushUpdate { | ||
| 252 | 283 | * only one git considers non-experimental, and the only one immune to our |
| 253 | 284 | * own background fetcher. An empty `<expect>` (a ref being created) means |
| 254 | 285 | * "must not already exist", which is exactly the check we want. |
| 286 | * | |
| 287 | * `policy` is the origin's (`originPolicy`) unless the caller pushes to an | |
| 288 | * address an operator configured, such as this forge's parent. | |
| 255 | 289 | */ |
| 256 | 290 | export async function pushToOrigin( |
| 257 | 291 | dir: string, |
| @@ -259,6 +293,7 @@ export async function pushToOrigin( | ||
| 259 | 293 | updates: readonly PushUpdate[], |
| 260 | 294 | authEnv: Record<string, string>, |
| 261 | 295 | options: RunOptions = {}, |
| 296 | policy: OutboundPolicy = originPolicy(cloneUrl), | |
| 262 | 297 | ): Promise<Result<void, GitMirrorError>> { |
| 263 | 298 | // A push with no refspec is the `--mirror` accident waiting to happen; |
| 264 | 299 | // refuse it here so no caller can construct one. |
| @@ -290,10 +325,12 @@ export async function pushToOrigin( | ||
| 290 | 325 | ); |
| 291 | 326 | } |
| 292 | 327 | args.push(url, ...refspecs); |
| 328 | const env = await remoteEnv(url, authEnv, policy); | |
| 329 | if (!env.ok) return env; | |
| 293 | 330 | |
| 294 | 331 | const run = await runGitCapture(args, { |
| 295 | 332 | ...options, |
| 296 | env: { ...authEnv, ...(options.env ?? {}) }, | |
| 333 | env: { ...env.value, ...(options.env ?? {}) }, | |
| 297 | 334 | cwd: dir, |
| 298 | 335 | timeoutMs: options.timeoutMs ?? PUSH_TIMEOUT_MS, |
| 299 | 336 | }); |
src/web/pages/settings.ts +2 −1
| @@ -1723,7 +1723,8 @@ export async function webhookCreate(ctx: Ctx): Promise<Response> { | ||
| 1723 | 1723 | if (!created.ok) { |
| 1724 | 1724 | return flashTo(ctx, `${repoBase(repo)}/settings/hooks`, { |
| 1725 | 1725 | tone: "danger", |
| 1726 | message: "That URL is not one this forge will deliver to.", | |
| 1726 | message: | |
| 1727 | "That URL is not one this forge will deliver to: it takes an https address outside its own network.", | |
| 1727 | 1728 | }); |
| 1728 | 1729 | } |
| 1729 | 1730 | // The only moment the secret exists outside the database: show it once. |
test/helpers/overlap-worker.ts +3 −1
| @@ -30,7 +30,9 @@ if (mode === "queue") { | ||
| 30 | 30 | } else { |
| 31 | 31 | const until = Date.now() + 3000; |
| 32 | 32 | while (Date.now() < until) { |
| 33 | const sent = await deliverDue(app.db, app.log); | |
| 33 | // Its receiver is on this machine: the policy of a development forge, | |
| 34 | // said here because this child's bare environment is production's. | |
| 35 | const sent = await deliverDue(app.db, app.log, new Date(), { loopback: true }); | |
| 34 | 36 | done += sent; |
| 35 | 37 | if (sent === 0) await Bun.sleep(20); |
| 36 | 38 | } |
test/migrate.test.ts +2 −5
| @@ -17,11 +17,8 @@ import { mkdtemp, rm } from "node:fs/promises"; | ||
| 17 | 17 | import { tmpdir } from "node:os"; |
| 18 | 18 | import { join } from "node:path"; |
| 19 | 19 | import { createApp, type App } from "../src/app.ts"; |
| 20 | import { | |
| 21 | isPrivateHost, | |
| 22 | migrateRepo, | |
| 23 | migrateUrl, | |
| 24 | } from "../src/actions/migrate.ts"; | |
| 20 | import { migrateRepo, migrateUrl } from "../src/actions/migrate.ts"; | |
| 21 | import { isPrivateHost } from "../src/kernel/outbound.ts"; | |
| 25 | 22 | import { createAgent, listCrew } from "../src/actions/crew.ts"; |
| 26 | 23 | import { |
| 27 | 24 | commitToBranch, |
test/origins-oauth.test.ts +8 −3
| @@ -625,14 +625,19 @@ 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) is refused in | |
| 629 | // production, and reachable only in development. | |
| 629 | 630 | expect(allowedOrigin("codeberg.org", env())).toBe("https://codeberg.org"); |
| 630 | expect(allowedOrigin("http://localhost:3000", env())).toBe( | |
| 631 | expect(allowedOrigin("http://localhost:3000", env())).toBeUndefined(); | |
| 632 | expect(allowedOrigin("https://127.0.0.1:9", env())).toBeUndefined(); | |
| 633 | const dev = { FORGE_DEV: "1" }; | |
| 634 | expect(allowedOrigin("http://localhost:3000", dev)).toBe( | |
| 631 | 635 | "http://localhost:3000", |
| 632 | 636 | ); |
| 633 | expect(allowedOrigin("http://127.0.0.1:9", env())).toBe( | |
| 637 | expect(allowedOrigin("http://127.0.0.1:9", dev)).toBe( | |
| 634 | 638 | "http://127.0.0.1:9", |
| 635 | 639 | ); |
| 640 | expect(allowedOrigin("http://10.1.2.3:9", dev)).toBeUndefined(); | |
| 636 | 641 | |
| 637 | 642 | // And discovery itself refuses the same input without making a request. |
| 638 | 643 | expect(await discover("file:///etc/passwd", env())).toEqual({ |
test/outbound.test.ts added +353
| @@ -0,0 +1,353 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { createRepo } from "../src/core/repos.ts"; | |
| 7 | import { createUser } from "../src/core/users.ts"; | |
| 8 | import { createWebhook, deliverDue } from "../src/core/webhooks.ts"; | |
| 9 | import { runGitCapture } from "../src/git/env.ts"; | |
| 10 | import { initBareRepo } from "../src/git/repos.ts"; | |
| 11 | import { | |
| 12 | devLoopback, | |
| 13 | isPrivateHost, | |
| 14 | outboundFetch, | |
| 15 | pinnedGitEnv, | |
| 16 | resolveTarget, | |
| 17 | type Lookup, | |
| 18 | type OutboundPolicy, | |
| 19 | } from "../src/kernel/outbound.ts"; | |
| 20 | import { fetchMirror } from "../src/origins/git-mirror.ts"; | |
| 21 | ||
| 22 | /** DNS that answers from a table, so no test leaves the machine. */ | |
| 23 | const dns = | |
| 24 | (table: Record<string, string[]>): Lookup => | |
| 25 | async (host) => { | |
| 26 | const found = table[host]; | |
| 27 | if (found === undefined) throw new Error(`ENOTFOUND ${host}`); | |
| 28 | return found; | |
| 29 | }; | |
| 30 | ||
| 31 | const production: OutboundPolicy = { loopback: false }; | |
| 32 | ||
| 33 | describe("the outbound guard", () => { | |
| 34 | test("refuses loopback, private, link-local and metadata addresses", async () => { | |
| 35 | for (const url of [ | |
| 36 | "https://127.0.0.1/", | |
| 37 | "https://127.1.2.3/", | |
| 38 | "https://localhost/", | |
| 39 | "https://10.0.0.1/", | |
| 40 | "https://10.255.1.2/", | |
| 41 | "https://172.16.0.1/", | |
| 42 | "https://192.168.1.1/", | |
| 43 | "https://100.64.0.1/", | |
| 44 | "https://169.254.169.254/latest/meta-data/", | |
| 45 | "https://[::1]/", | |
| 46 | "https://[fd00::1]/", | |
| 47 | "https://[fe80::1]/", | |
| 48 | "https://[::ffff:169.254.169.254]/", | |
| 49 | "https://[::ffff:7f00:1]/", | |
| 50 | "https://[64:ff9b::a9fe:a9fe]/", | |
| 51 | "https://0.0.0.0/", | |
| 52 | "https://224.0.0.1/", | |
| 53 | "https://2130706433/", // 127.0.0.1, as the URL parser reads it | |
| 54 | ]) | |
| 55 | expect(await resolveTarget(url, production)).toEqual({ | |
| 56 | ok: false, | |
| 57 | error: "private_address", | |
| 58 | }); | |
| 59 | }); | |
| 60 | ||
| 61 | test("a public name that resolves inside the network is refused", async () => { | |
| 62 | const lookup = dns({ | |
| 63 | "rebind.example": ["127.0.0.1"], | |
| 64 | "metadata.example": ["169.254.169.254"], | |
| 65 | "cluster.example": ["10.42.0.7"], | |
| 66 | // One public answer does not excuse a private one beside it. | |
| 67 | "both.example": ["93.184.216.34", "10.0.0.5"], | |
| 68 | "public.example": ["93.184.216.34"], | |
| 69 | }); | |
| 70 | for (const host of [ | |
| 71 | "rebind.example", | |
| 72 | "metadata.example", | |
| 73 | "cluster.example", | |
| 74 | "both.example", | |
| 75 | ]) | |
| 76 | expect( | |
| 77 | await resolveTarget(`https://${host}/hook`, { loopback: false, lookup }), | |
| 78 | ).toEqual({ ok: false, error: "private_address" }); | |
| 79 | expect( | |
| 80 | await resolveTarget("https://public.example/hook", { | |
| 81 | loopback: false, | |
| 82 | lookup, | |
| 83 | }), | |
| 84 | ).toEqual({ ok: true, value: "93.184.216.34" }); | |
| 85 | expect( | |
| 86 | await resolveTarget("https://nowhere.example/", { loopback: false, lookup }), | |
| 87 | ).toEqual({ ok: false, error: "unresolved" }); | |
| 88 | }); | |
| 89 | ||
| 90 | test("loopback is reached only in development, and private ranges never", async () => { | |
| 91 | expect(devLoopback({})).toBe(false); | |
| 92 | expect(devLoopback({ NODE_ENV: "production" })).toBe(false); | |
| 93 | expect(devLoopback({ FORGE_DEV: "1" })).toBe(true); | |
| 94 | expect(devLoopback({ NODE_ENV: "test" })).toBe(true); | |
| 95 | const dev: OutboundPolicy = { loopback: true }; | |
| 96 | expect((await resolveTarget("http://127.0.0.1:9/", dev)).ok).toBe(true); | |
| 97 | expect((await resolveTarget("http://localhost:9/", dev)).ok).toBe(true); | |
| 98 | expect((await resolveTarget("http://10.0.0.1/", dev)).ok).toBe(false); | |
| 99 | expect((await resolveTarget("http://169.254.169.254/", dev)).ok).toBe(false); | |
| 100 | // An operator's word reaches anywhere, still at one judged address. | |
| 101 | expect( | |
| 102 | await resolveTarget("http://10.0.0.1/", { loopback: false, anywhere: true }), | |
| 103 | ).toEqual({ ok: true, value: "10.0.0.1" }); | |
| 104 | }); | |
| 105 | ||
| 106 | test("the literal judgment keeps public addresses public", () => { | |
| 107 | for (const h of ["8.8.8.8", "github.com", "[2606:4700::1]", "::ffff:8.8.8.8", "172.32.0.1"]) | |
| 108 | expect(isPrivateHost(h)).toBe(false); | |
| 109 | }); | |
| 110 | }); | |
| 111 | ||
| 112 | describe("outboundFetch", () => { | |
| 113 | let hits = 0; | |
| 114 | let lastHost = ""; | |
| 115 | let target: ReturnType<typeof Bun.serve>; | |
| 116 | let hop: ReturnType<typeof Bun.serve>; | |
| 117 | ||
| 118 | beforeAll(() => { | |
| 119 | target = Bun.serve({ | |
| 120 | port: 0, | |
| 121 | hostname: "127.0.0.1", | |
| 122 | fetch(req) { | |
| 123 | hits++; | |
| 124 | lastHost = req.headers.get("host") ?? ""; | |
| 125 | return new Response("here"); | |
| 126 | }, | |
| 127 | }); | |
| 128 | hop = Bun.serve({ | |
| 129 | port: 0, | |
| 130 | hostname: "127.0.0.1", | |
| 131 | fetch: () => | |
| 132 | new Response(null, { | |
| 133 | status: 302, | |
| 134 | headers: { location: `http://127.0.0.1:${target.port}/private` }, | |
| 135 | }), | |
| 136 | }); | |
| 137 | }); | |
| 138 | afterAll(() => { | |
| 139 | hop.stop(true); | |
| 140 | target.stop(true); | |
| 141 | }); | |
| 142 | ||
| 143 | test("a refused address is never connected to", async () => { | |
| 144 | hits = 0; | |
| 145 | const sent = await outboundFetch(`http://127.0.0.1:${target.port}/`, {}, production); | |
| 146 | expect(sent).toEqual({ ok: false, error: "private_address" }); | |
| 147 | const rebound = await outboundFetch( | |
| 148 | `http://rebind.example:${target.port}/`, | |
| 149 | {}, | |
| 150 | { loopback: false, lookup: dns({ "rebind.example": ["127.0.0.1"] }) }, | |
| 151 | ); | |
| 152 | expect(rebound).toEqual({ ok: false, error: "private_address" }); | |
| 153 | expect(hits).toBe(0); | |
| 154 | }); | |
| 155 | ||
| 156 | test("the connection goes to the judged address, under the name asked for", async () => { | |
| 157 | hits = 0; | |
| 158 | const sent = await outboundFetch( | |
| 159 | `http://pinned.example:${target.port}/`, | |
| 160 | {}, | |
| 161 | { loopback: true, lookup: dns({ "pinned.example": ["127.0.0.1"] }) }, | |
| 162 | ); | |
| 163 | expect(sent.ok && sent.value.status).toBe(200); | |
| 164 | expect(hits).toBe(1); | |
| 165 | expect(lastHost).toBe(`pinned.example:${target.port}`); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a redirect to a private address is not followed", async () => { | |
| 169 | hits = 0; | |
| 170 | const sent = await outboundFetch( | |
| 171 | `http://127.0.0.1:${hop.port}/`, | |
| 172 | { redirect: "follow" }, | |
| 173 | { loopback: true }, | |
| 174 | ); | |
| 175 | expect(sent.ok && sent.value.status).toBe(302); | |
| 176 | expect(hits).toBe(0); | |
| 177 | }); | |
| 178 | }); | |
| 179 | ||
| 180 | describe("webhooks go through the guard", () => { | |
| 181 | let dataDir: string; | |
| 182 | let app: App; | |
| 183 | let userId = ""; | |
| 184 | let repoId = ""; | |
| 185 | let hits = 0; | |
| 186 | let receiver: ReturnType<typeof Bun.serve>; | |
| 187 | let redirector: ReturnType<typeof Bun.serve>; | |
| 188 | ||
| 189 | beforeAll(async () => { | |
| 190 | dataDir = await mkdtemp(join(tmpdir(), "forge-outbound-")); | |
| 191 | app = createApp({ dataDir, port: 0 }); | |
| 192 | const user = await createUser(app.db, { | |
| 193 | origin: "seed", | |
| 194 | trusted: true, | |
| 195 | username: "outward", | |
| 196 | email: "[email protected]", | |
| 197 | password: "outbound-is-guarded", | |
| 198 | }); | |
| 199 | if (!user.ok) throw new Error("user"); | |
| 200 | userId = user.value.id; | |
| 201 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: userId, name: "r" }); | |
| 202 | if (!repo.ok) throw new Error("repo"); | |
| 203 | repoId = repo.value.id; | |
| 204 | receiver = Bun.serve({ | |
| 205 | port: 0, | |
| 206 | hostname: "127.0.0.1", | |
| 207 | fetch() { | |
| 208 | hits++; | |
| 209 | return new Response("ok"); | |
| 210 | }, | |
| 211 | }); | |
| 212 | redirector = Bun.serve({ | |
| 213 | port: 0, | |
| 214 | hostname: "127.0.0.1", | |
| 215 | fetch: () => | |
| 216 | new Response(null, { | |
| 217 | status: 307, | |
| 218 | headers: { location: `http://127.0.0.1:${receiver.port}/` }, | |
| 219 | }), | |
| 220 | }); | |
| 221 | }); | |
| 222 | afterAll(async () => { | |
| 223 | redirector.stop(true); | |
| 224 | receiver.stop(true); | |
| 225 | app.close(); | |
| 226 | await rm(dataDir, { recursive: true, force: true }); | |
| 227 | }); | |
| 228 | ||
| 229 | const lastStatus = (): number | undefined => | |
| 230 | app.db | |
| 231 | .query<{ last_status: number }, []>( | |
| 232 | "SELECT last_status FROM webhook_delivery ORDER BY id DESC LIMIT 1", | |
| 233 | ) | |
| 234 | .get()?.last_status; | |
| 235 | ||
| 236 | test("a hook is https, outside the network", () => { | |
| 237 | for (const url of [ | |
| 238 | "http://example.com/hook", | |
| 239 | "https://10.0.0.1/hook", | |
| 240 | "https://169.254.169.254/latest/meta-data/", | |
| 241 | "https://localhost/hook", | |
| 242 | "https://user:[email protected]/hook", | |
| 243 | "ftp://example.com/hook", | |
| 244 | ]) | |
| 245 | expect(createWebhook(app.db, { repoId, url }, production)).toEqual({ | |
| 246 | ok: false, | |
| 247 | error: "invalid_url", | |
| 248 | }); | |
| 249 | expect( | |
| 250 | createWebhook(app.db, { repoId, url: "http://127.0.0.1:9/hook" }, production).ok, | |
| 251 | ).toBe(false); | |
| 252 | expect( | |
| 253 | createWebhook(app.db, { repoId, url: "http://127.0.0.1:9/hook" }, { loopback: true }).ok, | |
| 254 | ).toBe(true); | |
| 255 | expect(createWebhook(app.db, { repoId, url: "https://hooks.example.com/x" }, production).ok).toBe(true); | |
| 256 | app.db.query("DELETE FROM webhook").run(); | |
| 257 | }); | |
| 258 | ||
| 259 | test("delivery outside development never reaches this machine", async () => { | |
| 260 | hits = 0; | |
| 261 | createWebhook(app.db, { repoId, url: `http://127.0.0.1:${receiver.port}/`, kinds: "a" }, { loopback: true }); | |
| 262 | app.bus.append({ kind: "a", repoId, actorId: userId, payload: {} }); | |
| 263 | await deliverDue(app.db, app.log, new Date(), production); | |
| 264 | expect(hits).toBe(0); | |
| 265 | expect(lastStatus()).toBe(0); | |
| 266 | app.db.query("DELETE FROM webhook").run(); | |
| 267 | }); | |
| 268 | ||
| 269 | test("delivery to a public name resolving to 127.0.0.1 reaches nothing", async () => { | |
| 270 | hits = 0; | |
| 271 | createWebhook(app.db, { repoId, url: `https://rebind.example:${receiver.port}/`, kinds: "b" }, production); | |
| 272 | app.bus.append({ kind: "b", repoId, actorId: userId, payload: {} }); | |
| 273 | await deliverDue(app.db, app.log, new Date(), { | |
| 274 | loopback: false, | |
| 275 | lookup: dns({ "rebind.example": ["127.0.0.1"] }), | |
| 276 | }); | |
| 277 | expect(hits).toBe(0); | |
| 278 | expect(lastStatus()).toBe(0); | |
| 279 | app.db.query("DELETE FROM webhook").run(); | |
| 280 | }); | |
| 281 | ||
| 282 | test("a redirect from the endpoint is not followed", async () => { | |
| 283 | hits = 0; | |
| 284 | createWebhook(app.db, { repoId, url: `http://127.0.0.1:${redirector.port}/`, kinds: "c" }, { loopback: true }); | |
| 285 | app.bus.append({ kind: "c", repoId, actorId: userId, payload: {} }); | |
| 286 | await deliverDue(app.db, app.log, new Date(), { loopback: true }); | |
| 287 | expect(hits).toBe(0); | |
| 288 | expect(lastStatus()).toBe(307); | |
| 289 | app.db.query("DELETE FROM webhook").run(); | |
| 290 | }); | |
| 291 | }); | |
| 292 | ||
| 293 | describe("git reaches the judged address and no other", () => { | |
| 294 | test("a mirror's clone URL inside the network is refused before git runs", async () => { | |
| 295 | const dir = await mkdtemp(join(tmpdir(), "forge-outbound-git-")); | |
| 296 | try { | |
| 297 | await initBareRepo(dir); | |
| 298 | for (const url of [ | |
| 299 | "https://10.1.2.3/x.git", | |
| 300 | "https://169.254.169.254/x.git", | |
| 301 | "http://192.168.0.1/x.git", | |
| 302 | ]) { | |
| 303 | const fetched = await fetchMirror(dir, url, {}); | |
| 304 | expect(fetched.ok).toBe(false); | |
| 305 | if (!fetched.ok) | |
| 306 | expect(fetched.error.message).toBe("refusing a clone URL inside the network"); | |
| 307 | } | |
| 308 | } finally { | |
| 309 | await rm(dir, { recursive: true, force: true }); | |
| 310 | } | |
| 311 | }); | |
| 312 | ||
| 313 | test("the pinned environment connects git to the judged address", async () => { | |
| 314 | let host = ""; | |
| 315 | const server = Bun.serve({ | |
| 316 | port: 0, | |
| 317 | hostname: "127.0.0.1", | |
| 318 | fetch(req) { | |
| 319 | host = req.headers.get("host") ?? ""; | |
| 320 | return new Response("no", { status: 404 }); | |
| 321 | }, | |
| 322 | }); | |
| 323 | const dir = await mkdtemp(join(tmpdir(), "forge-outbound-pin-")); | |
| 324 | try { | |
| 325 | const url = `http://pinned.invalid:${server.port}/x.git`; | |
| 326 | const env = pinnedGitEnv({}, url, "127.0.0.1"); | |
| 327 | expect(env.GIT_ALLOW_PROTOCOL).toBe("https:http"); | |
| 328 | await runGitCapture(["ls-remote", "--", url], { | |
| 329 | cwd: dir, | |
| 330 | env: { ...env, GIT_TERMINAL_PROMPT: "0" }, | |
| 331 | }); | |
| 332 | // `.invalid` never resolves: the request arrived only because of the pin. | |
| 333 | expect(host).toBe(`pinned.invalid:${server.port}`); | |
| 334 | } finally { | |
| 335 | server.stop(true); | |
| 336 | await rm(dir, { recursive: true, force: true }); | |
| 337 | } | |
| 338 | }); | |
| 339 | ||
| 340 | test("entries a credential brought are kept, and the pin follows them", () => { | |
| 341 | const env = pinnedGitEnv( | |
| 342 | { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: "x" }, | |
| 343 | "https://git.example/x.git", | |
| 344 | "2606:4700::1", | |
| 345 | ); | |
| 346 | expect(env.GIT_CONFIG_COUNT).toBe("3"); | |
| 347 | expect(env.GIT_CONFIG_KEY_0).toBe("http.extraHeader"); | |
| 348 | expect(env.GIT_CONFIG_KEY_1).toBe("http.followRedirects"); | |
| 349 | expect(env.GIT_CONFIG_VALUE_1).toBe("false"); | |
| 350 | expect(env.GIT_CONFIG_KEY_2).toBe("http.curloptResolve"); | |
| 351 | expect(env.GIT_CONFIG_VALUE_2).toBe("git.example:443:[2606:4700::1]"); | |
| 352 | }); | |
| 353 | }); |
new above
offline
Low: this lookup is not covered by the caller's
AbortSignal.timeout. A slow resolver holds a webhook batch, or a discovery request, for as long as the system resolver retries. A follow-up could race the lookup against the same timeout.