|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `POST /keys` mints only for a principal a signed-in session admitted. |
| 5 | + * |
| 6 | + * Minting is a credential-lifecycle act. The door reads which credential |
| 7 | + * admitted the caller from `HttpProtocolContext.admission`, which the |
| 8 | + * dispatcher's identity step writes from the shared resolver, and refuses |
| 9 | + * every other admission with `403 PERMISSION_DENIED` before the body is read |
| 10 | + * and before any service is resolved. |
| 11 | + * |
| 12 | + * ## What is pinned, through `dispatch()` (the real identity step) |
| 13 | + * |
| 14 | + * - a session-admitted caller mints: `201`, one row, pinned to that caller; |
| 15 | + * - an API-key-admitted caller is refused `403 PERMISSION_DENIED` and nothing |
| 16 | + * is written, in each spelling the key header accepts (`x-api-key`, |
| 17 | + * `Authorization: ApiKey`, `Authorization: Bearer osk_…`); |
| 18 | + * - a session cookie sent beside the key does not lift the refusal (the key |
| 19 | + * is the credential that admitted the caller); |
| 20 | + * - the refusal is domain-wide: every verb answers it, not the `405`; |
| 21 | + * - control: an anonymous caller still answers `401 UNAUTHENTICATED`. |
| 22 | + * |
| 23 | + * ## And at the handler (`handleKeys`) |
| 24 | + * |
| 25 | + * - an authenticated context with NO admission recorded is refused too: an |
| 26 | + * admitting credential the door was never told about is not a session; |
| 27 | + * - a refused caller's body is never read. |
| 28 | + * |
| 29 | + * Refusals assert the ADR-0112 envelope (`code` and `status`), never prose. |
| 30 | + */ |
| 31 | + |
| 32 | +import { describe, expect, it, vi } from 'vitest'; |
| 33 | + |
| 34 | +import { hashApiKey } from '@objectstack/core'; |
| 35 | + |
| 36 | +import { deferRequestBody } from '../deferred-request-body.js'; |
| 37 | +import { HttpDispatcher, type HttpProtocolContext } from '../http-dispatcher.js'; |
| 38 | + |
| 39 | +const ORIGIN = 'http://tenant.example'; |
| 40 | +const KEY = 'osk_keys_mint_session_pin_0001'; |
| 41 | +const KEY_OWNER = 'u_key_owner'; |
| 42 | +const SESSION_USER = 'u_session_user'; |
| 43 | + |
| 44 | +function kernelWith(services: Record<string, unknown>): any { |
| 45 | + return { |
| 46 | + getState: () => 'running', |
| 47 | + getService: (n: string) => services[n] ?? null, |
| 48 | + getServiceAsync: async (n: string) => services[n] ?? null, |
| 49 | + context: { getService: (n: string) => services[n] ?? null }, |
| 50 | + }; |
| 51 | +} |
| 52 | + |
| 53 | +/** A data engine that knows one live key (owned by `KEY_OWNER`) and records every insert. */ |
| 54 | +function engine() { |
| 55 | + const keyHash = hashApiKey(KEY); |
| 56 | + const inserted: Array<{ object: string; row: Record<string, unknown> }> = []; |
| 57 | + const ql = { |
| 58 | + find: vi.fn(async (object: string, q: any) => ( |
| 59 | + object === 'sys_api_key' && q?.where?.key === keyHash |
| 60 | + ? [{ id: 'key_existing', key: keyHash, user_id: KEY_OWNER, revoked: false, scopes: '[]' }] |
| 61 | + : [] |
| 62 | + )), |
| 63 | + insert: vi.fn(async (object: string, row: Record<string, unknown>) => { |
| 64 | + inserted.push({ object, row }); |
| 65 | + return { id: `key_${inserted.length}` }; |
| 66 | + }), |
| 67 | + getObjects: vi.fn().mockReturnValue({}), |
| 68 | + registry: { |
| 69 | + getObject: vi.fn().mockReturnValue(null), |
| 70 | + getRegisteredTypes: vi.fn().mockReturnValue([]), |
| 71 | + }, |
| 72 | + }; |
| 73 | + return { ql, inserted }; |
| 74 | +} |
| 75 | + |
| 76 | +/** An auth service whose session read answers `SESSION_USER` whenever a cookie is sent. */ |
| 77 | +function authService() { |
| 78 | + const getSession = vi.fn(async ({ headers }: { headers: Headers }) => { |
| 79 | + if (!headers.get('cookie')) return null; |
| 80 | + return { user: { id: SESSION_USER }, session: { id: 'sess_1', userId: SESSION_USER } }; |
| 81 | + }); |
| 82 | + return { isAuthGateActive: () => false, getApi: async () => ({ getSession }) }; |
| 83 | +} |
| 84 | + |
| 85 | +function harness() { |
| 86 | + const { ql, inserted } = engine(); |
| 87 | + const dispatcher = new HttpDispatcher( |
| 88 | + kernelWith({ objectql: ql, auth: authService() }), |
| 89 | + undefined, |
| 90 | + { enforceProjectMembership: false }, |
| 91 | + ); |
| 92 | + (dispatcher as any).domainDeps.logger = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }; |
| 93 | + return { dispatcher, ql, inserted }; |
| 94 | +} |
| 95 | + |
| 96 | +const request = (method: string, headers: Record<string, string>) => new Request(`${ORIGIN}/api/v1/keys`, { |
| 97 | + method, |
| 98 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 99 | + ...(method === 'GET' || method === 'HEAD' ? {} : { body: JSON.stringify({ name: 'k' }) }), |
| 100 | +}); |
| 101 | + |
| 102 | +async function mint(headers: Record<string, string>, method = 'POST') { |
| 103 | + const h = harness(); |
| 104 | + const ctx: HttpProtocolContext = { request: request(method, headers) }; |
| 105 | + const result: any = await h.dispatcher.dispatch(method, '/keys', { name: 'k' }, {}, ctx); |
| 106 | + return { ...h, result, ctx }; |
| 107 | +} |
| 108 | + |
| 109 | +describe('POST /keys — minting requires an interactive session (through dispatch)', () => { |
| 110 | + it('a session-admitted caller mints: 201, one row pinned to the session user', async () => { |
| 111 | + const { result, inserted, ctx } = await mint({ cookie: 'session=live' }); |
| 112 | + expect(ctx.admission?.credential).toBe('session'); |
| 113 | + expect(result.response?.status).toBe(201); |
| 114 | + expect(typeof result.response?.body?.data?.key).toBe('string'); |
| 115 | + expect(inserted).toHaveLength(1); |
| 116 | + expect(inserted[0].object).toBe('sys_api_key'); |
| 117 | + expect(inserted[0].row.user_id).toBe(SESSION_USER); |
| 118 | + }); |
| 119 | + |
| 120 | + it.each([ |
| 121 | + ['x-api-key', { 'x-api-key': KEY }], |
| 122 | + ['Authorization: ApiKey', { authorization: `ApiKey ${KEY}` }], |
| 123 | + ['Authorization: Bearer', { authorization: `Bearer ${KEY}` }], |
| 124 | + ])('an API-key-admitted caller (%s) is refused 403 PERMISSION_DENIED, nothing written', async (_label, headers) => { |
| 125 | + const { result, inserted, ctx } = await mint(headers); |
| 126 | + // The principal WAS resolved, by the key: this is the authorization |
| 127 | + // refusal, not the anonymous floor. |
| 128 | + expect(ctx.executionContext?.userId).toBe(KEY_OWNER); |
| 129 | + expect(ctx.admission?.credential).toBe('api_key'); |
| 130 | + expect(result.response?.status).toBe(403); |
| 131 | + expect(result.response?.body?.success).toBe(false); |
| 132 | + expect(result.response?.body?.error?.code).toBe('PERMISSION_DENIED'); |
| 133 | + expect(result.response?.body?.error?.httpStatus).toBe(403); |
| 134 | + expect(inserted).toHaveLength(0); |
| 135 | + }); |
| 136 | + |
| 137 | + it('a session cookie beside the key does not lift the refusal', async () => { |
| 138 | + const { result, inserted, ctx } = await mint({ 'x-api-key': KEY, cookie: 'session=live' }); |
| 139 | + expect(ctx.admission?.credential).toBe('api_key'); |
| 140 | + expect(result.response?.status).toBe(403); |
| 141 | + expect(result.response?.body?.error?.code).toBe('PERMISSION_DENIED'); |
| 142 | + expect(inserted).toHaveLength(0); |
| 143 | + }); |
| 144 | + |
| 145 | + it.each(['GET', 'PUT', 'PATCH', 'DELETE'])('domain-wide: an API-key-admitted %s answers the same 403, not the 405', async (method) => { |
| 146 | + const { result, inserted } = await mint({ 'x-api-key': KEY }, method); |
| 147 | + expect(result.response?.status).toBe(403); |
| 148 | + expect(result.response?.body?.error?.code).toBe('PERMISSION_DENIED'); |
| 149 | + expect(inserted).toHaveLength(0); |
| 150 | + }); |
| 151 | + |
| 152 | + it('control: a session-admitted wrong verb still answers 405', async () => { |
| 153 | + const { result } = await mint({ cookie: 'session=live' }, 'GET'); |
| 154 | + expect(result.response?.status).toBe(405); |
| 155 | + expect(result.response?.body?.error?.code).toBe('METHOD_NOT_ALLOWED'); |
| 156 | + }); |
| 157 | + |
| 158 | + it('control: an anonymous caller still answers 401 UNAUTHENTICATED', async () => { |
| 159 | + const { result, inserted } = await mint({}); |
| 160 | + expect(result.response?.status).toBe(401); |
| 161 | + expect(result.response?.body?.error?.code).toBe('UNAUTHENTICATED'); |
| 162 | + expect(inserted).toHaveLength(0); |
| 163 | + }); |
| 164 | +}); |
| 165 | + |
| 166 | +describe('POST /keys — the handler judges the recorded admission (handleKeys)', () => { |
| 167 | + const signedIn = { userId: 'u1', isSystem: false, positions: [], permissions: [] }; |
| 168 | + |
| 169 | + function direct(admission: HttpProtocolContext['admission']) { |
| 170 | + const { ql, inserted } = engine(); |
| 171 | + const services: Record<string, unknown> = { objectql: ql }; |
| 172 | + const resolved: string[] = []; |
| 173 | + const kernel: any = { |
| 174 | + getService: (n: string) => { resolved.push(n); return services[n]; }, |
| 175 | + getServiceAsync: async (n: string) => { resolved.push(n); return services[n]; }, |
| 176 | + }; |
| 177 | + let bodyReads = 0; |
| 178 | + const body = deferRequestBody({ get body() { bodyReads += 1; return { name: 'k' }; } }); |
| 179 | + const ctx: HttpProtocolContext = { |
| 180 | + request: { headers: {} }, |
| 181 | + executionContext: signedIn as any, |
| 182 | + ...(admission ? { admission } : {}), |
| 183 | + }; |
| 184 | + const dispatcher = new HttpDispatcher(kernel); |
| 185 | + return { |
| 186 | + // Lookups made while CONSTRUCTING the dispatcher are not the |
| 187 | + // handler's; only the ones `handleKeys` makes are counted. |
| 188 | + run: () => { resolved.length = 0; return dispatcher.handleKeys('POST', body, ctx); }, |
| 189 | + inserted, |
| 190 | + resolved, |
| 191 | + bodyReads: () => bodyReads, |
| 192 | + }; |
| 193 | + } |
| 194 | + |
| 195 | + it('no admission recorded: refused 403 PERMISSION_DENIED, body unread, no service resolved', async () => { |
| 196 | + const d = direct(undefined); |
| 197 | + const res: any = await d.run(); |
| 198 | + expect(res.response?.status).toBe(403); |
| 199 | + expect(res.response?.body?.error?.code).toBe('PERMISSION_DENIED'); |
| 200 | + expect(d.bodyReads()).toBe(0); |
| 201 | + expect(d.resolved).toEqual([]); |
| 202 | + expect(d.inserted).toHaveLength(0); |
| 203 | + }); |
| 204 | + |
| 205 | + it('an api_key admission: refused 403 PERMISSION_DENIED, body unread, no service resolved', async () => { |
| 206 | + const d = direct({ credential: 'api_key', authGate: undefined }); |
| 207 | + const res: any = await d.run(); |
| 208 | + expect(res.response?.status).toBe(403); |
| 209 | + expect(res.response?.body?.error?.code).toBe('PERMISSION_DENIED'); |
| 210 | + expect(d.bodyReads()).toBe(0); |
| 211 | + expect(d.resolved).toEqual([]); |
| 212 | + expect(d.inserted).toHaveLength(0); |
| 213 | + }); |
| 214 | + |
| 215 | + it('control: a session admission mints (201)', async () => { |
| 216 | + const d = direct({ credential: 'session', authGate: undefined }); |
| 217 | + const res: any = await d.run(); |
| 218 | + expect(res.response?.status).toBe(201); |
| 219 | + expect(d.bodyReads()).toBe(1); |
| 220 | + expect(d.inserted).toHaveLength(1); |
| 221 | + }); |
| 222 | +}); |
0 commit comments