Skip to content

Commit ecd4b2b

Browse files
fix(plugin-auth)!: SSO discovery connects only to addresses that are public at connect time (#35781)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D1WDVL9JpCQhTUF97fpymtZ)_ Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no published skill teaches SSO provider registration or sign-in; the rule is written into the hand-written SSO guide in this diff ## 维护者速读 - 平台管理员登记或更新企业单点登录身份提供方、员工经单点登录登录时,服务器每次读取身份提供方配置,都只连接到连接那一刻判定为公网的地址;部署受信来源未列出的内网地址一律不连、什么都不发送,其余照旧。 - 延续上一轮“登记前先检查发现文档主机”的同一条规则:把判定放到连接发生的那一刻,并补上登出开关与登录回调的读取,替部署运维把这条规则收成一处实现。 - 碰到的是身份提供方放在内网、又没列入受信来源的部署:登记、打开“同时登出公司登录”或单点登录会被拒并说明怎么办;运维把它的来源加入受信来源即可恢复;不改任何已存数据,可直接回滚。 - 无。 ## What changes **The rule: SSO discovery connects only to addresses that are public at connect time.** Every read plugin-auth has the server make of an identity provider's OpenID Connect configuration is sent through the core outbound-request guard (`@objectstack/core/egress`, the same guard webhook and flow `http` requests use): the connection resolves the host, judges every address with the platform's address classes (`classifyAddress`), and connects to an address it judged, never resolving again. So the address judged is the address connected. A host that is not public is refused and nothing is sent to it; so is a name that does not resolve when the read connects. `OS_TRUSTED_ORIGINS` (the deployment's configured trusted origins) stays the one way to an identity provider on an internal network; `OS_EGRESS_ALLOWED_TARGETS` does not open SSO discovery. The reads it covers: the registration's discovery document (`/sso/register`, and the Register SSO Provider bridge that re-dispatches there), the sign-out switch's read of that document on register and on update-provider, a sign-in's discovery (`/sign-in/sso`), and the callback's token, key-set and userinfo reads (`/sso/callback/*`). The vendor's own update-provider endpoint reads nothing. - **How the reads reach the guard** (`sso-discovery-egress.ts`, new). `@better-auth/sso` 1.7.12 takes no fetch and no dispatcher: its reads go through `betterFetch`, which reads `globalThis.fetch` when called, and a bare `fetch` for the key set. So the request routing opens an SSO discovery scope (AsyncLocalStorage, opened with `run` around the whole vendor request, as the SCIM scope is) for the three endpoint paths that read, and a wrapper over the global fetch sends a read inside that scope through the guard. The wrapper is inert outside a scope, and inside one it judges only a read at an origin the request's provider configuration names; a scope starts naming none. The origins are named where the configuration is read, before anything reads from them: a registration's from its body (issuer, every `oidcConfig` endpoint, the discovery document, companion origins) by the global before-hook, which reads nothing; a stored provider's as the vendor reads its row, through the auth context's adapter, which a plugin mounted with `sso` (`ssoProviderReadsObserverPlugin`) hands the context as an observed view; the sign-out read's by its caller. Every other request in the same request (a datastore or a rate-limit store reached over HTTP, a host's own call), before or after the origins are named, is sent as it was. A context whose adapter is not observed (a later 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. The scope store and the wrapper are keyed process-wide (`Symbol.for`), so a second copy of the module finds both and never wraps the global fetch again; the wrapper keeps the wrapped fetch's own properties. A refused read rejects with the vendor's own `DiscoveryError`, 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). - **The sign-out read** (`AuthManager.assertSsoSignOutOfIdpSupported`) runs in its own scope, which names the origins of the body's and the stored provider configuration (the one document it reads) and judges a read at them unless the configured trust lists it. - **The registration's early check** (`refuseSsoDiscoveryHostNotPublic`) now asks the guard's own judgement (`judgeUrl`, same resolver, same policy) instead of resolving and classifying on its own, so the early check and the connection apply one rule with one implementation. That brings the platform's address classes to it, an address literal included: `168.63.129.16` (the Azure host-platform endpoint, in `METADATA_ADDRESSES`) is refused there, where the vendor's own predicate admits it. A name that does not resolve at that check is left to the read, as before; the connection then refuses it and sends nothing. - **One answer for a registration.** A registration whose discovery read is refused when it connects is answered `400 VALIDATION_FAILED` on `issuer` / `oidcConfig.discoveryEndpoint`, the same answer the early check gives (after-hook `explainSsoDiscoveryConnectRefusal`, and the sign-out path on register). An update with the switch on is refused on `signOutOfIdp`; a callback ends on the error page with `invalid_provider`. - **`@objectstack/core`**: the guarded fetch's init takes fetch's `redirect` mode (it already reached undici; the type now says so). The vendor reads with `redirect: 'manual'` and refuses redirects itself. - **`AuthManagerOptions.ssoDiscoveryEgress`** (optional): the guard to send through; absent, the real one is built once per manager with the manager's logger. A suite that fakes the identity provider over a stubbed global fetch hands the stand-in in `sso-discovery-egress.testkit.ts` (it judges with the real policy over `node:dns/promises`, then hands an admitted read to the stub). - Docs: the SSO guide's paragraph on discovery hosts now states the connect-time rule. **Read first (by risk):** 1. `packages/plugins/plugin-auth/src/sso-discovery-egress.ts`: `installFetchWrapper` / `sendThroughGuard` / `judges` (only named origins are judged), `observingSsoProviderReads` + `ssoProviderReadsObserverPlugin` (a stored provider's origins, named from the row the vendor reads), and `declareSsoDiscoveryReadsOf` (a registration's origins; no read). 2. `packages/plugins/plugin-auth/src/auth-manager-request-routing.ts` (the `runHandler` choice: which endpoint paths open the scope) and `auth-manager.ts` `runSsoDiscoveryEgress` (answers a context whose adapter is not observed `503 SERVICE_UNAVAILABLE` before the endpoint runs); the observer is mounted in `auth-manager-plugin-list.ts`. 3. `packages/plugins/plugin-auth/src/auth-manager.ts`: `assertSsoSignOutOfIdpSupported` (the sign-out read's own scope and its register answer). ## Tests - `sso-discovery-connect-time.test.ts` (new, 25 cases): a real `AuthManager` with the real `sso()` plugin and the real guard (its policy and transport), name resolution as a double, and the ordinary transport (the global fetch) as a double that resolves again at connect and records the address it connects to. The host answers a public address to every check before a read and `127.0.0.1` / `169.254.169.254` / `10.0.0.5` / `168.63.129.16` when the read connects: - register: refused `400 VALIDATION_FAILED` on `issuer`, the answer never names the address, nothing connects (the ordinary transport records nothing, the loopback receiver gets nothing), the guard logs one refusal with its class (4 cases); - register with the sign-out switch on: the same, on its first read (4 cases); - update-provider turning the switch on: refused on `signOutOfIdp`, row unchanged (1 case); - sign-in callback: the token read is refused, the callback redirects with `invalid_provider`, nothing connects (4 cases); - CONTROL: a host whose address is public at connect registers, its document read over the guard's own connection (127.0.0.1 standing in for the public host, as `guarded-fetch.test.ts` does); - CONTROL: an origin `OS_TRUSTED_ORIGINS` lists is read as before (both reads, nothing judged); - CONTROL: a registration whose datastore and rate-limit counter store are reached over the global fetch, both on internal addresses the guard would refuse: their requests are sent through the ordinary transport before the guard's first judgement (the counter store, ahead of the global before-hook), between, and after its discovery read (the provider row's insert); the guard is never asked for either host; - CONTROL: the same for a sign-in by email and its callback: the provider lookup's datastore read and the counter store are sent as they were, while the callback's token read is the one read judged, and it is refused; - the scope: CONTROL: a read at an origin no provider configuration names is sent as it was, before and after naming, while a named one is judged unless configured-trusted; a provider row the observed adapter answers names its origins (another model's row names none; the view is idempotent and writes nothing onto the adapter); outside a scope the global fetch is the fetch it was, keeping its own properties; a second copy of the module (registry reset) shares the wrapper and the scope: the global fetch is wrapped once across 3 alternating rounds. - a context whose adapter is not the observed view (a later plugin rebuilt it as a plain object): `/sso/register`, `/sign-in/sso` and `/sso/callback/:providerId` are each answered `503 SERVICE_UNAVAILABLE` before the endpoint runs: no rate-limit consume, no datastore read, no judgement, no connection, the stored row unchanged (3 cases); 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 (1 case); - `sso-discovery-companion-origins.test.ts`: the early-check unit cases take the shared judgement; new case: an address literal the vendor admits (`168.63.129.16`) is refused by the platform's classes. Its relying party hands the stubbed-fetch stand-in. - `guarded-fetch.test.ts` (core): a manual redirect mode answers the redirect and follows nothing. <details><summary>Before (base wiring) / after / ablation</summary> ```text BEFORE plugin-auth wiring at merge base 92ab056 (after-hook, before-hook, routing, AuthManager, plugin list, early check), new module + test in place sso-discovery-connect-time.test.ts: Tests 16 failed | 5 passed (21) failures: registrations answered 200 and stored the provider; the ordinary transport recorded the internal address (register, register + switch, update, callback); the public CONTROL and the registration datastore CONTROL answered 502 (no guarded transport); the sign-in datastore CONTROL saw no judgement of the token read passing: the configured-trust CONTROL and the four scope cases; restored: 6 blobs == HEAD, git diff HEAD empty AFTER HEAD 608a01f: Tests 25 passed (25) ABLATION 1 (HEAD 8b4ca8c, 21 cases) wrapper hands every read on (installFetchWrapper; anchor 1 -> 0, blob 0e5c2dd -> cc78b532de98) Tests 19 failed | 2 passed (21); restored: blob == HEAD (0e5c2dd), git diff HEAD empty ABLATION 2 (HEAD 8b4ca8c, 21 cases) the scope judges every read, no origin filter (judges(); anchor 1 -> 0, blob 0e5c2dd -> 48bdf224a512) Tests 4 failed | 17 passed (21): both datastore CONTROLs, the scope CONTROL, the adapter-observation case; restored: blob == HEAD, git diff HEAD empty ABLATION 3 HEAD 608a01f: runSsoDiscoveryEgress hands an unobserved context on (auth-manager.ts; anchor 1 -> 0; blob 5d28c23 -> 4796447f4aab) Tests 3 failed | 1 passed | 21 skipped (25): the three doors answered 409 / 200 / 302 where 503 is pinned; the CONTROL held; restored: blob == HEAD (5d28c23), git diff HEAD empty ``` </details> <details><summary>Package suites and typecheck</summary> ```text pnpm --filter @objectstack/plugin-auth exec vitest run VERDICT command-exit 0 Test Files 289 passed (289) · Tests 6110 passed | 10 skipped (6120) HEAD 608a01f pnpm --filter @objectstack/plugin-auth typecheck VERDICT command-exit 0 (tsc, examples, check:test-typecheck OK, debt held) pnpm --filter @objectstack/core test && typecheck VERDICT command-exit 0 Test Files 154 passed (154) · Tests 3671 passed (3671) HEAD 8b4ca8c; packages/core unchanged since ``` </details> <details><summary>Derived gate families (local, HEAD 608a01f)</summary> ```text node scripts/pm/dispatch-gates.mjs --commands 109 commands derived from the change set (14 paths vs merge base 92ab056) 109 exit 0 (3 of them re-run on the same head after a first-pass exit 3: check:type-check-debt under the verify lock, then spec check:skill-examples and check:dual-build-cjs-loads once the re-measure build produced the dists they read) dispatch-gates --ran (with exit codes): 109 derived, 109 run, 0 NOT-MEASURED, 0 UNRUN node scripts/check-platform-checklist.mjs --changed-from origin/main exit 0 (1 anchored file, 18 anchors judged, 0 lost) ``` </details> <details><summary>Full dogfood battery (HEAD 608a01f)</summary> ```text pnpm --filter '@objectstack/dogfood^...' build VERDICT command-exit 0 (7m26s) pnpm --filter @objectstack/dogfood test VERDICT command-exit 0 · held the lock 38m11s Test Files 482 passed | 3 skipped (485) · Tests 4094 passed | 68 skipped (4162) ``` </details> ## Acceptance notes - The sign-in's discovery (`/sign-in/sso` for a provider stored without endpoints) reads only origins the deployment trusts: the vendor validates that discovery URL and every endpoint it names against the configured trusted origins at sign-in. Those reads stay exempt, as the rule says; the scope still sits under them. - The registration's early check stays open on a lookup error (a name that does not resolve there is left to the read); the read's connection is where an unresolved name is refused, and nothing is sent. The register answer for that case is the vendor's `502 discovery_unexpected_error`. - The guard connects with its own transport, as it does for webhook deliveries and flow `http` requests: a deployment that sends outbound HTTP through a global dispatcher or an outbound proxy no longer has these reads go through it. An identity provider reachable only that way is listed in `OS_TRUSTED_ORIGINS`, whose reads are sent through the global fetch as before. - The wrapper over the global fetch is installed on the first SSO request, once per process (a process-wide mark every copy of the module reads), and again over a fetch someone set after it; a runtime whose global fetch cannot be replaced refuses the read rather than sending it unjudged. - Every adapter read of the auth context passes through the observed view (one extra await and a model check per findOne / findMany); it names origins only for `ssoProvider` rows inside an SSO scope. The before-hook no longer reads the provider table: the rows that matter are the ones the vendor reads anyway. ## Verification Two minutes: `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/sso-discovery-connect-time.test.ts` (after building `@objectstack/plugin-auth`'s dependencies) prints `Tests 25 passed (25)`. Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: security#2 · os-elon-musk · session_016WV4czt69hUUaG5XcgFNYL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent aaa11a2 commit ecd4b2b

14 files changed

Lines changed: 1735 additions & 102 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
'@objectstack/core': patch
4+
---
5+
6+
fix(plugin-auth)!: SSO discovery connects only to addresses that are public at connect time
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
11+
<!-- 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. -->
12+
13+
**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`.
14+
15+
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.
16+
17+
`@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.
18+
19+
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.

‎content/docs/permissions/sso.mdx‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -178,19 +178,36 @@ identity provider on an internal or private network is refused **400
178178
`VALIDATION_FAILED`** on `signOutOfIdp` until the provider's origin is listed in
179179
`OS_TRUSTED_ORIGINS`.
180180

181-
**A registration checks that its discovery host resolves to public addresses
182-
before reading it.** Before a registration reads its discovery document, the
183-
server resolves that document's host (the `discoveryEndpoint` the registration
184-
names, else the issuer's) and every address it resolves to must be public. A
185-
host that resolves to a private, loopback, link-local or otherwise non-public
186-
address is refused **400 `VALIDATION_FAILED`** on `issuer` or
187-
`oidcConfig.discoveryEndpoint`, and nothing is read from it; the Register SSO
188-
Provider bridge answers the same refusal as `SSO_REGISTER_FAILED`. The check
189-
comes before the **Sign Out of the Company Sign-In Too** check above, so a
190-
registration that also turns that switch on is refused on the same member.
191-
Trust an origin gains because a registration names it never stands in for this
192-
check. An identity provider on an internal network registers once its origin
193-
is listed in `OS_TRUSTED_ORIGINS`.
181+
**SSO discovery connects only to addresses that are public at connect time.**
182+
Every read the server makes of an identity provider's OpenID Connect
183+
configuration (a registration's discovery document, the **Sign Out of the
184+
Company Sign-In Too** check's read of the same document on a registration or
185+
an update, a sign-in's discovery, and the token, key-set and userinfo reads of
186+
a sign-in's callback) goes through the platform's outbound-request guard: the
187+
connection itself resolves the host, judges every address it resolves to, and
188+
connects only to an address it judged. An address that is private, loopback,
189+
link-local, a cloud metadata or host-platform address (`168.63.129.16`
190+
included) or in any other non-public range is refused and nothing is sent to
191+
it, whatever an earlier lookup of the same name answered; so is a host whose
192+
name does not resolve when the read connects. Only reads at the origins the
193+
provider's configuration names are judged: every other request the server
194+
makes while answering (a datastore or a rate-limit store reached over HTTP)
195+
is sent as before.
196+
197+
A registration also judges its discovery host before reading it, by the same
198+
rule: the host of the `discoveryEndpoint` the registration names, else the
199+
issuer's. A host that is not public is refused **400 `VALIDATION_FAILED`** on
200+
`issuer` or `oidcConfig.discoveryEndpoint`, and nothing is read from it; the
201+
same answer comes back when the host answers a non-public address only once
202+
its read connects. The Register SSO Provider bridge answers that refusal as
203+
`SSO_REGISTER_FAILED`. The check comes before the **Sign Out of the Company
204+
Sign-In Too** check above, so a registration that also turns that switch on is
205+
refused on the same member. A refused callback read ends the sign-in on the
206+
error page with `invalid_provider`. Trust an origin gains because a
207+
registration names it never stands in for this rule, and neither does
208+
`OS_EGRESS_ALLOWED_TARGETS`. An identity provider on an internal network is
209+
reached once its origin is listed in `OS_TRUSTED_ORIGINS`: a read of an origin
210+
the deployment trusts is sent as before.
194211

195212
Google is one such provider: its discovery document names the token endpoint,
196213
the key set and the userinfo endpoint each on a host of its own, so a Google

‎packages/core/src/egress/guarded-fetch.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,18 @@ describe('CONTROL: an allowed target delivers, and redirects between allowed tar
184184
expect(hits).toEqual([`hooks.example:${port} /redirect?to=${to}`, `second.example:${port} /landed`]);
185185
});
186186

187+
it('a manual redirect mode answers the redirect itself and follows nothing', async () => {
188+
const to = encodeURIComponent(`http://second.example:${port}/landed`);
189+
const res = await guard('hooks.example,second.example').fetch(
190+
`http://hooks.example:${port}/redirect?to=${to}`,
191+
{ redirect: 'manual' },
192+
ctx,
193+
);
194+
expect(res.status).toBe(302);
195+
expect(res.headers.get('location')).toBe(decodeURIComponent(to));
196+
expect(hits).toEqual([`hooks.example:${port} /redirect?to=${to}`]);
197+
});
198+
187199
it('a policy that allows public addresses lets them through (the stand-in public host)', async () => {
188200
const g = createEgressGuard({
189201
policy: { canConnect: () => ({ allow: true }) },

‎packages/core/src/egress/guarded-fetch.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,18 @@ export interface EgressGuardOptions {
108108
logger?: EgressLogger;
109109
}
110110

111-
/** The init the guarded fetch takes — what both callers send. */
111+
/** The init the guarded fetch takes — what its callers send. */
112112
export interface EgressFetchInit {
113113
method?: string;
114114
headers?: Record<string, string>;
115115
body?: string;
116116
signal?: AbortSignal;
117+
/**
118+
* Fetch's redirect mode. `follow` (the default) judges every hop it
119+
* follows; `manual` answers a redirect response as it is, following
120+
* nothing, for a caller that refuses redirects itself.
121+
*/
122+
redirect?: 'follow' | 'manual' | 'error';
117123
}
118124

119125
/** The installed guard: the policy and the one fetch every guarded caller uses. */

‎packages/plugins/plugin-auth/src/auth-manager-after-hook.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import { stampInvitationDeliveryOutcome } from './invitation-delivery-outcome.js
6060
import { retireExpiredInvitationsOnReissue } from './invitation-expired-supersede.js';
6161
import { codeInviteRoleNotFound } from './invite-role-not-found-code.js';
6262
import { explainUntrustedDiscoveryRefusal } from './sso-discovery-companion-origins.js';
63+
import { explainSsoDiscoveryConnectRefusal } from './sso-discovery-egress.js';
6364
import { readRequestClientAddress } from './request-client-address.js';
6465
import { stampRoleChangeGrantedSet } from './role-change-granted-set.js';
6566
import { attachSessionToCredentialResponse } from './session-envelope-completion.js';
@@ -534,6 +535,12 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
534535
// the vendor's message (`sso-discovery-companion-origins.ts`).
535536
await explainUntrustedDiscoveryRefusal(ctx);
536537

538+
// ── A registration's discovery read refused when it connected ──
539+
// `/sso/register` only: answered as the before-hook answers a discovery
540+
// host that is not public, on the member that names it
541+
// (`sso-discovery-egress.ts`). Throws on a match.
542+
await explainSsoDiscoveryConnectRefusal(ctx);
543+
537544
// ── #29163: update-user's uncoded refusal carries its code ──
538545
// Same seam as the change-email section above; throws on a match.
539546
await codeSelfServiceRefusal(ctx);

‎packages/plugins/plugin-auth/src/auth-manager-before-hook.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ import { ORGANIZATION_DELETE_PATH } from './organization-delete.js';
9494
import { carriesPrincipalSession } from './principal-session-mint.js';
9595
import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js';
9696
import { refuseSsoDiscoveryHostNotPublic, ssoDiscoveryCompanionContext } from './sso-discovery-companion-origins.js';
97+
import { declareSsoDiscoveryReadsOf, judgeSsoDiscoveryUrl } from './sso-discovery-egress.js';
9798
import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js';
9899
import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js';
99100

@@ -241,6 +242,20 @@ export async function globalBeforeHook(
241242
// `principal-session-mint.ts` (3b).
242243
if (carriesPrincipalSession(ctx)) await setShouldSkipSessionRefresh(true);
243244

245+
// ── SSO discovery connects only to addresses public at connect time ──
246+
// Ahead of every branch below that may answer early: a vendor endpoint
247+
// that reads an identity provider (`/sso/register`, `/sign-in/sso`,
248+
// `/sso/callback/*`) runs in the SSO discovery scope the request routing
249+
// opened, which judges only reads at origins the request's provider
250+
// configuration names (`sso-discovery-egress.ts`). Here the scope takes the
251+
// deployment's configured trust from this request's context and, on a
252+
// registration, the origins its body has the server read; a stored
253+
// provider's are named as the vendor reads its row. This reads nothing.
254+
// Naming an origin trusts nothing: a read of it is sent through the
255+
// outbound-request guard, unless the deployment's configured trusted
256+
// origins list it. Outside that scope this does nothing.
257+
await declareSsoDiscoveryReadsOf(ctx);
258+
244259
// ── An auth request is judged and executed as one account ────────
245260
// AHEAD OF EVERY GATE BELOW, and of the endpoint: a request whose
246261
// session cookie and bearer token name two different signed-in
@@ -633,19 +648,21 @@ export async function globalBeforeHook(
633648
// [#32085] One email domain, one provider: a domain another
634649
// provider already serves is refused 409, naming that provider.
635650
await this.assertSsoProviderDomainFree(ctx);
636-
// SSO discovery fetches only hosts that resolve to public addresses:
637-
// the host this registration's discovery reads is resolved before the
638-
// vendor's endpoint runs, and every address must be public, unless the
639-
// deployment's configured trusted origins (read here, before any
640-
// body-named origin joins them) list it
651+
// SSO discovery connects only to addresses that are public at connect
652+
// time: the host this registration's discovery reads is judged before
653+
// the vendor's endpoint runs, by the rule its read is judged by when it
654+
// connects, unless the deployment's configured trusted origins (read
655+
// here, before any body-named origin joins them) list it
641656
// (`refuseSsoDiscoveryHostNotPublic`). Asked before the sign-out
642657
// switch below, whose check reads the same discovery document: a host
643658
// that is not public is refused on the member that names it, whatever
644-
// the switch says, and nothing is read from it.
659+
// the switch says, and nothing is read from it. A host that answers
660+
// otherwise when its read connects is refused there, nothing sent.
645661
const notPublic = await refuseSsoDiscoveryHostNotPublic({
646662
body: ctx?.body,
647663
isConfiguredTrusted: (url) =>
648664
typeof ctx?.context?.isTrustedOrigin === 'function' && ctx.context.isTrustedOrigin(url) === true,
665+
judge: judgeSsoDiscoveryUrl,
649666
});
650667
if (notPublic) {
651668
const { APIError } = await import('better-auth/api');

‎packages/plugins/plugin-auth/src/auth-manager-plugin-list.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,11 @@ export async function buildPluginList(this: PluginListHost): Promise<any[]> {
786786
//
787787
// Toggle with `OS_SSO_ENABLED` (mirrors `OS_OIDC_PROVIDER_ENABLED`).
788788
if (enabled.sso) {
789+
// SSO discovery connects only to addresses that are public at connect
790+
// time: the adapter the vendor reads its providers through names their
791+
// origins for the request's scope (`sso-discovery-egress.ts`).
792+
const { ssoProviderReadsObserverPlugin } = await import('./sso-discovery-egress.js');
793+
plugins.push(ssoProviderReadsObserverPlugin() as any);
789794
await this.addOptionalPlugin(plugins, 'sso', async () => {
790795
const { sso } = await import('@better-auth/sso');
791796
// NOTE: the `ssoProvider` model is bridged to `sys_sso_provider` by the

‎packages/plugins/plugin-auth/src/auth-manager-request-routing.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import { SESSION_ERASURE_PATHS } from './session-tombstone.js';
6868
import { envelopeVendorAdminRefusal } from './vendor-admin-refusal-envelope.js';
6969
import { OAUTH_REVOKE_PATH } from './mcp-token-revocation.js';
7070
import { ssoCallbackOf } from './sso-oidc-refusal-cause.js';
71+
import { isSsoDiscoveryEgressPath } from './sso-discovery-egress.js';
7172
import { samlSingleLogoutProviderId, SIGN_OUT_ENDPOINT_PATH } from './sso-sign-out-of-idp.js';
7273
import type { ScimRequestScope } from './scim-connection-service.js';
7374

@@ -91,11 +92,12 @@ export interface RequestRoutingHost {
9192
answerOAuthTokenRevocation: AuthManager['answerOAuthTokenRevocation'];
9293
runSsoCallback: AuthManager['runSsoCallback'];
9394
runSsoLogout: AuthManager['runSsoLogout'];
95+
runSsoDiscoveryEgress: AuthManager['runSsoDiscoveryEgress'];
9496
resolveAuthSecret: AuthManager['resolveAuthSecret'];
9597
}
9698

9799
/** The body of `AuthManager#handleRequest`; the method's docblock there is its contract. */
98-
export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically' | 'answerOAuthTokenRevocation' | 'runSsoCallback' | 'runSsoLogout' | 'resolveAuthSecret'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
100+
export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically' | 'answerOAuthTokenRevocation' | 'runSsoCallback' | 'runSsoLogout' | 'runSsoDiscoveryEgress' | 'resolveAuthSecret'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
99101
// ADR-0069 D7 — the client address this request's sign-in audit stamps,
100102
// established ONCE, here, by the same trust rule the D5 allow-list judges
101103
// with (`resolveClientAddress`). Read before any rewrite below, and carried
@@ -214,14 +216,28 @@ export async function handleRequest(this: Pick<RequestRoutingHost, 'config' | 'b
214216
// `await`, not a bare return: both scope helpers are generic over their
215217
// callback, so the composed call is typed `Promise< Promise< Response > >`.
216218
// The previous single call site flattened it with the `await` below.
217-
const runHandler = async (): Promise<Response> =>
219+
const runVendorHandler = async (): Promise<Response> =>
218220
await runWithAuthActorScope(() =>
219221
runWithRequestState(
220222
new WeakMap<object, unknown>(clientAddressStateEntries(clientAddress)),
221223
() => auth.handler(request),
222224
),
223225
);
224226

227+
// SSO discovery connects only to addresses that are public at connect time
228+
// (`sso-discovery-egress.ts`): a vendor endpoint that reads an identity
229+
// provider (`/sso/register`, `/sign-in/sso`, `/sso/callback/*`) runs inside
230+
// the scope whose reads the outbound-request guard sends. Opened HERE, with
231+
// `run(...)` around the whole request, for the reason the SCIM scope below
232+
// is: the vendor's endpoint handler is resumed from a continuation that a
233+
// scope entered inside a hook never reaches. Only reads at origins the
234+
// request's provider configuration names are judged (the global before-hook
235+
// names a registration's, the observed adapter a stored provider's as the
236+
// vendor reads it); every other read is sent as it was.
237+
const runHandler = isSsoDiscoveryEgressPath(this.betterAuthEndpointPath(request))
238+
? (): Promise<Response> => this.runSsoDiscoveryEgress(runVendorHandler)
239+
: runVendorHandler;
240+
225241
// [#7724] A subject-erasure request is ONE unit of work, and better-auth
226242
// does not treat it as one: `internalAdapter.deleteUser` deletes the
227243
// sessions, then the accounts, then the user, in three unrelated adapter

0 commit comments

Comments
 (0)