Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/sso-discovery-connect-time.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped. What moves is runtime answers of the SSO doors: a read of an identity provider's OpenID Connect configuration is sent only to an address that is public when the connection is made, unless the deployment's trusted origins list its origin. `AuthManagerOptions` gains one optional member and the guarded fetch's init one optional member; nothing stored, no registry key and no authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->

**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.
43 changes: 30 additions & 13 deletions content/docs/permissions/sso.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/egress/guarded-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) },
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/egress/guarded-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
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. */
Expand Down
7 changes: 7 additions & 0 deletions packages/plugins/plugin-auth/src/auth-manager-after-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down
29 changes: 23 additions & 6 deletions packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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');
Expand Down
5 changes: 5 additions & 0 deletions packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,11 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
//
// 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
Expand Down
20 changes: 18 additions & 2 deletions packages/plugins/plugin-auth/src/auth-manager-request-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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<RequestRoutingHost, 'config' | 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically' | 'answerOAuthTokenRevocation' | 'runSsoCallback' | 'runSsoLogout' | 'resolveAuthSecret'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically' | 'answerOAuthTokenRevocation' | 'runSsoCallback' | 'runSsoLogout' | 'runSsoDiscoveryEgress' | 'resolveAuthSecret'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
// 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
Expand Down Expand Up @@ -214,14 +216,28 @@ export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'b
// `await`, not a bare return: both scope helpers are generic over their
// callback, so the composed call is typed `Promise< Promise< Response > >`.
// The previous single call site flattened it with the `await` below.
const runHandler = async (): Promise<Response> =>
const runVendorHandler = async (): Promise<Response> =>
await runWithAuthActorScope(() =>
runWithRequestState(
new WeakMap<object, unknown>(clientAddressStateEntries(clientAddress)),
() => auth.handler(request),
),
);

// SSO discovery connects only to addresses that are public at connect time
// (`sso-discovery-egress.ts`): a vendor endpoint that reads an identity
// provider (`/sso/register`, `/sign-in/sso`, `/sso/callback/*`) runs inside
// the scope whose reads the outbound-request guard sends. Opened HERE, with
// `run(...)` around the whole request, for the reason the SCIM scope below
// is: the vendor's endpoint handler is resumed from a continuation that a
// scope entered inside a hook never reaches. Only reads at origins the
// request's provider configuration names are judged (the global before-hook
// names a registration's, the observed adapter a stored provider's as the
// vendor reads it); every other read is sent as it was.
const runHandler = isSsoDiscoveryEgressPath(this.betterAuthEndpointPath(request))
? (): Promise<Response> => 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
Expand Down
Loading
Loading