Skip to content

Commit 3c44a97

Browse files
fix(auth)!: an unmapped SAML sign-in reads the standard email and name claims before the NameID; SSO creates accounts only for email addresses (#33418)
Fixes #32146 Clause-②: yes (narrowing) — narrowed: a new account a SAML or OIDC sign-in would create through an `@better-auth/sso` provider is refused `403 INVALID_EMAIL` (`error=INVALID_EMAIL` on the sign-in's error redirect) when the email the sign-in resolved to is not an email address, with SSO domain verification off as well as on. Widened: for each SAML attribute-mapping member a provider leaves unset, the sign-in first reads the standard claim the assertion carries (`.../identity/claims/emailaddress`, `givenname`, `surname`, `name`). No first-party composition in this repository registers a SAML or OIDC provider. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches the SAML attribute mapping or SSO account creation; `content/docs/permissions/sso.mdx` gains both rules in this change. ## 维护者速读 - **改了什么**:SAML 登录在管理员没配属性映射时,先读 Entra ID / AD FS 默认发送的标准声明(emailaddress、givenname、surname、name),再退回 `email` 属性与 NameID;另外,无论是否开启域名验证,SSO 只为真实邮箱地址建账号,否则以 `INVALID_EMAIL` 拒绝。 - **为什么改**:Entra 不发 `email` 属性,未配映射时账号邮箱取自 NameID:从登录页进入是 UPN,从 Entra「我的应用」进入是不透明的持久 ID,同一个人会多出第二个账号(而且带着映射的权限集)。 - **风险与回滚**:SAML 或 OIDC 提供方若把用户解析成非邮箱值(只发不透明 NameID、或映射到用户名声明),新用户将不再被创建(已有账号不受影响);回滚即 revert 本 PR。读取标准声明依赖供应商内部行为(见 Acceptance notes),供应商升级若改变它,端到端测试会变红。 - **先看**:`packages/plugins/plugin-auth/src/sso-saml-standard-claims.ts`(整个机制与其对供应商的依赖)· `packages/plugins/plugin-auth/src/sso-account-at-proven-domain.ts` 末尾的 `refuseSsoAccountWithoutAddress` · `packages/plugins/plugin-auth/src/auth-manager.ts` 中 `runSsoCallback` 的 SAML 分支。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/sso-saml-refusal-landing.test.ts -t "standard claims"`,预期 10 个用例全绿;其中「SP-initiated then IdP-initiated」与「portal-first」两例显示两次进入后只有一个账号,第二次进入被拒(account_not_linked)。 - **需要你做的**:决定同一人从 IdP 门户第二次进入时,是否应自动登录到同一账号(今天按平台关联规则以 `account_not_linked` 拒绝,不再建第二个账号)—— 选项见报告的 needs_user_decision。 ## What changes - **An unmapped SAML sign-in reads the standard claims before the NameID** (`sso-saml-standard-claims.ts`). For each of `email`, `firstName`, `lastName`, `name` the provider's mapping leaves unset, a sign-in whose assertion carries the standard claim (`http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`, `givenname`, `surname`, `name`) reads it before the vendor's own default and before the NameID. A mapped member is read as mapped; a provider that sends `email` and none of these claims signs in exactly as before; when the mapping is unset and the assertion carries both a plain `email` attribute and the `emailaddress` claim, the standard claim takes precedence (where the two differ, a new account is created at the claim address; an existing account still signs in by its account key). The stored mapping is never written. - Mechanism: `@better-auth/sso` 1.7.12 reads one attribute name per member off `samlConfig.mapping` and offers no seam between verifying the assertion and resolving the user. So the ACS request's posted response is read once, before the vendor runs, for the attribute NAMES of its one unencrypted assertion (values always come from the vendor's verified extract), and the adapter's read of that provider's row in that request hands the vendor a mapping that also names those claims, as non-enumerable members so the vendor's provider fingerprint (taken at the sign-in's start and again at the ACS) does not change. - **Verification on or off, an SSO provider creates an account only for an email address** (`refuseSsoAccountWithoutAddress`, wired into `validateUserInfo` after the proven-domain rule). A SAML or OIDC creation whose resolved email is not an address is refused `INVALID_EMAIL` (an existing ledger code for plugin-auth) with a description naming the remedy and not the value. With verification on, the proven-domain rule still answers first (`EMAIL_DOMAIN_NOT_ALLOWED`), unchanged. Existing accounts, linking and non-SSO creations are unchanged. - Docs: `content/docs/permissions/sso.mdx` (the register table, the mapping section, the verification section). Changeset: `patch`, declared BREAKING with its ADR-0087 disposition. ## Tests All end-to-end cases run the real `AuthManager` with the real `better-auth` + `@better-auth/sso` over the in-memory engine; the IdP is played with the vendor's own `samlify`, signing with a key generated in the test (`sso-saml-refusal-landing.test.ts`, two new top-level `describe` blocks in the existing harness): - SP-initiated (email-format NameID = UPN) then IdP-initiated (persistent opaque NameID), Entra default claims: one account `mia.chen@acme.com (Mia Chen)`; the second entry reaches it and is refused `account_not_linked` by the platform's linking rule, verification off and on. IdP-initiated first: the account is made for the address, never the opaque id. - Claim before an `email` attribute; the `name` claim when no given/surname; an admin-named member wins; a stored mapping naming only the groups attribute still completes an SP-initiated sign-in (fingerprint); CONTROL: an `email`-only IdP is unchanged; CONTROL: the stored mapping is unchanged. - No email attribute/claim and an opaque NameID: refused `INVALID_EMAIL`, nothing written (IdP- and SP-initiated); CONTROL: an address is admitted. - Pure halves: `sso-saml-standard-claims.test.ts` (name reading: encrypted, two or nested assertions, oversize, non-XML read nothing; member choice; the adapter read half incl. non-enumerability and no mutation of the engine object), and a new `describe` in `sso-account-at-proven-domain.test.ts` (SAML and OIDC, refusal names no value, only SSO creations judged). Ablations (each through `scripts/ablation-replace.mjs` on a committed head, restore verified as blob == HEAD and `git diff HEAD` empty): 1. Drop the adapter read half (`applyStandardSamlClaimsOnRead` in `findOne`): 8 of the 9 standard-claim cases red; the `email`-only CONTROL stays green. 2. Make the added mapping members enumerable: exactly the 3 SP-initiated cases red with `error=invalid_state&error_description=sso_provider_changed_during_authentication` (the fingerprint). 3. Unwire `refuseSsoAccountWithoutAddress`: both `INVALID_EMAIL` cases red; the CONTROL stays green. ## Acceptance notes - **Vendor reliance.** The standard-claim read depends on `@better-auth/sso` reading `parsedSamlConfig.mapping` off the object the adapter returns, and fingerprinting only enumerable members. A vendor upgrade that copies the config first returns the old defaults (ablation 1 shape: the end-to-end pins go red); one that fingerprints non-enumerable members refuses SP-initiated sign-ins at the ACS (ablation 2 shape). The durable fix is upstream: a default-candidates option for the SAML mapping. - **Encrypted assertions** carry no readable names before the vendor decrypts them, so such a provider reads only what it maps (documented). - **The second, IdP-initiated entry is refused `account_not_linked`, not signed in**: the account the first entry made is not email-verified, and an unverified provider is not trusted to link itself to an existing account. Whether that entry should sign in to the same account (key on a stable attribute, or a verified link) is a product choice, reported to the dispatching seat, not decided here. - **Form text, not changed here**: `packages/platform-objects/src/identity/sys-sso-provider.object.ts` (held by another card) still says the SAML email member "Defaults to "email", then the NameID", and the mapping summary says "Empty means the default: email from "email" (SAML: then the NameID)". Both now read the standard claim first; the help text wants that sentence. - **Console copy**: `ui/apps/console/src/pages/auth/ssoCallbackRefusal.ts` maps no sentence for `INVALID_EMAIL` (nor, already, for `EMAIL_DOMAIN_NOT_ALLOWED`) on an SSO callback, so the end user reads the generic "the sign-in link expired or was already used" with the code behind the details toggle. Read from the code, not measured in a browser. - An Entra user whose `mail` differs from the UPN and who already has an account keyed on the UPN (made before this change) still has that account found by its account key on SP-initiated sign-in; an IdP-initiated entry now resolves to `mail`, finds no user by that address, and creates one (as an opaque-id account was created before). ## Verification All readings below at head `e90385832` (the branch merged with `origin/main` `e0ce1b523`), on a shared container. <details><summary>plugin-auth: full suite, typecheck, lint</summary> - `pnpm --filter @objectstack/plugin-auth test` (after building `@objectstack/plugin-auth...`): `Test Files 273 passed (273)`, `Tests 5283 passed | 10 skipped (5293)`, lock `VERDICT command-exit 0`. - `pnpm --filter @objectstack/plugin-auth typecheck` (tsc, examples, `check:test-typecheck`): `VERDICT command-exit 0`; `check:test-typecheck: OK`. Taken before the merge with `origin/main` at `946912a7a`; the merge touched `auth-manager.ts` outside these hunks, and the post-merge suite above compiles every file. - `eslint --no-inline-config` over the changed `.ts` files: exit 0, no output. - Public surface: no export of the package entry changes (`src/index.ts` untouched by this diff), so no dependent owes a test; `packages/qa/dogfood` is the one dependent with an SSO test, and it ran in the battery below. </details> <details><summary>Dogfood battery (title carries a breaking marker)</summary> - `pnpm --filter '@objectstack/dogfood^...' build && pnpm --filter @objectstack/dogfood test` at `e90385832`: `Test Files 465 passed | 3 skipped (468)`, `Tests 3932 passed | 42 skipped (3974)`, lock `VERDICT command-exit 0`. </details> <details><summary>Derived gate families (dispatch-gates --commands, 106)</summary> - 103 exit 0. `check:type-check-debt` first answered PREREQUISITE NOT MET (its closure build queued behind the dogfood holder), re-run under the lock: `--re-measure: OK`, `VERDICT command-exit 0`. - NOT MEASURED locally, exit 3 PREREQUISITE NOT MET (built output of packages outside this diff absent in this container): `@objectstack/spec check:skill-examples` (client SDK dist), `check:dual-build-cjs-loads` (several plugin dists). Both are CI's. - `dispatch-gates --ran`: 106 derived, 106 run, 0 unrun. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1NJYFGVi2FRztyBNo)_ <!-- signed: domain:server#5 · os-elon-musk · session_016WV4d1NJYFGVi2FRztyBNo --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3c231cd commit 3c44a97

13 files changed

Lines changed: 821 additions & 48 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+
---
4+
5+
fix(auth)!: an unmapped SAML sign-in reads the standard email and name claims before the NameID, and an SSO provider creates an account only for an email address
6+
7+
Clause-②: yes (narrowing) — narrowed: a new account a SAML or OIDC sign-in would create through an `@better-auth/sso` provider is refused `403 INVALID_EMAIL` (`error=INVALID_EMAIL` on the sign-in's error redirect) when the email the sign-in resolved to is not an email address, with SSO domain verification off as well as on, where it was created with that value as its email. Widened: for each SAML attribute-mapping member a provider leaves unset, the sign-in first reads the standard claim the assertion carries (`http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`, `givenname`, `surname`, `name`), where it read only `email` / `givenName` / `surname` / `displayName` and the NameID. No first-party composition in this repository registers a SAML or OIDC provider.
8+
Metadata-protocol: none
9+
Skills-docs: none — no skill under `skills/**` teaches the SAML attribute mapping or SSO account creation; `content/docs/permissions/sso.mdx` gains both rules in this change.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped, and no stored row changes: the provider's stored mapping is read as before, the added claims are read at sign-in only, and the moved answer is a runtime refusal at account creation, so there is nothing for a migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** for a deployment whose SAML or OIDC provider resolves a person to a value that is not an email address: such a sign-in no longer creates an account. The common case is an identity provider that sends no email attribute, so the sign-in fell back to an opaque persistent or transient NameID (Microsoft Entra ID's IdP-initiated sign-in is one), or an OIDC mapping that names a claim holding a user name. With SSO domain verification on, such a value was already refused `EMAIL_DOMAIN_NOT_ALLOWED`, and still is. Also moved: for a SAML provider with no email mapping set whose assertion carries both a plain `email` attribute and the standard `emailaddress` claim, the standard claim now takes precedence, so where the two differ a new account is created at the claim's address rather than the `email` attribute's (an existing account still signs in by its account key).
14+
15+
Unchanged: an account that already exists signs in as before, whatever its email; linking; and every account creation that is not through an SSO provider.
16+
17+
What to do: nothing, unless a provider's users are created with a value that is not an address. For such a provider, map its email attribute (SAML) or claim (OIDC) to the one that carries the user's address.
18+
19+
The standard claims: Microsoft Entra ID and AD FS send them by default, and neither sends an `email` attribute, so an Entra ID provider with nothing mapped keyed its users on the NameID, an email-format user principal name when the sign-in started from the sign-in page and an opaque persistent id when it started from the identity provider's app portal. Both entries now resolve to the address in the `emailaddress` claim, so the second entry never creates another account: it finds the account the first one made and is refused `account_not_linked`, creating nothing, until that account is linked to it. A member an administrator mapped is always read as mapped, and a provider that sends `email` and none of these claims signs in exactly as before. A provider that encrypts its assertions reads only what it maps.

‎content/docs/permissions/sso.mdx‎

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,15 @@ What verification decides, with it on:
386386
So if your people first sign in with addresses at a subdomain or at another
387387
domain, list each such domain on the provider as a bare host name and verify it.
388388

389+
**With verification on or off, a provider creates an account only for an email
390+
address.** A SAML or OIDC sign-in that resolves to a value that is not an
391+
address (an IdP that sends no email attribute and an opaque persistent or
392+
transient NameID, or a mapping that names a claim holding a user name) is
393+
refused with `error=INVALID_EMAIL`, and nothing is created. Map the provider's
394+
email attribute or claim to the one that carries the address. With verification
395+
on, such a value is refused `error=EMAIL_DOMAIN_NOT_ALLOWED` by the rule above,
396+
as before. An account that already exists signs in as before.
397+
389398
**A provider's domain list takes bare host names only.** Registering a provider,
390399
or editing its domain, with an entry written any other way (a URL, a port, a
391400
path, a user part) is refused with **400 `VALIDATION_FAILED`** on `domain`,
@@ -442,10 +451,10 @@ Fill in the IdP details collected by the **Register SAML Provider** action:
442451
| `entryPoint` | ✅ | The IdP's SAML single sign-on (redirect) URL that receives the `SAMLRequest`. |
443452
| `cert` | ✅ | The IdP's X.509 signing certificate (PEM body) — used to verify assertion signatures. |
444453
| `identifierFormat` | — | Requested SAML NameID format (defaults to the IdP's configured format), e.g. `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`. |
445-
| `mapEmail` | — | Assertion attribute the user's email is read from. Defaults to `email`, then the NameID. |
446-
| `mapFirstName` | — | Assertion attribute the user's first name is read from. Defaults to `givenName`. |
447-
| `mapLastName` | — | Assertion attribute the user's last name is read from. Defaults to `surname`. |
448-
| `mapName` | — | Assertion attribute the user's full name is read from when the first and last name are absent. Defaults to `displayName`, then the NameID. |
454+
| `mapEmail` | — | Assertion attribute the user's email is read from. Left blank: the standard `…/claims/emailaddress` claim when the assertion carries it, else `email`, else the NameID. |
455+
| `mapFirstName` | — | Assertion attribute the user's first name is read from. Left blank: the standard `…/claims/givenname` claim when present, else `givenName`. |
456+
| `mapLastName` | — | Assertion attribute the user's last name is read from. Left blank: the standard `…/claims/surname` claim when present, else `surname`. |
457+
| `mapName` | — | Assertion attribute the user's full name is read from when the first and last name are absent. Left blank: the standard `…/claims/name` claim when present, else `displayName`, else the NameID. |
449458
| `mapGroups` | — | Assertion attribute that carries the user's groups (see [Grant permission sets from IdP groups](#grant-permission-sets-from-idp-groups)). |
450459

451460
On success the response returns the two **Service Provider (SP)** URLs you
@@ -485,11 +494,37 @@ configure on the IdP side:
485494
486495
### Map the user's email and name
487496

488-
A SAML sign-in reads the user's email and name from assertion attributes. With
489-
nothing mapped, the email is the `email` attribute (else the NameID) and the name
490-
is `givenName` + `surname`, else `displayName`, else the NameID. Okta and Entra ID
491-
use other attribute names, so their users are named after their NameID until the
492-
provider maps them:
497+
A SAML sign-in reads the user's email and name from assertion attributes. For
498+
each member left unmapped, the sign-in first reads the standard claim Microsoft
499+
Entra ID and AD FS send by default, when the assertion carries it:
500+
501+
| Member | Standard claim, read first when unmapped |
502+
| :--- | :--- |
503+
| Email | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress` |
504+
| First name | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname` |
505+
| Last name | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname` |
506+
| Full name | `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name` |
507+
508+
Without that claim, the email is the `email` attribute (else the NameID) and the
509+
name is `givenName` + `surname`, else `displayName`, else the NameID. So an Entra
510+
ID provider with nothing mapped keys its users on the address in the
511+
`emailaddress` claim, whether the person enters from your sign-in page (an
512+
email-format NameID) or from the IdP's app portal (Entra's default persistent
513+
NameID, an opaque id), so the two entries resolve to one address and never make a
514+
second account. Each entry is still its own sign-in identity: whichever entry
515+
comes second finds the account the first one made and is refused with
516+
`error=account_not_linked`, creating nothing, until that account is linked to it.
517+
When the assertion carries both an `email` attribute and the `emailaddress`
518+
claim, the claim is read. A member you map is always read as mapped. Two limits:
519+
520+
- The claims are recognised by the attribute names in the assertion as posted.
521+
An encrypted assertion's names cannot be read before it is decrypted, so a
522+
provider that encrypts assertions reads only what it maps: map its members.
523+
- The stored mapping does not change: **Show Attribute Mapping** still shows an
524+
unmapped member as empty.
525+
526+
Okta uses other attribute names, so its users are named after their NameID until
527+
the provider maps them:
493528

494529
| Member | Default | Okta (common) | Entra ID |
495530
| :--- | :--- | :--- | :--- |

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ import { logAfterResponseSendFailure, sendAfterResponseOnPublicDoor } from './ru
7474
import { isVisitorResendInEndpointContext } from './visitor-verification-resend.js';
7575
import { createBetterAuthLogSink } from './sso-oidc-refusal-cause.js';
7676
import { withSystemReadContext } from './objectql-adapter.js';
77-
import { refuseSsoAccountOutsideProvenDomain } from './sso-account-at-proven-domain.js';
77+
import { refuseSsoAccountOutsideProvenDomain, refuseSsoAccountWithoutAddress } from './sso-account-at-proven-domain.js';
7878

7979
/** The path better-auth declares for the email sign-up endpoint. */
8080
const SIGN_UP_EMAIL_PATH = '/sign-up/email';
@@ -352,7 +352,8 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
352352
// for an email address at a domain it has proven
353353
// (`sso-account-at-proven-domain.ts`). Judged first, on its own: no
354354
// posture, invitation or JIT toggle relaxes it, and the audience gate
355-
// must admit as well.
355+
// must admit as well. Then, verification on or off, an SSO provider
356+
// creates an account only for a value that is an email address.
356357
validateUserInfo: async (data: any, ctx: any) => {
357358
this.idpLocale.stage(data, ctx);
358359
const outsideProvenDomain = await refuseSsoAccountOutsideProvenDomain(data, {
@@ -361,6 +362,10 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
361362
logger: this.config.logger,
362363
});
363364
if (outsideProvenDomain) return outsideProvenDomain;
365+
// Verification on or off, an SSO provider creates an account only for
366+
// an email address (same module): an opaque NameID is no account key.
367+
const notAnAddress = refuseSsoAccountWithoutAddress(data, this.config.logger);
368+
if (notAnAddress) return notAnAddress;
364369
return (await refuseImplicitAccountLink(data, ctx, {
365370
requireLocalEmailVerified: this.implicitLinkRequiresLocalEmailVerified(),
366371
resolveContext: () => this.linkingContext(),

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,7 @@ import { createAuthInstance, type AuthInstanceHost } from './auth-manager-auth-i
287287
import { readSamlAcsLanding, runSsoCallbackScope, type SamlLandingContext, type SsoCallbackRequest } from './sso-oidc-refusal-cause.js';
288288
import { createEngineSsoProviderConfigReader, emailClaimOfStoredOidcConfig, type SsoProviderConfigEngine } from './register-sso-provider.js';
289289
import { readSsoProviderSignInOptions, runWithSamlProviderScope } from './sso-sign-in-options.js';
290+
import { readSamlAssertionAttributeNames } from './sso-saml-standard-claims.js';
290291
import {
291292
judgeSignOutOfIdpCapability,
292293
parkOidcEndSessionEndpoint,
@@ -4308,7 +4309,16 @@ export class AuthManager {
43084309
const auth: any = await this.getOrCreateAuth();
43094310
return readStoredSamlConfig(await auth.$context, callback.providerId);
43104311
};
4311-
return runWithSamlProviderScope({ allowIdpInitiated: options.allowIdpInitiated, singleLogout: options.signOutOfIdp }, () =>
4312+
// An unmapped member reads the standard claim the assertion
4313+
// carries, before the NameID (`sso-saml-standard-claims.ts`): the
4314+
// attribute names, read before the vendor consumes the body.
4315+
const assertionAttributeNames = await readSamlAssertionAttributeNames(callback.request);
4316+
return runWithSamlProviderScope({
4317+
allowIdpInitiated: options.allowIdpInitiated,
4318+
singleLogout: options.signOutOfIdp,
4319+
providerId: callback.providerId,
4320+
assertionAttributeNames,
4321+
}, () =>
43124322
runSsoSamlRefusalCauseScope(callback, this.config.logger, readSamlConfig, run),
43134323
);
43144324
}

‎packages/plugins/plugin-auth/src/objectql-adapter.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
restoreUserInfoEndpointOnWrite,
2525
stripIdpInitiatedFromOidcConfigOnWrite,
2626
} from './sso-sign-in-options.js';
27+
import { applyStandardSamlClaimsOnRead } from './sso-saml-standard-claims.js';
2728
import {
2829
reattachInternalFieldsOnRead,
2930
type InternalFieldResolvingEngine,
@@ -1014,6 +1015,10 @@ export function createObjectQLAdapterFactory(
10141015
// The vendor reads `oidcConfig.allowIdpInitiated`; the column answers it.
10151016
applyIdpInitiatedToOidcConfigOnRead(objectName, result);
10161017
applyUserInfoOptOutOnRead(objectName, result);
1018+
// At a SAML ACS only: an unmapped member reads the standard claim its
1019+
// assertion carries (`sso-saml-standard-claims.ts`). Not on the write
1020+
// echoes below, which no sign-in reads a mapping from.
1021+
applyStandardSamlClaimsOnRead(objectName, result);
10171022
// [#18728] Ruling C's producer half: `sys_organization.metadata` is a
10181023
// text column holding JSON, and better-auth decodes it on its two
10191024
// write echoes only. Decode it here so all four READ routes
@@ -1065,6 +1070,7 @@ export function createObjectQLAdapterFactory(
10651070
await injectClientSecretOnRead(secretEngine, objectName, r);
10661071
applyIdpInitiatedToOidcConfigOnRead(objectName, r);
10671072
applyUserInfoOptOutOnRead(objectName, r);
1073+
applyStandardSamlClaimsOnRead(objectName, r);
10681074
}
10691075

10701076
return results.map((r) => {

‎packages/plugins/plugin-auth/src/register-sso-provider.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1265,10 +1265,13 @@ export async function runSsoProviderDeleteImpact(
12651265
// - SAML: email = attribute `mapping.email` (default `email`), else the
12661266
// NameID; name = `mapping.firstName` (default `givenName`) + `mapping.lastName`
12671267
// (default `surname`), else `mapping.name` (default `displayName`), else the
1268-
// NameID. An IdP whose attribute names differ from those defaults — Okta's
1269-
// `name`, Entra ID's claim URIs (`http://schemas.xmlsoap.org/ws/2005/05/
1270-
// identity/claims/givenname`, …) — names every user after their NameID until
1271-
// the provider maps them.
1268+
// NameID. An IdP whose attribute names differ from those defaults (Okta's
1269+
// `name`) names every user after their NameID until the provider maps them.
1270+
// A member left unset reads the standard claim first when the assertion
1271+
// carries it (Entra ID's and AD FS's `http://schemas.xmlsoap.org/ws/2005/05/
1272+
// identity/claims/emailaddress`, `givenname`, `surname`, `name`), at the ACS
1273+
// only (`sso-saml-standard-claims.ts`); the stored mapping is unchanged, so
1274+
// the get bridge below still answers `null` for such a member.
12721275
// - OIDC: email = claim `mapping.email` (default `email`), name = claim
12731276
// `mapping.name` (default `name`). The OIDC mapping has no first/last-name
12741277
// member (`oidcMappingSchema` is strict).

‎packages/plugins/plugin-auth/src/sso-account-at-proven-domain.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import { describe, expect, it, vi } from 'vitest';
1313
import { EMAIL_DOMAIN_NOT_ALLOWED } from './audience-posture.js';
1414
import {
1515
SSO_ACCOUNT_DOMAIN_REFUSAL_DESCRIPTION,
16+
SSO_ACCOUNT_NOT_AN_ADDRESS_DESCRIPTION,
1617
refuseSsoAccountOutsideProvenDomain,
18+
refuseSsoAccountWithoutAddress,
19+
ssoValueIsAddress,
1720
ssoAddressAtProvenDomain,
1821
ssoAddressDomain,
1922
ssoDomainEntryHosts,
@@ -323,3 +326,34 @@ describe('[#32960] a requested domain entry that is not a bare host name is refu
323326
expect(ssoDomainEntryNotBare(undefined)).toBeUndefined();
324327
});
325328
});
329+
330+
describe('verification on or off, an SSO provider creates an account only for an email address', () => {
331+
const NOT_AN_ADDRESS = { error: 'INVALID_EMAIL', errorDescription: SSO_ACCOUNT_NOT_AN_ADDRESS_DESCRIPTION };
332+
333+
it('refuses INVALID_EMAIL for a value that is not an address, SAML and OIDC alike, naming no value', () => {
334+
for (const email of ['pov4hy2mt2-opaque-id', '', '@acme.com', 'mia chen@acme.com', 'mia@', 'mia@acme.com:443', 'mia@acme.com.', undefined, 42]) {
335+
for (const method of ['sso-saml', 'sso-oidc']) {
336+
const info = vi.fn();
337+
expect(refuseSsoAccountWithoutAddress(creation(email, method), { info }), `${method} ${String(email)}`).toEqual(NOT_AN_ADDRESS);
338+
expect(JSON.stringify(info.mock.calls)).not.toContain('pov4hy2mt2');
339+
}
340+
}
341+
expect(SSO_ACCOUNT_NOT_AN_ADDRESS_DESCRIPTION).not.toMatch(/#\d/);
342+
});
343+
344+
it('admits an address, at any domain', () => {
345+
for (const email of ['mia.chen@acme.com', 'Mia@ACME.com', 'bob@other.example', 'bob@xn--bcher-kva.de', 'a@b']) {
346+
expect(ssoValueIsAddress(email), email).toBe(true);
347+
expect(refuseSsoAccountWithoutAddress(creation(email, 'sso-saml'))).toBeUndefined();
348+
}
349+
});
350+
351+
it('CONTROL: judges only a creation from an SSO provider', () => {
352+
const opaque = 'pov4hy2mt2-opaque-id';
353+
expect(refuseSsoAccountWithoutAddress({ user: { email: opaque }, source: { action: 'sign-in', method: 'sso-saml', sso: { providerId: PROVIDER } } })).toBeUndefined();
354+
expect(refuseSsoAccountWithoutAddress({ user: { email: opaque }, source: { action: 'link-account', method: 'sso-saml', sso: { providerId: PROVIDER } } })).toBeUndefined();
355+
expect(refuseSsoAccountWithoutAddress({ user: { email: opaque }, source: { action: 'create-user', method: 'oauth', oauth: { providerId: 'github' } } })).toBeUndefined();
356+
expect(refuseSsoAccountWithoutAddress({ user: { email: opaque }, source: { action: 'create-user', method: 'scim' } })).toBeUndefined();
357+
expect(refuseSsoAccountWithoutAddress(undefined)).toBeUndefined();
358+
});
359+
});

0 commit comments

Comments
 (0)