Repository navigation
fix(platform): close SSO login gaps and remove dead SSO paths - #3224
Merged
Merged
Conversation
GET /api/sso/set-session signed whatever `?token=` it was handed into the Better Auth session cookie — no session lookup, no ownership check — and nothing in the repo ever sent a browser there, so it was pure login-CSRF surface behind the proxy's `/api/sso/*` lane (sso-1). POST /api/sso/discover and its chain (discover_handler, config.discoverByEmail, the shim and handler-name entries) had no client but the integration check, while letting anonymous callers learn which org owns an email domain; the login page uses the /api/app/sso/discovery pair instead (sso-11). Both doors are gone with everything that served only them; the integration check drops its discover probe, and a routes test pins the 404s.
…ports `core/enterprise_sso/find_or_create_sso_user.ts` was the 0.4 Convex find-or-create written against `components.betterAuth.adapter.*`, reachable from nothing (`domains/sso/service.ts` imported only `shouldSyncMemberRole` from it) and a divergent copy of the org-binding logic — it auto-joined an existing outside user, the cross-org path the PG service refuses. It goes, with `core/members/mirror_sync.ts` that only it imported; the one live helper moves next to its caller with its tests (sso-5). Also gone, each verified caller-less: `getSupportedProviders`, the JSON (de)serializers in file_utils, the adapters' never-invoked `mapToRole` and the interface member, the `resolveProvisioning` shim entry no handler name reaches, the four capability flags nothing reads (only `supportsPkce` is consulted), and the trusted-headers result fields only its tests read. The three hand-rolled session-cookie builders (routes.ts, trusted-headers, finish_login) collapse onto `buildSessionCookie` + `sessionCookieName` so the cookie shape cannot drift between doors (sso-12).
The Entra adapter's `validateConfig` carries a client-credentials probe that maps a wrong, missing or expired secret to a readable reason — but the `/config/test` schema stripped `clientSecret`, `testSsoConnection` had no field for it and the form never sent one, so the branch was unreachable: a bad secret passed "Test connection" and failed only at real sign-in (sso-12 g), although the docs promise the test confirms credentials. The route now accepts the secret, the service probes with the typed one or — reuse-on-omit, the save's own posture — the stored one, and the form sends what the admin typed. Unit tests cover all three paths.
The first-login attach query looked for an org with a member whose role is exactly `admin`. Better Auth seats an org's creator as `owner` (`creatorRole: 'owner'`), so every org created through sign-up never matched: the first proxy user founded a second org, and every later proxy user joined THAT one, splitting users and knowledge across two tenants with no merge tool (sso-4). The query now matches the repo's own admin predicate — `ADMIN_ROLES` (`owner` + `admin`), exported from auth/membership.ts so there is one definition — and the tests pin both the owner-only attach and the found-a-default-org fallback.
The trusted-headers door decoded the session cookie with `decodeURIComponent` outside its try/catch, so a cookie value with a stray `%E0` threw URIError into Hono's bare 500 instead of the readable error page every other failure on that route answers (sso-v2). Cookie reading moves to a shared `readCookie` that treats malformed percent-encoding as "no cookie" and logs it. The OIDC callback's IdP-error branch swallowed state-parse failures in a comment-only catch, leaving no operator trace for a signature-verified but malformed state (sso-v1); it now warns with the cause.
The generic OIDC and OAuth2 adapters fail fast on a stalled IdP socket (`AbortSignal.timeout(OIDC_FETCH_TIMEOUT_MS)`, the rationale documented in oidc_discovery.ts), but the Entra adapter passed no signal on any of its five fetches — token exchange, Graph `/me`, the memberOf/appRoleAssignments pages (up to 50 each) and both validateConfig probes. A hung Microsoft endpoint pinned the /callback request for undici's default per call, long enough for the state's 10-minute window to expire mid-hang (sso-8). Every call now carries the shared timeout; the adapter tests assert each fetch receives an AbortSignal.
Every adapter guarded `sub` but let `email` through as whatever the IdP sent — `undefined` when the scope set lacks `email`, the userinfo endpoint emits only `sub`, `claimMappings.email` names a path that does not exist, or Graph `/me` returns neither `mail` nor a UPN. The 0.5 shim then cast the `handleSsoLogin` args without the validation 0.4's Convex boundary had, so `args.email.toLowerCase()` threw and the raw "Cannot read properties of undefined" reached the login page and the audit row (sso-7). The three adapters now funnel their candidates through one `requireEmailClaim` (claims.ts) that names the missing claim and the response it was missing from, and the shim parses the provisioning payload with zod so no protocol handler can hand provisioning a malformed identity. Tests cover each adapter and the shim boundary.
The admin door requires `idpEntityId`, the metadata parser extracts it and the config resolver returns it — but the validator never received it, so an assertion signed with the connection's certificate was accepted under any Issuer. A required, stored value whose only purpose was never applied dropped the defence-in-depth check for shared or rotated signing certificates (sso-10). `validateSamlResponseImpl` now takes the entity ID, sets node-saml's `idpIssuer` (which 5.1 applies to logout messages only) and compares the validated profile's Issuer itself, refusing a mismatch or a missing Issuer readably. Both callers (ACS, SP-initiated login) pass it; the real-node-saml test pins a correctly signed assertion from another issuer as refused.
SP metadata emitted the SP certificate under `use="signing"` only, while the ACS uses the matching key to DECRYPT assertions. A metadata-driven IdP (Keycloak, ADFS, Shibboleth) finds no encryption KeyDescriptor and never encrypts, so an admin who then requires encrypted assertions refuses every login with sso.errors.assertionNotEncrypted (sso-9). The one certificate is now advertised under both uses — signing stays, since node-saml signs the AuthnRequest when the SP key is configured — and a metadata handler test pins the two descriptors sharing one certificate.
/authorize signed any caller-chosen `redirect_uri` into the state and /callback adopted that URI's origin for every redirect it answered with — the IdP `?error=` bounce (reachable with no code and no IdP) and the dashboard redirect alike. The signature proved we minted the state, not that it pointed at us: an unauthenticated open redirect off the trusted domain (sso-2). Both doors now accept only SITE_URL or the request's own origin (either loopback spelling); /authorize answers a foreign value with a plain 400 and /callback falls back to SITE_URL. A valid, unexpired state was also all /callback demanded, and the ACS accepted any SP-initiated response answering a request THIS DEPLOYMENT issued — nothing tied a completion to the browser that started it, the login-CSRF shape RFC 6749 §10.12 / RFC 9700 §4.7 require state to close (sso-3). The starting doors now set an HttpOnly `sso_flow` nonce cookie (`__Host-`, `SameSite=None; Secure` over HTTPS — the seamless flow runs the whole round inside an iframe and the SAML ACS is a cross-site POST; the binding is the secret nonce, not the attribute) and carry its sha256 in the signed state / a `<org>.<hash>` RelayState; the finishing doors refuse a mismatch readably (`sso.errors.flowMismatch`, audited) and spend the cookie. The validator reports InResponseTo — from the Response or the signed Subject — so the ACS demands the binding exactly for SP-initiated responses; IdP-initiated posts keep working and the docs say so. The integration check carries the cookie like a browser, follows the new RelayState, and probes the two no-cookie refusals.
The backend has long stored and enforced an SP keypair (metadata KeyDescriptor, assertion decryption), the two assertion requirements and the attribute-name overrides, and the docs promised encrypted assertions "when you supply an SP keypair" — but the Enterprise SSO form had no input for any of them and only echoed the stored values back on save, so no admin could reach the feature through the product. The admin door also accepted `wantAssertionsEncrypted: true` with no private key anywhere, a state that refuses every SAML login because node-saml cannot decrypt (sso-6). The SAML branch gains an Advanced disclosure (the PKCE precedent) with the SP certificate, the SP private key (a secret: blank keeps the stored one, like the client secret), the two switches and the three attribute names; `upsertSamlConnection` refuses the encryption switch without a key under `sso_sp_key_required`, which the form pins to the key field the way it already pins a missing client secret, and validates client-side first. Form and admin tests cover the round-trip, the typed keypair, both refusals and the stored-key reuse; the SAML docs describe the inputs in all three locales.
Formatter output (line wrapping, quote style, one import order) over the files the SSO fixes touched, and a plain placeholder instead of a PEM-shaped fake key in the admin test — the SAST gate rightly flags the shape, and the guard under test only checks the key's presence. No behaviour change.
…ably Two polish notes from the review of #3224 (sso-6, sso-12g): - `hasSpKeypair` in the admin view was derived from the public SP certificate in connection.yml, while the encryption guard and the form's "blank keeps the stored key" rule are about the private key in the secrets sidecar. Clearing the certificate with a key stored showed "no keypair" although the guard passed. The view now reads the sidecar and reports the stored key. - `readExisting` throws on a corrupt connection.yml so a save never clobbers it, but through the admin doors that was a bare 500 — and the Test-connection door (which now reads the stored secret) had inherited it. Every admin read goes through one wrapper that maps the throw to 409 `sso_config_unreadable`, with the cause in the server log only (a JSON.parse message quotes the source, which for the sidecar could echo a secret); the test door consults the files only when no secret was typed; GET /config gets the same error contract. Tests in admin.test.ts cover the typed-secret probe past a corrupt file, the 409 on the fallback and on a save, and hasSpKeypair with/without a stored key, certificate cleared, and a corrupt sidecar.
Review notes on #3224 (sso-3): over plain http:// (dev only) the cookie carries no SameSite attribute, so a browser that defaults to Lax withholds it on the cross-site SAML ACS POST and the login bounces with flowMismatch — say so where the attribute is chosen, so a dev SAML failure is recognised (HTTPS deployments are unaffected). And the single fixed cookie name means two flows started in one browser overwrite each other's nonce; keying the name by the hash is not a one-line change (the completing doors clear by name even when the state carries no hash), so the limit is documented instead.
This was referenced Sep 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes the Enterprise SSO login gaps from the backend deep review and removes the SSO paths nothing reaches. Every login door (
/authorize,/callback,/saml/login,/acs, trusted headers) is now bound to our own origins and to the browser that started the flow; the deadset-sessionanddiscoverdoors, the Convex-era find-or-create and a set of caller-less exports are gone; the SAML SP keypair / assertion options the backend already enforced are reachable from the product; and every Entra network call, every adapter's email claim and the SAML Issuer are now checked.Findings fixed
GET /api/sso/set-session(minted a session cookie from?token=, no consumer) deleted with itsescapeHtml; routes test pins the 404. (c2ff8a4)POST /api/sso/discoverchain (handler,discoverByEmail, shim + handler-name entries, itest block) deleted. (c2ff8a4)findOrCreateSsoUser+core/members/mirror_sync.tsdeleted;shouldSyncMemberRolemoved next to its only caller with its tests. (b472058)getSupportedProviders, JSON (de)serializers, adaptermapToRole+ interface member,resolveProvisioningshim entry, four unread capability flags, unread trusted-headers result fields removed; the three hand-rolled session-cookie builders collapse ontobuildSessionCookie. (b472058) — (g) the unreachable Entra client-secret probe is now wired:/config/testacceptsclientSecret,testSsoConnectionprobes the typed or stored one, the form sends it. (b0ea578)ADMIN_ROLES(owner+admin, one definition exported fromauth/membership.ts) instead ofrole = 'admin'only. (5117b69)readCookiethat treats malformed percent-encoding as "no cookie" (no more bare 500). (844914f)AbortSignal.timeout(OIDC_FETCH_TIMEOUT_MS). (a2a39e0)requireEmailClaimacross the three adapters; the shim parseshandleSsoLoginargs with zod. (d0bc5df)idpEntityIdreaches the validator (idpIssuer+ an explicit Issuer comparison, since node-saml 5.1 appliesidpIssuerto logout only). (2108947)signingandencryption. (d5425c2)redirect_urimust be SITE_URL or the request's own origin (both loopback spellings);/authorizeanswers a foreign value with 400,/callbackfalls back to SITE_URL. (8d35c27)sso_flownonce cookie (__Host-,SameSite=None; Secureover HTTPS) set by/authorizeand/saml/login; sha256 rides in the signed state /<org>.<hash>RelayState;/callbackand/acsrefuse a mismatch readably (sso.errors.flowMismatch, audited) and spend the cookie. SAML demands the binding exactly when the response answers an AuthnRequest (InResponseTo on the Response or in the signed Subject); IdP-initiated posts keep working and the docs say so (en/de/fr). (8d35c27)upsertSamlConnectionrefuseswantAssertionsEncryptedwithout a key (sso_sp_key_required), pinned to the field in the form; locales en/de/fr; docs en/de/fr. (fe53255)Polish pass (review notes on the approved PR)
sso_sp_key_requiredguard checks and the form's "blank keeps the stored key" rule relies on — instead of the public certificate; clearing the certificate with a key stored no longer shows "no keypair". (d492838)/config,/config/test, the PUTs, enabled, client-id) with 409sso_config_unreadableinstead of a bare 500; the cause stays in the server log (aJSON.parsemessage quotes the source text, which for the secrets sidecar could echo a secret)./config/testconsults the files only when no secret was typed, so a typed-secret probe is file-independent as before. (d492838)flow_cookie.ts): over plain http:// (dev) the cookie has no SameSite attribute, so a Lax-by-default browser withholds it on the cross-site SAML ACS POST → a dev SAML login bouncing withsso.errors.flowMismatchis that, not a broken IdP; and the single fixed cookie name means two flows started in one browser overwrite each other's nonce — keying the name by the hash is not a one-line change (the completing doors clear the cookie by name even when the state carries no hash), so the limit is documented, not changed. (62d61cf)Skipped
wantAuthnResponseSigned=false— an IdP that omitsSubjectConfirmationData/@InResponseToon an SP-initiated response is treated as IdP-initiated and skips the browser binding. Accepted by sso-3's scope (the binding is demanded exactly when the response answers an AuthnRequest); a separate "require SP-initiated only" switch is a follow-up, not added here.Tests & gates observed
Original pass, run in the worktree on 99a433e:
bunx tsc --noEmit— exit 0bunx oxlint --type-aware— exit 0bunx vitest --run --project server—Test Files 501 passed (501)/Tests 6033 passed (6033)bunx vitest --run --config vitest.ui.config.ts app/features/settings/enterprise-sso—Test Files 1 passed (1)/Tests 33 passed (33)services/docs:bun run test—Test Files 30 passed (30)/Tests 194 passed (194)bun run check(root) —Tasks: 8 successful, 8 total, exit 0bun run knip:check— exit 0 (one pre-existing configuration hint:cron-parser … Remove from ignoreDependencies)Ran 5 rules on 14 files: 0 findingsrun-itest.sh, with PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7 cherry-picked temporarily and reset afterwards): 119/133 lanes ran, PASS=406, FAIL=3. Every SSO lane passed, including the new probes:PASS enterprise SSO login (OIDC + PKCE + provisioning over PG)·PASS an SSO callback outside the browser that started the flow is refused — authorize=302 flowCookie=true, callback=302→log-in key=true session=none, audited=1·PASS SAML: SP metadata + AuthnRequest redirect·PASS SAML: a signed assertion signs the user in and provisions them·PASS SAML: InResponseTo one-time use (replay + forged request refused)·PASS SAML: an SP-initiated response outside the browser that started it is refused — issued=true, acs=302→log-in key=true noCookie=true, audited=1·PASS SAML: an existing user outside the org is refused·PASS SAML: a connection requiring encrypted assertions refuses a plaintext one·PASS Entra ID: Graph identity + groups + app roles drive provisioning·PASS sso admin config surface (view/upsert/history/secrets/metadata/remove)·PASS trusted-headers auth (proxy hand-off + session role override)·PASS trusted-headers sessions: cookie-bound reuse, no cross-device sharing, account switch·PASS a failed SSO callback leaves a durable audit row·PASS SSO team sync prunes only what it created·PASS oauth app reuses the Entra SSO registration.The three failures are outside this theme (see notes):
FAIL knowledge: corpus scope drift is corrected and reported — drifted=null …,FAIL webdav re-home (protocol + tree + locks + visibility on pg)(red on main before the campaign),FAIL harness: checkReviewArc runs to completion — RUN TRUNCATED at lane 119 of 133 (checkReviewArc) — 14 later lane(s) never ran; threw SyntaxError: Unexpected token 'I', "Internal S"... is not valid JSON.Polish pass, run on 62d61cf:
bunx tsc --noEmit— exit 0bunx oxlint --type-aware— exit 0bunx vitest --run --project server—Test Files 501 passed (501)/Tests 6038 passed (6038)bunx vitest --run --config vitest.ui.config.ts app/features/settings/enterprise-sso—Test Files 1 passed (1)/Tests 33 passed (33)bun run check(root) —Tasks: 40 successful, 40 total, exit 0bun run knip:check— exit 0 (same pre-existingcron-parserhint)Ran 5 rules on 5 files: 0 findings/Ran 5 rules on 1 file: 0 findingsrun-itest.sh, fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7 cherry-picked temporarily and reset):[itest] 466/468 checks passed across 133/133 lanes(no truncation this run — checkReviewArc and the 14 lanes after it completed). Every SSO lane passed, includingsso admin config surface (view/upsert/history/secrets/metadata/remove),an SSO callback outside the browser that started the flow is refused, andSAML: an SP-initiated response outside the browser that started it is refused. The two failures are the same out-of-theme ones as before:knowledge: corpus scope drift is corrected and reported — drifted=null …(only under the fix(platform): pass the corpus scope rows as one jsonb parameter #3222 cherry-pick) andwebdav re-home(red on main).Notes for the reviewer
SameSite=None(sso-3): chosen deliberately — the seamless flow runs authorize→callback inside an iframe (use-seamless-sso.ts/silent-sso-frame.tsx) whereLaxis withheld on a cross-site-initiated subframe navigation, and the SAML ACS is a cross-site POST. The binding strength is the secret nonce (HttpOnly,__Host-), not the attribute. Over plain HTTP (dev) no SameSite attribute is emitted.flowfield) is refused at/callback— a login in flight across the deploy has to be restarted. An IdP-initiated SAML assertion carries no binding by protocol shape; documented.Path=/;__Host-requires noDomainandPath=/, which is what both starting doors emit.idpIssueris only compared on logout messages in practice, so the validator compares the profile's Issuer itself; the test uses a real node-saml round-trip with a second issuer.chore(platform): format …commit is formatter output over the touched files plus a non-PEM placeholder for a fake key the SAST pre-commit flags; PRs squash-merge so it folds in.domains/knowledge,domains/documentsor WebDAV):knowledge: corpus scope drift— on plain main the lane truncates (jsonb_to_recordset, fixed by PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222); with that commit cherry-picked the lane now FAILS withdrifted=null: its seedingUPDATE … WHERE org_slug = $1 AND file_id = $2on the corpus matched no row for theLIMIT 1document it picked (a file-backed document with no corpus row — e.g. the 'unsupported' image upload from an earlier lane), so nothing drifted and nothing was corrected. A lane-selection defect for the knowledge fixer, not an SSO regression.webdav re-home— red on main before this campaign (known).checkReviewArc— threw parsing an "Internal Server Error" body at lane 119/133 and truncated the run; the 14 later lanes never ran (checkTasksCollabIntegrity, checkSandboxSessions, checkAutomationRunToolLane, checkSandboxSpawner, checkSandboxGatewayKeyReclaim, checkStuckSendRecovery, checkDeferredSendRecovery, checkBackfillRecovery, checkWatchdogs, checkDocumentWriteGuards, checkLoginThrottleAndAuditChain, checkDevSeed, checkWebTierOracles, checkOrganizationLifecycle). None exercises the SSO doors;checkLoginThrottleAndAuditChaincovers the password login throttle, which this branch does not touch. The document review arc is outside this theme; noted for whoever owns it.