Skip to content

Commit 30e364e

Browse files
fix(auth)!: with SSO-only mode on, an IdP-provisioned user is given no local password at any door; a platform administrator may still set their own (#33177)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoASGPj15PDYEW3irdvMYnjH)_ Clause-②: yes (narrowing) — narrowed: with SSO-only mode on (`ssoOnlyMode`, or `OS_AUTH_SSO_ONLY=true`), the four doors that write a local password, `POST /set-initial-password`, `POST /admin/set-user-password`, `POST /reset-password` and `POST /phone-number/reset-password`, answer `409 RESOURCE_CONFLICT` to a user whose `sys_user.source` is `idp_provisioned`, where they set the password; and the two reset doors answer `503 SERVICE_UNAVAILABLE` when the reset record they would judge cannot be read. Widened: two public members, `AuthManager#isSsoOnlyMode()` (the read of the SSO-only switch the manager already resolves) and the optional `ssoOnlyMode?(): boolean` on `AdminUserEndpointDeps`. No first-party composition in this repository turns SSO-only mode on. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches SSO-only mode or these four doors; `content/docs/permissions/authentication.mdx` gains the rule in this change, and `content/docs/deployment/self-hosting.mdx` names SSO-only mode only for the missing-credential log level, which does not move. Part of #32087 (item 5, the server half under ruling record 6866334319: honour the SSO-only switch. The administrator's set-password warning and the governed ADR-0135 D5.2 note follow as their own work, and item 4 is its own pull request.) ## 维护者速读 - 改了什么:环境开了"仅 SSO 登录"(`ssoOnlyMode` / `OS_AUTH_SSO_ONLY`)时,服务端在四处会生成本地密码的入口(自设初始密码、管理员"设置密码"、邮件重置、短信重置)都拒绝给公司登录系统开通的员工(`idp_provisioned`)本地密码,回 409 并写明是"仅 SSO 模式";唯一例外是平台管理员给自己设应急密码。 - 为什么改:按你 11-13 对 #32087 第 5 项选的 D:兑现已有的"仅 SSO 登录"开关,开了就真的生效;spec 里 `ssoOnlyMode` 的描述同步写明服务端现在强制的规则。 - 风险与回滚:patch 级,但对**已经开着 SSO-only 的部署**是破坏性收紧(BREAKING):升级后,身份提供方开通的员工在这四处拿不到本地密码,改为走 SSO;平台管理员仍可给自己设应急密码。没开 SSO-only 的部署、本地(`env_native`)用户、云托管环境的规则都不变;已持有本地密码的员工照常用它登录和改密码(不追溯)。重置入口在读不到重置记录时拒绝(503),不放行。两处防锁死守卫没动。回滚就是还原本 PR。 - 先看:`packages/plugins/plugin-auth/src/sso-only-local-password.ts`(共用判定与重置入口的读法)、`auth-manager-before-hook.ts` 新增的重置入口分支、`admin-user-endpoints.ts` 的 set-user-password 分支。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/sso-only-local-password.test.ts src/cloud-managed.test.ts src/password-reset-ends-sessions.test.ts`,预期 81 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes **The rule.** With SSO-only mode on, the server gives a user whose `sys_user.source` is `idp_provisioned` no local password at any door that writes one without the user proving a current one. Each door answers `409 RESOURCE_CONFLICT` (the registered code the cloud-managed refusals answer) with a message that names SSO-only mode, and writes nothing. One exception keeps break-glass reachable: a platform administrator setting their own local password. | Door | SSO-only on, IdP-provisioned user | Exception (platform administrator, own password) | Predicate asked | |:--|:--|:--|:--| | `POST /set-initial-password` | 409 | allowed | the session user's `isPlatformAdminUser` (the cloud-managed door's own) | | `POST /admin/set-user-password` (`sys_user#set_user_password`) | 409, another administrator as target included | allowed when the target is the caller (the route's gate admits platform administrators only) | `actor.id === userId` behind `gateAdmin` | | `POST /reset-password` (emailed link) | 409 | allowed | `isPlatformAdminUserId` (the manager's platform-admin standing) | | `POST /phone-number/reset-password` (texted code) | 409 | allowed | `isPlatformAdminUserId` | - `sso-only-local-password.ts` (new): the rule, its messages and refusal envelope, `readUserSource` (moved here from `admin-user-endpoints.ts`, the read the cloud-managed administrator door already asked, so both rules read one), the shared verdict `judgeSsoOnlyLocalPassword` (`allow` / `refuse` / `unreadable`, which fails closed as `503 SERVICE_UNAVAILABLE`, as the cloud-managed door does), and `resolveResetDoorUserId`. The module header names both platform-administrator predicates, where they differ, and ADR-0135 D5.2's `env_native` stamp. - The reset doors judge only a credential the door itself would accept, read without spending it: a live reset token, or a texted code that matches the live stored one inside its attempt budget (better-auth's own non-consuming predicate for that door). Any other request answers exactly as before. When the reset record (or the user it names) cannot be read, the reset doors fail closed with `503 SERVICE_UNAVAILABLE` instead of handing the request on unjudged. - `admin-user-endpoints.ts`: the set-user-password arm after the cloud-managed arm; the deps take `ssoOnlyMode()`, read live per call. - `auth-plugin.ts`: the set-initial-password arm after the cloud-managed arm; `adminUserDeps` passes `ssoOnlyMode`. - `auth-manager-before-hook.ts`: the reset-door arm, ahead of the password complexity check so the refusal names the real reason. The host gains `getDataEngine` and `isSsoOnlyMode`. - `auth-manager.ts`: `isSsoOnlyMode()`, the public read of the existing `resolveSsoOnly()`. - `packages/spec` `AuthConfigSchema.ssoOnlyMode`: TSDoc and `.describe` say what the server now enforces; `content/docs/references/system/auth-config.mdx` regenerated. No key, value or export changes. - `content/docs/permissions/authentication.mdx`: a short "SSO-only mode: IdP-provisioned users get no local password" section, including the fail-closed answer and which body shape each door answers. **Unchanged:** SSO-only mode off; environment-native users (and rows with no source) at every door; a local password a user already holds (it still signs in, and `/change-password` still changes it); the cloud-managed rules, which answer first on a cloud-managed environment; `last-admin-guard.ts` and `last-local-credential.ts`. Not doors: `/change-password` (proves the current password), `/sign-up/email` (SSO-only already forces sign-up off), admin create-user and import-users (new rows only; import never changes an existing user's password), SCIM (writes no credential), the email-OTP reset (not mounted). ## Breaking **BREAKING** for a deployment already running with SSO-only mode on: an IdP-provisioned user can no longer be given a local password at the four doors above; each answers `409 RESOURCE_CONFLICT` and writes nothing. Such a user signs in through the identity provider; a platform administrator can still set their own break-glass password; a deployment that needs a managed user to hold a local password turns SSO-only mode off. Level stays `patch` (a non-protocol change; AGENTS.md, Post-Task Checklist step 3). The widening is two additive public members: `AuthManager#isSsoOnlyMode()` and the optional `AdminUserEndpointDeps.ssoOnlyMode?()`. ADR-0087 disposition: `not-required (no-migration-prescription)`, in the changeset: no schema key, value or type moves, and nothing stored needs a migration. ## Why Ruling record 6866334319 on #32087, item 5 → D: when SSO-only mode is on, the server refuses to give an IdP-provisioned user a local password at every door, with the one break-glass exception the cloud-hosted rule already makes; SSO-only off is unchanged; not retroactive. ## Tests - `sso-only-local-password.test.ts` (new, the module's own pins): the verdict table (off reads nothing; refuse; the platform-administrator exception; environment-native and source-less rows ask no standing; fail closed on no engine, no read surface, a throwing read); the refusal envelope and that its code and status equal the cloud-managed ones; `resolveResetDoorUserId` names a user only for a live token or a matching in-budget code, reads nothing on another path, and answers unreadable when the reset record or the user lookup has no read surface or throws. - `cloud-managed.test.ts` (the set doors' shared harness, a real `AuthManager` behind `registerAuthRoutes` on Hono), new top-level describe: per door, SSO-only on refuses the IdP-provisioned user with 409 + code + sentence and writes no credential; the IdP-provisioned platform administrator setting their own is allowed; an administrator setting one for another IdP-provisioned administrator is refused; an environment-native user and an anonymous caller answer as before; SSO-only off answers as before (CONTROL); on a cloud-managed environment the cloud-managed refusal answers. Not retroactive: an IdP-provisioned user holding a password still signs in and changes it, while no door sets it anew. - The existing leg "unmanaged with SSO-only on, both doors answer the idp user as before" pinned the behaviour this ruling reverses. It now asserts that the SSO-only refusal answers there, never the cloud-managed sentence, and a new leg keeps the SSO-only-off control. - `password-reset-ends-sessions.test.ts` (the reset doors' shared harness, a real ObjectQL on SQLite), new top-level describe: for each reset door, SSO-only on refuses the IdP-provisioned user (409 + code + sentence, no credential written); a holder is refused too and their password still signs in; the platform administrator resetting their own is allowed; an environment-native user answers as before; an unmatched token or a wrong code answers exactly as it does with SSO-only off; a reset record that cannot be read (every `sys_verification` read made to throw) answers `503 SERVICE_UNAVAILABLE` and writes no credential; SSO-only off resets as before (CONTROL). ## Acceptance notes - Reading confirmed by the seat before the edit: the set and reset doors refuse an IdP-provisioned user even when one already holds a password (the cloud-managed administrator door does the same); "not retroactive" means an existing password keeps working. - The reset-door refusal leaves in better-auth's flat `{ code, message }` body, the shape those doors' other refusals (`INVALID_TOKEN`, `INVALID_OTP`) take; the set doors answer the nested ADR-0112 envelope, as their cloud-managed refusals do. - The cloud mounts its own twin of `set-initial-password` from `runSetInitialPassword`; this PR puts the SSO-only arm in this repository's route, as the cloud-managed arm is, and a cloud-managed environment answers the stricter cloud-managed rule first. - Contract review 6868317289 (FAIL at `f3393c48`, must-fix ②): this head declares the narrowing and the widening, adds `!`, the BREAKING banner, the ADR-0087 disposition and the `Skills-docs:` line, and runs the dogfood battery. Nits 2, 3 and 5 are taken as prose (module header, `authentication.mdx`). Nit 4 (the request-reset doors still send a mail or text to a user whose reset will be refused) is not in the ruling and is left for the seat. - Remainders, not in this PR: the administrator's set-password warning (ui card), the governed ADR-0135 D5.2 note (kept in step with cloud ADR-0024 D5.2), and the question of managed users who already hold a local password. ## Verification All readings at head `f183d45b` (round 2, after contract review 6868317289), objectstack-ai/objectstack. Round 1 readings were at `f3393c48`. <details><summary>Tests</summary> - `pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2` (whole package): Test Files 267 passed (267), Tests 5075 passed, 10 skipped, exit 0. - The three files that carry this rule's pins (`sso-only-local-password`, `cloud-managed`, `password-reset-ends-sessions`): 3 files, 81 tests passed. - `pnpm --filter @objectstack/plugin-auth typecheck` (with `check:test-typecheck`): exit 0, after a full declaration build. - eslint over the changed `.ts` files: exit 0. - Dogfood battery (`packages/qa/dogfood`, `vitest run`, all shards in one process): Test Files 462 passed, 3 skipped (465); Tests 3905 passed, 42 skipped; exit 0. Run on `35395b46` plus the changeset commit; the one later commit, `f183d45b`, changes only the module's docblock. </details> <details><summary>Ablation (one shot each, not kept)</summary> - Round 1: the shared judge's refuse verdict replaced with an unconditional allow; 9 failed, 68 passed, every refusal leg. Restored, `git diff HEAD` empty. - Round 2: the reset-door reader's unreadable answer (its `catch`) replaced with "names nobody"; 3 failed: the module pin for an unreadable record and the two reset doors' 503 pins. Restored, `git diff HEAD` empty. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 120 families derived for this diff (the same list as round 1); all 120 run with exit codes recorded first, all exit 0. - `dispatch-gates --ran`: 120 derived, 120 run, 0 NOT-MEASURED, 0 UNRUN. - `check-adr-0087-registration --base origin/main`: 1 declared-breaking changeset, `[BREAKING+bang+clause-②-narrowing]`, `not-required (no-migration-prescription)`, exit 0. - `pnpm --filter @objectstack/spec check:generated`: green (round 1 regenerated `content/docs/references/system/auth-config.mdx`; round 2 does not touch `packages/spec`). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (Description text only.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint over the changed files, exit 0.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (`check:generated --fix` regenerated the one it proved stale, `content/docs/references/system/auth-config.mdx`.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwgMDk9yn3MZdGMqEM)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibwgMDk9yn3MZdGMqEM <!-- signed: security#2 · os-tesla · session_01L9qibwgMDk9yn3MZdGMqEM --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent de31809 commit 30e364e

14 files changed

Lines changed: 1133 additions & 35 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(auth)!: with SSO-only mode on, the server gives an IdP-provisioned user no local password at any door; a platform administrator may still set their own
7+
8+
Clause-②: yes (narrowing) — narrowed: with SSO-only mode on (`ssoOnlyMode`, or `OS_AUTH_SSO_ONLY=true`), the four doors that write a local password, `POST /set-initial-password`, `POST /admin/set-user-password`, `POST /reset-password` and `POST /phone-number/reset-password`, answer `409 RESOURCE_CONFLICT` to a user whose `sys_user.source` is `idp_provisioned`, where they set the password; and the two reset doors answer `503 SERVICE_UNAVAILABLE` when the reset record they would judge cannot be read. Widened: two public members, `AuthManager#isSsoOnlyMode()` (the read of the SSO-only switch the manager already resolves) and the optional `ssoOnlyMode?(): boolean` on `AdminUserEndpointDeps`. No first-party composition in this repository turns SSO-only mode on.
9+
Metadata-protocol: none
10+
Skills-docs: none — no skill under `skills/**` teaches SSO-only mode or these four doors; `content/docs/permissions/authentication.mdx` gains the rule in this change, and `content/docs/deployment/self-hosting.mdx` names SSO-only mode only for the missing-credential log level, which does not move.
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped: `ssoOnlyMode` keeps its key, type and default, and only its description changes. The moved answers are runtime refusals at four auth doors under a deployment switch, so there is nothing stored for a migration to rewrite and no tombstone. -->
13+
14+
**BREAKING** for a deployment already running with SSO-only mode on: a user the identity provider provisioned can no longer be given a local password at `POST /set-initial-password`, by an administrator at `POST /admin/set-user-password` (the Set Password action on a user), or through `POST /reset-password` (the emailed link) or `POST /phone-number/reset-password` (the texted code). Each answers `409 RESOURCE_CONFLICT` with a message that names SSO-only mode, and writes nothing. The one exception keeps break-glass reachable: a platform administrator setting their own local password. An administrator setting one for another IdP-provisioned user, another administrator included, is refused. The reset doors judge only a reset token or code they would accept, so any other request answers as before; when the reset record cannot be read they fail closed with `503 SERVICE_UNAVAILABLE`.
15+
16+
Unchanged: SSO-only mode off; environment-native users at every door; a local password a user already holds (it still signs in, and `/change-password` still changes it); the cloud-managed rules, which answer first on a cloud-managed environment; and the guards that keep the last local password and the last administrator.
17+
18+
What to do: nothing, unless an IdP-provisioned user relies on setting or resetting a local password while SSO-only mode is on. Such a user signs in through the identity provider instead. A platform administrator can still set their own break-glass password. A deployment that needs a managed user to hold a local password turns SSO-only mode off.
19+
20+
`@objectstack/spec`: the `ssoOnlyMode` description says what the server now enforces. No key, value or export changes.

‎content/docs/permissions/authentication.mdx‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,34 @@ Two refusals are deliberate and are what separate this from a password reset:
343343
The Console reaches it from **Profile → Password** when `hasLocalPassword()`
344344
reports no credential.
345345

346+
#### SSO-only mode: IdP-provisioned users get no local password
347+
348+
With SSO-only mode on (`ssoOnlyMode`, or `OS_AUTH_SSO_ONLY=true`), the server
349+
gives a user whose `sys_user.source` is `idp_provisioned` no local password, at
350+
every door that sets one: `POST /api/v1/auth/set-initial-password`, an
351+
administrator's `POST /api/v1/auth/admin/set-user-password` (the **Set
352+
Password** action), and the two resets, `POST /api/v1/auth/reset-password` and
353+
`POST /api/v1/auth/phone-number/reset-password`. Each answers
354+
`409 RESOURCE_CONFLICT` with a message that names SSO-only mode, and writes
355+
nothing; the user signs in through the identity provider.
356+
357+
- **Break-glass stays reachable.** A platform administrator may set their own
358+
local password at any of these doors. An administrator setting one for
359+
another IdP-provisioned user, another administrator included, is refused.
360+
- **The resets judge only a credential they would accept.** A reset token or a
361+
texted code that does not match answers exactly as it does with SSO-only mode
362+
off. If the reset record or the user's identity source cannot be read, the
363+
reset answers `503 SERVICE_UNAVAILABLE` and sets nothing.
364+
- **The two resets answer in the auth library's flat body**,
365+
`{ "code": "RESOURCE_CONFLICT", "message": "…" }`, the shape their other
366+
refusals (an invalid token, an invalid code) take. The two set doors answer
367+
the platform's `{ "success": false, "error": { "code", "message" } }`
368+
envelope.
369+
- **Unchanged:** environment-native users at every door, SSO-only mode off, and
370+
a local password a user already holds — it still signs in, and
371+
`POST /api/v1/auth/change-password` still changes it. On a cloud-managed
372+
environment the cloud-managed rules answer first.
373+
346374
### Email Verification
347375

