Skip to content

Commit 850f14e

Browse files
committed
fix(plugin-auth): the auth settings save refuses turning off the last sign-in method
Turning email and password off while no other sign-in method is in force used to save, and the next sign-out locked everyone out. The plugin now registers write predicates on the settings service for email_password_enabled and the Google keys, so such a save is refused before anything is written, with a localized reason naming what to set up first. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CXhZcHuALPAjkDCiiT
1 parent 5fa9375 commit 850f14e

4 files changed

Lines changed: 617 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): saving the auth settings refuses to turn off the last way to sign in (#30202)
6+
7+
Clause-②: no (narrowing) — a save an administrator could make before is now refused at the settings save door with the existing `SETTINGS_VALIDATION` / `invalid_value` field error: email and password off while nothing else signs anyone in, and, while email and password is already off, the Google change that removes the last provider. No new error code, export or settings key. Nothing is widened.
8+
Metadata-protocol: none
9+
Skills-docs: none — no file under `skills/**` teaches `auth.email_password_enabled`; `content/docs/deployment/environment-variables.mdx` already names the `OS_AUTH_EMAIL_PASSWORD_ENABLED` override used for recovery below.
10+
11+
- **Before.** Setup → Settings → Authentication, "Enable email/password login" off, save: "Settings saved", with no social provider and SSO off. After the next sign-out nobody could sign in, the administrator included.
12+
- **Now.** `PUT /api/settings/auth` with `email_password_enabled: false` answers `400 SETTINGS_VALIDATION`, with a field error at `email_password_enabled` (`code: invalid_value`, `constraint.lastSignInMethod: email_password`) whose message, in the caller's language (en, zh-CN, ja-JP, es-ES), says to set up and save another sign-in method first. Nothing in that batch is written, and email and password stays on.
13+
- **What counts as another way in.** A social or OIDC provider in force; enterprise SSO switched on with at least one identity provider registered (the switch alone does not count); phone-number sign-in; a host sign-in handoff the host declared. `ssoOnlyMode` alone, magic link and passkeys do not count.
14+
- **The other direction.** While email and password is off, `google_enabled: false`, or clearing `google_client_id` / `google_client_secret` when no environment variable or stack config supplies it, is refused (`constraint.lastSignInMethod: google`) if Google is the last way in.
15+
- **Already locked out.** Set `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` and restart: the environment override wins over the stored `false`, and email and password sign-in comes back. Then set up another method before turning it off again.

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ import {
108108
reportIfNoSignInAccountExists,
109109
type SignInPathConfigView,
110110
} from './boot-sign-in-reachability.js';
111+
import { registerSignInMethodFloor } from './sign-in-method-floor.js';
111112
import { judgePlatformAdmin, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
112113
import {
113114
decideDemoStaffEnvironmentGate,
@@ -2047,6 +2048,27 @@ export class AuthPlugin implements Plugin {
20472048
}
20482049
if (!settings || typeof settings.getNamespace !== 'function') return;
20492050

2051+
// The save door refuses turning off the last sign-in method, before the
2052+
// value is stored; the pass below would only apply it. See the module.
2053+
const floorManager = this.authManager;
2054+
registerSignInMethodFloor(
2055+
settings,
2056+
{
2057+
publicConfig: () => floorManager.getPublicConfig(),
2058+
engine: () => {
2059+
try {
2060+
return ctx.getService<IDataEngine>('objectql');
2061+
} catch {
2062+
return undefined;
2063+
}
2064+
},
2065+
hostSignInHandoff: this.options.hostSignInHandoff === true,
2066+
stackConfiguredGoogle: () => !!this.configuredSocialProviders?.google,
2067+
env: () => ((globalThis as any)?.process?.env ?? {}) as Record<string, string | undefined>,
2068+
},
2069+
ctx.logger,
2070+
);
2071+
20502072
const applySettings = async (): Promise<void> => {
20512073
if (!this.authManager) return;
20522074
const authManager = this.authManager;
Lines changed: 318 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,318 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The auth settings save keeps a way to sign in (`sign-in-method-floor.ts`).
5+
*
6+
* Through the REAL settings service (`@objectstack/service-settings`, aliased
7+
* to its source) and the real `AuthPlugin` / `AuthManager`: the plugin
8+
* registers the write predicates when it binds the `auth` namespace, and a
9+
* save goes through `setMany`, or through the real `PUT /api/settings/:ns`
10+
* route for the envelope. The data engine is a stub that answers
11+
* `sys_sso_provider` reads from the case's rows and `[]` for everything else.
12+
*
13+
* Pinned:
14+
* 1. email and password off with nothing else in force is refused before
15+
* anything is written: the stored value and the runtime stay on, and the
16+
* batch it rode in writes nothing;
17+
* 2. the HTTP door answers 400 `SETTINGS_VALIDATION` with the field error, in
18+
* the caller's language;
19+
* 3. each way in that counts lets it turn off; the SSO switch alone, or an
20+
* unreadable provider table, does not;
21+
* 4. with email and password off, the Google change that removes the last
22+
* provider is refused, and the same change is accepted where something
23+
* else keeps a way in;
24+
* 5. recovery: a stored `false` from before this check is overridden by
25+
* `OS_AUTH_EMAIL_PASSWORD_ENABLED=true` (control: without it, it rules).
26+
*/
27+
28+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
29+
import type { PluginContext } from '@objectstack/core';
30+
import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts';
31+
import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/objectql';
32+
import {
33+
InMemoryCryptoProvider,
34+
SettingsService,
35+
SettingsValidationError,
36+
builtinSettingsManifests,
37+
registerSettingsRoutes,
38+
} from '@objectstack/service-settings';
39+
import { AuthPlugin } from './auth-plugin.js';
40+
import type { AuthManager } from './auth-manager.js';
41+
import { SSO_PROVIDER_OBJECT } from './sso-client-secret.js';
42+
import { SIGN_IN_FLOOR_COPY } from './sign-in-method-floor.js';
43+
44+
const SECRET = 'test-secret-at-least-32-chars-long';
45+
46+
const ENV_KEYS = [
47+
'OS_AUTH_EMAIL_PASSWORD_ENABLED',
48+
'OS_AUTH_GOOGLE_ENABLED',
49+
'GOOGLE_CLIENT_ID',
50+
'GOOGLE_CLIENT_SECRET',
51+
'OS_SSO_ENABLED',
52+
'OS_AUTH_SSO_ONLY',
53+
'OS_SCIM_ENABLED',
54+
] as const;
55+
56+
const GOOGLE = {
57+
google_enabled: true,
58+
google_client_id: 'google-settings-client-id',
59+
google_client_secret: 'google-settings-client-secret',
60+
};
61+
62+
/** The error `setMany` refused with, or a failure naming what happened instead. */
63+
async function refusalOf(write: Promise<unknown>): Promise<SettingsValidationError> {
64+
const outcome = await write.then(
65+
() => undefined,
66+
(err: unknown) => err,
67+
);
68+
expect(outcome, 'the save went through').toBeInstanceOf(SettingsValidationError);
69+
return outcome as SettingsValidationError;
70+
}
71+
72+
describe('the auth settings save keeps a way to sign in', () => {
73+
const saved: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> = {};
74+
let ssoRows: () => Promise<unknown[]>;
75+
76+
beforeEach(() => {
77+
for (const key of ENV_KEYS) {
78+
saved[key] = process.env[key];
79+
delete process.env[key];
80+
}
81+
ssoRows = async () => [];
82+
});
83+
84+
afterEach(() => {
85+
for (const key of ENV_KEYS) {
86+
if (saved[key] === undefined) delete process.env[key];
87+
else process.env[key] = saved[key];
88+
}
89+
});
90+
91+
const makeEngine = () => ({
92+
insert: vi.fn(async (_object: string, row: any) => row),
93+
find: vi.fn(async (object: string) => (object === SSO_PROVIDER_OBJECT ? ssoRows() : [])),
94+
findOne: vi.fn(async (object: string, query?: EngineFindOneQueryInput) => {
95+
assertEngineFindOnePredicate(object, query);
96+
return null;
97+
}),
98+
});
99+
100+
const makeSettings = (env: Record<string, string | undefined> = {}) => {
101+
// A crypto provider, so the Google client secret can be stored.
102+
const settings = new SettingsService({ env, cryptoProvider: new InMemoryCryptoProvider() });
103+
for (const manifest of builtinSettingsManifests) {
104+
if (manifest.namespace === 'auth') settings.registerManifest(manifest);
105+
}
106+
return settings;
107+
};
108+
109+
/** Boot as a host does: init → start → kernel:ready (the auth namespace binds there). */
110+
const boot = async (opts: { settings?: SettingsService; pluginOptions?: Record<string, unknown> } = {}) => {
111+
const settings = opts.settings ?? makeSettings();
112+
const engine = makeEngine();
113+
const hooks = new Map<string, Array<() => Promise<void>>>();
114+
const ctx = {
115+
registerService: vi.fn(),
116+
getService: vi.fn((name: string) => {
117+
if (name === 'manifest') return { register: vi.fn() };
118+
if (name === 'settings') return settings;
119+
if (name === 'data' || name === 'objectql') return engine;
120+
return undefined;
121+
}),
122+
getServices: vi.fn(() => new Map()),
123+
hook: vi.fn((name: string, handler: () => Promise<void>) => {
124+
if (!hooks.has(name)) hooks.set(name, []);
125+
hooks.get(name)!.push(handler);
126+
}),
127+
trigger: vi.fn(),
128+
logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
129+
getKernel: vi.fn(),
130+
} as unknown as PluginContext;
131+
const plugin = new AuthPlugin({ secret: SECRET, baseUrl: 'http://localhost:3000', ...(opts.pluginOptions ?? {}) });
132+
await plugin.init(ctx);
133+
const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager;
134+
await plugin.start(ctx);
135+
for (const handler of hooks.get('kernel:ready') ?? []) await handler();
136+
return { settings, manager };
137+
};
138+
139+
const passwordOn = (manager: AuthManager) => manager.getPublicConfig().emailPassword.enabled;
140+
const googleOn = (manager: AuthManager) =>
141+
manager.getPublicConfig().socialProviders.some((p: { id: string }) => p.id === 'google');
142+
143+
/** Save Google through the console and wait for the pass to apply it. */
144+
const saveGoogle = async (settings: SettingsService, manager: AuthManager) => {
145+
await settings.setMany('auth', GOOGLE);
146+
await vi.waitFor(() => expect(googleOn(manager)).toBe(true));
147+
};
148+
149+
// ── 1 + 2. The refusal ─────────────────────────────────────────────────────
150+
151+
it('refuses email and password off when nothing else signs anyone in; nothing in the batch is written', async () => {
152+
const { settings, manager } = await boot();
153+
154+
const refusal = await refusalOf(
155+
settings.setMany('auth', { email_password_enabled: false, password_min_length: 12 }),
156+
);
157+
expect(refusal.code).toBe('SETTINGS_VALIDATION');
158+
expect(refusal.fields).toEqual([
159+
expect.objectContaining({
160+
field: 'email_password_enabled',
161+
code: 'invalid_value',
162+
constraint: { lastSignInMethod: 'email_password' },
163+
}),
164+
]);
165+
166+
expect(await settings.get('auth', 'email_password_enabled')).toMatchObject({ value: true, source: 'default' });
167+
expect(await settings.get('auth', 'password_min_length')).toMatchObject({ source: 'default' });
168+
expect(passwordOn(manager)).toBe(true);
169+
// Turning it back on, or saving the value in force, is never refused.
170+
await expect(settings.setMany('auth', { email_password_enabled: true })).resolves.toBeDefined();
171+
});
172+
173+
it('the settings PUT door answers 400 SETTINGS_VALIDATION at the key, in the caller language', async () => {
174+
const { settings, manager } = await boot();
175+
const routes = new Map<string, RouteHandler>();
176+
const add = (method: string) => (path: string, handler: RouteHandler) => {
177+
routes.set(`${method} ${path}`, handler);
178+
return http;
179+
};
180+
const http = {
181+
get: add('GET'),
182+
post: add('POST'),
183+
put: add('PUT'),
184+
delete: add('DELETE'),
185+
patch: add('PATCH'),
186+
use: () => http,
187+
listen: async () => {},
188+
close: async () => {},
189+
getInstance: () => null,
190+
} as unknown as IHttpServer;
191+
registerSettingsRoutes(http, settings, {
192+
contextFromRequest: () => ({ enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }),
193+
});
194+
195+
const state: { status: number; body?: any } = { status: 200 };
196+
const res = {
197+
json: vi.fn((data: unknown) => {
198+
state.body = data;
199+
}),
200+
send: vi.fn(),
201+
status: vi.fn((code: number) => {
202+
state.status = code;
203+
return res;
204+
}),
205+
header: vi.fn(() => res),
206+
} as unknown as IHttpResponse;
207+
const req = {
208+
params: { namespace: 'auth' },
209+
query: {},
210+
body: { email_password_enabled: false },
211+
headers: { 'accept-language': 'zh-CN,zh;q=0.9' },
212+
method: 'PUT',
213+
path: '/api/settings/auth',
214+
} as unknown as IHttpRequest;
215+
await routes.get('PUT /api/settings/:namespace')!(req, res);
216+
217+
expect(state.status).toBe(400);
218+
expect(state.body.error.code).toBe('SETTINGS_VALIDATION');
219+
const [field] = state.body.error.details.fields;
220+
expect(field).toMatchObject({ field: 'email_password_enabled', code: 'invalid_value' });
221+
expect(field.message).toBe(SIGN_IN_FLOOR_COPY['zh-CN'].emailPassword);
222+
expect(passwordOn(manager)).toBe(true);
223+
});
224+
225+
// ── 3. What counts ─────────────────────────────────────────────────────────
226+
227+
const COUNTED: Array<{ name: string; pluginOptions: Record<string, unknown>; rows?: unknown[] }> = [
228+
{ name: 'a social provider in the stack config', pluginOptions: { socialProviders: { github: { clientId: 'gh-id', clientSecret: 'gh-secret' } } } },
229+
{ name: 'phone-number sign-in', pluginOptions: { plugins: { phoneNumber: true } } },
230+
{ name: 'a host sign-in handoff', pluginOptions: { hostSignInHandoff: true } },
231+
{ name: 'enterprise SSO with an identity provider registered', pluginOptions: { plugins: { sso: true } }, rows: [{ id: 'sso_1' }] },
232+
];
233+
234+
it.each(COUNTED)('$name lets email and password turn off', async ({ pluginOptions, rows = [] }) => {
235+
ssoRows = async () => rows;
236+
const { settings, manager } = await boot({ pluginOptions });
237+
238+
await settings.setMany('auth', { email_password_enabled: false });
239+
await vi.waitFor(() => expect(passwordOn(manager)).toBe(false));
240+
});
241+
242+
it('Google saved on the same page first lets email and password turn off', async () => {
243+
const { settings, manager } = await boot();
244+
await saveGoogle(settings, manager);
245+
246+
await settings.setMany('auth', { email_password_enabled: false });
247+
await vi.waitFor(() => expect(passwordOn(manager)).toBe(false));
248+
});
249+
250+
it('the SSO switch with no identity provider registered, or an unreadable provider table, does not count', async () => {
251+
const { settings, manager } = await boot({ pluginOptions: { plugins: { sso: true } } });
252+
await refusalOf(settings.setMany('auth', { email_password_enabled: false }));
253+
254+
ssoRows = async () => {
255+
throw new Error('store unavailable');
256+
};
257+
await refusalOf(settings.setMany('auth', { email_password_enabled: false }));
258+
expect(passwordOn(manager)).toBe(true);
259+
});
260+
261+
// ── 4. The last provider, while email and password is off ─────────────────
262+
263+
it('refuses removing Google when it is the last way in: switched off, or a credential cleared', async () => {
264+
const { settings, manager } = await boot();
265+
await saveGoogle(settings, manager);
266+
await settings.setMany('auth', { email_password_enabled: false });
267+
await vi.waitFor(() => expect(passwordOn(manager)).toBe(false));
268+
269+
for (const patch of [{ google_enabled: false }, { google_client_secret: null }, { google_client_id: '' }]) {
270+
const refusal = await refusalOf(settings.setMany('auth', patch));
271+
expect(refusal.fields).toEqual([
272+
expect.objectContaining({ code: 'invalid_value', constraint: { lastSignInMethod: 'google' } }),
273+
]);
274+
}
275+
expect(googleOn(manager)).toBe(true);
276+
277+
// With email and password back on, Google may go.
278+
await settings.setMany('auth', { email_password_enabled: true });
279+
await vi.waitFor(() => expect(passwordOn(manager)).toBe(true));
280+
await settings.setMany('auth', { google_enabled: false });
281+
await vi.waitFor(() => expect(googleOn(manager)).toBe(false));
282+
});
283+
284+
it('accepts the same Google change where something else keeps a way in, or the env still supplies it', async () => {
285+
const withGithub = await boot({
286+
pluginOptions: { socialProviders: { github: { clientId: 'gh-id', clientSecret: 'gh-secret' } } },
287+
});
288+
await saveGoogle(withGithub.settings, withGithub.manager);
289+
await withGithub.settings.setMany('auth', { email_password_enabled: false });
290+
await vi.waitFor(() => expect(passwordOn(withGithub.manager)).toBe(false));
291+
await withGithub.settings.setMany('auth', { google_enabled: false });
292+
await vi.waitFor(() => expect(googleOn(withGithub.manager)).toBe(false));
293+
294+
// A cleared secret the env variable still supplies removes nothing.
295+
const alone = await boot();
296+
await saveGoogle(alone.settings, alone.manager);
297+
await alone.settings.setMany('auth', { email_password_enabled: false });
298+
await vi.waitFor(() => expect(passwordOn(alone.manager)).toBe(false));
299+
process.env.GOOGLE_CLIENT_SECRET = 'google-env-client-secret';
300+
await alone.settings.setMany('auth', { google_client_secret: null });
301+
expect(googleOn(alone.manager)).toBe(true);
302+
});
303+
304+
// ── 5. Recovery for a deployment that already stored the dead end ─────────
305+
306+
it('OS_AUTH_EMAIL_PASSWORD_ENABLED=true overrides a stored false (control: without it, the stored false rules)', async () => {
307+
// The pre-fix save: written before any predicate is registered.
308+
const lockedOut = makeSettings();
309+
await lockedOut.setMany('auth', { email_password_enabled: false });
310+
expect(passwordOn((await boot({ settings: lockedOut })).manager)).toBe(false);
311+
312+
const env: Record<string, string | undefined> = {};
313+
const recovered = makeSettings(env);
314+
await recovered.setMany('auth', { email_password_enabled: false });
315+
env.OS_AUTH_EMAIL_PASSWORD_ENABLED = 'true';
316+
expect(passwordOn((await boot({ settings: recovered })).manager)).toBe(true);
317+
});
318+
});

0 commit comments

Comments
 (0)