diff --git a/.changeset/sso-discovery-public-hosts.md b/.changeset/sso-discovery-public-hosts.md new file mode 100644 index 00000000000..3344fd5f4ea --- /dev/null +++ b/.changeset/sso-discovery-public-hosts.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: SSO discovery fetches only hosts that resolve to public addresses + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for an SSO provider registration (`POST /api/v1/auth/sso/register`, or the Register SSO Provider bridge `POST /api/v1/auth/admin/sso/register`) whose OpenID Connect discovery document sits on a host that resolves to a private, loopback, link-local or otherwise non-public address, on an origin `OS_TRUSTED_ORIGINS` does not list: it is refused `400 VALIDATION_FAILED` on `issuer` (or on `oidcConfig.discoveryEndpoint` when the registration names one), and the bridge answers `400 SSO_REGISTER_FAILED`. It ships `patch` because it is a non-protocol breaking change (AGENTS.md Post-Task Checklist step 3): no metadata author writes an SSO provider registration, so `Metadata-protocol` is `none`. + +SSO discovery fetches only hosts that resolve to public addresses. Before a registration reads its discovery document, the server resolves that document's host and every address must be public (the same predicate `@better-auth/sso` applies to the endpoints it reads at sign-in). The origins a registration names stay trusted for that registration's discovery checks, as before; that trust never stands in for this one. A registration that reads no discovery document (a SAML provider, or `skipDiscovery`) resolves nothing, and a registration with no session is answered `401` before any name is resolved. + +Fix for an operator whose identity provider runs on an internal network: list its origin in `OS_TRUSTED_ORIGINS`, and the registration reads its discovery document as before. diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 8416815b2c2..0cb5905d180 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -178,6 +178,20 @@ identity provider on an internal or private network is refused **400 `VALIDATION_FAILED`** on `signOutOfIdp` until the provider's origin is listed in `OS_TRUSTED_ORIGINS`. +**A registration checks that its discovery host resolves to public addresses +before reading it.** Before a registration reads its discovery document, the +server resolves that document's host (the `discoveryEndpoint` the registration +names, else the issuer's) and every address it resolves to must be public. A +host that resolves to a private, loopback, link-local or otherwise non-public +address is refused **400 `VALIDATION_FAILED`** on `issuer` or +`oidcConfig.discoveryEndpoint`, and nothing is read from it; the Register SSO +Provider bridge answers the same refusal as `SSO_REGISTER_FAILED`. The check +comes before the **Sign Out of the Company Sign-In Too** check above, so a +registration that also turns that switch on is refused on the same member. +Trust an origin gains because a registration names it never stands in for this +check. An identity provider on an internal network registers once its origin +is listed in `OS_TRUSTED_ORIGINS`. + Google is one such provider: its discovery document names the token endpoint, the key set and the userinfo endpoint each on a host of its own, so a Google registration names all three, either in the **Token URL**, **JWKS URL** and diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 990a149fe2d..5ec97d73626 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -87,7 +87,7 @@ import { isPendingSsoSource, PENDING_SSO_MESSAGES } from './pending-sso-marker.j import { ORGANIZATION_DELETE_PATH } from './organization-delete.js'; import { carriesPrincipalSession } from './principal-session-mint.js'; import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js'; -import { ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins.js'; +import { refuseSsoDiscoveryHostNotPublic, ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins.js'; import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js'; import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js'; @@ -592,6 +592,10 @@ export async function globalBeforeHook( // answered `200` and the provider row landed, in every held state. if (ctx?.path === '/sso/register') { const actor = await this.resolveActor(ctx); + // The origins the body names reach the vendor's register endpoint only + // for an actor these gates admitted, and only after the host its + // discovery reads was resolved (below). + let bodyOrigins: string[] = []; if (actor?.userId) { await this.assertActorNotHeld(actor); const ok = await this.isPlatformAdminUserId(actor.userId); @@ -605,8 +609,31 @@ export async function globalBeforeHook( // [#32085] One email domain, one provider: a domain another // provider already serves is refused 409, naming that provider. await this.assertSsoProviderDomainFree(ctx); + // SSO discovery fetches only hosts that resolve to public addresses: + // the host this registration's discovery reads is resolved before the + // vendor's endpoint runs, and every address must be public, unless the + // deployment's configured trusted origins (read here, before any + // body-named origin joins them) list it + // (`refuseSsoDiscoveryHostNotPublic`). Asked before the sign-out + // switch below, whose check reads the same discovery document: a host + // that is not public is refused on the member that names it, whatever + // the switch says, and nothing is read from it. + const notPublic = await refuseSsoDiscoveryHostNotPublic({ + body: ctx?.body, + isConfiguredTrusted: (url) => + typeof ctx?.context?.isTrustedOrigin === 'function' && ctx.context.isTrustedOrigin(url) === true, + }); + if (notPublic) { + const { APIError } = await import('better-auth/api'); + throw new APIError(notPublic.status, { + code: notPublic.code, + message: notPublic.message, + field: notPublic.field, + }); + } // Ruling record 6866334319: the sign-out switch, as on update-provider. await this.assertSsoSignOutOfIdpSupported(ctx); + bodyOrigins = await this.ssoDiscoveryTrustedOrigins(ctx?.body); } // The origins the body names (its issuer and any explicit `oidcConfig` // endpoint) and a known IdP's companion origins (Microsoft Entra ID's @@ -614,7 +641,7 @@ export async function globalBeforeHook( // fetch and validation only: the router's origin check has already run // against the configured trusted origins alone, and never sees them // (`sso-discovery-companion-origins.ts`). - return ssoDiscoveryCompanionContext(ctx, await this.ssoDiscoveryTrustedOrigins(ctx?.body)); + return ssoDiscoveryCompanionContext(ctx, bodyOrigins); } // ── D5.1: cloud-as-IdP authorization gate ─────────────────── diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index c05fc524c34..189ed4c259e 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -6188,8 +6188,11 @@ export class AuthManager { * `/sso/update-provider` body; the answer is the PUBLIC-ROUTABLE origins of its `issuer` and every explicit * `oidcConfig` endpoint. Private / internal / loopback hosts are never * trusted this way (better-auth's `isPublicRoutableHost`, the same predicate - * its own sub-endpoint check uses). Best-effort: anything unreadable yields - * `[]`. + * its own sub-endpoint check uses). A name that looks public is judged by + * its name here; the host a registration's discovery reads is resolved, and + * each address judged, before the register door hands this list on + * (`refuseSsoDiscoveryHostNotPublic`). Best-effort: anything unreadable + * yields `[]`. * * ⛔ Never an accepted `Origin`: the request's own origin check reads the * deployment's configured trusted origins alone. This list reaches two diff --git a/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.test.ts b/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.test.ts index f499059c4f0..c0d48738062 100644 --- a/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.test.ts +++ b/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.test.ts @@ -24,6 +24,7 @@ import { createMemoryEngine } from './impersonation-bearer-rotation.test'; import { SSO_DISCOVERY_COMPANION_ORIGINS, explainUntrustedDiscoveryEndpoint, + refuseSsoDiscoveryHostNotPublic, ssoDiscoveryCompanionOrigins, trustingBodyNamedOrigins, } from './sso-discovery-companion-origins'; @@ -79,6 +80,50 @@ function stubDiscovery(documents: Record>) { }; } +/** + * Name resolution for a case: each listed host answers its addresses, and + * every other name answers ENOTFOUND, so no case leans on the runner's own + * resolver. The vendor and plugin-auth load `node:dns/promises` natively, so + * the double goes on the builtin's exports and is published to ES importers + * (as `sso-domain-verification-instructed-record.test.ts` does for TXT + * records). `asked` lists every name looked up. + */ +function stubNameResolution(addresses: Record): { asked: string[]; restore: () => void } { + const exportsObject = dnsPromises as unknown as { lookup: typeof dnsPromises.lookup }; + const original = exportsObject.lookup; + const asked: string[] = []; + exportsObject.lookup = (async (name: string) => { + asked.push(name); + const answer = Object.prototype.hasOwnProperty.call(addresses, name) ? addresses[name] : undefined; + if (answer) return answer.map((address) => ({ address, family: address.includes(':') ? 6 : 4 })); + throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${name}`), { code: 'ENOTFOUND', hostname: name }); + }) as unknown as typeof dnsPromises.lookup; + syncBuiltinESMExports(); + return { + asked, + restore: () => { + exportsObject.lookup = original; + syncBuiltinESMExports(); + }, + }; +} + +/** Records the URL of every fetch made while it is installed, then hands the fetch on. */ +function recordFetches(): { fetched: string[]; restore: () => void } { + const inner = globalThis.fetch; + const fetched: string[] = []; + globalThis.fetch = ((input: unknown, init?: RequestInit) => { + fetched.push(typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request).url); + return inner(input as never, init); + }) as typeof globalThis.fetch; + return { + fetched, + restore: () => { + globalThis.fetch = inner; + }, + }; +} + interface Rp { manager: AuthManager; engine: ReturnType; @@ -455,27 +500,16 @@ describe('an origin a register or update body names is trusted for that provider /** * The identity provider's environment for a switch-on case: its discovery - * documents over `fetch`, and name resolution. The vendor loads - * `node:dns/promises` natively, so the double goes on the builtin's exports - * and is published to ES importers (as - * `sso-domain-verification-instructed-record.test.ts` does for TXT records). - * `privateHost` resolves to a private address; every other name answers - * ENOTFOUND, which the vendor's check passes, so no case leans on the - * runner's own resolver. + * documents over `fetch`, and name resolution ({@link stubNameResolution}): + * `privateHost` resolves to a private address, every other name answers + * ENOTFOUND. */ function stubIdp(documents: Record>, privateHost?: string): () => void { - const exportsObject = dnsPromises as unknown as { lookup: typeof dnsPromises.lookup }; - const original = exportsObject.lookup; - exportsObject.lookup = (async (name: string) => { - if (privateHost !== undefined && name === privateHost) return [{ address: '10.0.0.5', family: 4 }]; - throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${name}`), { code: 'ENOTFOUND', hostname: name }); - }) as unknown as typeof dnsPromises.lookup; - syncBuiltinESMExports(); + const names = stubNameResolution(privateHost === undefined ? {} : { [privateHost]: ['10.0.0.5'] }); const undoDiscovery = stubDiscovery(documents); return () => { undoDiscovery(); - exportsObject.lookup = original; - syncBuiltinESMExports(); + names.restore(); }; } @@ -532,19 +566,25 @@ describe('an origin a register or update body names is trusted for that provider expect(JSON.stringify(storedRows(rp))).toBe(before); }); - it('the sign-out capability check trusts a body-named origin for the logout endpoint only: on register, its discovery read keeps the configured trust', async () => { + it('on register with the switch on, an issuer whose host resolves to a private address is refused on issuer, before the sign-out check reads it', async () => { restore = stubIdp({ [OTHER_ISSUER]: withLogout(OTHER_ISSUER, `${OTHER_ISSUER}/logout`) }, new URL(OTHER_ISSUER).hostname); const rp = await makeCheckedRp(); const res = await postAs(rp, '/sso/register', { ...registration('other-oidc', OTHER_ISSUER), signOutOfIdp: true }, BASE); expect(res.status, await res.clone().text()).toBe(400); - expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'signOutOfIdp' }); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); expect(storedRows(rp)).toEqual([]); }); it('the sign-out capability check trusts a body-named origin for the logout endpoint only: on update, its discovery read keeps the configured trust', async () => { - restore = stubIdp({ [OTHER_ISSUER]: withLogout(OTHER_ISSUER, `${OTHER_ISSUER}/logout`) }, new URL(OTHER_ISSUER).hostname); + // Registered while the issuer's host does not resolve to a private address + // (a registration reads its discovery document only from a host that + // resolves to public addresses); it does by the time the update turns the + // switch on. + restore = stubIdp({ [OTHER_ISSUER]: withLogout(OTHER_ISSUER, `${OTHER_ISSUER}/logout`) }); const rp = await makeCheckedRp(); expect((await postAs(rp, '/sso/register', registration('other-oidc', OTHER_ISSUER), BASE)).status).toBe(200); + restore(); + restore = stubIdp({ [OTHER_ISSUER]: withLogout(OTHER_ISSUER, `${OTHER_ISSUER}/logout`) }, new URL(OTHER_ISSUER).hostname); const before = JSON.stringify(storedRows(rp)); const res = await postAs(rp, '/sso/update-provider', { providerId: 'other-oidc', issuer: OTHER_ISSUER, signOutOfIdp: true }, BASE); expect(res.status, await res.clone().text()).toBe(400); @@ -568,3 +608,230 @@ describe('an origin a register or update body names is trusted for that provider expect(fromSelf.status, await fromSelf.clone().text()).toBe(200); }); }); + +// ── SSO discovery reads only hosts that resolve to public addresses ───────── + +/** An address no non-public range holds. */ +const PUBLIC_ADDRESS = '93.184.215.14'; +const RESOLVED_ISSUER = 'https://idp.resolved-corp.example'; +const RESOLVED_HOST = new URL(RESOLVED_ISSUER).hostname; +const RESOLVED_DISCOVERY = `${RESOLVED_ISSUER}/.well-known/openid-configuration`; +/** A discovery host other than the issuer's, named by `oidcConfig.discoveryEndpoint`. */ +const DISCOVERY_ORIGIN = 'https://discovery.resolved-corp.example'; +const DISCOVERY_HOST = new URL(DISCOVERY_ORIGIN).hostname; + +describe('SSO discovery reads only hosts that resolve to public addresses', () => { + let undo: Array<() => void> = []; + afterEach(() => { + for (const step of undo.reverse()) step(); + undo = []; + vi.restoreAllMocks(); + }); + + /** The IdP's discovery documents over `fetch` and its name resolution, with a record of both. */ + function idp(documents: Record>, addresses: Record) { + const undoDiscovery = stubDiscovery(documents); + const reads = recordFetches(); + const names = stubNameResolution(addresses); + undo.push(undoDiscovery, reads.restore, names.restore); + return { fetched: reads.fetched, asked: names.asked }; + } + + const readFrom = (fetched: readonly string[], host: string) => fetched.filter((url) => new URL(url).hostname === host); + + it.each(['10.0.0.5', '127.0.0.1', '169.254.169.254'])( + 'a registration whose discovery host resolves to %s is refused on issuer, and nothing is read from that host', + async (address) => { + const io = idp({ [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, { [RESOLVED_HOST]: [address] }); + const rp = await makeRp(); + const res = await register(rp, registration('resolved-oidc', RESOLVED_ISSUER)); + expect(res.status, await res.clone().text()).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(io.asked).toContain(RESOLVED_HOST); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }, + ); + + it('with the sign-out switch on, the registration is refused on issuer by this rule, and nothing is read from that host', async () => { + const io = idp( + { [RESOLVED_ISSUER]: { ...discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`), end_session_endpoint: `${RESOLVED_ISSUER}/logout` } }, + { [RESOLVED_HOST]: ['10.0.0.5'] }, + ); + const rp = await makeRp(); + const res = await register(rp, { ...registration('resolved-oidc', RESOLVED_ISSUER), signOutOfIdp: true }); + expect(res.status, await res.clone().text()).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(io.asked).toContain(RESOLVED_HOST); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); + + it('a discovery host with one public and one private address is refused: every address must be public', async () => { + const io = idp( + { [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, + { [RESOLVED_HOST]: [PUBLIC_ADDRESS, '10.0.0.5'] }, + ); + const rp = await makeRp(); + const res = await register(rp, registration('resolved-oidc', RESOLVED_ISSUER)); + expect(res.status, await res.clone().text()).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); + + it('an explicit discovery endpoint on a host that resolves to a private address is refused on that member', async () => { + const io = idp( + { [DISCOVERY_ORIGIN]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, + { [RESOLVED_HOST]: [PUBLIC_ADDRESS], [DISCOVERY_HOST]: ['10.0.0.5'] }, + ); + const rp = await makeRp(); + const body = registration('resolved-oidc', RESOLVED_ISSUER, { discoveryEndpoint: `${DISCOVERY_ORIGIN}/.well-known/openid-configuration` }); + const res = await register(rp, body); + expect(res.status, await res.clone().text()).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'oidcConfig.discoveryEndpoint' }); + expect(readFrom(io.fetched, DISCOVERY_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); + + it('the Register SSO Provider bridge answers the same rule, and nothing is read from the host', async () => { + const io = idp({ [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, { [RESOLVED_HOST]: ['127.0.0.1'] }); + const rp = await makeRp(); + const res = await registerThroughBridge(rp, { ...GOOGLE_FORM, providerId: 'resolved-oidc', issuer: RESOLVED_ISSUER }); + expect(res.status, JSON.stringify(res.body)).toBe(400); + expect(res.body.error?.code).toBe('SSO_REGISTER_FAILED'); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); + + it('CONTROL: a discovery host that resolves to public addresses registers, reading its discovery document alone, and the endpoints the body names stay trusted for the discovery checks', async () => { + const io = idp( + { [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${BODY_HOST}/userinfo`) }, + { [RESOLVED_HOST]: [PUBLIC_ADDRESS], [new URL(BODY_HOST).hostname]: [PUBLIC_ADDRESS] }, + ); + const rp = await makeRp(); + const res = await register(rp, registration('resolved-oidc', RESOLVED_ISSUER, { userInfoEndpoint: `${BODY_HOST}/userinfo` })); + expect(res.status, await res.clone().text()).toBe(200); + expect(io.asked).toContain(RESOLVED_HOST); + expect(io.fetched).toEqual([RESOLVED_DISCOVERY]); + expect((await storedConfig(rp, 'resolved-oidc')).userInfoEndpoint).toBe(`${BODY_HOST}/userinfo`); + }); + + it('CONTROL: an origin the deployment lists registers though its host resolves to a private address', async () => { + idp({ [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, { [RESOLVED_HOST]: ['10.0.0.5'] }); + const rp = await makeRp([BASE, RESOLVED_ISSUER]); + const res = await register(rp, registration('resolved-oidc', RESOLVED_ISSUER)); + expect(res.status, await res.clone().text()).toBe(200); + expect((await storedConfig(rp, 'resolved-oidc')).issuer).toBe(RESOLVED_ISSUER); + }); + + it('CONTROL: a registration with no session resolves no name and is answered 401', async () => { + const io = idp({ [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, { [RESOLVED_HOST]: ['10.0.0.5'] }); + const rp = await makeRp(); + const res = await rp.manager.handleRequest( + new Request(`${AUTH}/sso/register`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: BASE }, + body: JSON.stringify(registration('resolved-oidc', RESOLVED_ISSUER)), + }), + ); + expect(res.status, await res.clone().text()).toBe(401); + expect(io.asked).toEqual([]); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); + + it('CONTROL: a registration by a signed-in user who is not a platform admin resolves no name and is answered 403', async () => { + const io = idp({ [RESOLVED_ISSUER]: discoveryDocument(RESOLVED_ISSUER, `${RESOLVED_ISSUER}/userinfo`) }, { [RESOLVED_HOST]: ['10.0.0.5'] }); + const rp = await makeRp(); + vi.spyOn(rp.manager as any, 'isPlatformAdminUserId').mockResolvedValue(false); + const res = await register(rp, registration('resolved-oidc', RESOLVED_ISSUER)); + expect(res.status, await res.clone().text()).toBe(403); + expect(await res.json()).toMatchObject({ code: 'SSO_REGISTER_FORBIDDEN' }); + expect(io.asked).toEqual([]); + expect(readFrom(io.fetched, RESOLVED_HOST)).toEqual([]); + expect(storedRows(rp)).toEqual([]); + }); +}); + +describe('the host a registration\'s discovery reads is the one host resolved', () => { + /** A resolver answering a private address for every name, recording each name asked. */ + function privateResolver() { + const asked: string[] = []; + const resolve = async (hostname: string) => { + asked.push(hostname); + return [{ address: '10.0.0.5' }]; + }; + return { asked, resolve }; + } + const configured = (url: string) => url.startsWith(BASE); + const oidc = (extra: Record = {}) => ({ clientId: 'client-id', clientSecret: 'client-secret', ...extra }); + + it('the issuer\'s well-known URL is resolved when the registration names no discovery endpoint, and refused on issuer', async () => { + const r = privateResolver(); + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc() }, + isConfiguredTrusted: configured, + resolve: r.resolve, + }); + expect(refusal).toMatchObject({ status: 'BAD_REQUEST', code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(r.asked).toEqual([RESOLVED_HOST]); + }); + + it('an explicit discovery endpoint is the host resolved, not the issuer\'s, and the refusal names that member', async () => { + const r = privateResolver(); + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc({ discoveryEndpoint: `${DISCOVERY_ORIGIN}/.well-known/openid-configuration` }) }, + isConfiguredTrusted: configured, + resolve: r.resolve, + }); + expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', field: 'oidcConfig.discoveryEndpoint' }); + expect(r.asked).toEqual([DISCOVERY_HOST]); + }); + + it('a registration that reads no discovery document resolves nothing: a SAML registration, and skipDiscovery', async () => { + for (const body of [ + { issuer: RESOLVED_ISSUER, samlConfig: { entryPoint: `${RESOLVED_ISSUER}/sso` } }, + { issuer: RESOLVED_ISSUER, oidcConfig: oidc({ skipDiscovery: true, tokenEndpoint: `${RESOLVED_ISSUER}/token` }) }, + {}, + undefined, + ]) { + const r = privateResolver(); + expect(await refuseSsoDiscoveryHostNotPublic({ body, isConfiguredTrusted: configured, resolve: r.resolve }), JSON.stringify(body)).toBeUndefined(); + expect(r.asked, JSON.stringify(body)).toEqual([]); + } + }); + + it('a discovery URL the deployment trusts, an address literal and a non-public name are not resolved here', async () => { + for (const issuer of [RESOLVED_ISSUER, 'https://10.0.0.5', 'https://[fd00::1]', 'http://localhost:9000', 'https://metadata.google.internal']) { + const r = privateResolver(); + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer, oidcConfig: oidc() }, + isConfiguredTrusted: (url) => url.startsWith(RESOLVED_ISSUER), + resolve: r.resolve, + }); + expect(refusal, issuer).toBeUndefined(); + expect(r.asked, issuer).toEqual([]); + } + }); + + it('a name that does not resolve is left to the read, as the vendor\'s own check leaves it', async () => { + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc() }, + isConfiguredTrusted: configured, + resolve: async (hostname) => { + throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), { code: 'ENOTFOUND' }); + }, + }); + expect(refusal).toBeUndefined(); + }); + + it('a name whose every address is public is not refused', async () => { + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc() }, + isConfiguredTrusted: configured, + resolve: async () => [{ address: PUBLIC_ADDRESS }, { address: '2606:2800:21f:cb07:6820:80da:af6b:8b2c' }], + }); + expect(refusal).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts b/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts index 60cd5de4b8f..63d43815edd 100644 --- a/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts +++ b/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts @@ -49,6 +49,12 @@ * and its endpoint validation admits any public host on its own, so it reads * none of them. * + * That trust covers origin verdicts only. SSO discovery fetches only hosts + * that resolve to public addresses: the host a registration's discovery reads + * is resolved before the vendor's register endpoint runs, and the body-named + * origins are handed to it only after that check, for an actor the register + * gates admitted ({@link refuseSsoDiscoveryHostNotPublic}). + * * ⛔ An origin a fetched discovery document names is never trusted because the * document names it: an unknown issuer whose discovery points at a foreign * userinfo host is still refused. The remedy for any other IdP is the explicit @@ -140,6 +146,121 @@ export function trustingBodyNamedOrigins( }; } +// ── The host a registration's discovery reads resolves to public addresses ── + +/** A name resolver: every address a host name resolves to. */ +export type SsoHostResolver = (hostname: string) => Promise>; + +/** `node:dns/promises` `lookup` for every address, read when called; none on a runtime without it. */ +async function systemResolver(): Promise { + try { + const dns = await import('node:dns/promises'); + return (hostname) => dns.lookup(hostname, { all: true }); + } catch { + return undefined; + } +} + +/** The body member naming the URL a registration's discovery reads. */ +export type SsoDiscoveryReadMember = 'issuer' | 'oidcConfig.discoveryEndpoint'; + +/** + * The URL a `/sso/register` body has the vendor's register endpoint read + * server-side, and the member that names it: the OIDC discovery document, at + * the explicit `oidcConfig.discoveryEndpoint`, else at the issuer's well-known + * URL (`computeDiscoveryUrl`, the vendor's own). `undefined` when the + * registration reads none: no `oidcConfig` (a SAML registration), or + * `oidcConfig.skipDiscovery`. The vendor's register endpoint makes no other + * server-side read (`@better-auth/sso` 1.7.12 `discoverOIDCConfig`). With + * `signOutOfIdp` on, the register door's sign-out check + * (`assertSsoSignOutOfIdpSupported`) reads the same document first, under the + * configured trust only, and only after {@link refuseSsoDiscoveryHostNotPublic} + * has admitted its host. + */ +export function ssoRegisterDiscoveryRead( + body: unknown, + computeDiscoveryUrl: (issuer: string) => string, +): { member: SsoDiscoveryReadMember; url: string } | undefined { + if (!body || typeof body !== 'object') return undefined; + const oidc = (body as { oidcConfig?: unknown }).oidcConfig; + if (!oidc || typeof oidc !== 'object') return undefined; + if ((oidc as { skipDiscovery?: unknown }).skipDiscovery === true) return undefined; + const explicit = (oidc as { discoveryEndpoint?: unknown }).discoveryEndpoint; + if (typeof explicit === 'string' && explicit.length > 0) return { member: 'oidcConfig.discoveryEndpoint', url: explicit }; + const issuer = (body as { issuer?: unknown }).issuer; + if (typeof issuer === 'string' && issuer.length > 0) return { member: 'issuer', url: computeDiscoveryUrl(issuer) }; + return undefined; +} + +/** The refusal {@link refuseSsoDiscoveryHostNotPublic} answers. */ +export interface SsoDiscoveryHostRefusal { + status: 'BAD_REQUEST'; + code: 'VALIDATION_FAILED'; + field: SsoDiscoveryReadMember; + message: string; +} + +/** + * SSO discovery fetches only hosts that resolve to public addresses. + * + * The host whose discovery document a `/sso/register` body has the server + * read ({@link ssoRegisterDiscoveryRead}) is resolved here, before the + * vendor's register endpoint runs, and every address it resolves to must be + * public (`isPublicRoutableHost`, the predicate the vendor's own checks + * apply). The origins the body names are trusted for the origin verdicts of + * that registration's discovery (`ssoDiscoveryCompanionContext`); that trust + * never stands in for this check. The deployment's configured trusted origins + * stay the one way to register an identity provider on an internal network: + * a discovery URL they trust is not resolved here, as the vendor resolves none. + * + * Judged as the vendor judges its own resolution: an address literal is left + * to the vendor's synchronous host check, a name that looks non-public + * (`localhost`, a metadata name) to its refusal of an untrusted or private + * host, and a name that does not resolve, or a runtime with no + * `node:dns/promises`, to the read itself. Answers the refusal, or + * `undefined` when the registration may go on; it reads `body` only. + */ +export async function refuseSsoDiscoveryHostNotPublic(input: { + body: unknown; + /** The deployment's configured trusted-origin predicate (the request's, before any body-named origin joins it). */ + isConfiguredTrusted: (url: string) => boolean; + /** Name resolution; `node:dns/promises` when absent. */ + resolve?: SsoHostResolver; +}): Promise { + const { computeDiscoveryUrl } = await import('@better-auth/sso'); + const read = ssoRegisterDiscoveryRead(input.body, computeDiscoveryUrl); + if (!read) return undefined; + let url: URL; + try { + url = new URL(read.url); + } catch { + return undefined; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined; + const { classifyHost, isPublicRoutableHost } = await import('@better-auth/core/utils/host'); + const host = url.hostname; + if (classifyHost(host).literal !== 'fqdn' || !isPublicRoutableHost(host)) return undefined; + if (input.isConfiguredTrusted(url.href)) return undefined; + const resolve = input.resolve ?? (await systemResolver()); + if (!resolve) return undefined; + let addresses: ReadonlyArray<{ address: string }>; + try { + addresses = await resolve(host); + } catch { + return undefined; + } + if (addresses.every(({ address }) => isPublicRoutableHost(address))) return undefined; + return { + status: 'BAD_REQUEST', + code: 'VALIDATION_FAILED', + field: read.member, + message: + `The host "${host}" that ${read.member} names for this provider's discovery document resolves to an address that is not public, ` + + 'so the document was not read and the provider was not registered. SSO discovery reads only hosts that resolve to public addresses; ' + + `an identity provider on an internal network registers once the deployment's trusted origins (OS_TRUSTED_ORIGINS) list its origin, ${url.origin}.`, + }; +} + // ── The refusal: name the endpoint, and say how to name it explicitly ─────── /** The vendor's code for a discovery endpoint outside the trusted origins. */