348376
#### Send Verification Email

‎content/docs/references/system/auth-config.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Advanced / low-level Better-Auth options
8080
| **emailVerification** | `{ sendOnSignUp?: boolean; sendOnSignIn?: boolean; autoSignInAfterVerification?: boolean; expiresIn?: number }` | optional | Email verification options forwarded to better-auth |
8181
| **audience** | `{ posture?: Enum<'invite_only' \| 'email_domain' \| 'open'>; allowedEmailDomains?: string[]; selfRegistrationPermissionSet?: string }` | optional | Audience posture: who may self-register (invite_only — the default — \| email_domain \| open). See AudienceConfigSchema. |
8282
| **advanced** | `{ crossSubDomainCookies?: object; useSecureCookies?: boolean; disableCSRFCheck?: boolean; cookiePrefix?: string }` | optional | Advanced / low-level Better-Auth options |
83-
| **ssoOnlyMode** | `boolean` | optional | SSO-only login: hide the local password form + self-registration (the break-glass password endpoint stays enabled) |
83+
| **ssoOnlyMode** | `boolean` | optional | SSO-only login: hide the local password form + self-registration, and refuse to give an IdP-provisioned user a local password (a platform administrator may still set their own; the break-glass password endpoint stays enabled) |
8484
| **mutualTls** | `{ enabled?: boolean; clientCertRequired?: boolean; trustedCAs: string[]; crlUrl?: string; … }` | optional | Mutual TLS (mTLS) configuration |
8585

