diff --git a/.changeset/outbound-call-isolation.md b/.changeset/outbound-call-isolation.md new file mode 100644 index 00000000..193e6a9f --- /dev/null +++ b/.changeset/outbound-call-isolation.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +Callouts and OAuth provider requests each open a connection of their own instead of sharing Node's keep-alive pool, so the connect-time checks for `CALLOUT_PRIVATE_HOSTS` and `OAUTH_PROVIDER_PRIVATE_HOSTS` always run for the request they guard. A callout host is now compared with the `ISSUER` host without case or a trailing dot, and a callout to a private or loopback address and port the `ISSUER` host resolves to is refused as pointing at the API itself. The version on `/health/version` and the adapter manifest stays public; `docs/security-posture.md` records why. diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 3840ce49..cdd634e3 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -108,10 +108,10 @@ Among roles of one kind, sets apply in role-name order, so the last name alphabe `calloutTransport.ts` serves webhooks, hooks and sinks: -- `https` only in production, no userinfo, and not the API's own issuer host. That check compares host names exactly, so a trailing dot (`auth.example.com.`) or another DNS name for the same server is not caught by it ([#601](https://github.com/fells-code/seamless-auth-api/issues/601)). +- `https` only in production, no userinfo, and not the API itself. The host is compared with the `ISSUER` host without case or a trailing dot, and at connect time a host that resolves to a private or loopback address the `ISSUER` host also resolves to, on the `ISSUER` port, or to loopback on the port the API listens on, is refused, which catches another name for the same server ([#601](https://github.com/fells-code/seamless-auth-api/issues/601)). Public addresses are not compared (decided 2026-12-04): edge networks and load balancers put unrelated sites on one public address, so a match there would refuse receivers that are not this server, and a public address reaches only what any client on the internet reaches. - DNS resolves inside the socket's `lookup`, and every address a name resolves to must be allowed, which defeats rebinding. - Link-local, unspecified, multicast and broadcast addresses are never reachable, in any mode, for any host. -- Other private and loopback addresses are refused in production unless the host is listed in `CALLOUT_PRIVATE_HOSTS`. It is an env var, so nothing written through the API can widen it, and it is checked separately from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service does not also allow it as an identity provider. The checks run when a connection opens. Callouts and OAuth provider requests both use Node's global keep-alive agent, whose connection pool is keyed by destination and not by the lookup that checked it, so a callout can reuse an open connection that a provider request made to a host listed only in `OAUTH_PROVIDER_PRIVATE_HOSTS` and skip its own check. A dedicated agent per policy is tracked in [#601](https://github.com/fells-code/seamless-auth-api/issues/601). +- Other private and loopback addresses are refused in production unless the host is listed in `CALLOUT_PRIVATE_HOSTS`. It is an env var, so nothing written through the API can widen it, and it is checked separately from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service does not also allow it as an identity provider. The checks run when a connection opens, and every callout and OAuth provider request opens a connection of its own rather than taking one from Node's global keep-alive pool, which is keyed by destination and not by the lookup that checked it. A callout therefore never reuses a connection a provider request opened to a host listed only in `OAUTH_PROVIDER_PRIVATE_HOSTS` ([#601](https://github.com/fells-code/seamless-auth-api/issues/601)). - Redirects are never followed. Responses are capped at 64 KiB. The deadline covers the whole request, so a destination that trickles bytes cannot hold a sign-in open. - URLs are checked when written and again at connect time. - Failures are reported as `refused`, `misconfigured`, `timed_out`, `connection_failed`, `http_status`, `invalid_response` or `too_large`, never with the resolved address or the socket's error text, so the delivery log cannot be used to map the internal network. `refused` means the API would not connect to the destination's address; `misconfigured` means the destination's own settings cannot be used, so no call was attempted. diff --git a/docs/configuration.md b/docs/configuration.md index 8ffca37c..aae7a223 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -147,30 +147,34 @@ sinks need API 0.23.1 or later; 0.23.0 refuses them with a 400. ### Service tokens and secrets -| Variable | Required | Default | Notes | -| ------------------------------- | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. In production, boot refuses a value shorter than 32 bytes or a published default (such as the `docker-compose.yml` value). Generate one with `openssl rand -base64 48`. | -| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | -| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | -| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | -| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | -| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | -| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | -| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | -| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook and audit sink hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Checked separately from `OAUTH_PROVIDER_PRIVATE_HOSTS` (see the note below). Link-local, multicast and the unspecified address are always refused, as is the `ISSUER` host by name. | +| Variable | Required | Default | Notes | +| ------------------------------- | ------------------------------------ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. In production, boot refuses a value shorter than 32 bytes or a published default (such as the `docker-compose.yml` value). Generate one with `openssl rand -base64 48`. | +| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | +| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | +| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | +| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | +| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | +| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | +| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook and audit sink hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Checked separately from `OAUTH_PROVIDER_PRIVATE_HOSTS` (see the note below). Link-local, multicast and the unspecified address are always refused, as are the `ISSUER` host and the private addresses it resolves to (see the note below). | > None of these falls back to the service token. Development (any `NODE_ENV` other than > `production`) uses a fixed development-only value for each unset one, with a warning. See > [docs/production-operations.md](./production-operations.md) for upgrading from a deployment > that relied on the fallback. -> The callout host rules have two gaps, both tracked in -> [issue #601](https://github.com/fells-code/seamless-auth-api/issues/601). The `ISSUER` host -> check compares names exactly, so a trailing dot (`auth.example.com.`) or another DNS name for -> the same server is not caught by it. And the two private-host lists are checked when a -> connection opens, but callouts and OAuth provider requests share Node's keep-alive connection -> pool, so a callout can reuse an open connection a provider request made to a host listed only -> in `OAUTH_PROVIDER_PRIVATE_HOSTS`. +> A callout never points at the API itself. Its host is refused when it names the `ISSUER` host, +> compared without case or a trailing dot (`auth.example.com.`), and at connect time when it +> resolves to a private or loopback address that the `ISSUER` host also resolves to, on the +> `ISSUER` port, which catches another name for the same server. Loopback counts as one address, +> and loopback on the port the API listens on (`PORT`) is always refused. Behind a proxy that +> terminates TLS, the API's own private address on another port is not recognised, so do not list +> it in `CALLOUT_PRIVATE_HOSTS`. Public addresses are not compared, since edge networks +> and load balancers share them between unrelated sites. The two private-host lists stay separate +> at connect time too: callouts and OAuth provider requests each open a connection of their own +> rather than sharing a keep-alive pool, so a callout never reuses a connection a provider request +> opened to a host listed only in `OAUTH_PROVIDER_PRIVATE_HOSTS`. ### Database diff --git a/docs/security-posture.md b/docs/security-posture.md index fbc33eb2..d5c51c0b 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -1014,6 +1014,26 @@ The event is written server side and never reflected to the caller. The refusal the same `401 { "error": "unauthorized" }` whether or not a row is written, so the decoy rules above are untouched. +## Version and route map + +`GET /health/version` and `/.well-known/seamless-adapter.json` answer without +credentials in every mode, and both name the running release. This is accepted +(decided 2026-12-04, +[#601](https://github.com/fells-code/seamless-auth-api/issues/601)). + +The adapter manifest has to stay public: server adapters fetch it before they hold +any credential, to learn which routes to proxy and with which token. Its route map +already narrows the release to a range, so hiding `/health/version` alone would not +hide the version, and the operator checklist reads `/health/version` on a fresh +deployment to confirm which release is running. The source and the security +advisories are public, so the version tells a reader which published fixes a +deployment has, and nothing about its configuration or data. + +What keeps an older release safe is upgrading it, not hiding its number. A +deployment that does not want either endpoint reachable from the internet can block +`/health/version` at its reverse proxy and serve the manifest only to its own server +adapters. + ## Static analysis triage **Posture: gated on a zero baseline, deliberately.** CodeQL runs on every pull request, diff --git a/src/lib/auditSinkTransport.ts b/src/lib/auditSinkTransport.ts index 66c10f98..56c704bf 100644 --- a/src/lib/auditSinkTransport.ts +++ b/src/lib/auditSinkTransport.ts @@ -19,6 +19,7 @@ import { AUDIT_SINK_SECRET_ENV_PATTERN } from '@seamless-auth/types'; import { type ExportedAuthEvent, exportLine } from '../services/auditExport.js'; import { authEventOutcome } from './authEventCategories.js'; import { + assertCalloutAddress, CalloutError, calloutHostProblem, calloutLookup, @@ -253,7 +254,7 @@ function tlsMaterial(settings: SyslogSinkSettings, env: EnvSource) { * Writes every frame on one connection, ends it, and resolves once the collector closes its * side. Syslog has no acknowledgement, so that is as much as a sender can know. */ -function writeSyslog( +async function writeSyslog( settings: SyslogSinkSettings, payload: string, env: EnvSource, @@ -261,17 +262,11 @@ function writeSyslog( ): Promise { const destination = destinationProblem(settings, env); if (destination) { - return Promise.reject( - new CalloutError(destination.failure, `Audit sink ${destination.problem}`), - ); + throw new CalloutError(destination.failure, `Audit sink ${destination.problem}`); } - let material: ReturnType; - try { - material = tlsMaterial(settings, env); - } catch (error) { - return Promise.reject(error); - } + const material = tlsMaterial(settings, env); + await assertCalloutAddress(settings.host, settings.port, env); return new Promise((resolve, reject) => { let settled = false; @@ -285,7 +280,7 @@ function writeSyslog( }; const send = () => socket.end(payload); - const lookup = calloutLookup(env); + const lookup = calloutLookup(env, settings.port); const socket: Socket = settings.transport === 'tls' ? tlsConnect( diff --git a/src/lib/calloutTransport.ts b/src/lib/calloutTransport.ts index 7c32410d..72d52d7c 100644 --- a/src/lib/calloutTransport.ts +++ b/src/lib/calloutTransport.ts @@ -44,15 +44,19 @@ function isProduction(env: EnvSource) { return env.NODE_ENV === 'production'; } +// A trailing dot names the same host (`auth.example.com.`), so it is dropped before any comparison. function bare(hostname: string) { - return hostname.replace(/^\[|\]$/g, '').toLowerCase(); + return hostname + .replace(/^\[|\]$/g, '') + .replace(/\.+$/, '') + .toLowerCase(); } function privateHostsAllowed(env: EnvSource) { return new Set( (env[CALLOUT_PRIVATE_HOSTS_ENV] ?? '') .split(',') - .map((host) => host.trim().toLowerCase()) + .map((host) => bare(host.trim())) .filter(Boolean), ); } @@ -69,20 +73,73 @@ function addressAllowed(address: string, hostAllowlisted: boolean) { ); } -function issuerHost(env: EnvSource) { +function effectivePort(url: URL) { + return Number(url.port) || (url.protocol === 'https:' ? 443 : 80); +} + +function issuerTarget(env: EnvSource): { host: string; port: number } | null { try { - return env.ISSUER ? new URL(env.ISSUER).hostname.toLowerCase() : null; + if (!env.ISSUER) return null; + const url = new URL(env.ISSUER); + return { host: bare(url.hostname), port: effectivePort(url) }; } catch { return null; } } +async function issuerAddresses(host: string): Promise { + if (isIP(unmapIPv4(host))) return [unmapIPv4(host)]; + try { + return (await lookup(host, { all: true, verbatim: true })).map((entry) => + unmapIPv4(entry.address), + ); + } catch { + return []; + } +} + +const loopback = new BlockList(); +loopback.addSubnet('127.0.0.0', 8, 'ipv4'); +loopback.addAddress('::1', 'ipv6'); + +function listenPort(env: EnvSource) { + return Number(env.PORT) || 5312; +} + +/** + * Whether connecting to these addresses would reach the API itself, under another name than + * `ISSUER`'s: loopback on the port this process listens on, or a private or loopback address + * `ISSUER` resolves to, on its port (any port when none is given). Loopback counts as one + * address, since this process answers on all of it. Public addresses are not compared: they are + * shared by unrelated sites behind the same edge network or load balancer, so a match says nothing. + */ +async function reachesIssuer(addresses: string[], port: number | undefined, env: EnvSource) { + const internal = addresses.filter((address) => inList(nonPublic, address)); + if (internal.length === 0) return false; + + const onLoopback = internal.some((address) => inList(loopback, address)); + if (onLoopback && port === listenPort(env)) return true; + + const issuer = issuerTarget(env); + if (!issuer || (port !== undefined && port !== issuer.port)) return false; + + const own = new BlockList(); + let issuerOnLoopback = false; + for (const address of await issuerAddresses(issuer.host)) { + own.addAddress(address, isIP(address) === 4 ? 'ipv4' : 'ipv6'); + issuerOnLoopback ||= inList(loopback, address); + } + return (onLoopback && issuerOnLoopback) || internal.some((address) => inList(own, address)); +} + +const POINTS_AT_THIS_SERVER = 'must not point at this server'; + /** Whether a host may be the target of a callout, before any DNS. */ export function calloutHostProblem(hostname: string, env: EnvSource = process.env): string | null { const host = bare(hostname); if (!host) return 'has no host'; - if (host === issuerHost(env)) return 'must not point at this server'; + if (host === issuerTarget(env)?.host) return POINTS_AT_THIS_SERVER; if (isIP(unmapIPv4(host)) && !addressAllowed(host, hostMayBePrivate(host, env))) { return isProduction(env) && @@ -125,7 +182,7 @@ type LookupCallback = ( * name cannot answer one way for a check and another for the connection. Every address a name * resolves to must be allowed, not just the first. */ -export function calloutLookup(env: EnvSource = process.env): LookupFunction { +export function calloutLookup(env: EnvSource = process.env, port?: number): LookupFunction { const guarded = ( hostname: string, options: { family?: number | string; all?: boolean }, @@ -138,17 +195,29 @@ export function calloutLookup(env: EnvSource = process.env): LookupFunction { ? 4 : 0; - lookup(hostname, { all: true, verbatim: true, family }).then( - (addresses) => { - const allowed = hostMayBePrivate(hostname, env); - if ( - addresses.length === 0 || - addresses.some((entry) => !addressAllowed(entry.address, allowed)) - ) { - callback(new CalloutError('refused', `${hostname} resolves to a refused address`), []); - return; - } + const checked = async () => { + const addresses = await lookup(hostname, { all: true, verbatim: true, family }); + const allowed = hostMayBePrivate(hostname, env); + if ( + addresses.length === 0 || + addresses.some((entry) => !addressAllowed(entry.address, allowed)) + ) { + throw new CalloutError('refused', `${hostname} resolves to a refused address`); + } + if ( + await reachesIssuer( + addresses.map((entry) => entry.address), + port, + env, + ) + ) { + throw new CalloutError('refused', `Callout ${POINTS_AT_THIS_SERVER}`); + } + return addresses; + }; + checked().then( + (addresses) => { if (options.all) { callback(null, addresses); } else { @@ -162,6 +231,21 @@ export function calloutLookup(env: EnvSource = process.env): LookupFunction { return guarded as unknown as LookupFunction; } +/** + * The connect-time issuer check for a host given as an address, which never goes through + * `calloutLookup`. + */ +export async function assertCalloutAddress( + hostname: string, + port: number, + env: EnvSource = process.env, +): Promise { + const host = bare(hostname); + if (isIP(unmapIPv4(host)) && (await reachesIssuer([host], port, env))) { + throw new CalloutError('refused', `Callout ${POINTS_AT_THIS_SERVER}`); + } +} + /** Throws a `refused` CalloutError for a URL no callout may reach. */ export function assertCalloutDestination(target: string, env: EnvSource = process.env): URL { const problem = calloutUrlProblem(target, env); @@ -190,17 +274,14 @@ const USER_AGENT = 'seamless-auth-api'; * response, and the caller treats it as a failure, since following it would carry a signed body * to a host that was never checked. */ -export function calloutRequest( +export async function calloutRequest( target: string, { method = 'POST', headers = {}, body, timeoutMs, maxResponseBytes }: CalloutRequest, env: EnvSource = process.env, ): Promise { - let url: URL; - try { - url = assertCalloutDestination(target, env); - } catch (error) { - return Promise.reject(error); - } + const url = assertCalloutDestination(target, env); + const port = effectivePort(url); + await assertCalloutAddress(url.hostname, port, env); const send = url.protocol === 'https:' ? httpsRequest : httpRequest; const outgoing: Record = { 'user-agent': USER_AGENT, ...headers }; @@ -218,7 +299,9 @@ export function calloutRequest( const request = send( url, - { method, headers: outgoing, lookup: calloutLookup(env) }, + // Node's global agent pools sockets by destination, not by the lookup that checked them, + // so a socket another policy opened could be reused without this request's checks. + { method, headers: outgoing, lookup: calloutLookup(env, port), agent: false }, (response) => { const chunks: Buffer[] = []; let size = 0; diff --git a/src/lib/oauthProviderPolicy.ts b/src/lib/oauthProviderPolicy.ts index 82949d98..438b4d06 100644 --- a/src/lib/oauthProviderPolicy.ts +++ b/src/lib/oauthProviderPolicy.ts @@ -222,6 +222,9 @@ export function guardedRequest(url: URL, init: RequestInit, env: EnvSource): Pro method: init.method ?? 'GET', headers, lookup: guardedLookup(env), + // Not the global agent: it pools sockets by destination, not by the lookup that + // checked them, so a callout's socket could be reused without this request's checks. + agent: false, timeout: PROVIDER_TIMEOUT_MS, signal: init.signal ?? undefined, }, diff --git a/tests/unit/lib/auditSinkTransport.spec.ts b/tests/unit/lib/auditSinkTransport.spec.ts index a3cb8c53..da6ca52c 100644 --- a/tests/unit/lib/auditSinkTransport.spec.ts +++ b/tests/unit/lib/auditSinkTransport.spec.ts @@ -315,6 +315,13 @@ const RFC5424 = /^<(\d{1,3})>1 (\S+) (\S+) (\S+) - (\S+) (\[[^ ]+(?: [a-z]+="(?:[^"\\\]]|\\["\\\]])*")*\]) (.*)$/s; describe('syslog', () => { + it('refuses the issuer address and port before connecting', async () => { + const env = { NODE_ENV: 'development', ISSUER: 'http://127.0.0.1:6514' }; + const attempt = await sendToSink(syslog(6514), chain(1).map(eventRecord), env); + + expect(attempt.failure).toBe('refused'); + }); + let tcp: TcpServer; let streams: Promise[]; diff --git a/tests/unit/lib/calloutTransport.spec.ts b/tests/unit/lib/calloutTransport.spec.ts index a2f35574..ca093aa2 100644 --- a/tests/unit/lib/calloutTransport.spec.ts +++ b/tests/unit/lib/calloutTransport.spec.ts @@ -4,6 +4,7 @@ import type { AddressInfo } from 'node:net'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { + assertCalloutAddress, CALLOUT_PRIVATE_HOSTS_ENV, CalloutError, calloutHostProblem, @@ -83,6 +84,24 @@ describe('calloutUrlProblem', () => { expect(calloutUrlProblem('http://169.254.169.254/', development)).toContain('never reachable'); }); + it.each(['https://auth.example.com./hooks', 'https://AUTH.example.com/hooks'])( + 'refuses another spelling of the issuer host (%s)', + (url) => { + expect(calloutUrlProblem(url, production)).toBe('must not point at this server'); + }, + ); + + it('refuses the issuer host with several trailing dots', () => { + expect(calloutUrlProblem('https://auth.example.com../hooks', production)).toBe( + 'must not point at this server', + ); + }); + + it('matches a listed private host written with a trailing dot', () => { + const env = { ...production, [CALLOUT_PRIVATE_HOSTS_ENV]: '10.0.0.5.' }; + expect(calloutUrlProblem('https://10.0.0.5/hook', env)).toBeNull(); + }); + it('refuses a missing host', () => { expect(calloutHostProblem('', production)).toBe('has no host'); }); @@ -93,10 +112,12 @@ describe('calloutUrlProblem', () => { }); describe('calloutLookup', () => { - function resolve(hostname: string, env: Record, all = false) { + function resolve(hostname: string, env: Record, all = false, port?: number) { return new Promise<{ error: Error | null; address: unknown }>((done) => - (calloutLookup(env) as any)(hostname, { all }, (error: Error | null, address: unknown) => - done({ error, address }), + (calloutLookup(env, port) as any)( + hostname, + { all }, + (error: Error | null, address: unknown) => done({ error, address }), ), ); } @@ -121,7 +142,7 @@ describe('calloutLookup', () => { }); it('returns every address when asked for all of them', async () => { - const { error, address } = await resolve('localhost', development, true); + const { error, address } = await resolve('localhost', development, true, 4000); expect(error).toBeNull(); expect(Array.isArray(address)).toBe(true); @@ -140,6 +161,32 @@ describe('calloutLookup', () => { expect(result.error === null || result.error instanceof Error).toBe(true); }); + // Another name for the API, on the address and port ISSUER resolves to. + it('refuses a name that resolves to the issuer address and port', async () => { + const { error } = await resolve('localhost', development, false, 5312); + + expect(error).toBeInstanceOf(CalloutError); + expect((error as CalloutError).message).toContain('must not point at this server'); + }); + + it('refuses a name on an issuer address when no port is given', async () => { + const { error } = await resolve('localhost', development); + + expect(error).toBeInstanceOf(CalloutError); + }); + + it('admits a name on the issuer address but another port', async () => { + const { error } = await resolve('localhost', development, false, 4000); + + expect(error).toBeNull(); + }); + + it('admits a name when the issuer does not resolve or is not set', async () => { + const unresolvable = { NODE_ENV: 'development', ISSUER: 'http://does-not-exist.invalid:5313' }; + expect((await resolve('localhost', unresolvable, false, 5313)).error).toBeNull(); + expect((await resolve('localhost', { NODE_ENV: 'development' }, false, 5313)).error).toBeNull(); + }); + it('passes a DNS failure through', async () => { const { error } = await resolve('does-not-exist.invalid', development); @@ -148,9 +195,74 @@ describe('calloutLookup', () => { }); }); +describe('assertCalloutAddress', () => { + const issuer = { NODE_ENV: 'development', ISSUER: 'http://127.0.0.1:5312' }; + + it.each(['127.0.0.1', '[::ffff:127.0.0.1]', '::ffff:7f00:1'])( + 'refuses %s on the issuer port', + async (host) => { + await expect(assertCalloutAddress(host, 5312, issuer)).rejects.toBeInstanceOf(CalloutError); + }, + ); + + it('treats loopback as one address when the issuer is on loopback', async () => { + await expect(assertCalloutAddress('127.0.0.2', 5312, issuer)).rejects.toBeInstanceOf( + CalloutError, + ); + }); + + it('refuses loopback on the port this process listens on, whatever the issuer', async () => { + const elsewhere = { NODE_ENV: 'development', ISSUER: 'https://auth.example.com', PORT: '7000' }; + await expect(assertCalloutAddress('::1', 7000, elsewhere)).rejects.toBeInstanceOf(CalloutError); + await expect(assertCalloutAddress('::1', 7001, elsewhere)).resolves.toBeUndefined(); + }); + + it('admits the issuer address on another port', async () => { + await expect(assertCalloutAddress('127.0.0.1', 4000, issuer)).resolves.toBeUndefined(); + }); + + // Edge networks put unrelated sites on one public address, so a match there means nothing. + it('does not compare public addresses', async () => { + const publicIssuer = { NODE_ENV: 'production', ISSUER: 'https://93.184.216.34' }; + await expect(assertCalloutAddress('93.184.216.34', 443, publicIssuer)).resolves.toBeUndefined(); + }); + + it('leaves names to calloutLookup', async () => { + await expect(assertCalloutAddress('localhost', 5312, development)).resolves.toBeUndefined(); + }); +}); + describe('calloutRequest', () => { const base = { timeoutMs: 2000, maxResponseBytes: 1024 }; + it('refuses the issuer address and port before connecting', async () => { + let reached = false; + const port = await serve((req, res) => { + reached = true; + res.end('ok'); + }); + const env = { NODE_ENV: 'development', ISSUER: `http://localhost:${port}` }; + + expect(await failureOf(calloutRequest(`http://127.0.0.1:${port}/hook`, base, env))).toBe( + 'refused', + ); + expect(reached).toBe(false); + }); + + it('opens a connection of its own for every request', async () => { + const connections = new Set(); + const port = await serve((req, res) => { + connections.add(req.socket); + res.setHeader('connection', 'keep-alive'); + res.end('ok'); + }); + + await calloutRequest(`http://127.0.0.1:${port}/a`, base, development); + await calloutRequest(`http://127.0.0.1:${port}/b`, base, development); + + expect(connections.size).toBe(2); + }); + it('posts the body and returns the status, headers and body', async () => { let received = ''; const port = await serve((req, res) => { diff --git a/tests/unit/lib/oauthProviderPolicy.spec.ts b/tests/unit/lib/oauthProviderPolicy.spec.ts index 6af3077f..7dc3c911 100644 --- a/tests/unit/lib/oauthProviderPolicy.spec.ts +++ b/tests/unit/lib/oauthProviderPolicy.spec.ts @@ -368,6 +368,28 @@ describe('guardedRequest', () => { const url = (path: string) => new URL(`http://idp.corp.example:${port}${path}`); + it('opens a connection of its own for every request', async () => { + const sockets = new Set(); + const probe = createServer((req, res) => { + sockets.add(req.socket); + res.setHeader('connection', 'keep-alive'); + res.end('{}'); + }); + await new Promise((done) => probe.listen(0, '127.0.0.1', done)); + const probeUrl = new URL( + `http://idp.corp.example:${(probe.address() as AddressInfo).port}/token`, + ); + + try { + await (await guardedRequest(probeUrl, {}, allowLocal)).text(); + await (await guardedRequest(probeUrl, {}, allowLocal)).text(); + expect(sockets.size).toBe(2); + } finally { + probe.closeAllConnections(); + await new Promise((done) => probe.close(() => done())); + } + }); + it('lets providerFetch reach a private provider outside production', async () => { const response = await providerFetch(url('/token'), { method: 'POST' }, {});