Skip to content

Commit a93ef3e

Browse files
fix(plugin-auth)!: deleting the last identity provider is refused, and a boot that serves no sign-in method says so (#30300) (#30449)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgWXUffkVpeZMuUzb3Fkntr9)_ Fixes #30300 Clause-②: yes (narrowing) Metadata-protocol: none Skills-docs: none — no file under `skills/**` teaches deleting an SSO provider or the sign-in boot reports; `content/docs/deployment/self-hosting.mdx` gains "No sign-in method left". ## 维护者速读 - **改了什么**:邮箱密码登录关闭、只剩一个企业 SSO 身份提供方时,Setup 的「删除 SSO 提供方」被拒(409),不再删掉最后一条登录路;重部署后没有任何登录方式时,启动日志打一条 error,启动照常。 - **为什么改**:两扇门都在 main 上真实启动复现过:删完或重部署之后,全租户连同管理员都登录不了,而且没有任何提示。 - **风险与回滚**:只在「邮箱密码关、SSO 开、这是最后一个提供方、没有其他登录方式」时拒删,其余删除照旧;读不到提供方列表时返回 503 拒删。回滚即 revert 本 PR。 - **先看**:`sign-in-method-floor.ts` 的 `ssoProviderDeleteRefusal` 与 `resolveNoSignInMethodReport`;`auth-manager-before-hook.ts` 的 `/sso/delete-provider` 分支;`auth-plugin.ts` kernel:ready 新增的那一段。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run src/sign-in-method-floor.test.ts`,预期 35 条全过。 - **需要你做的**:无,席位落地。 ## What changes Two doors removed the last way to sign in without a word. Both are now judged by the sign-in method floor that #30298 added to the auth settings save (`sign-in-method-floor.ts`), so the three doors cannot drift apart. **Door 1: deleting the last identity provider.** `POST /api/v1/auth/sso/delete-provider` (Setup's "Delete SSO Provider") is refused in plugin-auth's global better-auth before-hook, before the vendor deletes anything, when all of these hold: - email and password sign-in is off; - enterprise SSO is switched on; - no other way in counts: a social or OIDC provider with a client ID and secret, phone-number sign-in, or a host sign-in handoff; - the provider being deleted is the last `sys_sso_provider` row. One bounded read of two rows answers this. The answer is `409` with `code: DELETE_RESTRICTED`, `lastSignInMethod: enterprise_sso`, and a message in the caller's language (en, zh-CN, ja-JP, es-ES). This is an existing standard code, the one an organization delete answers when it is refused for the same kind of reason. When the provider list cannot be read, the answer is `503 SERVICE_UNAVAILABLE`, because a guard that could not be evaluated does not pass. Nothing changes for an unauthenticated caller (still the vendor's `401`), an unknown provider (still the vendor's `404`), or the vendor's own provider-access check. - `AuthManager.setSsoProviderDeleteFloor()` (`@internal`): `AuthPlugin` hands the manager the judge, because the manager does not hold the host handoff declaration or the boot credential index. - `AuthPlugin.signInMethodFloorDeps()`: one builder of the floor's live facts, used by the settings save, the delete, and the boot report. **Door 2: a boot that serves no way in.** At the `kernel:ready` site that already reports `no_sign_in_account_at_boot`, after the auth settings are applied, a deployment that serves no sign-in method now reports `no_sign_in_method_at_boot` at `error`. The line names the consequence and the recovery: `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` and a restart. - It is a positive claim only: a provider table that cannot be read stays silent. - It is reported in every posture and **never refuses the boot** (seat ruling, option A). A platform-SSO tenant that signs in through a door this plugin cannot see, such as `ssoOnlyMode`, which the floor does not count, must keep starting. - **Refusing such a boot is a later option, not done here.** It fits only once every delegated path is counted. **Docs.** `content/docs/deployment/self-hosting.mdx` gains "No sign-in method left", covering the three doors and the recovery. ## Why Both doors were measured on `main` bfca0ef on a real boot before any code (report 6652003986). - **Door 1.** With email and password off and one SAML provider as the only way in, the delete answered `200 {"success":true}`. After sign-out, `/sign-in/email` answered `400 EMAIL_PASSWORD_DISABLED` and `/sign-in/sso` answered `404`. - **Door 2.** A redeploy without the `GOOGLE_CLIENT_*` pair booted to "Server is ready" with no sign-in line, and served no method. ## Tests Pins added to the floor's shared harness `packages/plugins/plugin-auth/src/sign-in-method-floor.test.ts`, as top-level describes. There are 18 new cases, and the file has 35 in all. - **Door 1, real composition.** `ObjectKernel` + `ObjectQLPlugin` over in-memory SQLite, the real `SettingsServicePlugin`, the real `AuthPlugin` with the SSO plugin, and a real sign-up and session cookie. Email and password is turned off through `settings.setMany`, which the floor admits while a provider row exists. Then the real `POST /api/v1/auth/sso/delete-provider`: - the last provider gets `409 DELETE_RESTRICTED`, the zh-CN copy under `Accept-Language: zh-CN`, then the en copy, and the row is still there; - CONTROL, two providers: the first delete goes through (`200`) and the one left is then refused; - CONTROL, email and password on: the delete goes through; - CONTROL: an unknown provider gets the vendor's `404`, and no session gets the vendor's `401`. - **Door 2, the same composition.** - `emailAndPassword.enabled: false` with no provider reports once at `error` and the boot completes; - the same with SSO on and no row; - CONTROL: `GOOGLE_CLIENT_*` set reports nothing; - recovery: `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` turns email and password back on over the stack config, and nothing is reported. - **The judge and the report**, for faults the composition cannot make: - an unreadable provider list gets `503` on the delete and silence at boot; - seven pass cases; - the report goes to `error`, or to `warn` on a sink without `error`, and a throwing sink does not throw. <details><summary>Ablations (each through <code>scripts/ablation-replace.mjs</code>, restored, worktree clean after)</summary> Each mutation landed (anchor 1 → 0, blob changed), the run went red as below, and the file was restored to the HEAD blob (`git status` clean). - **A1**, door 1 call removed from the before-hook (`await this.assertSsoProviderDeletable(ctx);`): the last-provider refusal and the "one left is then refused" control go red, `expected 200 to be 409`. 2 failed, 33 passed. This reproduces the bug on the test stack. - **A2**, the boot report call removed from `kernel:ready`: both door 2 report cases go red. 2 failed, 33 passed. - **A3**, an unreadable provider list read as "another provider remains": the 503 case goes red. 1 failed, 17 passed (run before the pins moved into the shared file). - **A4**, the boot report speaks unless a provider row is `present`: the positive-claim case goes red. 1 failed, 17 passed (same). - **A5**, `AuthPlugin` does not hand the manager the judge: the two door 1 refusal cases go red, `{"success":true}: expected 200 to be 409`. 2 failed, 16 passed (same). A1 and A2 were re-run against the final shared file. </details> ## Acceptance notes - **Clause-② re-measured: yes (narrowing).** The Claim wrote `no — the dev re-measures`. Measured: a request accepted before (`POST /sso/delete-provider` on the last provider, `200`) is now refused (`409`). That is an accept-set narrowing at a public endpoint, the same kind #30298 declared for the settings save. Hence the `!` and the BREAKING section in the changeset. The widening half is one `@internal` setter on the exported `AuthManager`. - **Metadata-protocol: none.** No metadata shape or semantics change. - **Out of scope, filed by the seat as #30352.** Setup's Register SAML Provider bridge always answers 400 on this vendor version, so the re-measure registered providers through the vendor's `/sso/register`. ## Verification All readings are on head `385ecdcc`: this branch merged with `origin/main` `7d7babb1`, which carries #30368 and #30376. Heavy runs were under `scripts/pm/os-verify-lock.sh` on a shared box. <details><summary>Real boot re-measure of both doors (pnpm dev, SqlDriver better-sqlite3)</summary> Door 1: fresh boot with `OS_SSO_ENABLED=true`, signed in as the dev admin. Two SAML providers were registered through `/api/v1/auth/sso/register`. `PUT /api/settings/auth {email_password_enabled:false}` answered `200`; the floor admits it while SSO has rows. - `POST /api/v1/auth/sso/delete-provider {providerId:"beta-saml"}` → `200 {"success":true}` (another provider remains). - `POST /api/v1/auth/sso/delete-provider {providerId:"acme-saml"}` → `409 {"code":"DELETE_RESTRICTED","message":"This is the last enterprise SSO identity provider, and with email and password off nothing else signs anyone in, …","lastSignInMethod":"enterprise_sso"}`. - The same with `Accept-Language: zh-CN` → `409` with the zh-CN copy. - `GET /api/v1/data/sys_sso_provider` → `acme-saml` still there; `/auth/config` `features.sso: true`. - After sign-out, `POST /api/v1/auth/sign-in/sso {email:"someone@acme.test"}` → `200` with the IdP redirect URL. Door 2: the database from the measurement round, with `auth.email_password_enabled` stored `false` and Google previously declared by env. - The redeploy without `GOOGLE_CLIENT_*` logged `ERROR [auth] no_sign_in_method_at_boot: this deployment serves NO way to sign in, … Recover: set OS_AUTH_EMAIL_PASSWORD_ENABLED=true and restart … The boot continues.`, then `✓ Server is ready`. - `/sign-in/email` → `400 EMAIL_PASSWORD_DISABLED`. - The recovery boot with `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` logged no such line, and `/sign-in/email` → `200`. </details> <details><summary>Suites, typecheck, lint</summary> - `pnpm exec turbo run build --filter='!@objectstack/docs' --concurrency=3` → `VERDICT command-exit 0`, 119/119 tasks. - `pnpm --filter @objectstack/plugin-auth test` → `VERDICT command-exit 0`; Test Files 224 passed (224), Tests 3967 passed, 10 skipped (3977). - `pnpm --filter @objectstack/plugin-auth typecheck` → `VERDICT command-exit 0` (`check:test-typecheck: OK`, debt ledger unchanged). - `src/sign-in-method-floor.test.ts` alone → 35/35. - `pnpm lint` → `VERDICT command-exit 0`. </details> <details><summary>Full dogfood battery (owed by the narrowing arm)</summary> `pnpm --filter @objectstack/dogfood test` (no shard, no path), after the whole-workspace build above → `VERDICT command-exit 0`, held the lock 33m24s. Test Files 419 passed, 3 skipped (422). Tests 3492 passed, 36 skipped (3528). No failure. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 95 commands on `385ecdcc`. Each was run with its exit code recorded before any pipe, and all 95 exited 0. `--ran`: 95 derived, 95 run, 0 NOT-MEASURED, 0 UNRUN. On the pre-merge head `e5f6926f`, two commands were non-zero: - `check:liveness`: main's own red, fixed by #30368 and green after the merge. - `check-plugin-teardown-shape --self-test`: exit 3, its pinned fixture commit missing from the shallow clone. It passed after `git fetch --depth=1` of that commit. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [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: n/a. - [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 (the 维护者速读 block is the maintainers' Chinese summary). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CadeYZeJahkVWxXfYx <!-- signed: domain:server#3 · os-bill · session_01Utp6CadeYZeJahkVWxXfYx --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 648089d commit a93ef3e

8 files changed

Lines changed: 702 additions & 28 deletions

File tree

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(plugin-auth)!: deleting the last identity provider is refused, and a boot that serves no sign-in method says so (#30300)
6+
7+
Clause-②: yes (narrowing) — a request an administrator could make before is now refused: `POST /api/v1/auth/sso/delete-provider` (Setup's "Delete SSO Provider") on the last identity provider, while email and password is off and nothing else signs anyone in, answers `409 DELETE_RESTRICTED` (an existing standard code, the one an organization delete refused for the same reason answers), or `503 SERVICE_UNAVAILABLE` when the provider list cannot be read to tell. No new error code, setting or field. The widening half: `AuthManager` gains `setSsoProviderDeleteFloor()`, marked `@internal`, through which `AuthPlugin` hands it the judge. The boot report is a new `error` log line only; nothing about the boot's outcome changes.
8+
Metadata-protocol: none
9+
Skills-docs: none — no file under `skills/**` teaches deleting an SSO provider or the sign-in boot reports; `content/docs/deployment/self-hosting.mdx` gains "No sign-in method left" with the three doors and the recovery.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped: sys_sso_provider keeps its columns and the delete endpoint keeps its request shape; it now refuses only the delete that leaves no way to sign in. Nothing stored is rewritten, so there is nothing at rest for a migration to rewrite. -->
12+
13+
**BREAKING** accept-set narrowing at `POST /api/v1/auth/sso/delete-provider`: deleting the identity provider that is the last way to sign in is refused, where it was deleted before.
14+
15+
- **Before.** Email and password off, one SSO identity provider registered and nothing else in force. Setup → the provider → "Delete SSO Provider": `200 {"success":true}`, the row gone. From then on nobody could sign in, the administrator included (measured on a real boot).
16+
- **Now.** That delete answers `409` with `code: DELETE_RESTRICTED`, `lastSignInMethod: enterprise_sso`, and a message in the caller's language (en, zh-CN, ja-JP, es-ES) saying to turn email and password back on, or register another identity provider or set up another sign-in method, first. Nothing is deleted. When the provider list cannot be read to tell, it answers `503 SERVICE_UNAVAILABLE` instead of letting the delete through.
17+
- **Still allowed.** Deleting a provider while another one remains, while email and password is on, while enterprise SSO is switched off, or while another way in counts: a social or OIDC provider with a client ID and secret, phone-number sign-in, or a host sign-in handoff. An unknown provider is still the vendor's `404`, and a caller with no session the vendor's `401`; the vendor's own provider-access check still decides who may delete which provider.
18+
- **The redeploy door.** A boot whose configuration no longer declares the last way in (for example a redeploy without the `GOOGLE_CLIENT_*` pair while email and password is off) still boots, as before, and now reports at `error` under the grep token `no_sign_in_method_at_boot`, naming the consequence and the recovery. It is a positive claim only: a provider table that cannot be read says nothing. Refusing such a boot is a later option, not done: a deployment that signs people in through a door the auth plugin cannot see must keep starting.
19+
- **Already locked out.** Set `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` and restart: the environment override wins over a stored `auth.email_password_enabled = false` and over the stack config, and email and password sign-in comes back.

‎content/docs/deployment/self-hosting.mdx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,28 @@ logins too, or leave the directory empty until the first administrator exists.
628628
A deployment that boots with zero human rows is the case both paths above
629629
describe, and it needs none of this.
630630

631+
### No sign-in method left
632+
633+
Accounts are not enough if nothing serves a way to use them. With email and
634+
password sign-in off, the deployment depends on its other sign-in methods: a
635+
social or OIDC provider with a client ID and secret, enterprise SSO with at
636+
least one registered identity provider, phone-number sign-in, or a host
637+
sign-in handoff. Three doors used to remove the last of them without a word;
638+
each now answers:
639+
640+
| Door | What happens now |
641+
|:---|:---|
642+
| The auth settings save turns email and password off, or removes Google, leaving nothing | Refused `400 SETTINGS_VALIDATION` at the field |
643+
| Setup's **Delete SSO Provider** on the last identity provider (`POST /api/v1/auth/sso/delete-provider`) | Refused `409 DELETE_RESTRICTED`, nothing deleted; `503 SERVICE_UNAVAILABLE` when the provider list cannot be read to tell |
644+
| A redeploy whose configuration no longer declares the last provider (for example, without the `GOOGLE_CLIENT_*` pair) | Boots, and reports at **error** under the grep token `no_sign_in_method_at_boot` |
645+
646+
The boot is not refused: a deployment that signs people in through a door the
647+
auth plugin cannot see keeps starting. **Recovery:** set
648+
`OS_AUTH_EMAIL_PASSWORD_ENABLED=true` and restart. The environment override
649+
wins over a stored `auth.email_password_enabled = false` and over the stack
650+
config, and email and password sign-in comes back. Or restore the sign-in
651+
method the configuration no longer declares.
652+
631653
## Who may sign up — and what each posture tells a stranger
632654

633655
`auth.audience.posture` is the one declaration answering who may become a user

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ export interface AuthInstanceHost {
129129
assertPhoneOtpSendAllowed: AuthManager['assertPhoneOtpSendAllowed'];
130130
assertRemoveMemberPermitted: AuthManager['assertRemoveMemberPermitted'];
131131
assertRevokeSessionIdentifiesRecord: AuthManager['assertRevokeSessionIdentifiesRecord'];
132+
assertSsoProviderDeletable: AuthManager['assertSsoProviderDeletable'];
132133
auditRefusedSignIn: AuthManager['auditRefusedSignIn'];
133134
buildPluginList: AuthManager['buildPluginList'];
134135
composeDatabaseHooks: AuthManager['composeDatabaseHooks'];
@@ -780,6 +781,7 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
780781
assertPhoneOtpSendAllowed: (...a) => this.assertPhoneOtpSendAllowed(...a),
781782
assertRemoveMemberPermitted: (...a) => this.assertRemoveMemberPermitted(...a),
782783
assertRevokeSessionIdentifiesRecord: (...a) => this.assertRevokeSessionIdentifiesRecord(...a),
784+
assertSsoProviderDeletable: (...a) => this.assertSsoProviderDeletable(...a),
783785
get config() { return readConfig(); },
784786
existingAddressSignUpAnswersSuccess: (...a) => this.existingAddressSignUpAnswersSuccess(...a),
785787
hasExistingUserFor: (...a) => this.hasExistingUserFor(...a),

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ import {
7171
} from './last-local-credential.js';
7272
import { ORGANIZATION_DELETE_PATH } from './organization-delete.js';
7373
import { carriesPrincipalSession } from './principal-session-mint.js';
74+
import { SSO_PROVIDER_DELETE_PATH } from './sign-in-method-floor.js';
7475
import { snapshotRoleChangeGrants, UPDATE_MEMBER_ROLE_PATH } from './role-change-granted-set.js';
7576
import { refuseVisitorResendWithoutLiveTransport } from './visitor-verification-resend.js';
7677

@@ -91,6 +92,7 @@ export interface BeforeHookHost {
9192
assertPhoneOtpSendAllowed: AuthManager['assertPhoneOtpSendAllowed'];
9293
assertRemoveMemberPermitted: AuthManager['assertRemoveMemberPermitted'];
9394
assertRevokeSessionIdentifiesRecord: AuthManager['assertRevokeSessionIdentifiesRecord'];
95+
assertSsoProviderDeletable: AuthManager['assertSsoProviderDeletable'];
9496
readonly config: AuthManager['config'];
9597
existingAddressSignUpAnswersSuccess: AuthManager['existingAddressSignUpAnswersSuccess'];
9698
hasExistingUserFor: AuthManager['hasExistingUserFor'];
@@ -308,6 +310,17 @@ export async function globalBeforeHook(
308310
// fall through — the vendor's own provider-access check still runs
309311
}
310312

313+
// ── [#30300] nor delete the last way to sign in ───────────────────
314+
// With email and password off and one identity provider as the only
315+
// other way in, Setup's "Delete SSO Provider" answered 200 and nobody
316+
// could sign in again (measured on a real boot). Asked after the
317+
// held-caller refusal above and before the vendor's first write; the
318+
// sign-in method floor decides (`sign-in-method-floor.ts`).
319+
if (ctx?.path === SSO_PROVIDER_DELETE_PATH) {
320+
await this.assertSsoProviderDeletable(ctx);
321+
// fall through — the vendor's own provider-access check still runs
322+
}
323+
311324
// ── ADR-0135 D6 + ADR-0068 D4: registering an identity provider is ──
312325
// a PLATFORM-OPERATOR action.
313326
//

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import type { TenancyService } from './tenancy-service.js';
8282
import { OtpSendGuard, assertOtpCooldownSeconds } from './otp-send-guard.js';
8383
import { assertPasswordResetEndsSessions } from './password-reset-ends-sessions.js';
8484
import type { CounterStore } from './rate-limit-storage.js';
85+
import type { SsoProviderDeleteRefusal } from './sign-in-method-floor.js';
8586
import {
8687
applyUserBan,
8788
applyUserUnban,
@@ -1588,6 +1589,22 @@ export class AuthManager {
15881589
setOrganizationDeleteStandingJudge(judge: (organizationId: string) => Promise<void>): void {
15891590
this.organizationDeleteStandingJudge = judge;
15901591
}
1592+
1593+
/**
1594+
* [#30300] The sign-in method floor's question about an identity-provider
1595+
* delete (`sign-in-method-floor.ts` `ssoProviderDeleteRefusal`), handed over
1596+
* by `AuthPlugin`, which holds what the floor reads beyond this manager (the
1597+
* host's sign-in handoff, the boot's provider credentials). Absent on a
1598+
* manager no plugin composed, where nothing judges the delete.
1599+
*/
1600+
private ssoProviderDeleteFloor?: (providerId: string, locale?: string) => Promise<SsoProviderDeleteRefusal | undefined>;
1601+
1602+
/** @internal [#30300] See {@link ssoProviderDeleteFloor}; called by `AuthPlugin`. */
1603+
setSsoProviderDeleteFloor(
1604+
judge: (providerId: string, locale?: string) => Promise<SsoProviderDeleteRefusal | undefined>,
1605+
): void {
1606+
this.ssoProviderDeleteFloor = judge;
1607+
}
15911608
// ADR-0069 — cached "does any org require MFA" flag (per-org tightening).
15921609
// Refreshed lazily with a TTL so isAuthGateActive() stays synchronous + cheap.
15931610
private _orgMfaCache: { value: boolean; at: number } = { value: false, at: 0 };
@@ -1744,6 +1761,7 @@ export class AuthManager {
17441761
assertPhoneOtpSendAllowed: (...a) => this.assertPhoneOtpSendAllowed(...a),
17451762
assertRemoveMemberPermitted: (...a) => this.assertRemoveMemberPermitted(...a),
17461763
assertRevokeSessionIdentifiesRecord: (...a) => this.assertRevokeSessionIdentifiesRecord(...a),
1764+
assertSsoProviderDeletable: (...a) => this.assertSsoProviderDeletable(...a),
17471765
auditRefusedSignIn: (...a) => this.auditRefusedSignIn(...a),
17481766
buildPluginList: (...a) => this.buildPluginList(...a),
17491767
composeDatabaseHooks: (...a) => this.composeDatabaseHooks(...a),
@@ -5044,6 +5062,35 @@ export class AuthManager {
50445062
return assertOrganizationDeletable.call(host, ctx);
50455063
}
50465064

5065+
/**
5066+
* [#30300] `/sso/delete-provider` admission: refuse the delete that would
5067+
* remove the last way to sign in, before the vendor deletes anything
5068+
* ({@link ssoProviderDeleteFloor} decides; `409 DELETE_RESTRICTED`, or `503
5069+
* SERVICE_UNAVAILABLE` when the provider list cannot be read). Asked only of
5070+
* an authenticated caller with a `providerId`: what the vendor itself answers
5071+
* (no session, a malformed body) falls through to it. The refusal states a
5072+
* deployment-wide fact `/auth/config` already publishes (email and password
5073+
* off, what else signs anyone in), so it is not held back for a caller the
5074+
* vendor would refuse as not the provider's owner.
5075+
*/
5076+
private async assertSsoProviderDeletable(ctx: any): Promise<void> {
5077+
const judge = this.ssoProviderDeleteFloor;
5078+
if (!judge) return;
5079+
const providerId = typeof ctx?.body?.providerId === 'string' ? ctx.body.providerId : '';
5080+
if (!providerId) return;
5081+
const actor = await this.resolveActor(ctx);
5082+
if (!actor?.userId) return;
5083+
const header = acceptLanguageHeader(ctx);
5084+
const refusal = await judge(providerId, header ? preferredLocaleFromHeader(header) : undefined);
5085+
if (!refusal) return;
5086+
const { APIError } = await import('better-auth/api');
5087+
throw new APIError(refusal.status, {
5088+
code: refusal.code,
5089+
message: refusal.message,
5090+
lastSignInMethod: refusal.lastSignInMethod,
5091+
});
5092+
}
5093+
50475094
private assertRemoveMemberPermitted(ctx: any): Promise<void> {
50485095
// [#25224 cut 1] The body moved to `auth-manager-actor-guards.ts` (see `ActorGuardHost`).
50495096
const readOrgRolesMap = () => this.orgRolesMap;

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

Lines changed: 57 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,14 @@ import {
110110
reportIfNoSignInAccountExists,
111111
type SignInPathConfigView,
112112
} from './boot-sign-in-reachability.js';
113-
import { providerCredentialIndex, providerCredentialsFrom, registerSignInMethodFloor } from './sign-in-method-floor.js';
113+
import {
114+
providerCredentialIndex,
115+
providerCredentialsFrom,
116+
registerSignInMethodFloor,
117+
reportIfNoSignInMethodAtBoot,
118+
ssoProviderDeleteRefusal,
119+
type SignInMethodFloorDeps,
120+
} from './sign-in-method-floor.js';
114121
import { judgePlatformAdmin, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
115122
import {
116123
decideDemoStaffEnvironmentGate,
@@ -800,6 +807,12 @@ export class AuthPlugin implements Plugin {
800807
// ADR-0092 D6 — remember the storage better-auth will actually use so the
801808
// identity write guard can keep cached session snapshots coherent.
802809
this.effectiveSecondaryStorage = authConfig.secondaryStorage;
810+
// [#30300] Deleting the last identity provider is judged by the same
811+
// sign-in method floor as the auth settings save (`sign-in-method-floor.ts`).
812+
const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager);
813+
this.authManager.setSsoProviderDeleteFloor((providerId, locale) =>
814+
ssoProviderDeleteRefusal(floorDeps, providerId, locale),
815+
);
803816

804817
// Register auth service
805818
ctx.registerService('auth', this.authManager);
@@ -1509,6 +1522,23 @@ export class AuthPlugin implements Plugin {
15091522
ctx.logger,
15101523
);
15111524
}
1525+
1526+
// [#30300, ruling A] "Is there ANY way to sign in?" — the question the
1527+
// account report above does not ask: a redeploy that drops the last
1528+
// identity provider while email and password is off boots a deployment
1529+
// that serves no sign-in method at all, and said nothing. Said at
1530+
// `error` in every posture, NEVER refused: a platform-SSO tenant that
1531+
// signs in through a door this plugin cannot see must keep booting.
1532+
// Judged after the auth settings are applied, by the same floor as the
1533+
// settings save (`sign-in-method-floor.ts`).
1534+
if (this.authManager) {
1535+
try {
1536+
await this.ensureAuthSettingsBound(ctx);
1537+
} catch {
1538+
// The binding reports its own failure; judge what is in force.
1539+
}
1540+
await reportIfNoSignInMethodAtBoot(this.signInMethodFloorDeps(ctx, this.authManager), ctx.logger);
1541+
}
15121542
});
15131543

15141544
// Dev-only: provision a known, loginable platform admin on an empty DB.
@@ -2013,6 +2043,31 @@ export class AuthPlugin implements Plugin {
20132043
return this.authSettingsBinding;
20142044
}
20152045

2046+
/**
2047+
* [#30202, #30300] The facts the sign-in method floor reads, live: the
2048+
* manager's advertisement, the data engine `sys_sso_provider` is read from,
2049+
* the host handoff declaration, and the boot credential index. One builder
2050+
* for the three doors that judge by it — the auth settings save, the delete
2051+
* of an identity provider, and the boot report — so they cannot drift apart.
2052+
*/
2053+
private signInMethodFloorDeps(ctx: PluginContext, manager: AuthManager): SignInMethodFloorDeps {
2054+
return {
2055+
publicConfig: () => manager.getPublicConfig(),
2056+
engine: () => {
2057+
try {
2058+
return ctx.getService<IDataEngine>('objectql');
2059+
} catch {
2060+
return undefined;
2061+
}
2062+
},
2063+
hostSignInHandoff: this.options.hostSignInHandoff === true,
2064+
stackConfiguredGoogle: () => !!this.configuredSocialProviders?.google,
2065+
// Read when judged: the index is set in init, after `auth:configure`.
2066+
providerHasCredentials: (provider) => providerCredentialsFrom(this.bootProviderCredentials)(provider),
2067+
env: () => ((globalThis as any)?.process?.env ?? {}) as Record<string, string | undefined>,
2068+
};
2069+
}
2070+
20162071
/**
20172072
* [#23367, ruling A] Record the API-key lifecycle policy's landing — the
20182073
* anchor of the inactivity clock for keys with no recorded use, and of the
@@ -2086,26 +2141,7 @@ export class AuthPlugin implements Plugin {
20862141

20872142
// The save door refuses turning off the last sign-in method, before the
20882143
// value is stored; the pass below would only apply it. See the module.
2089-
const floorManager = this.authManager;
2090-
registerSignInMethodFloor(
2091-
settings,
2092-
{
2093-
publicConfig: () => floorManager.getPublicConfig(),
2094-
engine: () => {
2095-
try {
2096-
return ctx.getService<IDataEngine>('objectql');
2097-
} catch {
2098-
return undefined;
2099-
}
2100-
},
2101-
hostSignInHandoff: this.options.hostSignInHandoff === true,
2102-
stackConfiguredGoogle: () => !!this.configuredSocialProviders?.google,
2103-
// Read at save time: the index is set in init, after `auth:configure`.
2104-
providerHasCredentials: (provider) => providerCredentialsFrom(this.bootProviderCredentials)(provider),
2105-
env: () => ((globalThis as any)?.process?.env ?? {}) as Record<string, string | undefined>,
2106-
},
2107-
ctx.logger,
2108-
);
2144+
registerSignInMethodFloor(settings, this.signInMethodFloorDeps(ctx, this.authManager), ctx.logger);
21092145

21102146
const applySettings = async (): Promise<void> => {
21112147
if (!this.authManager) return;

0 commit comments

Comments
 (0)