8686
### Nested Shape: `AuthConfig.providers[number]`

‎packages/plugins/plugin-auth/src/admin-user-endpoints.ts‎

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,12 @@ export interface AdminUserEndpointDeps {
9191
noteMustChangePasswordIssued(): void;
9292
/** Is the better-auth phoneNumber plugin wired (#2766 V1.5)? */
9393
phoneNumberEnabled?(): boolean;
94+
/**
95+
* Is SSO-only mode on (`AuthManager.isSsoOnlyMode()`)? Read per call. Under
96+
* it, set-user-password refuses an IdP-provisioned target other than the
97+
* administrator themselves (`sso-only-local-password.ts`). Absent ⇒ off.
98+
*/
99+
ssoOnlyMode?(): boolean;
94100
/**
95101
* ADR-0093 D3 — accessor for the `tenancy` service. When present, the
96102
* create-user membership bind resolves its target org through
@@ -232,6 +238,7 @@ import { resolveDefaultOrgId } from './tenancy-service.js';
232238
import type { AddMemberCapableApi } from './organization-add-member.js';
233239
import { readJsonRequestBody } from './request-json-body.js';
234240
import { cloudManagedRefusal } from './cloud-managed.js';
241+
import { identitySourceUnreadable, judgeSsoOnlyLocalPassword, readUserSource, ssoOnlyPasswordRefusal } from './sso-only-local-password.js';
235242
import { temporaryPasswordLength } from './temporary-password-length.js';
236243
import { isCloudManaged } from '@objectstack/core';
237244
import { resolveThrownHttpError, validationFailureDetails } from '@objectstack/types';
@@ -408,32 +415,6 @@ async function resolvePassword(
408415
* fail-open gate, so a failed stamp must not fail the whole operation; we
409416
* surface the *actual* stamped state in the response instead.
410417
*/
411-
/**
412-
* [#25083] The target's `sys_user.source` (`idp_provisioned` | `env_native`),
413-
* read as the system. `ok: false` when it cannot be read at all (no engine,
414-
* no read surface, or the read throws), so the cloud-managed check above
415-
* fails closed instead of reading an outage as a local account.
416-
*/
417-
async function readUserSource(
418-
deps: AdminUserEndpointDeps,
419-
userId: string,
420-
): Promise<{ ok: true; value: string | null } | { ok: false }> {
421-
const engine = deps.getDataEngine();
422-
if (!engine?.find) return { ok: false };
423-
try {
424-
const rows = await engine.find('sys_user', {
425-
where: { id: userId },
426-
fields: ['id', 'source'],
427-
limit: 1,
428-
context: SYSTEM_CTX,
429-
});
430-
const row = Array.isArray(rows) ? (rows[0] as { source?: unknown } | undefined) : undefined;
431-
return { ok: true, value: typeof row?.source === 'string' ? row.source : null };
432-
} catch {
433-
return { ok: false };
434-
}
435-
}
436-
437418
async function stampMustChangePassword(
438419
deps: AdminUserEndpointDeps,
439420
userId: string,
@@ -1118,7 +1099,7 @@ export async function runAdminSetUserPassword(
11181099
// `env_native` row (the break-glass administrator among them) still
11191100
// answers, because ADR-0135 D5.2 narrows by population, never wholesale.
11201101
if (isCloudManaged()) {
1121-
const source = await readUserSource(deps, userId);
1102+
const source = await readUserSource(deps.getDataEngine(), userId);
11221103
if (!source.ok) {
11231104
return {
11241105
status: 503,
@@ -1136,6 +1117,20 @@ export async function runAdminSetUserPassword(
11361117
if (source.value === 'idp_provisioned') return cloudManagedRefusal('setUserPassword');
11371118
}
11381119

1120+
// With SSO-only mode on, an IdP-provisioned user signs in through the
1121+
// identity provider and is given no local password here; the one exception
1122+
// is a platform administrator (this route's gate admitted the actor as
1123+
// one) setting their own break-glass password. `sso-only-local-password.ts`
1124+
// states the rule; an environment-native target answers as before.
1125+
const ssoOnly = await judgeSsoOnlyLocalPassword({
1126+
ssoOnly: deps.ssoOnlyMode?.() === true,
1127+
engine: deps.getDataEngine(),
1128+
userId,
1129+
selfPlatformAdmin: () => actor.id === userId,
1130+
});
1131+
if (ssoOnly === 'unreadable') return identitySourceUnreadable('this SSO-only environment may set their password here');
1132+
if (ssoOnly === 'refuse') return ssoOnlyPasswordRefusal('setUserPassword');
1133+
11391134
// Mirrors the stock /admin/set-user-password core: hash, then update the
11401135
// credential account or create one for SSO/invite-onboarded users.
11411136
const hashed = await authCtx.password.hash(resolved.password);

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ export interface AuthInstanceHost {
151151
getAudience: AuthManager['getAudience'];
152152
getCanonicalOrigin: AuthManager['getCanonicalOrigin'];
153153
getConsolePageUrl: AuthManager['getConsolePageUrl'];
154+
getDataEngine: AuthManager['getDataEngine'];
154155
getEmailService: AuthManager['getEmailService'];
155156
hasExistingUserFor: AuthManager['hasExistingUserFor'];
156157
readonly idpLocale: AuthManager['idpLocale'];
@@ -161,6 +162,7 @@ export interface AuthInstanceHost {
161162
isOperatorProvisioning: AuthManager['isOperatorProvisioning'];
162163
isPlatformAdminUserId: AuthManager['isPlatformAdminUserId'];
163164
isSsoDomainVerificationEnabled: AuthManager['isSsoDomainVerificationEnabled'];
165+
isSsoOnlyMode: AuthManager['isSsoOnlyMode'];
164166
isSsoWired: AuthManager['isSsoWired'];
165167
linkingContext: AuthManager['linkingContext'];
166168
logDurabilityDegradation: AuthManager['logDurabilityDegradation'];
@@ -824,12 +826,14 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
824826
assertSsoSignOutOfIdpSupported: (...a) => this.assertSsoSignOutOfIdpSupported(...a),
825827
get config() { return readConfig(); },
826828
existingAddressSignUpAnswersSuccess: (...a) => this.existingAddressSignUpAnswersSuccess(...a),
829+
getDataEngine: (...a) => this.getDataEngine(...a),
827830
hasExistingUserFor: (...a) => this.hasExistingUserFor(...a),
828831
isAuthGateActive: (...a) => this.isAuthGateActive(...a),
829832
isBootstrapCreation: (...a) => this.isBootstrapCreation(...a),
830833
isEmailDeliveryLive: (...a) => this.isEmailDeliveryLive(...a),
831834
isOperatorProvisioning: (...a) => this.isOperatorProvisioning(...a),
832835
isPlatformAdminUserId: (...a) => this.isPlatformAdminUserId(...a),
836+
isSsoOnlyMode: (...a) => this.isSsoOnlyMode(...a),
833837
resolveActor: (...a) => this.resolveActor(...a),
834838
resolvePasswordChangeUserId: (...a) => this.resolvePasswordChangeUserId(...a),
835839
roleChangeGrantDeps: (...a) => this.roleChangeGrantDeps(...a),

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ import {
7070
LAST_LOCAL_CREDENTIAL_MESSAGE,
7171
} from './last-local-credential.js';
7272
import { refuseRequestNamingDifferentAccounts } from './one-account-per-request.js';
73+
import {
74+
SSO_ONLY_RESET_UNREADABLE_MESSAGE,
75+
judgeSsoOnlyLocalPassword,
76+
PHONE_RESET_PASSWORD_PATH,
77+
RESET_PASSWORD_PATH,
78+
resolveResetDoorUserId,
79+
SSO_ONLY_REFUSAL_CODE,
80+
SSO_ONLY_REFUSAL_MESSAGES,
81+
} from './sso-only-local-password.js';
7382
import { ORGANIZATION_DELETE_PATH } from './organization-delete.js';
7483
import { carriesPrincipalSession } from './principal-session-mint.js';
7584
import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js';
@@ -99,12 +108,14 @@ export interface BeforeHookHost {
99108
assertSsoSignOutOfIdpSupported: AuthManager['assertSsoSignOutOfIdpSupported'];
100109
readonly config: AuthManager['config'];
101110
existingAddressSignUpAnswersSuccess: AuthManager['existingAddressSignUpAnswersSuccess'];
111+
getDataEngine: AuthManager['getDataEngine'];
102112
hasExistingUserFor: AuthManager['hasExistingUserFor'];
103113
isAuthGateActive: AuthManager['isAuthGateActive'];
104114
isBootstrapCreation: AuthManager['isBootstrapCreation'];
105115
isEmailDeliveryLive: AuthManager['isEmailDeliveryLive'];
106116
isOperatorProvisioning: AuthManager['isOperatorProvisioning'];
107117
isPlatformAdminUserId: AuthManager['isPlatformAdminUserId'];
118+
isSsoOnlyMode: AuthManager['isSsoOnlyMode'];
108119
resolveActor: AuthManager['resolveActor'];
109120
resolvePasswordChangeUserId: AuthManager['resolvePasswordChangeUserId'];
110121
roleChangeGrantDeps: AuthManager['roleChangeGrantDeps'];
@@ -182,6 +193,49 @@ export async function globalBeforeHook(
182193
await this.assertPhoneOtpSendAllowed(phone);
183194
}
184195

196+
// ── SSO-only: the reset doors give an IdP-provisioned user no ──
197+
// local password. Both doors create the credential account when the
198+
// user holds none (better-auth's `resetCredentialPassword`), so under
199+
// SSO-only mode the user the presented token or code would reset is
200+
// judged here, ahead of the vendor's handler, by the rule every door
201+
// shares (`sso-only-local-password.ts`); a platform administrator
202+
// resetting their own keeps break-glass. Judged only for a credential
203+
// the door itself would accept, read without spending it, so any other
204+
// request is answered exactly as before; a reset record that cannot be
205+
// read fails closed (503). Ahead of the complexity check,
206+
// so the refusal names the real reason.
207+
if (
208+
(ctx?.path === RESET_PASSWORD_PATH || ctx?.path === PHONE_RESET_PASSWORD_PATH) &&
209+
this.isSsoOnlyMode()
210+
) {
211+
const subject = await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3);
212+
// A reset record that cannot be read fails closed, as a source that
213+
// cannot be read does.
214+
let verdict: 'allow' | 'refuse' | 'unreadable' = subject.ok ? 'allow' : 'unreadable';
215+
if (subject.ok && subject.userId) {
216+
const userId = subject.userId;
217+
verdict = await judgeSsoOnlyLocalPassword({
218+
ssoOnly: true,
219+
engine: this.getDataEngine(),
220+
userId,
221+
selfPlatformAdmin: () => this.isPlatformAdminUserId(userId),
222+
});
223+
}
224+
if (verdict !== 'allow') {
225+
const { APIError } = await import('better-auth/api');
226+
if (verdict === 'refuse') {
227+
throw new APIError('CONFLICT', {
228+
message: SSO_ONLY_REFUSAL_MESSAGES.resetPassword,
229+
code: SSO_ONLY_REFUSAL_CODE,
230+
});
231+
}
232+
throw new APIError('SERVICE_UNAVAILABLE', {
233+
message: SSO_ONLY_RESET_UNREADABLE_MESSAGE,
234+
code: 'SERVICE_UNAVAILABLE',
235+
});
236+
}
237+
}
238+
185239
// ── ADR-0069 D1: password complexity (validator) ────────────
186240
// better-auth enforces only min/max length; class-mix is custom.
187241
// Runs on the password-mutating endpoints; reads the candidate from

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,6 +2101,7 @@ export class AuthManager {
21012101
getAudience: (...a) => this.getAudience(...a),
21022102
getCanonicalOrigin: (...a) => this.getCanonicalOrigin(...a),
21032103
getConsolePageUrl: (...a) => this.getConsolePageUrl(...a),
2104+
getDataEngine: (...a) => this.getDataEngine(...a),
21042105
getEmailService: (...a) => this.getEmailService(...a),
21052106
hasExistingUserFor: (...a) => this.hasExistingUserFor(...a),
21062107
get idpLocale() { return readIdpLocale(); },
@@ -2112,6 +2113,7 @@ export class AuthManager {
21122113
isPlatformAdminUserId: (...a) => this.isPlatformAdminUserId(...a),
21132114
isSsoDomainVerificationEnabled: (...a) => this.isSsoDomainVerificationEnabled(...a),
21142115
isSsoWired: (...a) => this.isSsoWired(...a),
2116+
isSsoOnlyMode: (...a) => this.isSsoOnlyMode(...a),
21152117
linkingContext: (...a) => this.linkingContext(...a),
21162118
logDurabilityDegradation: (...a) => this.logDurabilityDegradation(...a),
21172119
recordPasswordHistory: (...a) => this.recordPasswordHistory(...a),
@@ -5438,6 +5440,16 @@ export class AuthManager {
54385440
return readSsoOnlyEnv() ?? (this.config.ssoOnlyMode ?? false);
54395441
}
54405442

5443+
/**
5444+
* Is SSO-only mode on ({@link resolveSsoOnly}, read live)? The doors that
5445+
* give a user a local password ask it: under it an IdP-provisioned user is
5446+
* given none, except a platform administrator setting their own
5447+
* (`sso-only-local-password.ts`).
5448+
*/
5449+
public isSsoOnlyMode(): boolean {
5450+
return this.resolveSsoOnly();
5451+
}
5452+
54415453
/**
54425454
* Is local self-registration forced off, whatever `disableSignUp` says?
54435455
* Under SSO-only ({@link resolveSsoOnly}), and [#25083] on a cloud-managed

0 commit comments

Comments
 (0)