|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The global `auth.mfa_required` switch cannot be saved on while |
| 5 | + * `OS_AUTH_TWO_FACTOR` pins enrollment off (`mfa-required-enrollment-predicate.ts`). |
| 6 | + * |
| 7 | + * Through the REAL settings service (`@objectstack/service-settings`) and the |
| 8 | + * real `AuthPlugin` / `AuthManager`: the plugin registers the predicate when it |
| 9 | + * binds the `auth` namespace, and a save goes through `setMany`, or through the |
| 10 | + * real `PUT /api/settings/:ns` route for the envelope. No data engine is |
| 11 | + * composed; the settings service keeps its in-memory store. |
| 12 | + * |
| 13 | + * Pinned: |
| 14 | + * 1. under `OS_AUTH_TWO_FACTOR=false`, turning the switch on is refused |
| 15 | + * before anything is written: the stored value, the batch it rode in, the |
| 16 | + * runtime requirement and `features.twoFactor` all stay as they were; |
| 17 | + * 2. the HTTP door answers 400 `SETTINGS_VALIDATION` at the key, in the |
| 18 | + * caller's language; |
| 19 | + * 3. controls: with the env var unset or on, the same save is accepted and |
| 20 | + * the pass turns the requirement and enrollment on; turning it off is |
| 21 | + * never refused; |
| 22 | + * 4. a switch stored on before the check is not re-judged: saving it again |
| 23 | + * passes, and the gate's own reading stays off. |
| 24 | + */ |
| 25 | + |
| 26 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 27 | +import type { PluginContext } from '@objectstack/core'; |
| 28 | +import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts'; |
| 29 | +import { |
| 30 | + SettingsService, |
| 31 | + SettingsValidationError, |
| 32 | + builtinSettingsManifests, |
| 33 | + registerSettingsRoutes, |
| 34 | +} from '@objectstack/service-settings'; |
| 35 | +import { AuthPlugin } from './auth-plugin.js'; |
| 36 | +import type { AuthManager } from './auth-manager.js'; |
| 37 | +import { |
| 38 | + MFA_REQUIRED_ENROLLMENT_COPY, |
| 39 | + mfaRequiredEnrollmentPredicate, |
| 40 | + registerMfaRequiredEnrollmentPredicate, |
| 41 | +} from './mfa-required-enrollment-predicate.js'; |
| 42 | + |
| 43 | +const SECRET = 'test-secret-at-least-32-chars-long'; |
| 44 | +const ENV = 'OS_AUTH_TWO_FACTOR'; |
| 45 | + |
| 46 | +/** The error `setMany` refused with, or a failure naming what happened instead. */ |
| 47 | +async function refusalOf(write: Promise<unknown>): Promise<SettingsValidationError> { |
| 48 | + const outcome = await write.then( |
| 49 | + () => undefined, |
| 50 | + (err: unknown) => err, |
| 51 | + ); |
| 52 | + expect(outcome, 'the save went through').toBeInstanceOf(SettingsValidationError); |
| 53 | + return outcome as SettingsValidationError; |
| 54 | +} |
| 55 | + |
| 56 | +describe('the global mfa_required switch needs two-factor enrollment', () => { |
| 57 | + let saved: string | undefined; |
| 58 | + |
| 59 | + beforeEach(() => { |
| 60 | + saved = process.env[ENV]; |
| 61 | + delete process.env[ENV]; |
| 62 | + }); |
| 63 | + |
| 64 | + afterEach(() => { |
| 65 | + if (saved === undefined) delete process.env[ENV]; |
| 66 | + else process.env[ENV] = saved; |
| 67 | + }); |
| 68 | + |
| 69 | + const makeSettings = () => { |
| 70 | + const settings = new SettingsService({ env: {} }); |
| 71 | + for (const manifest of builtinSettingsManifests) { |
| 72 | + if (manifest.namespace === 'auth') settings.registerManifest(manifest); |
| 73 | + } |
| 74 | + return settings; |
| 75 | + }; |
| 76 | + |
| 77 | + /** Boot as a host does: init → start → kernel:ready (the auth namespace binds there). */ |
| 78 | + const boot = async (settings: SettingsService = makeSettings()) => { |
| 79 | + const hooks = new Map<string, Array<() => Promise<void>>>(); |
| 80 | + const warn = vi.fn(); |
| 81 | + const ctx = { |
| 82 | + registerService: vi.fn(), |
| 83 | + getService: vi.fn((name: string) => { |
| 84 | + if (name === 'manifest') return { register: vi.fn() }; |
| 85 | + if (name === 'settings') return settings; |
| 86 | + return undefined; |
| 87 | + }), |
| 88 | + getServices: vi.fn(() => new Map()), |
| 89 | + hook: vi.fn((name: string, handler: () => Promise<void>) => { |
| 90 | + if (!hooks.has(name)) hooks.set(name, []); |
| 91 | + hooks.get(name)!.push(handler); |
| 92 | + }), |
| 93 | + trigger: vi.fn(), |
| 94 | + logger: { info: vi.fn(), error: vi.fn(), warn, debug: vi.fn() }, |
| 95 | + getKernel: vi.fn(), |
| 96 | + } as unknown as PluginContext; |
| 97 | + const plugin = new AuthPlugin({ secret: SECRET, baseUrl: 'http://localhost:3000' }); |
| 98 | + await plugin.init(ctx); |
| 99 | + const manager = (ctx.registerService as any).mock.calls.find(([name]: [string]) => name === 'auth')?.[1] as AuthManager; |
| 100 | + await plugin.start(ctx); |
| 101 | + for (const handler of hooks.get('kernel:ready') ?? []) await handler(); |
| 102 | + return { settings, manager, warn }; |
| 103 | + }; |
| 104 | + |
| 105 | + const required = (manager: AuthManager) => (manager as any).config.mfaRequired === true; |
| 106 | + |
| 107 | + // ── 1. The refusal ────────────────────────────────────────────────────────── |
| 108 | + |
| 109 | + it('OS_AUTH_TWO_FACTOR=false: turning it on is refused; nothing in the batch is written', async () => { |
| 110 | + process.env[ENV] = 'false'; |
| 111 | + const { settings, manager } = await boot(); |
| 112 | + |
| 113 | + const refusal = await refusalOf(settings.setMany('auth', { mfa_required: true, mfa_grace_period_days: 3 })); |
| 114 | + expect(refusal.code).toBe('SETTINGS_VALIDATION'); |
| 115 | + expect(refusal.fields).toEqual([ |
| 116 | + expect.objectContaining({ |
| 117 | + field: 'mfa_required', |
| 118 | + code: 'invalid_value', |
| 119 | + constraint: { twoFactor: false, overriddenBy: 'OS_AUTH_TWO_FACTOR' }, |
| 120 | + }), |
| 121 | + ]); |
| 122 | + |
| 123 | + expect(await settings.get('auth', 'mfa_required')).toMatchObject({ value: false, source: 'default' }); |
| 124 | + expect(await settings.get('auth', 'mfa_grace_period_days')).toMatchObject({ source: 'default' }); |
| 125 | + expect(required(manager)).toBe(false); |
| 126 | + expect(manager.isTwoFactorEnabled()).toBe(false); |
| 127 | + expect(manager.getPublicConfig().features.twoFactor).toBe(false); |
| 128 | + // Off, or the value in force, is never refused. |
| 129 | + await expect(settings.setMany('auth', { mfa_required: false })).resolves.toBeDefined(); |
| 130 | + }); |
| 131 | + |
| 132 | + it('the settings PUT door answers 400 SETTINGS_VALIDATION at the key, in the caller language', async () => { |
| 133 | + process.env[ENV] = '0'; |
| 134 | + const { settings } = await boot(); |
| 135 | + const routes = new Map<string, RouteHandler>(); |
| 136 | + const add = (method: string) => (path: string, handler: RouteHandler) => { |
| 137 | + routes.set(`${method} ${path}`, handler); |
| 138 | + return http; |
| 139 | + }; |
| 140 | + const http = { |
| 141 | + get: add('GET'), |
| 142 | + post: add('POST'), |
| 143 | + put: add('PUT'), |
| 144 | + delete: add('DELETE'), |
| 145 | + patch: add('PATCH'), |
| 146 | + use: () => http, |
| 147 | + listen: async () => {}, |
| 148 | + close: async () => {}, |
| 149 | + getInstance: () => null, |
| 150 | + } as unknown as IHttpServer; |
| 151 | + registerSettingsRoutes(http, settings, { |
| 152 | + contextFromRequest: () => ({ enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' }), |
| 153 | + }); |
| 154 | + |
| 155 | + const state: { status: number; body?: any } = { status: 200 }; |
| 156 | + const res = { |
| 157 | + json: vi.fn((data: unknown) => { |
| 158 | + state.body = data; |
| 159 | + }), |
| 160 | + send: vi.fn(), |
| 161 | + status: vi.fn((code: number) => { |
| 162 | + state.status = code; |
| 163 | + return res; |
| 164 | + }), |
| 165 | + header: vi.fn(() => res), |
| 166 | + } as unknown as IHttpResponse; |
| 167 | + const req = { |
| 168 | + params: { namespace: 'auth' }, |
| 169 | + query: {}, |
| 170 | + body: { mfa_required: true }, |
| 171 | + headers: { 'accept-language': 'zh-CN,zh;q=0.9' }, |
| 172 | + method: 'PUT', |
| 173 | + path: '/api/settings/auth', |
| 174 | + } as unknown as IHttpRequest; |
| 175 | + await routes.get('PUT /api/settings/:namespace')!(req, res); |
| 176 | + |
| 177 | + expect(state.status).toBe(400); |
| 178 | + expect(state.body.error.code).toBe('SETTINGS_VALIDATION'); |
| 179 | + const [field] = state.body.error.details.fields; |
| 180 | + expect(field).toMatchObject({ field: 'mfa_required', code: 'invalid_value' }); |
| 181 | + expect(field.message).toBe(MFA_REQUIRED_ENROLLMENT_COPY['zh-CN']); |
| 182 | + }); |
| 183 | + |
| 184 | + // ── 3. Controls ───────────────────────────────────────────────────────────── |
| 185 | + |
| 186 | + it.each([ |
| 187 | + ['unset', undefined], |
| 188 | + ['on', 'true'], |
| 189 | + ])('control: OS_AUTH_TWO_FACTOR %s — the save is accepted and the pass turns enrollment on with it', async (_label, value) => { |
| 190 | + if (value !== undefined) process.env[ENV] = value; |
| 191 | + const { settings, manager } = await boot(); |
| 192 | + |
| 193 | + await settings.setMany('auth', { mfa_required: true }); |
| 194 | + expect(await settings.get('auth', 'mfa_required')).toMatchObject({ value: true }); |
| 195 | + await vi.waitFor(() => expect(required(manager)).toBe(true)); |
| 196 | + expect(manager.isTwoFactorEnabled()).toBe(true); |
| 197 | + expect(manager.getPublicConfig().features.twoFactor).toBe(true); |
| 198 | + }); |
| 199 | + |
| 200 | + // ── 4. A switch stored on before the check ────────────────────────────────── |
| 201 | + |
| 202 | + it('a switch stored on before the check is not re-judged, and the gate still reads enrollment off', async () => { |
| 203 | + const settings = makeSettings(); |
| 204 | + await settings.setMany('auth', { mfa_required: true }); |
| 205 | + process.env[ENV] = 'false'; |
| 206 | + const { manager } = await boot(settings); |
| 207 | + |
| 208 | + // The value in force: the settings service asks no predicate about it. |
| 209 | + await expect(settings.setMany('auth', { mfa_required: true })).resolves.toBeDefined(); |
| 210 | + // Read as on, enforced by nobody: `features.twoFactor` is what says so. |
| 211 | + expect(required(manager)).toBe(true); |
| 212 | + expect(manager.isTwoFactorEnabled()).toBe(false); |
| 213 | + expect(manager.getPublicConfig().features.twoFactor).toBe(false); |
| 214 | + }); |
| 215 | + |
| 216 | + // ── The predicate and its registration, alone ─────────────────────────────── |
| 217 | + |
| 218 | + it('judges a change to on only, and only while enrollment stays off', () => { |
| 219 | + const off = mfaRequiredEnrollmentPredicate(() => false); |
| 220 | + expect(off({ next: true, current: false })?.constraint).toEqual({ twoFactor: false, overriddenBy: 'OS_AUTH_TWO_FACTOR' }); |
| 221 | + // Stored toggles read as `bindAuthSettings` reads them. |
| 222 | + expect(off({ next: 'true', current: null })).toBeDefined(); |
| 223 | + expect(off({ next: 1, current: undefined })).toBeDefined(); |
| 224 | + expect(off({ next: false, current: true })).toBeUndefined(); |
| 225 | + expect(off({ next: null, current: true })).toBeUndefined(); |
| 226 | + expect(off({ next: true, current: 'true' })).toBeUndefined(); |
| 227 | + expect(mfaRequiredEnrollmentPredicate(() => true)({ next: true, current: false })).toBeUndefined(); |
| 228 | + // Unknown locales fall back to English. |
| 229 | + expect(off({ next: true, current: false, locale: 'fr-FR' })?.message).toBe(MFA_REQUIRED_ENROLLMENT_COPY.en); |
| 230 | + }); |
| 231 | + |
| 232 | + it('a settings service without write predicates is said at warn, only while the pin makes it matter', () => { |
| 233 | + const warn = vi.fn(); |
| 234 | + registerMfaRequiredEnrollmentPredicate({}, { warn }); |
| 235 | + expect(warn).not.toHaveBeenCalled(); |
| 236 | + process.env[ENV] = 'false'; |
| 237 | + registerMfaRequiredEnrollmentPredicate({}, { warn }); |
| 238 | + expect(warn).toHaveBeenCalledTimes(1); |
| 239 | + expect(String(warn.mock.calls[0][0])).toMatch(/OS_AUTH_TWO_FACTOR/); |
| 240 | + }); |
| 241 | +}); |
0 commit comments