Skip to content

Commit d23dd1b

Browse files
committed
fix(plugin-auth): keep the last way to sign in on provider delete and say a boot without one
Deleting the last identity provider while email and password is off is refused in the global before-hook (409 DELETE_RESTRICTED, 503 when the provider list cannot be read), judged by the sign-in method floor. A boot that serves no sign-in method says no_sign_in_method_at_boot at error and still boots. Claude-Session: https://claude.ai/code/session_01Utp6CadeYZeJahkVWxXfYx Co-authored-by: Claude <noreply@anthropic.com>
1 parent 870ebce commit d23dd1b

6 files changed

Lines changed: 668 additions & 25 deletions

File tree

‎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,
@@ -1552,6 +1553,22 @@ export class AuthManager {
15521553
setOrganizationDeleteStandingJudge(judge: (organizationId: string) => Promise<void>): void {
15531554
this.organizationDeleteStandingJudge = judge;
15541555
}
1556+
1557+
/**
1558+
* [#30300] The sign-in method floor's question about an identity-provider
1559+
* delete (`sign-in-method-floor.ts` `ssoProviderDeleteRefusal`), handed over
1560+
* by `AuthPlugin`, which holds what the floor reads beyond this manager (the
1561+
* host's sign-in handoff, the boot's provider credentials). Absent on a
1562+
* manager no plugin composed, where nothing judges the delete.
1563+
*/
1564+
private ssoProviderDeleteFloor?: (providerId: string, locale?: string) => Promise<SsoProviderDeleteRefusal | undefined>;
1565+
1566+
/** @internal [#30300] See {@link ssoProviderDeleteFloor}; called by `AuthPlugin`. */
1567+
setSsoProviderDeleteFloor(
1568+
judge: (providerId: string, locale?: string) => Promise<SsoProviderDeleteRefusal | undefined>,
1569+
): void {
1570+
this.ssoProviderDeleteFloor = judge;
1571+
}
15551572
// ADR-0069 — cached "does any org require MFA" flag (per-org tightening).
15561573
// Refreshed lazily with a TTL so isAuthGateActive() stays synchronous + cheap.
15571574
private _orgMfaCache: { value: boolean; at: number } = { value: false, at: 0 };
@@ -1708,6 +1725,7 @@ export class AuthManager {
17081725
assertPhoneOtpSendAllowed: (...a) => this.assertPhoneOtpSendAllowed(...a),
17091726
assertRemoveMemberPermitted: (...a) => this.assertRemoveMemberPermitted(...a),
17101727
assertRevokeSessionIdentifiesRecord: (...a) => this.assertRevokeSessionIdentifiesRecord(...a),
1728+
assertSsoProviderDeletable: (...a) => this.assertSsoProviderDeletable(...a),
17111729
auditRefusedSignIn: (...a) => this.auditRefusedSignIn(...a),
17121730
buildPluginList: (...a) => this.buildPluginList(...a),
17131731
composeDatabaseHooks: (...a) => this.composeDatabaseHooks(...a),
@@ -4998,6 +5016,35 @@ export class AuthManager {
49985016
return assertOrganizationDeletable.call(host, ctx);
49995017
}
50005018

5019+
/**
5020+
* [#30300] `/sso/delete-provider` admission: refuse the delete that would
5021+
* remove the last way to sign in, before the vendor deletes anything
5022+
* ({@link ssoProviderDeleteFloor} decides; `409 DELETE_RESTRICTED`, or `503
5023+
* SERVICE_UNAVAILABLE` when the provider list cannot be read). Asked only of
5024+
* an authenticated caller with a `providerId`: what the vendor itself answers
5025+
* (no session, a malformed body) falls through to it. The refusal states a
5026+
* deployment-wide fact `/auth/config` already publishes (email and password
5027+
* off, what else signs anyone in), so it is not held back for a caller the
5028+
* vendor would refuse as not the provider's owner.
5029+
*/
5030+
private async assertSsoProviderDeletable(ctx: any): Promise<void> {
5031+
const judge = this.ssoProviderDeleteFloor;
5032+
if (!judge) return;
5033+
const providerId = typeof ctx?.body?.providerId === 'string' ? ctx.body.providerId : '';
5034+
if (!providerId) return;
5035+
const actor = await this.resolveActor(ctx);
5036+
if (!actor?.userId) return;
5037+
const header = acceptLanguageHeader(ctx);
5038+
const refusal = await judge(providerId, header ? preferredLocaleFromHeader(header) : undefined);
5039+
if (!refusal) return;
5040+
const { APIError } = await import('better-auth/api');
5041+
throw new APIError(refusal.status, {
5042+
code: refusal.code,
5043+
message: refusal.message,
5044+
lastSignInMethod: refusal.lastSignInMethod,
5045+
});
5046+
}
5047+
50015048
private assertRemoveMemberPermitted(ctx: any): Promise<void> {
50025049
// [#25224 cut 1] The body moved to `auth-manager-actor-guards.ts` (see `ActorGuardHost`).
50035050
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
@@ -109,7 +109,14 @@ import {
109109
reportIfNoSignInAccountExists,
110110
type SignInPathConfigView,
111111
} from './boot-sign-in-reachability.js';
112-
import { providerCredentialIndex, providerCredentialsFrom, registerSignInMethodFloor } from './sign-in-method-floor.js';
112+
import {
113+
providerCredentialIndex,
114+
providerCredentialsFrom,
115+
registerSignInMethodFloor,
116+
reportIfNoSignInMethodAtBoot,
117+
ssoProviderDeleteRefusal,
118+
type SignInMethodFloorDeps,
119+
} from './sign-in-method-floor.js';
113120
import { judgePlatformAdmin, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
114121
import {
115122
decideDemoStaffEnvironmentGate,
@@ -799,6 +806,12 @@ export class AuthPlugin implements Plugin {
799806
// ADR-0092 D6 — remember the storage better-auth will actually use so the
800807
// identity write guard can keep cached session snapshots coherent.
801808
this.effectiveSecondaryStorage = authConfig.secondaryStorage;
809+
// [#30300] Deleting the last identity provider is judged by the same
810+
// sign-in method floor as the auth settings save (`sign-in-method-floor.ts`).
811+
const floorDeps = this.signInMethodFloorDeps(ctx, this.authManager);
812+
this.authManager.setSsoProviderDeleteFloor((providerId, locale) =>
813+
ssoProviderDeleteRefusal(floorDeps, providerId, locale),
814+
);
802815

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

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

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

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

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

0 commit comments

Comments
 (0)