|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect } from 'vitest'; |
| 4 | + |
| 5 | +import { HttpDispatcher } from './http-dispatcher.js'; |
| 6 | +import { resolveExecutionContext } from './security/resolve-execution-context.js'; |
| 7 | +import { hashApiKey } from './security/api-key.js'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Security-critical: the `POST /keys` mint path. We assert the show-once |
| 11 | + * contract, that only the hash is persisted, the principal is pinned (no |
| 12 | + * impersonation / forgery via the body), auth is fail-closed, and that a minted |
| 13 | + * key actually authenticates through the verify path (round-trip). |
| 14 | + */ |
| 15 | + |
| 16 | +function makeKernel() { |
| 17 | + const rows: any[] = []; |
| 18 | + const ql = { |
| 19 | + insert: async (_obj: string, data: any, _opts: any) => { |
| 20 | + const id = `key_${rows.length + 1}`; |
| 21 | + rows.push({ id, ...data }); |
| 22 | + return { id }; |
| 23 | + }, |
| 24 | + // Minimal find for the round-trip via resolveExecutionContext. |
| 25 | + find: async (obj: string, opts: any) => { |
| 26 | + const where = opts?.where ?? {}; |
| 27 | + if (obj !== 'sys_api_key') return []; |
| 28 | + return rows.filter((r) => Object.entries(where).every(([k, v]) => r[k] === v)); |
| 29 | + }, |
| 30 | + update: async () => ({}), |
| 31 | + delete: async () => ({}), |
| 32 | + }; |
| 33 | + const kernel: any = { |
| 34 | + getService: (n: string) => (n === 'objectql' ? ql : undefined), |
| 35 | + getServiceAsync: async (n: string) => (n === 'objectql' ? ql : undefined), |
| 36 | + }; |
| 37 | + return { kernel, rows }; |
| 38 | +} |
| 39 | + |
| 40 | +function ctx(overrides: any = {}) { |
| 41 | + return { |
| 42 | + request: { headers: {} }, |
| 43 | + response: {}, |
| 44 | + environmentId: undefined, |
| 45 | + executionContext: { userId: 'u1', isSystem: false, roles: [], permissions: [] }, |
| 46 | + ...overrides, |
| 47 | + }; |
| 48 | +} |
| 49 | + |
| 50 | +function dispatcher(kernel: any) { |
| 51 | + return new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); |
| 52 | +} |
| 53 | + |
| 54 | +describe('HttpDispatcher.handleKeys (POST /keys — key generation)', () => { |
| 55 | + it('mints a key: 201, returns raw once, stores only the hash', async () => { |
| 56 | + const { kernel, rows } = makeKernel(); |
| 57 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'CI token' }, ctx()); |
| 58 | + |
| 59 | + expect(res.response.status).toBe(201); |
| 60 | + const data = res.response.body.data; |
| 61 | + expect(data.key).toMatch(/^osk_/); |
| 62 | + expect(data.prefix).toBe(data.key.slice(0, data.prefix.length)); |
| 63 | + expect(data.name).toBe('CI token'); |
| 64 | + |
| 65 | + // Exactly one row, storing the HASH not the raw key. |
| 66 | + expect(rows).toHaveLength(1); |
| 67 | + expect(rows[0].key).toBe(hashApiKey(data.key)); |
| 68 | + expect(rows[0].key).not.toBe(data.key); |
| 69 | + expect(rows[0].user_id).toBe('u1'); |
| 70 | + expect(rows[0].revoked).toBe(false); |
| 71 | + }); |
| 72 | + |
| 73 | + it('round-trip: the minted raw key authenticates via resolveExecutionContext', async () => { |
| 74 | + const { kernel } = makeKernel(); |
| 75 | + const ql = await (kernel.getServiceAsync('objectql')); |
| 76 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'agent' }, ctx()); |
| 77 | + const raw = res.response.body.data.key; |
| 78 | + |
| 79 | + const resolved = await resolveExecutionContext({ |
| 80 | + getService: async () => undefined, |
| 81 | + getQl: async () => ql, |
| 82 | + request: { headers: { 'x-api-key': raw } }, |
| 83 | + }); |
| 84 | + expect(resolved.userId).toBe('u1'); |
| 85 | + }); |
| 86 | + |
| 87 | + it('rejects anonymous requests (401, no row created)', async () => { |
| 88 | + const { kernel, rows } = makeKernel(); |
| 89 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'x' }, ctx({ executionContext: undefined })); |
| 90 | + expect(res.response.status).toBe(401); |
| 91 | + expect(rows).toHaveLength(0); |
| 92 | + }); |
| 93 | + |
| 94 | + it('pins user_id to the caller — body cannot impersonate', async () => { |
| 95 | + const { kernel, rows } = makeKernel(); |
| 96 | + await dispatcher(kernel).handleKeys('POST', { name: 'x', user_id: 'evil', userId: 'evil' }, ctx()); |
| 97 | + expect(rows[0].user_id).toBe('u1'); |
| 98 | + }); |
| 99 | + |
| 100 | + it('ignores body-injected key/id/revoked — cannot forge a known secret', async () => { |
| 101 | + const { kernel, rows } = makeKernel(); |
| 102 | + const res = await dispatcher(kernel).handleKeys( |
| 103 | + 'POST', |
| 104 | + { name: 'x', key: 'attacker-known', id: 'fixed', revoked: false, prefix: 'evil_' }, |
| 105 | + ctx(), |
| 106 | + ); |
| 107 | + const data = res.response.body.data; |
| 108 | + // Stored key is the hash of the GENERATED raw, never the attacker's value. |
| 109 | + expect(rows[0].key).toBe(hashApiKey(data.key)); |
| 110 | + expect(rows[0].key).not.toBe('attacker-known'); |
| 111 | + expect(rows[0].key).not.toBe(hashApiKey('attacker-known')); |
| 112 | + expect(data.prefix).toMatch(/^osk_/); |
| 113 | + }); |
| 114 | + |
| 115 | + it('rejects non-POST methods (405)', async () => { |
| 116 | + const { kernel } = makeKernel(); |
| 117 | + const res = await dispatcher(kernel).handleKeys('GET', {}, ctx()); |
| 118 | + expect(res.response.status).toBe(405); |
| 119 | + }); |
| 120 | + |
| 121 | + it('defaults the name when omitted', async () => { |
| 122 | + const { kernel, rows } = makeKernel(); |
| 123 | + await dispatcher(kernel).handleKeys('POST', {}, ctx()); |
| 124 | + expect(rows[0].name).toBe('API Key'); |
| 125 | + }); |
| 126 | + |
| 127 | + it('accepts a valid future expires_at and stores it', async () => { |
| 128 | + const { kernel, rows } = makeKernel(); |
| 129 | + const future = '2999-01-01T00:00:00.000Z'; |
| 130 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'x', expires_at: future }, ctx()); |
| 131 | + expect(res.response.status).toBe(201); |
| 132 | + expect(rows[0].expires_at).toBe(future); |
| 133 | + }); |
| 134 | + |
| 135 | + it('rejects a past expires_at (400, no row)', async () => { |
| 136 | + const { kernel, rows } = makeKernel(); |
| 137 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'x', expires_at: '2000-01-01T00:00:00Z' }, ctx()); |
| 138 | + expect(res.response.status).toBe(400); |
| 139 | + expect(rows).toHaveLength(0); |
| 140 | + }); |
| 141 | + |
| 142 | + it('rejects an unparseable expires_at (400, no row)', async () => { |
| 143 | + const { kernel, rows } = makeKernel(); |
| 144 | + const res = await dispatcher(kernel).handleKeys('POST', { name: 'x', expires_at: 'not-a-date' }, ctx()); |
| 145 | + expect(res.response.status).toBe(400); |
| 146 | + expect(rows).toHaveLength(0); |
| 147 | + }); |
| 148 | + |
| 149 | + it('an expired minted key does NOT authenticate (end-to-end with verify path)', async () => { |
| 150 | + // Insert directly with a past expiry to confirm the verify path rejects it |
| 151 | + // (handleKeys refuses to mint past-dated keys, so we simulate a stale one). |
| 152 | + const { kernel } = makeKernel(); |
| 153 | + const ql = await kernel.getServiceAsync('objectql'); |
| 154 | + const raw = 'osk_stale_demo'; |
| 155 | + await ql.insert('sys_api_key', { |
| 156 | + key: hashApiKey(raw), |
| 157 | + prefix: 'osk_stale_de', |
| 158 | + user_id: 'u1', |
| 159 | + revoked: false, |
| 160 | + expires_at: '2000-01-01T00:00:00Z', |
| 161 | + }, { context: { isSystem: true } }); |
| 162 | + |
| 163 | + const resolved = await resolveExecutionContext({ |
| 164 | + getService: async () => undefined, |
| 165 | + getQl: async () => ql, |
| 166 | + request: { headers: { 'x-api-key': raw } }, |
| 167 | + }); |
| 168 | + expect(resolved.userId).toBeUndefined(); |
| 169 | + }); |
| 170 | +}); |
0 commit comments