diff --git a/.changeset/sso-discovery-connect-time.md b/.changeset/sso-discovery-connect-time.md new file mode 100644 index 00000000000..6d4058fb2ba --- /dev/null +++ b/.changeset/sso-discovery-connect-time.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/core': patch +--- + +fix(plugin-auth)!: SSO discovery connects only to addresses that are public at connect time + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for an identity provider whose OpenID Connect host resolves to a private, loopback, link-local, cloud metadata or host-platform address (`168.63.129.16` included), or to any other non-public address, on an origin `OS_TRUSTED_ORIGINS` does not list, at the moment the server reads it: a registration (`POST /api/v1/auth/sso/register`, or the Register SSO Provider bridge) is refused `400 VALIDATION_FAILED` on `issuer` (or on `oidcConfig.discoveryEndpoint` when the registration names one), an update that turns "sign out of the company sign-in too" on is refused `400 VALIDATION_FAILED` on `signOutOfIdp`, and a sign-in's callback ends on the error page with `invalid_provider`. 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, so `Metadata-protocol` is `none`. + +SSO discovery connects only to addresses that are public at connect time. Every read the server makes of an identity provider (a registration's discovery document, the sign-out switch's read of that document on a registration or an update, a sign-in's discovery, and the token, key-set and userinfo reads of a sign-in's callback) is sent through the platform's outbound-request guard (`@objectstack/core/egress`): the connection resolves the host, judges every address by the platform's address classes, and connects to an address it judged, so the address judged is the address connected. A host that is not public is refused and nothing is sent to it, whatever an earlier lookup of the same name answered, and so is a name that does not resolve when the read connects. Only reads at the origins the provider's configuration names are judged (the registration's body, or the provider row the sign-in reads): every other request the server makes while answering, such as a datastore or a rate-limit store reached over HTTP, is sent as before. A registration still judges its discovery host before reading it, now by the same rule and the same address classes, an address literal included; a name that does not resolve there is left to the read, which refuses it. The origins a registration names stay trusted for that registration's discovery checks only, and `OS_EGRESS_ALLOWED_TARGETS` does not open SSO discovery. + +`@objectstack/core`: the guarded fetch's init takes fetch's `redirect` mode; `manual` answers a redirect response as it is and follows nothing, for a caller that refuses redirects itself. + +Fix for an operator whose identity provider runs on an internal network: list its origin in `OS_TRUSTED_ORIGINS`, and its reads are sent as before. diff --git a/content/docs/permissions/sso.mdx b/content/docs/permissions/sso.mdx index 0cb5905d180..6a98b3e52ef 100644 --- a/content/docs/permissions/sso.mdx +++ b/content/docs/permissions/sso.mdx @@ -178,19 +178,36 @@ 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`. +**SSO discovery connects only to addresses that are public at connect time.** +Every read the server makes of an identity provider's OpenID Connect +configuration (a registration's discovery document, the **Sign Out of the +Company Sign-In Too** check's read of the same document on a registration or +an update, a sign-in's discovery, and the token, key-set and userinfo reads of +a sign-in's callback) goes through the platform's outbound-request guard: the +connection itself resolves the host, judges every address it resolves to, and +connects only to an address it judged. An address that is private, loopback, +link-local, a cloud metadata or host-platform address (`168.63.129.16` +included) or in any other non-public range is refused and nothing is sent to +it, whatever an earlier lookup of the same name answered; so is a host whose +name does not resolve when the read connects. Only reads at the origins the +provider's configuration names are judged: every other request the server +makes while answering (a datastore or a rate-limit store reached over HTTP) +is sent as before. + +A registration also judges its discovery host before reading it, by the same +rule: the host of the `discoveryEndpoint` the registration names, else the +issuer's. A host that is not public is refused **400 `VALIDATION_FAILED`** on +`issuer` or `oidcConfig.discoveryEndpoint`, and nothing is read from it; the +same answer comes back when the host answers a non-public address only once +its read connects. The Register SSO Provider bridge answers that 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. A refused callback read ends the sign-in on the +error page with `invalid_provider`. Trust an origin gains because a +registration names it never stands in for this rule, and neither does +`OS_EGRESS_ALLOWED_TARGETS`. An identity provider on an internal network is +reached once its origin is listed in `OS_TRUSTED_ORIGINS`: a read of an origin +the deployment trusts is sent as before. 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 diff --git a/packages/core/src/egress/guarded-fetch.test.ts b/packages/core/src/egress/guarded-fetch.test.ts index 04514f5d224..2efb002214d 100644 --- a/packages/core/src/egress/guarded-fetch.test.ts +++ b/packages/core/src/egress/guarded-fetch.test.ts @@ -184,6 +184,18 @@ describe('CONTROL: an allowed target delivers, and redirects between allowed tar expect(hits).toEqual([`hooks.example:${port} /redirect?to=${to}`, `second.example:${port} /landed`]); }); + it('a manual redirect mode answers the redirect itself and follows nothing', async () => { + const to = encodeURIComponent(`http://second.example:${port}/landed`); + const res = await guard('hooks.example,second.example').fetch( + `http://hooks.example:${port}/redirect?to=${to}`, + { redirect: 'manual' }, + ctx, + ); + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe(decodeURIComponent(to)); + expect(hits).toEqual([`hooks.example:${port} /redirect?to=${to}`]); + }); + it('a policy that allows public addresses lets them through (the stand-in public host)', async () => { const g = createEgressGuard({ policy: { canConnect: () => ({ allow: true }) }, diff --git a/packages/core/src/egress/guarded-fetch.ts b/packages/core/src/egress/guarded-fetch.ts index 6ab24c78b18..919c3a6c98a 100644 --- a/packages/core/src/egress/guarded-fetch.ts +++ b/packages/core/src/egress/guarded-fetch.ts @@ -108,12 +108,18 @@ export interface EgressGuardOptions { logger?: EgressLogger; } -/** The init the guarded fetch takes — what both callers send. */ +/** The init the guarded fetch takes — what its callers send. */ export interface EgressFetchInit { method?: string; headers?: Record; body?: string; signal?: AbortSignal; + /** + * Fetch's redirect mode. `follow` (the default) judges every hop it + * follows; `manual` answers a redirect response as it is, following + * nothing, for a caller that refuses redirects itself. + */ + redirect?: 'follow' | 'manual' | 'error'; } /** The installed guard: the policy and the one fetch every guarded caller uses. */ diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index c288b225059..b3559caafa7 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -60,6 +60,7 @@ import { stampInvitationDeliveryOutcome } from './invitation-delivery-outcome.js import { retireExpiredInvitationsOnReissue } from './invitation-expired-supersede.js'; import { codeInviteRoleNotFound } from './invite-role-not-found-code.js'; import { explainUntrustedDiscoveryRefusal } from './sso-discovery-companion-origins.js'; +import { explainSsoDiscoveryConnectRefusal } from './sso-discovery-egress.js'; import { readRequestClientAddress } from './request-client-address.js'; import { stampRoleChangeGrantedSet } from './role-change-granted-set.js'; import { attachSessionToCredentialResponse } from './session-envelope-completion.js'; @@ -534,6 +535,12 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // the vendor's message (`sso-discovery-companion-origins.ts`). await explainUntrustedDiscoveryRefusal(ctx); + // ── A registration's discovery read refused when it connected ── + // `/sso/register` only: answered as the before-hook answers a discovery + // host that is not public, on the member that names it + // (`sso-discovery-egress.ts`). Throws on a match. + await explainSsoDiscoveryConnectRefusal(ctx); + // ── #29163: update-user's uncoded refusal carries its code ── // Same seam as the change-email section above; throws on a match. await codeSelfServiceRefusal(ctx); 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 76b85fe7aaf..85924c040b1 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -94,6 +94,7 @@ 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 { refuseSsoDiscoveryHostNotPublic, ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins.js'; +import { declareSsoDiscoveryReadsOf, judgeSsoDiscoveryUrl } from './sso-discovery-egress.js'; import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js'; import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js'; @@ -241,6 +242,20 @@ export async function globalBeforeHook( // `principal-session-mint.ts` (3b). if (carriesPrincipalSession(ctx)) await setShouldSkipSessionRefresh(true); + // ── SSO discovery connects only to addresses public at connect time ── + // Ahead of every branch below that may answer early: a vendor endpoint + // that reads an identity provider (`/sso/register`, `/sign-in/sso`, + // `/sso/callback/*`) runs in the SSO discovery scope the request routing + // opened, which judges only reads at origins the request's provider + // configuration names (`sso-discovery-egress.ts`). Here the scope takes the + // deployment's configured trust from this request's context and, on a + // registration, the origins its body has the server read; a stored + // provider's are named as the vendor reads its row. This reads nothing. + // Naming an origin trusts nothing: a read of it is sent through the + // outbound-request guard, unless the deployment's configured trusted + // origins list it. Outside that scope this does nothing. + await declareSsoDiscoveryReadsOf(ctx); + // ── An auth request is judged and executed as one account ──────── // AHEAD OF EVERY GATE BELOW, and of the endpoint: a request whose // session cookie and bearer token name two different signed-in @@ -633,19 +648,21 @@ 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 + // SSO discovery connects only to addresses that are public at connect + // time: the host this registration's discovery reads is judged before + // the vendor's endpoint runs, by the rule its read is judged by when it + // connects, 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. + // the switch says, and nothing is read from it. A host that answers + // otherwise when its read connects is refused there, nothing sent. const notPublic = await refuseSsoDiscoveryHostNotPublic({ body: ctx?.body, isConfiguredTrusted: (url) => typeof ctx?.context?.isTrustedOrigin === 'function' && ctx.context.isTrustedOrigin(url) === true, + judge: judgeSsoDiscoveryUrl, }); if (notPublic) { const { APIError } = await import('better-auth/api'); diff --git a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts index c188609faa7..620e102b358 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts @@ -786,6 +786,11 @@ export async function buildPluginList(this: PluginListHost): Promise { // // Toggle with `OS_SSO_ENABLED` (mirrors `OS_OIDC_PROVIDER_ENABLED`). if (enabled.sso) { + // SSO discovery connects only to addresses that are public at connect + // time: the adapter the vendor reads its providers through names their + // origins for the request's scope (`sso-discovery-egress.ts`). + const { ssoProviderReadsObserverPlugin } = await import('./sso-discovery-egress.js'); + plugins.push(ssoProviderReadsObserverPlugin() as any); await this.addOptionalPlugin(plugins, 'sso', async () => { const { sso } = await import('@better-auth/sso'); // NOTE: the `ssoProvider` model is bridged to `sys_sso_provider` by the diff --git a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts index 6c06f106006..a944e060743 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-request-routing.ts @@ -68,6 +68,7 @@ import { SESSION_ERASURE_PATHS } from './session-tombstone.js'; import { envelopeVendorAdminRefusal } from './vendor-admin-refusal-envelope.js'; import { OAUTH_REVOKE_PATH } from './mcp-token-revocation.js'; import { ssoCallbackOf } from './sso-oidc-refusal-cause.js'; +import { isSsoDiscoveryEgressPath } from './sso-discovery-egress.js'; import { samlSingleLogoutProviderId, SIGN_OUT_ENDPOINT_PATH } from './sso-sign-out-of-idp.js'; import type { ScimRequestScope } from './scim-connection-service.js'; @@ -91,11 +92,12 @@ export interface RequestRoutingHost { answerOAuthTokenRevocation: AuthManager['answerOAuthTokenRevocation']; runSsoCallback: AuthManager['runSsoCallback']; runSsoLogout: AuthManager['runSsoLogout']; + runSsoDiscoveryEgress: AuthManager['runSsoDiscoveryEgress']; resolveAuthSecret: AuthManager['resolveAuthSecret']; } /** The body of `AuthManager#handleRequest`; the method's docblock there is its contract. */ -export async function handleRequest(this: Pick, request: Request, transport?: { remoteAddress?: string }): Promise { +export async function handleRequest(this: Pick, request: Request, transport?: { remoteAddress?: string }): Promise { // ADR-0069 D7 — the client address this request's sign-in audit stamps, // established ONCE, here, by the same trust rule the D5 allow-list judges // with (`resolveClientAddress`). Read before any rewrite below, and carried @@ -214,7 +216,7 @@ export async function handleRequest(this: Pick >`. // The previous single call site flattened it with the `await` below. - const runHandler = async (): Promise => + const runVendorHandler = async (): Promise => await runWithAuthActorScope(() => runWithRequestState( new WeakMap(clientAddressStateEntries(clientAddress)), @@ -222,6 +224,20 @@ export async function handleRequest(this: Pick => this.runSsoDiscoveryEgress(runVendorHandler) + : runVendorHandler; + // [#7724] A subject-erasure request is ONE unit of work, and better-auth // does not treat it as one: `internalAdapter.deleteUser` deletes the // sessions, then the accounts, then the user, in three unrelated adapter diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts index 189ed4c259e..5d28c23737c 100644 --- a/packages/plugins/plugin-auth/src/auth-manager.ts +++ b/packages/plugins/plugin-auth/src/auth-manager.ts @@ -44,6 +44,7 @@ import { type CredentialUseClient, } from '@objectstack/core'; import type { AuthGate } from '@objectstack/core'; +import type { EgressGuard } from '@objectstack/core/egress'; import { effectiveSessionLimits, isMfaRequirementLevel, @@ -1440,6 +1441,18 @@ export interface AuthManagerOptions extends Partial { * deliberately still wins for this budget — see `getOtpSendGuard`. */ sharedCounterStore?: () => Promise; + + /** + * The outbound-request guard SSO discovery sends its reads through + * (`sso-discovery-egress.ts`): the connection resolves the identity + * provider's host and connects only to an address that is public at that + * moment. Absent → `createSsoDiscoveryEgressGuard()`, whose policy refuses + * every address that is not public. A suite that fakes the identity provider + * by stubbing the global fetch hands a stand-in here + * (`sso-discovery-egress.testkit.ts`); the rule itself is pinned with the + * real guard. + */ + ssoDiscoveryEgress?: EgressGuard; } /** @@ -4318,7 +4331,7 @@ export class AuthManager { */ handleVendorRequest(request: Request, transport?: { remoteAddress?: string }): Promise { // [#25224 cut 10] The body moved to `auth-manager-request-routing.ts` (see `RequestRoutingHost`). - const host: Pick = { + const host: Pick = { config: this.config, betterAuthEndpointPath: (...a) => this.betterAuthEndpointPath(...a), getOrCreateAuth: (...a) => this.getOrCreateAuth(...a), @@ -4327,11 +4340,73 @@ export class AuthManager { answerOAuthTokenRevocation: (...a) => this.answerOAuthTokenRevocation(...a), runSsoCallback: (...a) => this.runSsoCallback(...a), runSsoLogout: (...a) => this.runSsoLogout(...a), + runSsoDiscoveryEgress: (...a) => this.runSsoDiscoveryEgress(...a), resolveAuthSecret: (...a) => this.resolveAuthSecret(...a), }; return handleRequest.call(host, request, transport); } + /** + * The guard SSO discovery sends its reads through: the host's + * ({@link AuthManagerOptions.ssoDiscoveryEgress}), else one built once per + * manager, whose refusals go to this manager's logger. + */ + private ssoDiscoveryEgressGuard(): Promise { + if (!this.ssoDiscoveryEgressGuardPromise) { + const configured = this.config.ssoDiscoveryEgress; + this.ssoDiscoveryEgressGuardPromise = configured + ? Promise.resolve(configured) + : import('./sso-discovery-egress.js').then(({ createSsoDiscoveryEgressGuard }) => + createSsoDiscoveryEgressGuard(this.config.logger ? { logger: this.config.logger } : {}), + ); + // A guard that cannot be built is asked again on the next read, not cached. + this.ssoDiscoveryEgressGuardPromise.catch(() => { + this.ssoDiscoveryEgressGuardPromise = undefined; + }); + } + return this.ssoDiscoveryEgressGuardPromise; + } + + private ssoDiscoveryEgressGuardPromise?: Promise; + + /** + * Run a vendor endpoint that reads an identity provider (`/sso/register`, + * `/sign-in/sso`, `/sso/callback/*`) inside the SSO discovery scope + * (`sso-discovery-egress.ts`). The scope judges only reads at origins the + * request's provider configuration names: the global before-hook names a + * registration's, and the auth context's observed adapter + * (`ssoProviderReadsObserverPlugin`, mounted with `sso`) names a stored + * provider's as the vendor reads its row. Every other read the request + * makes is sent as it was. A context whose adapter is not observed (a view + * that does not hand its reads on through the observed one) is answered + * `503 SERVICE_UNAVAILABLE` before the endpoint runs, so nothing is read or + * sent: its provider reads could not be judged. + */ + private async runSsoDiscoveryEgress(run: () => Promise): Promise { + const [{ runInSsoDiscoveryEgressScope, observesSsoProviderReads }, guard, auth] = await Promise.all([ + import('./sso-discovery-egress.js'), + this.ssoDiscoveryEgressGuard(), + this.getOrCreateAuth(), + ]); + const context = (await auth.$context) as { adapter?: unknown } | undefined; + if (!observesSsoProviderReads(context?.adapter)) { + this.audienceLogError( + '[AuthManager] SSO request refused: the auth context\'s adapter does not hand its provider reads on through the SSO discovery observer, so the reads they name could not be judged.', + ); + return new Response( + JSON.stringify({ + success: false, + error: { + code: 'SERVICE_UNAVAILABLE', + message: 'SSO is unavailable: this server cannot judge its reads of an identity provider. Nothing was read or sent.', + }, + }), + { status: 503, headers: { 'content-type': 'application/json' } }, + ); + } + return (await runInSsoDiscoveryEgressScope(guard, run)).value; + } + /** * Run one enterprise SSO callback inside the refusal scope * (`sso-oidc-refusal-cause.ts`): an OIDC callback (`/sso/callback/:providerId`) @@ -4515,6 +4590,14 @@ export class AuthManager { * (`ssoDiscoveryTrustedOrigins`) beside the configured ones, on both doors. * The discovery read it makes keeps the configured trust, and the request's * own origin check never sees them (`sso-discovery-companion-origins.ts`). + * + * That read connects only to addresses that are public at connect time: it + * runs in its own SSO discovery scope, which names the origins the body's + * and the stored provider configuration read, and sends a read at one of + * them the configured trust does not list through the outbound-request + * guard (`sso-discovery-egress.ts`). On a registration, a refusal of the + * discovery host the body names is answered on the member that names it, + * as the before-hook's earlier judgement of that host answers. */ private async assertSsoSignOutOfIdpSupported(ctx: any): Promise { const path = ctx?.path; @@ -4535,17 +4618,47 @@ export class AuthManager { (typeof ctx.body.issuer === 'string' && ctx.body.issuer) || (typeof stored?.issuer === 'string' && stored.issuer) || undefined; - const verdict = await judgeSignOutOfIdpCapability({ - providerId, - issuer, - stored: stored ? { samlConfig: stored.samlConfig, oidcConfig: stored.oidcConfig } : undefined, - body: { samlConfig: ctx.body.samlConfig, oidcConfig: ctx.body.oidcConfig }, - isTrustedOrigin: (url) => context.isTrustedOrigin(url), - isTrustedLogoutOrigin: trustingBodyNamedOrigins( - (url) => context.isTrustedOrigin(url), - await this.ssoDiscoveryTrustedOrigins(ctx.body), - ), - }); + const isTrustedLogoutOrigin = trustingBodyNamedOrigins( + (url) => context.isTrustedOrigin(url), + await this.ssoDiscoveryTrustedOrigins(ctx.body), + ); + const [{ runInSsoDiscoveryEgressScope, registerDiscoveryRefusalFor, oidcConfigReadUrls }, { computeDiscoveryUrl }, guard] = + await Promise.all([ + import('./sso-discovery-egress.js'), + import('@better-auth/sso'), + this.ssoDiscoveryEgressGuard(), + ]); + const { value: verdict, refused } = await runInSsoDiscoveryEgressScope( + guard, + () => + judgeSignOutOfIdpCapability({ + providerId, + issuer, + stored: stored ? { samlConfig: stored.samlConfig, oidcConfig: stored.oidcConfig } : undefined, + body: { samlConfig: ctx.body.samlConfig, oidcConfig: ctx.body.oidcConfig }, + isTrustedOrigin: (url) => context.isTrustedOrigin(url), + isTrustedLogoutOrigin, + }), + { + reads: [ + ...oidcConfigReadUrls(issuer, ctx.body.oidcConfig, computeDiscoveryUrl), + ...oidcConfigReadUrls(issuer, stored?.oidcConfig, computeDiscoveryUrl), + ], + isConfiguredTrusted: (url) => context.isTrustedOrigin(url) === true, + }, + ); + const hostRefusal = + refused && !refused.unresolved && path === '/sso/register' + ? await registerDiscoveryRefusalFor(ctx.body, refused) + : undefined; + if (hostRefusal) { + const { APIError } = await import('better-auth/api'); + throw new APIError(hostRefusal.status, { + code: hostRefusal.code, + message: hostRefusal.message, + field: hostRefusal.field, + }); + } if (!verdict.ok) { const { APIError } = await import('better-auth/api'); throw new APIError(verdict.refusal.status, { @@ -6191,7 +6304,8 @@ export class AuthManager { * 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 + * (`refuseSsoDiscoveryHostNotPublic`), and every read is judged again when + * it connects (`sso-discovery-egress.ts`). Best-effort: anything unreadable * yields `[]`. * * ⛔ Never an accepted `Origin`: the request's own origin check reads the 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 c0d48738062..653d0d63da8 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 @@ -29,6 +29,8 @@ import { trustingBodyNamedOrigins, } from './sso-discovery-companion-origins'; import { runRegisterSsoProviderFromForm } from './register-sso-provider'; +import { createSsoDiscoveryEgressGuard, SSO_DISCOVERY_EGRESS_SOURCE } from './sso-discovery-egress'; +import { stubbedSsoDiscoveryEgress } from './sso-discovery-egress.testkit'; import dnsPromises from 'node:dns/promises'; import { syncBuiltinESMExports } from 'node:module'; // better-auth's first module load is paid at module load, not inside the first @@ -145,6 +147,9 @@ async function makeRp(trustedOrigins: string[] = [BASE]): Promise { trustedOrigins, plugins: { sso: true }, logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() }, + // The identity provider answers over the stubbed fetch; the connect-time + // rule itself is pinned with the real guard (`sso-discovery-connect-time.test.ts`). + ssoDiscoveryEgress: await stubbedSsoDiscoveryEgress(), } as unknown as ConstructorParameters[0]); vi.spyOn(manager as any, 'isPlatformAdminUserId').mockResolvedValue(true); const ctx = await ((await manager.getAuthInstance()) as any).$context; @@ -609,7 +614,7 @@ describe('an origin a register or update body names is trusted for that provider }); }); -// ── SSO discovery reads only hosts that resolve to public addresses ───────── +// ── SSO discovery connects only to addresses that are public ──────────────── /** An address no non-public range holds. */ const PUBLIC_ADDRESS = '93.184.215.14'; @@ -620,7 +625,7 @@ const RESOLVED_DISCOVERY = `${RESOLVED_ISSUER}/.well-known/openid-configuration` 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', () => { +describe('SSO discovery connects only to addresses that are public: a registration\'s discovery host is judged before the vendor runs', () => { let undo: Array<() => void> = []; afterEach(() => { for (const step of undo.reverse()) step(); @@ -754,7 +759,7 @@ describe('SSO discovery reads only hosts that resolve to public addresses', () = }); }); -describe('the host a registration\'s discovery reads is the one host resolved', () => { +describe('the host a registration\'s discovery reads is the one host judged', () => { /** A resolver answering a private address for every name, recording each name asked. */ function privateResolver() { const asked: string[] = []; @@ -764,6 +769,11 @@ describe('the host a registration\'s discovery reads is the one host resolved', }; return { asked, resolve }; } + /** The judgement the connection applies, over `resolve`. */ + function judgeWith(resolve: (hostname: string) => Promise>) { + const guard = createSsoDiscoveryEgressGuard({ resolve }); + return async (url: string) => (await guard).judgeUrl(url, { source: SSO_DISCOVERY_EGRESS_SOURCE }); + } const configured = (url: string) => url.startsWith(BASE); const oidc = (extra: Record = {}) => ({ clientId: 'client-id', clientSecret: 'client-secret', ...extra }); @@ -772,7 +782,7 @@ describe('the host a registration\'s discovery reads is the one host resolved', const refusal = await refuseSsoDiscoveryHostNotPublic({ body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc() }, isConfiguredTrusted: configured, - resolve: r.resolve, + judge: judgeWith(r.resolve), }); expect(refusal).toMatchObject({ status: 'BAD_REQUEST', code: 'VALIDATION_FAILED', field: 'issuer' }); expect(r.asked).toEqual([RESOLVED_HOST]); @@ -783,7 +793,7 @@ describe('the host a registration\'s discovery reads is the one host resolved', const refusal = await refuseSsoDiscoveryHostNotPublic({ body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc({ discoveryEndpoint: `${DISCOVERY_ORIGIN}/.well-known/openid-configuration` }) }, isConfiguredTrusted: configured, - resolve: r.resolve, + judge: judgeWith(r.resolve), }); expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', field: 'oidcConfig.discoveryEndpoint' }); expect(r.asked).toEqual([DISCOVERY_HOST]); @@ -797,18 +807,18 @@ describe('the host a registration\'s discovery reads is the one host resolved', undefined, ]) { const r = privateResolver(); - expect(await refuseSsoDiscoveryHostNotPublic({ body, isConfiguredTrusted: configured, resolve: r.resolve }), JSON.stringify(body)).toBeUndefined(); + expect(await refuseSsoDiscoveryHostNotPublic({ body, isConfiguredTrusted: configured, judge: judgeWith(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 () => { + it('a discovery URL the deployment trusts, and a host the vendor\'s own check refuses (a non-public literal or name), are not judged 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, + judge: judgeWith(r.resolve), }); expect(refusal, issuer).toBeUndefined(); expect(r.asked, issuer).toEqual([]); @@ -819,18 +829,30 @@ describe('the host a registration\'s discovery reads is the one host resolved', const refusal = await refuseSsoDiscoveryHostNotPublic({ body: { issuer: RESOLVED_ISSUER, oidcConfig: oidc() }, isConfiguredTrusted: configured, - resolve: async (hostname) => { + judge: judgeWith(async (hostname) => { throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), { code: 'ENOTFOUND' }); - }, + }), }); expect(refusal).toBeUndefined(); }); + it('an address literal the vendor\'s own check admits is judged by the platform\'s address classes: the Azure host-platform endpoint is refused', async () => { + const r = privateResolver(); + const refusal = await refuseSsoDiscoveryHostNotPublic({ + body: { issuer: 'https://168.63.129.16', oidcConfig: oidc() }, + isConfiguredTrusted: configured, + judge: judgeWith(r.resolve), + }); + expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(refusal?.message).not.toContain('metadata'); + expect(r.asked).toEqual([]); + }); + 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' }], + judge: judgeWith(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 63d43815edd..f618f0b47b6 100644 --- a/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts +++ b/packages/plugins/plugin-auth/src/sso-discovery-companion-origins.ts @@ -49,11 +49,15 @@ * 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}). + * That trust covers origin verdicts only. SSO discovery connects only to + * addresses that are public at connect time: every read it makes is sent + * through the outbound-request guard, which judges the addresses the + * connection itself resolves (`sso-discovery-egress.ts`). The host a + * registration's discovery reads is also judged before the vendor's register + * endpoint runs, so a host that is not public is refused on the member that + * names it, and the body-named origins are handed to the vendor 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 @@ -146,20 +150,16 @@ export function trustingBodyNamedOrigins( }; } -// ── The host a registration's discovery reads resolves to public addresses ── +// ── The host a registration's discovery reads is public ───────────────────── -/** 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; - } -} +/** + * Judges, without sending anything, whether SSO discovery may read a URL: its + * host is resolved and every address judged by the rule the connection + * applies (`judgeSsoDiscoveryUrl` in `sso-discovery-egress.ts`). `unresolved` + * marks a name that did not resolve, answered allowed: the connection itself + * refuses it. + */ +export type SsoDiscoveryJudge = (url: string) => Promise<{ allow: boolean; unresolved?: boolean }>; /** The body member naming the URL a registration's discovery reads. */ export type SsoDiscoveryReadMember = 'issuer' | 'oidcConfig.discoveryEndpoint'; @@ -201,31 +201,54 @@ export interface SsoDiscoveryHostRefusal { } /** - * SSO discovery fetches only hosts that resolve to public addresses. + * The refusal of a registration whose discovery host is not public, on the + * member that names it. The same answer whether the host was judged before the + * vendor's register endpoint ran ({@link refuseSsoDiscoveryHostNotPublic}) or + * when its read connected (`explainSsoDiscoveryConnectRefusal`). It names the + * host and the rule, never the address the host resolved to. + */ +export function ssoDiscoveryHostRefusal(member: SsoDiscoveryReadMember, url: URL): SsoDiscoveryHostRefusal { + return { + status: 'BAD_REQUEST', + code: 'VALIDATION_FAILED', + field: member, + message: + `The host "${url.hostname}" that ${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 connects only to addresses that are public ' + + 'at connect time; an identity provider on an internal network registers once the deployment\'s trusted origins ' + + `(OS_TRUSTED_ORIGINS) list its origin, ${url.origin}.`, + }; +} + +/** + * SSO discovery connects only to addresses that are public at connect time; + * this is the registration's early answer. * * 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. + * read ({@link ssoRegisterDiscoveryRead}) is judged here, before the vendor's + * register endpoint runs, by the rule its read is judged by when it connects + * (`judge`): every address the host resolves to must be public, by the + * platform's address classes (`classifyAddress`: loopback, private, + * link-local, cloud metadata and host-platform addresses, and every other + * non-public range), an address literal included. 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 + * judged here, nor when it connects. * - * 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. + * A host the vendor's own synchronous check refuses (`localhost`, a private + * literal, a metadata name: not `isPublicRoutableHost`) is left to that + * refusal. A name that does not resolve is left to the read, whose connection + * refuses it and sends nothing. 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; + /** The judgement the connection applies (`judgeSsoDiscoveryUrl`). */ + judge: SsoDiscoveryJudge; }): Promise { const { computeDiscoveryUrl } = await import('@better-auth/sso'); const read = ssoRegisterDiscoveryRead(input.body, computeDiscoveryUrl); @@ -237,28 +260,12 @@ export async function refuseSsoDiscoveryHostNotPublic(input: { 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; + const { isPublicRoutableHost } = await import('@better-auth/core/utils/host'); + if (!isPublicRoutableHost(url.hostname)) 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}.`, - }; + const verdict = await input.judge(url.href); + if (verdict.allow) return undefined; + return ssoDiscoveryHostRefusal(read.member, url); } // ── The refusal: name the endpoint, and say how to name it explicitly ─────── diff --git a/packages/plugins/plugin-auth/src/sso-discovery-connect-time.test.ts b/packages/plugins/plugin-auth/src/sso-discovery-connect-time.test.ts new file mode 100644 index 00000000000..021bb1e3ec4 --- /dev/null +++ b/packages/plugins/plugin-auth/src/sso-discovery-connect-time.test.ts @@ -0,0 +1,793 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * SSO discovery connects only to addresses that are public at connect time — + * see `sso-discovery-egress.ts` for the rule this file pins. + * + * A real `AuthManager` with the real `sso()` plugin over the in-memory engine, + * driven through its HTTP surface, with the REAL SSO discovery guard + * (`createSsoDiscoveryEgressGuard`: its policy and its own transport). Name + * resolution is a double, and so is the platform's ordinary transport (the + * global fetch), which resolves the name again when it connects, records the + * address it connects to and answers the identity provider's document. + * + * The world these cases build: the identity provider's name answers a public + * address to every check made before a read (the vendor's own, and the + * registration's early one) and an internal address (loopback, cloud metadata, + * private, the Azure host-platform endpoint) when the read connects. + * + * - a registration, with and without the sign-out switch, is refused on the + * member naming the host, and nothing connects to the internal address; + * - an update turning the sign-out switch on is refused the same way; + * - a sign-in's callback reads (the token endpoint) are refused the same way; + * - CONTROL: a host whose address is public when the read connects registers, + * its document read over the guard's own connection; + * - CONTROL: an origin the deployment's configured trusted origins list is + * read as it always was; + * - CONTROL: a request's other reads over the global fetch (a datastore, a + * rate-limit counter store, both on internal addresses) are sent as they + * were, before and after the request's provider configuration is read. + * + * A request whose auth context adapter is not the observed view is refused + * before its endpoint runs (CONTROL: a view that hands its reads on through + * the observed one keeps it). + * + * Then the scope itself: what the wrapper over the global fetch judges, the + * adapter observation that names a stored provider's origins, and a second + * copy of the module in the same process. + */ + +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import dnsPromises from 'node:dns/promises'; +import { syncBuiltinESMExports } from 'node:module'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createEgressGuard, type EgressGuard, type EgressResolver } from '@objectstack/core/egress'; +import { AuthManager } from './auth-manager'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; +import { + createSsoDiscoveryEgressGuard, + declareSsoDiscoveryReads, + observesSsoProviderReads, + observingSsoProviderReads, + runInSsoDiscoveryEgressScope, +} from './sso-discovery-egress'; +// better-auth's first module load is paid at module load, not inside the first +// clocked case (AGENTS.md, Build & Test). `AuthManager` reaches these through a +// lazy `await import()`. +import 'better-auth'; +import 'better-auth/plugins'; +import '@better-auth/sso'; + +const SECRET = 'test-secret-at-least-32-chars-long-connect-time'; +const BASE = 'http://localhost:3000'; +const AUTH = `${BASE}/api/v1/auth`; +const FAILED = `${BASE}/sign-in-failed`; +const CLIENT_SECRET = 'client-secret'; + +/** An address no non-public range holds: what every check before a read is answered. */ +const PUBLIC_ADDRESS = '93.184.215.14'; + +/** Each internal address a read may find at connect time, and the class the guard refuses it as. */ +const INTERNAL: ReadonlyArray = [ + ['127.0.0.1', 'loopback'], + ['169.254.169.254', 'link-local'], + ['10.0.0.5', 'private'], + ['168.63.129.16', 'metadata'], +]; + +// ── The receiver: where a connection to 127.0.0.1 would land ─────────────── + +let receiver: Server; +let port: number; +const received: string[] = []; + +beforeAll(async () => { + receiver = createServer((req, res) => { + received.push(`${req.headers.host} ${req.url}`); + const host = String(req.headers.host); + if (req.url === '/.well-known/openid-configuration') { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify(discoveryDocument(`http://${host}`))); + return; + } + res.writeHead(404); + res.end(); + }); + await new Promise((resolve) => receiver.listen(0, '127.0.0.1', resolve)); + port = (receiver.address() as AddressInfo).port; +}); + +afterAll(async () => { + await new Promise((resolve) => receiver.close(() => resolve())); +}); + +/** The identity provider whose name answers otherwise at connect time. */ +const flipIssuer = () => `http://idp.flip-corp.example:${port}`; +const FLIP_HOST = 'idp.flip-corp.example'; +/** The identity provider whose name answers the stand-in public host. */ +const stableIssuer = () => `http://idp.stable-corp.example:${port}`; +const STABLE_HOST = 'idp.stable-corp.example'; +/** A datastore and a rate-limit counter store reached over the global fetch, on the deployment's network. */ +const DATASTORE_HOST = 'db.internal.example'; +const COUNTER_HOST = 'counters.internal.example'; + +function discoveryDocument(issuer: string, extra: Record = {}): Record { + return { + issuer, + authorization_endpoint: `${issuer}/authorize`, + token_endpoint: `${issuer}/token`, + jwks_uri: `${issuer}/jwks`, + userinfo_endpoint: `${issuer}/userinfo`, + response_types_supported: ['code'], + subject_types_supported: ['public'], + id_token_signing_alg_values_supported: ['RS256'], + ...extra, + }; +} + +// ── Name resolution and the ordinary transport ───────────────────────────── + +/** + * The checks' name resolution: `node:dns/promises` `lookup`, which the + * vendor's own pre-read check calls, answers {@link PUBLIC_ADDRESS} for the + * identity provider's names and ENOTFOUND for every other. Published to ES + * importers, as `sso-discovery-companion-origins.test.ts` does. + */ +function stubCheckResolution(): () => void { + const exportsObject = dnsPromises as unknown as { lookup: typeof dnsPromises.lookup }; + const original = exportsObject.lookup; + exportsObject.lookup = (async (name: string) => { + if (name === FLIP_HOST || name === STABLE_HOST) return [{ address: PUBLIC_ADDRESS, family: 4 }]; + throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${name}`), { code: 'ENOTFOUND', hostname: name }); + }) as unknown as typeof dnsPromises.lookup; + syncBuiltinESMExports(); + return () => { + exportsObject.lookup = original; + syncBuiltinESMExports(); + }; +} + +/** The guard's name resolution: each call for `hostname` answers the next of `answers` (the last repeats). */ +function guardResolution(hostname: string, answers: readonly string[]): { resolve: EgressResolver; asked: string[] } { + const asked: string[] = []; + return { + asked, + resolve: async (name) => { + if (name !== hostname) throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${name}`), { code: 'ENOTFOUND' }); + const address = answers[Math.min(asked.length, answers.length - 1)]!; + asked.push(name); + return [{ address }]; + }, + }; +} + +/** + * The platform's ordinary transport, as the global fetch: a request to the + * identity provider resolves its name again when it connects (`connectAddress`), + * is recorded with that address, and is answered as the identity provider + * answers. A request to the datastore or the counter store is recorded on + * `timeline` and answered. Every other request goes to the fetch underneath. + */ +function ordinaryTransport( + connectAddress: string, + timeline: string[] = [], +): { connected: Array<{ url: string; address: string }> } { + const connected: Array<{ url: string; address: string }> = []; + const underlying = globalThis.fetch; + const transport = (async (input: unknown, init?: RequestInit) => { + const href = typeof input === 'string' ? input : input instanceof URL ? input.href : (input as Request).url; + const url = new URL(href); + if (url.hostname === DATASTORE_HOST || url.hostname === COUNTER_HOST) { + timeline.push(`sent ${url.hostname}${url.pathname}`); + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + } + if (url.hostname !== FLIP_HOST) return underlying(input as never, init); + connected.push({ url: url.href, address: connectAddress }); + const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); + if (url.pathname === '/.well-known/openid-configuration') { + return json(discoveryDocument(url.origin, { end_session_endpoint: `${url.origin}/logout` })); + } + if (url.pathname === '/token') return json({ access_token: 'at-opaque', token_type: 'Bearer', expires_in: 300, id_token: 'not-a-token' }); + if (url.pathname === '/jwks') return json({ keys: [] }); + return json({ sub: 'subject' }); + }) as typeof globalThis.fetch; + vi.stubGlobal('fetch', transport); + return { connected }; +} + +// ── The relying party ─────────────────────────────────────────────────────── + +interface Rp { + manager: AuthManager; + engine: ReturnType; + token: string; + ctx: any; +} + +/** + * Every engine verb of `engine` first makes a request to the datastore over + * the global fetch, as a datastore driver reached over HTTP does. + */ +function overHttp(engine: ReturnType): void { + const verbs = ['insert', 'findOne', 'find', 'count', 'update', 'delete'] as const; + const target = engine as unknown as Record Promise>; + for (const verb of verbs) { + const original = target[verb]!; + target[verb] = async (...args: unknown[]) => { + await fetch(`http://${DATASTORE_HOST}:8080/v2/${verb}/${String(args[0])}`, { method: 'POST', body: '{}' }); + return original.apply(engine, args); + }; + } +} + +async function makeRp( + guard: EgressGuard, + trustedOrigins: string[] = [BASE], + options: { overHttp?: boolean } = {}, +): Promise { + const engine = createMemoryEngine(); + (engine as any).resolveSecretField = async () => CLIENT_SECRET; + if (options.overHttp) overHttp(engine); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: BASE, + dataEngine: engine, + trustedOrigins, + plugins: { sso: true }, + logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() }, + ssoDiscoveryEgress: guard, + // A rate-limit counter store reached over the global fetch: consumed + // ahead of every endpoint, before the global before-hook runs. + ...(options.overHttp + ? { + rateLimit: { enabled: true, window: 60, max: 100_000 }, + rateLimitStorage: { + consume: async () => { + await fetch(`http://${COUNTER_HOST}:6380/consume`, { method: 'POST', body: '{}' }); + return { allowed: true }; + }, + }, + } + : {}), + } as unknown as ConstructorParameters[0]); + vi.spyOn(manager as any, 'isPlatformAdminUserId').mockResolvedValue(true); + const ctx = await ((await manager.getAuthInstance()) as any).$context; + const user = await ctx.adapter.create({ + model: 'user', + data: { email: 'admin@acme.com', name: 'Admin', emailVerified: true, createdAt: new Date(), updatedAt: new Date() }, + }); + const token = (await ctx.internalAdapter.createSession(user.id)).token as string; + return { manager, engine, token, ctx }; +} + +function post(rp: Rp, path: string, body: Record): Promise { + return rp.manager.handleRequest( + new Request(`${AUTH}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: BASE, authorization: `Bearer ${rp.token}` }, + body: JSON.stringify(body), + }), + ); +} + +function registration(providerId: string, issuer: string, oidcConfig: Record = {}): Record { + return { + providerId, + issuer, + domain: 'acme.com', + oidcConfig: { + clientId: 'client-id', + clientSecret: CLIENT_SECRET, + scopes: ['openid', 'email', 'profile'], + mapping: { email: 'email', name: 'name' }, + ...oidcConfig, + }, + }; +} + +function storedRows(rp: Rp): Array> { + return (rp.engine.tables.get('sys_sso_provider') ?? []) as Array>; +} + +/** The real guard over the resolution double; its refusals, with their class, recorded. */ +async function realGuard(resolve: EgressResolver): Promise<{ guard: EgressGuard; refusals: Array> }> { + const refusals: Array> = []; + const guard = await createSsoDiscoveryEgressGuard({ + resolve, + logger: { warn: (_msg, meta) => refusals.push(meta ?? {}) }, + }); + return { guard, refusals }; +} + +let undo: Array<() => void> = []; +beforeEach(() => { + received.length = 0; + undo.push(stubCheckResolution()); +}); +afterEach(() => { + for (const step of undo.reverse()) step(); + undo = []; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('SSO discovery connects only to addresses that are public at connect time', () => { + it.each(INTERNAL)( + 'a registration whose discovery host answers %s when the read connects is refused on issuer, and nothing connects to it', + async (address, denyClass) => { + const transport = ordinaryTransport(address); + const names = guardResolution(FLIP_HOST, [PUBLIC_ADDRESS, address]); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard); + const res = await post(rp, '/sso/register', registration('flip-oidc', flipIssuer())); + const text = await res.clone().text(); + expect(res.status, text).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(text).not.toContain(address); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass, source: 'sso-discovery' })]); + expect(storedRows(rp)).toEqual([]); + }, + ); + + it.each(INTERNAL)( + 'with the sign-out switch on, a registration whose discovery host answers %s when its first read connects is refused on issuer, and nothing connects to it', + async (address, denyClass) => { + const transport = ordinaryTransport(address); + const names = guardResolution(FLIP_HOST, [PUBLIC_ADDRESS, address]); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard); + const res = await post(rp, '/sso/register', { ...registration('flip-oidc', flipIssuer()), signOutOfIdp: true }); + const text = await res.clone().text(); + expect(res.status, text).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'issuer' }); + expect(text).not.toContain(address); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass })]); + expect(storedRows(rp)).toEqual([]); + }, + ); + + it('an update turning the sign-out switch on is refused when the discovery host answers an internal address as its read connects', async () => { + const transport = ordinaryTransport('168.63.129.16'); + const names = guardResolution(FLIP_HOST, ['168.63.129.16']); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard); + // Registered with its endpoints named and discovery skipped: that reads nothing. + const issuer = flipIssuer(); + const registered = await post( + rp, + '/sso/register', + registration('flip-oidc', issuer, { + skipDiscovery: true, + authorizationEndpoint: `${issuer}/authorize`, + tokenEndpoint: `${issuer}/token`, + jwksEndpoint: `${issuer}/jwks`, + }), + ); + expect(registered.status, await registered.clone().text()).toBe(200); + expect(transport.connected).toEqual([]); + const before = JSON.stringify(storedRows(rp)); + const res = await post(rp, '/sso/update-provider', { providerId: 'flip-oidc', issuer, signOutOfIdp: true }); + const text = await res.clone().text(); + expect(res.status, text).toBe(400); + expect(await res.json()).toMatchObject({ code: 'VALIDATION_FAILED', field: 'signOutOfIdp' }); + expect(text).not.toContain('168.63.129.16'); + expect(transport.connected).toEqual([]); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass: 'metadata' })]); + expect(JSON.stringify(storedRows(rp))).toBe(before); + }); + + it.each(INTERNAL)( + 'a sign-in whose token endpoint answers %s when the callback\'s read connects is refused, and nothing connects to it', + async (address, denyClass) => { + const transport = ordinaryTransport(address); + const names = guardResolution(FLIP_HOST, [address]); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard); + const issuer = flipIssuer(); + await rp.ctx.adapter.create({ + model: 'ssoProvider', + data: { + providerId: 'flip-oidc', + issuer, + domain: 'acme.com', + oidcConfig: JSON.stringify({ + issuer, + clientId: 'client-id', + clientSecret: CLIENT_SECRET, + authorizationEndpoint: `${issuer}/authorize`, + tokenEndpoint: `${issuer}/token`, + jwksEndpoint: `${issuer}/jwks`, + pkce: true, + scopes: ['openid', 'email', 'profile'], + mapping: { id: 'sub', email: 'email', name: 'name' }, + }), + }, + }); + const start = await rp.manager.handleRequest( + new Request(`${AUTH}/sign-in/sso`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: BASE }, + body: JSON.stringify({ providerId: 'flip-oidc', callbackURL: `${BASE}/after`, errorCallbackURL: FAILED }), + }), + ); + const started: any = await start.clone().json(); + expect(start.status, JSON.stringify(started)).toBe(200); + const state = new URL(started.url).searchParams.get('state')!; + const cookie = (start.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).join('; '); + const callback = await rp.manager.handleRequest( + new Request(`${AUTH}/sso/callback/flip-oidc?code=idp-code&state=${encodeURIComponent(state)}`, { headers: { cookie } }), + ); + expect(callback.status).toBe(302); + const location = callback.headers.get('location') ?? ''; + expect(location).toContain('error=invalid_provider'); + expect(location).not.toContain(address); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass })]); + }, + ); + + it('CONTROL: a host whose address is public when the read connects registers, its document read over the guard\'s own connection', async () => { + const transport = ordinaryTransport('10.0.0.5'); + // The stand-in public host: 127.0.0.1, where the receiver serves the + // identity provider; every other address is judged by the real policy. + const { guard: real } = await realGuard(async () => [{ address: '127.0.0.1' }]); + const guard = createEgressGuard({ + policy: { + canConnect: (target, ctx) => (target.address === '127.0.0.1' ? { allow: true } : real.policy.canConnect(target, ctx)), + }, + resolve: async (name) => { + if (name !== STABLE_HOST) throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${name}`), { code: 'ENOTFOUND' }); + return [{ address: '127.0.0.1' }]; + }, + }); + const rp = await makeRp(guard); + const res = await post(rp, '/sso/register', registration('stable-oidc', stableIssuer())); + expect(res.status, await res.clone().text()).toBe(200); + expect(received).toEqual([`${STABLE_HOST}:${port} /.well-known/openid-configuration`]); + expect(transport.connected).toEqual([]); + expect(storedRows(rp)).toHaveLength(1); + }); + + it('CONTROL: an origin the deployment\'s configured trusted origins list is read as it always was, whatever it answers at connect time', async () => { + const transport = ordinaryTransport('10.0.0.5'); + const names = guardResolution(FLIP_HOST, [PUBLIC_ADDRESS, '10.0.0.5']); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard, [BASE, flipIssuer()]); + const res = await post(rp, '/sso/register', { ...registration('flip-oidc', flipIssuer()), signOutOfIdp: true }); + expect(res.status, await res.clone().text()).toBe(200); + expect(transport.connected.map((c) => new URL(c.url).pathname)).toEqual([ + '/.well-known/openid-configuration', + '/.well-known/openid-configuration', + ]); + expect(names.asked).toEqual([]); + expect(refusals).toEqual([]); + }); + + it('CONTROL: a registration\'s datastore and counter-store reads over the global fetch, on internal addresses, are sent as they were, before and after its discovery read', async () => { + const timeline: string[] = []; + const transport = ordinaryTransport('10.0.0.5', timeline); + const asked: string[] = []; + const realPolicy = (await realGuard(async () => [{ address: '10.0.0.5' }])).guard.policy; + const guard = createEgressGuard({ + // The stand-in public host is 127.0.0.1, where the receiver serves the + // identity provider; the real policy judges every other address. + policy: { + canConnect: (target, ctx) => + target.address === '127.0.0.1' ? { allow: true } : realPolicy.canConnect(target, ctx), + }, + resolve: async (name) => { + asked.push(name); + timeline.push(`judged ${name}`); + if (name === STABLE_HOST) return [{ address: '127.0.0.1' }]; + return [{ address: '10.0.0.5' }]; + }, + }); + const rp = await makeRp(guard, [BASE], { overHttp: true }); + timeline.length = 0; + const res = await post(rp, '/sso/register', registration('stable-oidc', stableIssuer())); + expect(res.status, await res.clone().text()).toBe(200); + expect(storedRows(rp)).toHaveLength(1); + expect(asked.length).toBeGreaterThan(0); + expect(new Set(asked)).toEqual(new Set([STABLE_HOST])); + const firstJudged = timeline.findIndex((entry) => entry.startsWith('judged ')); + const lastJudged = timeline.length - 1 - [...timeline].reverse().findIndex((entry) => entry.startsWith('judged ')); + // Before the global before-hook (the counter store), between the + // before-hook and the discovery read (the session), and after it (the + // provider's row): every one sent as it was, none judged. + expect(timeline.slice(0, firstJudged)).toContain(`sent ${COUNTER_HOST}/consume`); + expect(timeline.slice(0, lastJudged).some((entry) => entry.startsWith(`sent ${DATASTORE_HOST}/`))).toBe(true); + expect(timeline.slice(lastJudged + 1)).toContain(`sent ${DATASTORE_HOST}/v2/insert/sys_sso_provider`); + expect(received).toEqual([`${STABLE_HOST}:${port} /.well-known/openid-configuration`]); + expect(transport.connected).toEqual([]); + }); + + it('CONTROL: a sign-in\'s datastore and counter-store reads over the global fetch, on internal addresses, are sent as they were, while its token read is refused', async () => { + const timeline: string[] = []; + const transport = ordinaryTransport('10.0.0.5', timeline); + const names = guardResolution(FLIP_HOST, ['10.0.0.5']); + const { guard, refusals } = await realGuard(async (name) => { + timeline.push(`judged ${name}`); + return names.resolve(name); + }); + const rp = await makeRp(guard, [BASE], { overHttp: true }); + const issuer = flipIssuer(); + await rp.ctx.adapter.create({ + model: 'ssoProvider', + data: { + providerId: 'flip-oidc', + issuer, + domain: 'acme.com', + oidcConfig: JSON.stringify({ + issuer, + clientId: 'client-id', + clientSecret: CLIENT_SECRET, + authorizationEndpoint: `${issuer}/authorize`, + tokenEndpoint: `${issuer}/token`, + jwksEndpoint: `${issuer}/jwks`, + pkce: true, + scopes: ['openid', 'email', 'profile'], + mapping: { id: 'sub', email: 'email', name: 'name' }, + }), + }, + }); + timeline.length = 0; + const start = await rp.manager.handleRequest( + new Request(`${AUTH}/sign-in/sso`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: BASE }, + body: JSON.stringify({ email: 'someone@acme.com', callbackURL: `${BASE}/after`, errorCallbackURL: FAILED }), + }), + ); + const started: any = await start.clone().json(); + expect(start.status, JSON.stringify(started)).toBe(200); + expect(timeline).toContain(`sent ${COUNTER_HOST}/consume`); + expect(timeline.some((entry) => entry.startsWith(`sent ${DATASTORE_HOST}/v2/find`) && entry.endsWith('/sys_sso_provider'))).toBe(true); + expect(timeline.filter((entry) => entry.startsWith('judged '))).toEqual([]); + timeline.length = 0; + const state = new URL(started.url).searchParams.get('state')!; + const cookie = (start.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).join('; '); + const callback = await rp.manager.handleRequest( + new Request(`${AUTH}/sso/callback/flip-oidc?code=idp-code&state=${encodeURIComponent(state)}`, { headers: { cookie } }), + ); + expect(callback.status).toBe(302); + expect(callback.headers.get('location') ?? '').toContain('error=invalid_provider'); + const judged = timeline.findIndex((entry) => entry.startsWith('judged ')); + expect(timeline.slice(judged).filter((entry) => entry.startsWith('judged '))).toEqual([`judged ${FLIP_HOST}`]); + expect(timeline.slice(0, judged)).toContain(`sent ${COUNTER_HOST}/consume`); + expect(timeline.slice(0, judged).some((entry) => entry.startsWith(`sent ${DATASTORE_HOST}/v2/find`))).toBe(true); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass: 'private' })]); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + }); +}); + +describe('a request whose auth context adapter is not the observed view is refused, and nothing is read or sent', () => { + /** The flip identity provider's row, stored with its endpoints named. */ + async function storeFlipProvider(rp: Rp): Promise { + const issuer = flipIssuer(); + await rp.ctx.adapter.create({ + model: 'ssoProvider', + data: { + providerId: 'flip-oidc', + issuer, + domain: 'acme.com', + oidcConfig: JSON.stringify({ + issuer, + clientId: 'client-id', + clientSecret: CLIENT_SECRET, + authorizationEndpoint: `${issuer}/authorize`, + tokenEndpoint: `${issuer}/token`, + jwksEndpoint: `${issuer}/jwks`, + pkce: true, + scopes: ['openid', 'email', 'profile'], + mapping: { id: 'sub', email: 'email', name: 'name' }, + }), + }, + }); + } + + function signIn(rp: Rp): Promise { + return rp.manager.handleRequest( + new Request(`${AUTH}/sign-in/sso`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: BASE }, + body: JSON.stringify({ providerId: 'flip-oidc', callbackURL: `${BASE}/after`, errorCallbackURL: FAILED }), + }), + ); + } + + const doors: ReadonlyArray Promise]> = [ + ['/sso/register', (rp) => post(rp, '/sso/register', registration('flip-register', flipIssuer()))], + ['/sign-in/sso', signIn], + ['/sso/callback/:providerId', (rp) => rp.manager.handleRequest(new Request(`${AUTH}/sso/callback/flip-oidc?code=idp-code&state=any-state`))], + ]; + + it.each(doors)( + '%s is answered 503 SERVICE_UNAVAILABLE before its endpoint runs, when a later plugin rebuilt the context adapter as a plain object', + async (_path, send) => { + const timeline: string[] = []; + const transport = ordinaryTransport('10.0.0.5', timeline); + const names = guardResolution(FLIP_HOST, [PUBLIC_ADDRESS, '10.0.0.5']); + const { guard, refusals } = await realGuard(async (name) => { + timeline.push(`judged ${name}`); + return names.resolve(name); + }); + const rp = await makeRp(guard, [BASE], { overHttp: true }); + await storeFlipProvider(rp); + // A view that does not hand its reads on through the observed adapter: + // the observer's mark does not survive a plain-object rebuild. + rp.ctx.adapter = { ...rp.ctx.adapter }; + timeline.length = 0; + const res = await send(rp); + expect(res.status, await res.clone().text()).toBe(503); + expect(await res.json()).toMatchObject({ success: false, error: { code: 'SERVICE_UNAVAILABLE' } }); + // The endpoint never ran: no rate-limit consume, no datastore read, no + // judgement, no connection, and no provider written. + expect(timeline).toEqual([]); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + expect(refusals).toEqual([]); + expect(storedRows(rp).map((row) => row.providerId ?? row.provider_id)).toEqual(['flip-oidc']); + }, + ); + + it('CONTROL: a later view that hands its reads on through the observed adapter keeps it: the sign-in runs, and its callback\'s token read is judged and refused', async () => { + const transport = ordinaryTransport('10.0.0.5'); + const names = guardResolution(FLIP_HOST, ['10.0.0.5']); + const { guard, refusals } = await realGuard(names.resolve); + const rp = await makeRp(guard); + await storeFlipProvider(rp); + rp.ctx.adapter = new Proxy(rp.ctx.adapter, {}); + const start = await signIn(rp); + const started: any = await start.clone().json(); + expect(start.status, JSON.stringify(started)).toBe(200); + const state = new URL(started.url).searchParams.get('state')!; + const cookie = (start.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).join('; '); + const callback = await rp.manager.handleRequest( + new Request(`${AUTH}/sso/callback/flip-oidc?code=idp-code&state=${encodeURIComponent(state)}`, { headers: { cookie } }), + ); + expect(callback.status).toBe(302); + expect(callback.headers.get('location') ?? '').toContain('error=invalid_provider'); + expect(refusals).toEqual([expect.objectContaining({ hostname: FLIP_HOST, denyClass: 'private' })]); + expect(transport.connected).toEqual([]); + expect(received).toEqual([]); + }); +}); + +describe('the SSO discovery scope judges only the reads it names', () => { + /** A guard that answers every read itself, recording it. */ + function recordingGuard(): { guard: EgressGuard; sent: string[] } { + const sent: string[] = []; + return { + sent, + guard: { + policy: { canConnect: () => ({ allow: true }) }, + ready: async () => undefined, + describe: () => 'recording guard (tests)', + judgeUrl: async () => ({ allow: true }), + fetch: async (url) => { + sent.push(url); + return new Response('through the guard') as unknown as Response; + }, + }, + }; + } + + function ordinaryFetch(): string[] { + const sent: string[] = []; + vi.stubGlobal('fetch', (async (input: unknown) => { + sent.push(typeof input === 'string' ? input : (input as URL).href); + return new Response('ordinary'); + }) as typeof globalThis.fetch); + return sent; + } + + it('CONTROL: a read at an origin no provider configuration names is sent as it was, before and after the origins are named; a named one is judged, unless the configured trust lists it', async () => { + const ordinary = ordinaryFetch(); + const { guard, sent } = recordingGuard(); + await runInSsoDiscoveryEgressScope(guard, async () => { + await fetch('https://db.internal.example/v2/pipeline'); + declareSsoDiscoveryReads(['https://idp.acme.example/.well-known/openid-configuration', 'https://trusted.acme.example'], (url) => + url.startsWith('https://trusted.acme.example'), + ); + await fetch('https://idp.acme.example/token', { method: 'POST', body: 'grant_type=authorization_code' }); + await fetch('https://db.internal.example/v2/pipeline'); + await fetch('https://trusted.acme.example/.well-known/openid-configuration'); + return undefined; + }); + expect(sent).toEqual(['https://idp.acme.example/token']); + expect(ordinary).toEqual([ + 'https://db.internal.example/v2/pipeline', + 'https://db.internal.example/v2/pipeline', + 'https://trusted.acme.example/.well-known/openid-configuration', + ]); + }); + + it('a provider row the observed adapter answers inside the scope names its origins before the caller holds it; another model\'s row names none', async () => { + const ordinary = ordinaryFetch(); + const { guard, sent } = recordingGuard(); + const tables: Record>> = { + ssoProvider: [ + { + providerId: 'acme-oidc', + issuer: 'https://idp.acme.example', + oidcConfig: JSON.stringify({ tokenEndpoint: 'https://tokens.acme.example/token', jwksEndpoint: 'https://keys.acme.example/jwks' }), + }, + ], + account: [{ providerId: 'acme-oidc', issuer: 'https://elsewhere.example' }], + }; + const plain = { + findOne: async ({ model }: { model: string }) => tables[model]?.[0] ?? null, + findMany: async ({ model }: { model: string }) => tables[model] ?? [], + }; + const plainFindOne = plain.findOne; + const adapter = observingSsoProviderReads(plain); + expect(observesSsoProviderReads(adapter)).toBe(true); + expect(observingSsoProviderReads(adapter)).toBe(adapter); + expect(plain.findOne).toBe(plainFindOne); + expect(observesSsoProviderReads(plain)).toBe(false); + expect(observesSsoProviderReads({})).toBe(false); + await runInSsoDiscoveryEgressScope(guard, async () => { + expect(await adapter.findOne({ model: 'account' })).toEqual(tables.account![0]); + await fetch('https://elsewhere.example/'); + expect(await adapter.findMany({ model: 'ssoProvider' })).toEqual(tables.ssoProvider); + await fetch('https://tokens.acme.example/token', { method: 'POST', body: 'grant_type=authorization_code' }); + await fetch('https://keys.acme.example/jwks'); + await fetch('https://idp.acme.example/.well-known/openid-configuration'); + await fetch('https://db.internal.example/v2/pipeline'); + return undefined; + }); + expect(sent).toEqual([ + 'https://tokens.acme.example/token', + 'https://keys.acme.example/jwks', + 'https://idp.acme.example/.well-known/openid-configuration', + ]); + expect(ordinary).toEqual(['https://elsewhere.example/', 'https://db.internal.example/v2/pipeline']); + }); + + it('outside a scope, the global fetch is the fetch it was, keeping its own properties', async () => { + const ordinary = ordinaryFetch(); + (globalThis.fetch as unknown as Record).runtimeTag = 'kept'; + const { guard, sent } = recordingGuard(); + await runInSsoDiscoveryEgressScope(guard, async () => undefined, { + reads: ['https://idp.acme.example/.well-known/openid-configuration'], + }); + await fetch('https://idp.acme.example/.well-known/openid-configuration'); + expect(sent).toEqual([]); + expect(ordinary).toEqual(['https://idp.acme.example/.well-known/openid-configuration']); + expect((globalThis.fetch as unknown as Record).runtimeTag).toBe('kept'); + }); + + // Last in this file: it resets the module registry. + it('a second copy of the module finds the wrapper and the scope the first installed: the global fetch is wrapped once, and either copy\'s scope is judged', async () => { + const ordinary = ordinaryFetch(); + const { guard, sent } = recordingGuard(); + await runInSsoDiscoveryEgressScope(guard, async () => undefined); + const wrapped = globalThis.fetch; + vi.resetModules(); + const second = await import('./sso-discovery-egress'); + expect(second.runInSsoDiscoveryEgressScope).not.toBe(runInSsoDiscoveryEgressScope); + const token = 'https://idp.acme.example/token'; + const document = 'https://idp.acme.example/.well-known/openid-configuration'; + for (let round = 0; round < 3; round++) { + await second.runInSsoDiscoveryEgressScope(guard, async () => { + await fetch(token); + return undefined; + }, { reads: [token] }); + await runInSsoDiscoveryEgressScope(guard, async () => { + second.declareSsoDiscoveryReads([document]); + await fetch(document); + return undefined; + }); + } + expect(globalThis.fetch).toBe(wrapped); + expect(sent).toEqual([token, document, token, document, token, document]); + expect(ordinary).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-auth/src/sso-discovery-egress.testkit.ts b/packages/plugins/plugin-auth/src/sso-discovery-egress.testkit.ts new file mode 100644 index 00000000000..47d37d767bb --- /dev/null +++ b/packages/plugins/plugin-auth/src/sso-discovery-egress.testkit.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import dnsPromises from 'node:dns/promises'; +import { EgressRefusedError, type EgressGuard } from '@objectstack/core/egress'; +import { createSsoDiscoveryEgressGuard } from './sso-discovery-egress'; + +/** + * A stand-in for the SSO discovery guard, for a suite that fakes the identity + * provider by stubbing `globalThis.fetch`: the `AuthManager` is handed this + * (`ssoDiscoveryEgress`) instead of the real guard, so its reads reach the + * stub. + * + * The real guard never sends through the global fetch: its own transport + * resolves the host and connects to the address it judged, so a stubbed global + * fetch no longer stands in for the identity provider on its own. This one + * judges each read by the real rule (the SSO discovery policy) against the + * addresses `node:dns/promises` answers when it is asked (a suite's resolver + * double, read at each call), refuses as the real guard refuses, and hands an + * admitted read to the global fetch. A name the runner cannot resolve is handed + * on too: a stubbed identity provider has no real name. The connection-time + * rule itself is pinned with the real guard in + * `sso-discovery-connect-time.test.ts`. + */ +export async function stubbedSsoDiscoveryEgress(): Promise { + const real = await createSsoDiscoveryEgressGuard({ + resolve: (hostname) => dnsPromises.lookup(hostname, { all: true }), + }); + return { + policy: real.policy, + ready: async () => undefined, + describe: () => '[egress] an SSO discovery stand-in over a stubbed fetch (tests)', + judgeUrl: (url, ctx) => real.judgeUrl(url, ctx), + async fetch(url, init, ctx) { + const verdict = await real.judgeUrl(url, ctx); + if (!verdict.allow) { + const refusal = new EgressRefusedError(new URL(url).hostname, verdict.decision ?? { allow: false }); + throw Object.assign(new TypeError('fetch failed'), { cause: refusal }); + } + return globalThis.fetch(url, init as RequestInit); + }, + }; +} diff --git a/packages/plugins/plugin-auth/src/sso-discovery-egress.ts b/packages/plugins/plugin-auth/src/sso-discovery-egress.ts new file mode 100644 index 00000000000..aedf6a26184 --- /dev/null +++ b/packages/plugins/plugin-auth/src/sso-discovery-egress.ts @@ -0,0 +1,556 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * SSO discovery connects only to addresses that are public at connect time. + * + * ## The rule + * + * Every server-side read an SSO provider's OpenID Connect configuration has + * this server make (the discovery document a registration reads, the + * discovery a sign-in runs for a provider stored without its endpoints, the + * token, key-set and userinfo reads of a sign-in, and the discovery read of + * the "sign out of the company sign-in too" check) is sent through the + * platform's outbound-request guard (`@objectstack/core/egress`): the + * connection itself resolves the host, judges every address it resolves to, + * and connects to an address it judged, never resolving again. So the address + * judged is the address connected, whatever any earlier check of the same + * name answered. A host with an address that is not public + * (`classifyAddress`: loopback, private, link-local, cloud metadata and + * host-platform addresses, and every other non-public range) is refused and + * nothing is sent to it. + * + * The one way out is the deployment's configured trusted origins + * (`OS_TRUSTED_ORIGINS`), as it is for every other SSO discovery check: a read + * of an origin they list is sent as it always was. An origin a registration + * body names is trusted for that registration's origin verdicts only, and + * never stands in for this rule (`sso-discovery-companion-origins.ts`). + * `OS_EGRESS_ALLOWED_TARGETS`, the allow-list of webhook and flow `http` + * requests, does not open SSO discovery. + * + * ## How the reads reach the guard + * + * `@better-auth/sso` (1.7.12) takes no fetch and no dispatcher: its reads go + * through `betterFetch`, which reads `globalThis.fetch` when it is called, and + * through a bare `fetch` for the key set. So the reads are routed here by a + * wrapper over the global fetch that does nothing outside an SSO discovery + * scope. A scope is opened around the vendor endpoints that read + * ({@link SSO_DISCOVERY_EGRESS_ENDPOINTS}) and around this package's own + * sign-out read, and inside it only a read at an origin the request's + * provider configuration names is judged. A scope starts naming none, so + * every other request the scope sees (a datastore reached over HTTP, a host's + * own call), before or after the origins are named, passes through untouched. + * + * The origins are named where the configuration is read, before anything can + * read from them: + * + * - a registration's, from its body, by the global before-hook + * ({@link declareSsoDiscoveryReadsOf}): the issuer, every `oidcConfig` + * endpoint, the discovery document and the issuer's companion origins; + * - a stored provider's, as the vendor reads its row: the auth context's + * adapter is observed ({@link observingSsoProviderReads}), and every + * `ssoProvider` row it answers inside a scope names its issuer, discovery + * document and token, key-set, userinfo and authorization endpoints + * ({@link oidcConfigReadUrls}) before the vendor holds it. That is every + * provider the vendor's sign-in and callback can read from (plugin-auth + * configures no `defaultSSO`), and it costs no read of its own. An + * endpoint a sign-in's own discovery finds at another origin is read only + * when the configured trust lists that origin (the vendor's check), which + * is the one way out; + * - the sign-out read's, by the caller that opens its scope. + * + * The before-hook also hands the scope the deployment's configured + * trusted-origin predicate, read from the request's own context. + * + * Upgrade note for `@better-auth/sso`: the observer keys on the vendor's + * provider model and member names (`ssoProvider` / `sys_sso_provider`, + * `issuer`, `oidcConfig` and its endpoint members), so a bump re-checks + * every provider read site the vendor's sign-in and callback make. + * + * A refused read rejects with the vendor's own `DiscoveryError` + * (`discovery_private_host`, or `discovery_unexpected_error` for a name that + * did not resolve), so every vendor path answers it as its own refusal of a + * non-public host. The refusal names the host and the rule, never the + * resolved address; that goes to the server log through the guard's logger. + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { EgressGuard, EgressLogger, EgressPolicy, EgressResolver } from '@objectstack/core/egress'; +import { + SSO_REGISTER_PATH, + ssoDiscoveryCompanionOrigins, + ssoDiscoveryHostRefusal, + ssoRegisterDiscoveryRead, + type SsoDiscoveryJudge, +} from './sso-discovery-companion-origins.js'; + +/** The `source` every SSO discovery read is judged under. */ +export const SSO_DISCOVERY_EGRESS_SOURCE = 'sso-discovery'; + +/** + * The vendor endpoint paths whose handlers read an identity provider: the + * registration (`/sso/register`), and the OIDC sign-in and its callbacks + * (`/sign-in/sso`, `/sso/callback/:providerId`, `/sso/callback`). The vendor's + * `/sso/update-provider` reads nothing (`@better-auth/sso` 1.7.12). + */ +export const SSO_DISCOVERY_EGRESS_ENDPOINTS: readonly string[] = Object.freeze([ + '/sso/register', + '/sign-in/sso', + '/sso/callback', +]); + +/** Whether a vendor endpoint path (as the request names it) reads an identity provider. */ +export function isSsoDiscoveryEgressPath(endpointPath: string | undefined): boolean { + if (!endpointPath) return false; + if (endpointPath === '/sso/register' || endpointPath === '/sign-in/sso' || endpointPath === '/sso/callback') return true; + return endpointPath.startsWith('/sso/callback/'); +} + +/** + * The guard SSO discovery sends through: the platform's outbound-request + * guard with a policy that refuses every address that is not public and + * opens none. `resolve` replaces name resolution (tests); `logger` receives + * each refusal with its privileged reason (the resolved address and its class). + */ +export async function createSsoDiscoveryEgressGuard( + options: { resolve?: EgressResolver; logger?: EgressLogger } = {}, +): Promise { + const { createEgressGuard, parseAddress, classifyAddress } = await import('@objectstack/core/egress'); + const policy: EgressPolicy = { + describe: () => 'SSO discovery: public addresses only; OS_TRUSTED_ORIGINS is the one way to an internal identity provider', + canConnect(target) { + const parsed = parseAddress(target.address); + if (!parsed) return { allow: false, denyClass: 'reserved', reason: `'${target.address}' is not an IP address` }; + const denyClass = classifyAddress(parsed); + if (denyClass === null) return { allow: true }; + return { + allow: false, + denyClass, + reason: + `${target.hostname} resolves to ${target.address} (${denyClass}), which SSO discovery does not connect to; ` + + 'an identity provider on an internal network is reached once OS_TRUSTED_ORIGINS lists its origin', + }; + }, + }; + return createEgressGuard({ policy, ...(options.resolve ? { resolve: options.resolve } : {}), ...(options.logger ? { logger: options.logger } : {}) }); +} + +/** A read the guard refused, as the scope keeps it. */ +export interface SsoDiscoveryConnectRefusal { + /** The URL whose read was refused. */ + url: string; + /** Its host name, as the URL names it. */ + hostname: string; + /** Its origin. */ + origin: string; + /** The name did not resolve (nothing was judged); otherwise an address was refused. */ + unresolved: boolean; +} + +type DiscoveryErrorClass = new ( + code: string, + message: string, + details?: Record, + options?: { cause?: unknown }, +) => Error; + +interface SsoDiscoveryEgressScope { + readonly guard: EgressGuard; + readonly DiscoveryError: DiscoveryErrorClass; + /** The origins the request's provider configuration names: only a read at one of them is judged. */ + readonly targets: Set; + /** The deployment's configured trusted-origin predicate: a read of an origin it trusts is sent as before. */ + isConfiguredTrusted?: (url: string) => boolean; + /** The first read the guard refused. */ + refused?: SsoDiscoveryConnectRefusal; +} + +/** + * Process-wide keys, so that every copy of this module in a process (a dual + * build, a module registry that was reset) shares one scope store and one + * wrapper over the global fetch: a copy finds the wrapper another installed + * and the scope another opened, and never wraps the global fetch again. + */ +const SCOPE_STORE_KEY = Symbol.for('objectstack.plugin-auth.sso-discovery-egress.scope-store'); +const FETCH_WRAPPER_MARK = Symbol.for('objectstack.plugin-auth.sso-discovery-egress.fetch-wrapper'); +const OBSERVED_ADAPTER_MARK = Symbol.for('objectstack.plugin-auth.sso-discovery-egress.observed-adapter'); + +const scopeStore: AsyncLocalStorage = (() => { + const shared = globalThis as unknown as Record | undefined>; + return (shared[SCOPE_STORE_KEY] ??= new AsyncLocalStorage()); +})(); + +/** Add each http(s) URL's origin to `targets`; anything else names nothing. */ +function nameOrigins(targets: Set, urls: Iterable): void { + for (const candidate of urls) { + if (typeof candidate !== 'string' || candidate.length === 0) continue; + try { + const url = new URL(candidate); + if (url.protocol === 'https:' || url.protocol === 'http:') targets.add(url.origin); + } catch { + /* not a URL: nothing reads it */ + } + } +} + +function readUrl(input: unknown): URL | undefined { + try { + if (typeof input === 'string') return new URL(input); + if (input instanceof URL) return input; + if (input && typeof (input as { url?: unknown }).url === 'string') return new URL((input as { url: string }).url); + } catch { + return undefined; + } + return undefined; +} + +function judges(scope: SsoDiscoveryEgressScope, url: URL): boolean { + if (url.protocol !== 'https:' && url.protocol !== 'http:') return false; + if (!scope.targets.has(url.origin)) return false; + return !(scope.isConfiguredTrusted?.(url.href) === true); +} + +/** The refusal text: the host and the rule, the same for every cause, never the resolved address. */ +export function ssoDiscoveryConnectRefusalText(url: { hostname: string; origin: string }): string { + return ( + `The request to "${url.hostname}" was not sent: SSO discovery connects only to a host whose every address is public ` + + 'when the connection is made. An identity provider on an internal network is reached once the deployment\'s ' + + `trusted origins (OS_TRUSTED_ORIGINS) list its origin, ${url.origin}.` + ); +} + +async function sendThroughGuard(scope: SsoDiscoveryEgressScope, url: URL, input: unknown, init: unknown): Promise { + const request = new Request(input as RequestInfo | URL, init as RequestInit | undefined); + const method = request.method; + const headers: Record = {}; + request.headers.forEach((value, name) => { + headers[name] = value; + }); + const body = method === 'GET' || method === 'HEAD' ? undefined : await request.text(); + const { findEgressRefusal } = await import('@objectstack/core/egress'); + try { + // Outside the scope: a guard that hands the request on (a test's stand-in) + // reaches the next fetch, not this wrapper again. + return await scopeStore.exit(() => + scope.guard.fetch( + request.url, + { method, headers, ...(body === undefined ? {} : { body }), signal: request.signal, redirect: request.redirect }, + { source: SSO_DISCOVERY_EGRESS_SOURCE }, + ), + ); + } catch (error) { + const refusal = findEgressRefusal(error); + if (!refusal) throw error; + const record: SsoDiscoveryConnectRefusal = { + url: request.url, + hostname: url.hostname, + origin: url.origin, + unresolved: refusal.unresolved, + }; + scope.refused ??= record; + throw new scope.DiscoveryError( + refusal.unresolved ? 'discovery_unexpected_error' : 'discovery_private_host', + ssoDiscoveryConnectRefusalText(url), + { url: request.url, hostname: url.hostname }, + { cause: error }, + ); + } +} + +/** + * Put the wrapper over the global fetch, unless the global fetch is a wrapper + * already (this copy's or another's: the mark is process-wide). A fetch + * someone set after the last install (a test's stub, another wrapper) is + * wrapped once, and becomes the one this wrapper hands every other request + * to. The wrapper carries the own properties of the fetch it wraps. Throws + * when the global fetch cannot be replaced: the reads could not be judged. + */ +function installFetchWrapper(): void { + const current = globalThis.fetch; + if (typeof current !== 'function') { + throw new Error('SSO discovery cannot be judged: this runtime has no global fetch to route its reads through.'); + } + if ((current as unknown as Record)[FETCH_WRAPPER_MARK] === true) return; + const underlying = current; + const wrapper = function ssoDiscoveryEgressFetch(...args: Parameters): Promise { + const scope = scopeStore.getStore(); + const url = scope ? readUrl(args[0]) : undefined; + if (!scope || !url || !judges(scope, url)) return Reflect.apply(underlying, globalThis, args) as Promise; + return sendThroughGuard(scope, url, args[0], args[1]); + } as typeof globalThis.fetch; + for (const key of Reflect.ownKeys(underlying)) { + if (key === 'length' || key === 'name' || key === 'prototype') continue; + const descriptor = Object.getOwnPropertyDescriptor(underlying, key); + try { + if (descriptor) Object.defineProperty(wrapper, key, descriptor); + } catch { + /* a property this function cannot take: the wrapper sends the same requests without it */ + } + } + Object.defineProperty(wrapper, FETCH_WRAPPER_MARK, { value: true }); + globalThis.fetch = wrapper; + if (globalThis.fetch !== wrapper) { + throw new Error('SSO discovery cannot be judged: the global fetch could not be replaced to route its reads through the outbound-request guard.'); + } +} + +/** + * Run `run` inside an SSO discovery scope sending through `guard`. Only a read + * at an origin the scope names is judged: `reads` names the URLs a caller + * knows it will read (this package's sign-out read); a vendor endpoint's scope + * starts naming none, and its origins are named as its provider configuration + * is read ({@link declareSsoDiscoveryReadsOf}, {@link observingSsoProviderReads}). + * Answers `run`'s value and the first refused read. + */ +export async function runInSsoDiscoveryEgressScope( + guard: EgressGuard, + run: () => Promise, + options: { reads?: Iterable; isConfiguredTrusted?: (url: string) => boolean } = {}, +): Promise<{ value: T; refused?: SsoDiscoveryConnectRefusal }> { + const { DiscoveryError } = (await import('@better-auth/sso')) as unknown as { DiscoveryError: DiscoveryErrorClass }; + installFetchWrapper(); + const scope: SsoDiscoveryEgressScope = { + guard, + DiscoveryError, + targets: new Set(), + ...(options.isConfiguredTrusted ? { isConfiguredTrusted: options.isConfiguredTrusted } : {}), + }; + nameOrigins(scope.targets, options.reads ?? []); + const value = await scopeStore.run(scope, run); + return { value, ...(scope.refused ? { refused: scope.refused } : {}) }; +} + +/** Whether this request runs inside an SSO discovery scope. */ +export function inSsoDiscoveryEgressScope(): boolean { + return scopeStore.getStore() !== undefined; +} + +/** + * Name, for the request's SSO discovery scope, URLs its provider configuration + * reads (their origins), and, when given, the deployment's configured + * trusted-origin predicate. No-op outside a scope. + */ +export function declareSsoDiscoveryReads( + urls: Iterable, + isConfiguredTrusted?: (url: string) => boolean, +): void { + const scope = scopeStore.getStore(); + if (!scope) return; + if (isConfiguredTrusted) scope.isConfiguredTrusted = isConfiguredTrusted; + nameOrigins(scope.targets, urls); +} + +/** The first read the request's SSO discovery scope refused, if any. */ +export function ssoDiscoveryConnectRefused(): SsoDiscoveryConnectRefusal | undefined { + return scopeStore.getStore()?.refused; +} + +/** + * The URLs an OIDC configuration has the server read, and the issuer's: the + * discovery document (explicit, else the issuer's well-known URL), the token, + * key-set and userinfo endpoints, and the authorization endpoint. `config` is + * a parsed `oidcConfig` (a stored one is JSON text). + */ +export function oidcConfigReadUrls( + issuer: unknown, + config: unknown, + computeDiscoveryUrl: (issuer: string) => string, +): string[] { + let parsed: Record | undefined; + if (typeof config === 'string') { + try { + const value: unknown = JSON.parse(config); + if (value && typeof value === 'object') parsed = value as Record; + } catch { + parsed = undefined; + } + } else if (config && typeof config === 'object') { + parsed = config as Record; + } + const urls: string[] = []; + const push = (value: unknown) => { + if (typeof value === 'string' && value.length > 0) urls.push(value); + }; + push(issuer); + push(parsed?.issuer); + for (const member of ['discoveryEndpoint', 'authorizationEndpoint', 'tokenEndpoint', 'jwksEndpoint', 'userInfoEndpoint']) { + push(parsed?.[member]); + } + for (const value of [issuer, parsed?.issuer]) { + if (typeof value === 'string' && value.length > 0) { + try { + urls.push(computeDiscoveryUrl(value)); + } catch { + /* not an issuer the vendor reads */ + } + } + } + return urls; +} + +/** The guard a judgement outside any scope uses: the default one, built once (again only after a build failed). */ +let defaultGuard: Promise | undefined; + +/** + * Judge, without sending anything, whether SSO discovery may read `url`: the + * guard of the request's scope, else the default guard, resolving its host + * and judging every address as a connection would. A name that does not + * resolve is answered `unresolved` and allowed here: the connection itself + * refuses it, and nothing is sent. + */ +export const judgeSsoDiscoveryUrl: SsoDiscoveryJudge = async (url) => { + let guard = scopeStore.getStore()?.guard; + if (!guard) { + if (!defaultGuard) { + const building = createSsoDiscoveryEgressGuard(); + defaultGuard = building; + building.catch(() => { + if (defaultGuard === building) defaultGuard = undefined; + }); + } + guard = await defaultGuard; + } + return guard.judgeUrl(url, { source: SSO_DISCOVERY_EGRESS_SOURCE }); +}; + +/** The configured trusted-origin predicate of a hook's or endpoint's context (before any body-named origin joins it). */ +function configuredTrustOf(ctx: any): (url: string) => boolean { + const isTrustedOrigin = ctx?.context?.isTrustedOrigin; + return (url) => typeof isTrustedOrigin === 'function' && isTrustedOrigin.call(ctx.context, url) === true; +} + +/** + * Global before-hook half: hand the request's SSO discovery scope the + * deployment's configured trusted-origin predicate (the request's own + * context, before any body-named origin joins it), and, for a registration, + * name the origins its body has the server read: the issuer, every + * `oidcConfig` endpoint, the discovery document, and the issuer's companion + * origins. It reads nothing: a stored provider's origins are named as the + * vendor reads its row ({@link observingSsoProviderReads}). No-op outside a + * scope. + */ +export async function declareSsoDiscoveryReadsOf(ctx: any): Promise { + if (!inSsoDiscoveryEgressScope()) return; + const isConfiguredTrusted = configuredTrustOf(ctx); + if (ctx?.path !== SSO_REGISTER_PATH) { + declareSsoDiscoveryReads([], isConfiguredTrusted); + return; + } + const { computeDiscoveryUrl } = await import('@better-auth/sso'); + const body = ctx?.body as { issuer?: unknown; oidcConfig?: unknown } | undefined; + declareSsoDiscoveryReads( + [...oidcConfigReadUrls(body?.issuer, body?.oidcConfig, computeDiscoveryUrl), ...ssoDiscoveryCompanionOrigins(body?.issuer)], + isConfiguredTrusted, + ); +} + +/** The vendor's provider model (`@better-auth/sso` 1.7.12 reads it as `ssoProvider`), and the object it is stored in. */ +function isSsoProviderModel(model: unknown): boolean { + return model === 'ssoProvider' || model === 'sys_sso_provider'; +} + +/** Name the origins every provider row in `answer` (one row, a list, or none) has the server read. */ +async function nameProviderRowOrigins(answer: unknown): Promise { + const scope = scopeStore.getStore(); + if (!scope) return; + const rows = Array.isArray(answer) ? answer : answer ? [answer] : []; + if (rows.length === 0) return; + const { computeDiscoveryUrl } = await import('@better-auth/sso'); + for (const row of rows as Array | null | undefined>) { + if (!row || typeof row !== 'object') continue; + nameOrigins(scope.targets, oidcConfigReadUrls(row.issuer, row.oidcConfig ?? row.oidc_config, computeDiscoveryUrl)); + } +} + +/** + * The auth context's adapter, observed: every `ssoProvider` row its `findOne` + * or `findMany` answers inside an SSO discovery scope names, before the caller + * holds it, the origins that provider's configuration has the server read. + * The vendor's sign-in and callback read their provider through this adapter, + * so its reads are judged from the row they came from, and no read of its own + * is added. Outside a scope, and for every other model and method, the adapter + * answers as it did. A view over `adapter` (nothing is written onto it, which + * may itself be a view); an adapter observed already is answered as it is. + */ +export function observingSsoProviderReads(adapter: A): A { + if (observesSsoProviderReads(adapter)) return adapter; + const observe = (method: 'findOne' | 'findMany') => async (...args: unknown[]): Promise => { + const answer: unknown = await Reflect.apply((adapter as Record unknown>)[method]!, adapter, args); + if (scopeStore.getStore() && isSsoProviderModel((args[0] as { model?: unknown } | undefined)?.model)) { + await nameProviderRowOrigins(answer); + } + return answer; + }; + const findOne = observe('findOne'); + const findMany = observe('findMany'); + return new Proxy(adapter, { + get(target, prop, receiver) { + if (prop === OBSERVED_ADAPTER_MARK) return true; + if (prop === 'findOne' && typeof (target as Record).findOne === 'function') return findOne; + if (prop === 'findMany' && typeof (target as Record).findMany === 'function') return findMany; + return Reflect.get(target, prop, receiver); + }, + }); +} + +/** Whether `adapter` answers its provider reads through {@link observingSsoProviderReads} (any copy of this module's). */ +export function observesSsoProviderReads(adapter: unknown): boolean { + if (!adapter || typeof adapter !== 'object') return false; + const target = adapter as Record; + return target[OBSERVED_ADAPTER_MARK] === true && typeof target.findOne === 'function' && typeof target.findMany === 'function'; +} + +/** + * The better-auth plugin that hands the auth context the observed adapter + * ({@link observingSsoProviderReads}): mounted with the `sso` plugin. Its + * `init` runs before the session store and the endpoints read the adapter. + */ +export function ssoProviderReadsObserverPlugin() { + return { + id: 'objectstack-sso-provider-reads-observer', + init(ctx: { adapter?: unknown }) { + const adapter = ctx?.adapter; + if (!adapter || typeof adapter !== 'object') return undefined; + return { context: { adapter: observingSsoProviderReads(adapter) } }; + }, + }; +} + +/** + * After-hook half: a `/sso/register` whose discovery read the connection + * refused is answered as the before-hook answers a discovery host that is not + * public: `400 VALIDATION_FAILED` on the member that names the host + * ({@link ssoDiscoveryHostRefusal}). A host whose name did not resolve keeps + * the vendor's answer (`discovery_unexpected_error`), as does a refusal of + * any other read. + */ +export async function explainSsoDiscoveryConnectRefusal(ctx: any): Promise { + if (ctx?.path !== SSO_REGISTER_PATH) return; + const refused = ssoDiscoveryConnectRefused(); + if (!refused || refused.unresolved) return; + const { APIError, isAPIError } = await import('better-auth/api'); + if (!isAPIError(ctx?.context?.returned)) return; + const refusal = await registerDiscoveryRefusalFor(ctx?.body, refused); + if (!refusal) return; + throw new APIError(refusal.status, { code: refusal.code, message: refusal.message, field: refusal.field }); +} + +/** + * The register refusal for a refused read, when that read is the one the + * registration's discovery makes (its host is the one the body names for it). + */ +export async function registerDiscoveryRefusalFor( + body: unknown, + refused: SsoDiscoveryConnectRefusal, +): Promise | undefined> { + const { computeDiscoveryUrl } = await import('@better-auth/sso'); + const read = ssoRegisterDiscoveryRead(body, computeDiscoveryUrl); + if (!read) return undefined; + let url: URL; + try { + url = new URL(read.url); + } catch { + return undefined; + } + if (url.origin !== refused.origin) return undefined; + return ssoDiscoveryHostRefusal(read.member, url); +}