|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ruling record 6227928430, letter A item 2] The settings door, proven on the |
| 5 | + * one request-to-`ExecutionContext` composition by this pin plus its existing |
| 6 | + * ones. |
| 7 | + * |
| 8 | + * `SettingsServicePlugin`'s `verifiedContextFromRequest` resolves the caller |
| 9 | + * for every `/api/settings` route. The two answers a door owes before any other |
| 10 | + * are pinned here on the real listing route (`GET /api/settings`), with the |
| 11 | + * plugin booted for real and no seam captured, and read at the settings |
| 12 | + * service, the route's own work: |
| 13 | + * |
| 14 | + * - ADR-0096: a request that resolves no principal never reaches the service. |
| 15 | + * The family answers it at its anonymous floor (`401 UNAUTHENTICATED`). A |
| 16 | + * session read that fails resolved no caller, so it is the same refusal and |
| 17 | + * not an outage, and a refused API key never falls through to the cookie |
| 18 | + * beside it. |
| 19 | + * - ADR-0069: a principal the authentication policy holds is refused `403` |
| 20 | + * with its posture. The door carries the posture decided off the read that |
| 21 | + * admitted the caller and reads no second time, so a held session is |
| 22 | + * refused whatever the auth service's gate probe says; a key answers for its |
| 23 | + * own owner's `account`-scope posture, whatever cookie rides beside it. |
| 24 | + * |
| 25 | + * The CONTROL rows prove the door admits somebody: an ungated session, and an |
| 26 | + * API key on a host with no auth service (the key door stays open without a |
| 27 | + * session API). |
| 28 | + * |
| 29 | + * Every row was green on the door's hand-written composition and is green on |
| 30 | + * the shared one. |
| 31 | + */ |
| 32 | + |
| 33 | +import { describe, expect, it } from 'vitest'; |
| 34 | +import { |
| 35 | + ANONYMOUS_DENY_CODE, |
| 36 | + ANONYMOUS_DENY_MESSAGE, |
| 37 | + ANONYMOUS_DENY_STATUS, |
| 38 | + hashApiKey, |
| 39 | +} from '@objectstack/core'; |
| 40 | +import type { IHttpRequest, IHttpResponse, RouteHandler } from '@objectstack/spec/contracts'; |
| 41 | +import { SettingsServicePlugin } from './settings-service-plugin.js'; |
| 42 | +import type { SettingsContext } from './settings-service.types.js'; |
| 43 | +import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js'; |
| 44 | + |
| 45 | +const ORG = 'org_alpha'; |
| 46 | +const COOKIE = 'better-auth.session_token=tok_settings_door.c2ln'; |
| 47 | +const HELD_COOKIE = 'better-auth.session_token=tok_settings_door_held.c2ln'; |
| 48 | +const STRANGER_COOKIE = 'better-auth.session_token=tok_settings_door_unknown.c2ln'; |
| 49 | +const KEY = 'osk_settings_door_key'; |
| 50 | +const EX_MEMBER_KEY = 'osk_settings_door_ex_member'; |
| 51 | +const HELD_OWNER_KEY = 'osk_settings_door_held_owner'; |
| 52 | +const FUTURE = '2999-01-01T00:00:00Z'; |
| 53 | + |
| 54 | +const PASSWORD_EXPIRED = { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' }; |
| 55 | +const MFA_REQUIRED = { code: 'MFA_REQUIRED', message: 'Multi-factor authentication is required.' }; |
| 56 | + |
| 57 | +interface Host { |
| 58 | + /** Whether an auth service is registered at all. */ |
| 59 | + auth: boolean; |
| 60 | + /** What the auth service's gate probe answers (the door never asks it). */ |
| 61 | + gateActive?: boolean; |
| 62 | + /** The auth service's session read throws for every request. */ |
| 63 | + sessionReadFails?: boolean; |
| 64 | +} |
| 65 | + |
| 66 | +/** One deployment: a walled (`isolated`) posture, an engine answering the permission tables, an auth service. */ |
| 67 | +function services(host: Host): Record<string, unknown> { |
| 68 | + const tables: Record<string, Array<Record<string, unknown>>> = { |
| 69 | + sys_api_key: [ |
| 70 | + { id: 'k_live', key: hashApiKey(KEY), revoked: false, user_id: 'u_key', active_organization_id: ORG, expires_at: FUTURE }, |
| 71 | + { id: 'k_ex', key: hashApiKey(EX_MEMBER_KEY), revoked: false, user_id: 'u_ex', active_organization_id: ORG, expires_at: FUTURE }, |
| 72 | + { id: 'k_held', key: hashApiKey(HELD_OWNER_KEY), revoked: false, user_id: 'u_mfa', active_organization_id: ORG, expires_at: FUTURE }, |
| 73 | + ], |
| 74 | + sys_member: [ |
| 75 | + { user_id: 'u_key', organization_id: ORG, role: 'member' }, |
| 76 | + { user_id: 'u_mfa', organization_id: ORG, role: 'member' }, |
| 77 | + { user_id: 'u_ses', organization_id: ORG, role: 'member' }, |
| 78 | + { user_id: 'u_held', organization_id: ORG, role: 'member' }, |
| 79 | + ], |
| 80 | + }; |
| 81 | + const objectql = bindCatalogFromTables({ |
| 82 | + async find(object: string, q: { where?: Record<string, unknown>; limit?: number } | undefined) { |
| 83 | + const rows = (tables[object] ?? []).filter((row) => Object.entries(q?.where ?? {}).every(([k, v]) => { |
| 84 | + if (k.startsWith('$')) throw new Error(`fixture: unsupported combinator ${k}`); |
| 85 | + if (v !== null && typeof v === 'object') { |
| 86 | + return Array.isArray((v as { $in?: unknown[] }).$in) ? (v as { $in: unknown[] }).$in.includes(row[k]) : true; |
| 87 | + } |
| 88 | + return (v ?? null) === (row[k] ?? null); |
| 89 | + })); |
| 90 | + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; |
| 91 | + }, |
| 92 | + }, tables); |
| 93 | + |
| 94 | + const registered: Record<string, unknown> = { objectql, tenancy: { posture: 'isolated' } }; |
| 95 | + if (host.auth) { |
| 96 | + const sessions: Record<string, { user: Record<string, unknown>; session: Record<string, unknown> }> = { |
| 97 | + [COOKIE]: { user: { id: 'u_ses' }, session: { id: 'sess_ses', userId: 'u_ses', activeOrganizationId: ORG } }, |
| 98 | + [HELD_COOKIE]: { |
| 99 | + user: { id: 'u_held', authGate: PASSWORD_EXPIRED }, |
| 100 | + session: { id: 'sess_held', userId: 'u_held', activeOrganizationId: ORG }, |
| 101 | + }, |
| 102 | + }; |
| 103 | + registered.auth = { |
| 104 | + api: { |
| 105 | + async getSession(input: { headers: Headers }) { |
| 106 | + if (host.sessionReadFails) throw new Error('session backend unavailable'); |
| 107 | + return sessions[input.headers.get('cookie') ?? ''] ?? undefined; |
| 108 | + }, |
| 109 | + }, |
| 110 | + isAuthGateActive: () => host.gateActive ?? true, |
| 111 | + // `MFA_REQUIRED` is an `account`-scope posture: it holds every credential of its user. |
| 112 | + resolveUserAuthGates: async (userId: string) => (userId === 'u_mfa' ? [MFA_REQUIRED] : []), |
| 113 | + }; |
| 114 | + } |
| 115 | + return registered; |
| 116 | +} |
| 117 | + |
| 118 | +/** Boot the real plugin on `host` and answer one `GET /api/settings`. */ |
| 119 | +async function listing(host: Host, headers: Record<string, string>) { |
| 120 | + const routes = new Map<string, RouteHandler>(); |
| 121 | + const add = (verb: string) => (path: string, handler: RouteHandler) => { routes.set(`${verb} ${path}`, handler); }; |
| 122 | + const http = { |
| 123 | + get: add('GET'), post: add('POST'), put: add('PUT'), delete: add('DELETE'), patch: add('PATCH'), |
| 124 | + use() {}, async listen() {}, async close() {}, |
| 125 | + }; |
| 126 | + const registered: Record<string, unknown> = { ...services(host), 'http-server': http }; |
| 127 | + let readyHook: (() => Promise<void>) | undefined; |
| 128 | + let service: { listManifests(ctx: SettingsContext): unknown } | undefined; |
| 129 | + const ctx: any = { |
| 130 | + logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }, |
| 131 | + registerService: (name: string, value: unknown) => { if (name === 'settings') service = value as typeof service; }, |
| 132 | + getService: (name: string) => registered[name], |
| 133 | + hook: (event: string, fn: () => Promise<void>) => { if (event === 'kernel:ready') readyHook = fn; }, |
| 134 | + // The async registry the door reads the posture through; every name but |
| 135 | + // `tenancy` is registered or not exactly as `getService` answers it. |
| 136 | + getKernel: () => ({ getServiceAsync: async (name: string) => registered[name] }), |
| 137 | + }; |
| 138 | + const plugin = new SettingsServicePlugin({ manifests: [], env: {}, actionHandlers: {} }); |
| 139 | + await plugin.init(ctx); |
| 140 | + await plugin.start(ctx); |
| 141 | + await readyHook!(); |
| 142 | + if (!service) throw new Error('fixture: the settings service was not registered'); |
| 143 | + |
| 144 | + // The route's own work, read where it happens: which context reached it. |
| 145 | + const seen: SettingsContext[] = []; |
| 146 | + const listManifests = service.listManifests.bind(service); |
| 147 | + service.listManifests = (context: SettingsContext) => { seen.push(context); return listManifests(context); }; |
| 148 | + |
| 149 | + const handler = routes.get('GET /api/settings'); |
| 150 | + if (!handler) throw new Error('fixture: the listing route was not mounted'); |
| 151 | + const answer: { status: number; body: any } = { status: 200, body: undefined }; |
| 152 | + const res: any = { |
| 153 | + json(data: unknown) { answer.body = data; return res; }, |
| 154 | + send() { return res; }, |
| 155 | + status(code: number) { answer.status = code; return res; }, |
| 156 | + header() { return res; }, |
| 157 | + }; |
| 158 | + await handler( |
| 159 | + { params: {}, query: {}, headers, method: 'GET', path: '/api/settings' } as unknown as IHttpRequest, |
| 160 | + res as IHttpResponse, |
| 161 | + ); |
| 162 | + return { answer, seen }; |
| 163 | +} |
| 164 | + |
| 165 | +const ANONYMOUS = { status: ANONYMOUS_DENY_STATUS, code: ANONYMOUS_DENY_CODE, message: ANONYMOUS_DENY_MESSAGE }; |
| 166 | + |
| 167 | +const ROWS: Array<{ |
| 168 | + name: string; |
| 169 | + host: Host; |
| 170 | + headers: Record<string, string>; |
| 171 | + status: number; |
| 172 | + code?: string; |
| 173 | + message?: string; |
| 174 | + principal?: string; |
| 175 | +}> = [ |
| 176 | + { |
| 177 | + name: 'ADR-0096: no credential is refused at the anonymous floor, and the service is never asked', |
| 178 | + host: { auth: true }, headers: {}, ...ANONYMOUS, |
| 179 | + }, |
| 180 | + { |
| 181 | + name: 'ADR-0096: a cookie the auth service does not recognise is refused at the anonymous floor', |
| 182 | + host: { auth: true }, headers: { cookie: STRANGER_COOKIE }, ...ANONYMOUS, |
| 183 | + }, |
| 184 | + { |
| 185 | + name: 'ADR-0096: a session read that fails resolved no caller, so it is the anonymous floor, not an outage', |
| 186 | + host: { auth: true, sessionReadFails: true }, headers: { cookie: COOKIE }, ...ANONYMOUS, |
| 187 | + }, |
| 188 | + { |
| 189 | + name: "ADR-0096: an ex-member's organization-stamped key under the walled posture is refused, and the cookie beside it never answers for it", |
| 190 | + host: { auth: true }, headers: { 'x-api-key': EX_MEMBER_KEY, cookie: COOKIE }, ...ANONYMOUS, |
| 191 | + }, |
| 192 | + { |
| 193 | + name: 'ADR-0069: a held session is refused 403 with its posture, and the service is never asked', |
| 194 | + host: { auth: true }, headers: { cookie: HELD_COOKIE }, |
| 195 | + status: 403, code: PASSWORD_EXPIRED.code, message: PASSWORD_EXPIRED.message, |
| 196 | + }, |
| 197 | + { |
| 198 | + name: 'ADR-0069: the same held session is refused while the gate probe says no gate is active (the posture is the admitting read\'s)', |
| 199 | + host: { auth: true, gateActive: false }, headers: { cookie: HELD_COOKIE }, |
| 200 | + status: 403, code: PASSWORD_EXPIRED.code, message: PASSWORD_EXPIRED.message, |
| 201 | + }, |
| 202 | + { |
| 203 | + name: "ADR-0069: a key whose owner holds an account-scope posture is refused 403 with the owner's posture", |
| 204 | + host: { auth: true }, headers: { 'x-api-key': HELD_OWNER_KEY }, |
| 205 | + status: 403, code: MFA_REQUIRED.code, message: MFA_REQUIRED.message, |
| 206 | + }, |
| 207 | + { |
| 208 | + name: 'ADR-0069: a key beside the held cookie answers for its own owner, never for the cookie', |
| 209 | + host: { auth: true }, headers: { 'x-api-key': KEY, cookie: HELD_COOKIE }, |
| 210 | + status: 200, principal: 'u_key', |
| 211 | + }, |
| 212 | + { |
| 213 | + name: 'CONTROL: an ungated session is admitted, and the service is asked as that principal', |
| 214 | + host: { auth: true }, headers: { cookie: COOKIE }, |
| 215 | + status: 200, principal: 'u_ses', |
| 216 | + }, |
| 217 | + { |
| 218 | + name: 'CONTROL: an API key on a host with no auth service is admitted as its owner', |
| 219 | + host: { auth: false }, headers: { 'x-api-key': KEY }, |
| 220 | + status: 200, principal: 'u_key', |
| 221 | + }, |
| 222 | +]; |
| 223 | + |
| 224 | +describe("[ruling 6227928430 item 2] the settings door: the ADR-0096 principal-less refusal and the ADR-0069 gate on the listing route", () => { |
| 225 | + it.each(ROWS)('$name', async (row) => { |
| 226 | + const { answer, seen } = await listing(row.host, row.headers); |
| 227 | + |
| 228 | + expect(answer.status).toBe(row.status); |
| 229 | + if (row.code !== undefined) expect(answer.body?.error?.code).toBe(row.code); |
| 230 | + if (row.message !== undefined) expect(answer.body?.error?.message).toBe(row.message); |
| 231 | + if (row.principal === undefined) { |
| 232 | + expect(seen).toHaveLength(0); |
| 233 | + return; |
| 234 | + } |
| 235 | + expect(seen).toHaveLength(1); |
| 236 | + expect(seen[0]!.userId).toBe(row.principal); |
| 237 | + expect(seen[0]!.tenantId).toBe(ORG); |
| 238 | + expect(seen[0]!.enforced).toBe(true); |
| 239 | + expect('authGate' in seen[0]!).toBe(false); |
| 240 | + }); |
| 241 | +}); |
0 commit comments