|
| 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