|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#24299] The REST data door answers a `sys_api_key` read that REJECTS as the |
| 5 | + * store outage — `503 SERVICE_UNAVAILABLE`, the answer a session caller |
| 6 | + * already got for the same fault — on the real `GET /api/v1/data/:object`. |
| 7 | + * |
| 8 | + * Measured on the unrepaired tree through this harness, `sys_api_key` reads |
| 9 | + * rejecting and every other table healthy: |
| 10 | + * |
| 11 | + * caller | before | after |
| 12 | + * --------------------------------|-----------------------------|------------------------ |
| 13 | + * key only | 401 UNAUTHENTICATED | 503 SERVICE_UNAVAILABLE |
| 14 | + * key + another user's cookie | 200, served AS the cookie's | 503, the service is |
| 15 | + * | user | never called |
| 16 | + * session only | 200 as the cookie's user | unchanged |
| 17 | + * |
| 18 | + * The middle row is the defect's worse half: `resolveApiKeyAdmission` answered |
| 19 | + * the failed read "no key", so the request fell on to the session arm and a |
| 20 | + * credential the caller did not lead with answered for it. |
| 21 | + * |
| 22 | + * Controls: a healthy key is served as its owner, and a NEVER-PROVISIONED |
| 23 | + * `sys_api_key` stays "no key" (the anonymous floor's 401), the boundary the |
| 24 | + * 2026-08-30 ruling (option A) draws. |
| 25 | + */ |
| 26 | + |
| 27 | +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 28 | +import { hashApiKey } from '@objectstack/core'; |
| 29 | +import { RestServer } from './rest-server.js'; |
| 30 | + |
| 31 | +const KEY = 'osk_rest_read_outage_pin'; |
| 32 | +const KEY_OWNER = 'u_key_owner'; |
| 33 | +const COOKIE_USER = 'u_cookie'; |
| 34 | +const DATA_COLLECTION = '/api/v1/data/:object'; |
| 35 | + |
| 36 | +type KeyRead = 'healthy' | 'rejects' | 'unprovisioned'; |
| 37 | + |
| 38 | +/** Equality and `$in` — the two shapes the resolver's reads use here; any other operator is refused, never matched. */ |
| 39 | +function matchesWhere(row: any, where: any): boolean { |
| 40 | + for (const [field, cond] of Object.entries(where ?? {})) { |
| 41 | + if (field.startsWith('$')) throw new Error(`fixture where-matcher: unsupported combinator '${field}'`); |
| 42 | + if (cond !== null && typeof cond === 'object') { |
| 43 | + const ops = Object.keys(cond as object); |
| 44 | + if (ops.length !== 1 || ops[0] !== '$in' || !Array.isArray((cond as any).$in)) { |
| 45 | + throw new Error(`fixture where-matcher: unsupported operator shape on '${field}'`); |
| 46 | + } |
| 47 | + if (!(cond as any).$in.includes(row[field])) return false; |
| 48 | + continue; |
| 49 | + } |
| 50 | + if (row[field] !== cond) return false; |
| 51 | + } |
| 52 | + return true; |
| 53 | +} |
| 54 | + |
| 55 | +function makeQl(keyRead: KeyRead) { |
| 56 | + const tables: Record<string, any[]> = { |
| 57 | + sys_api_key: [{ id: 'key_1', key: hashApiKey(KEY), user_id: KEY_OWNER, revoked: false, scopes: '[]' }], |
| 58 | + sys_member: [], |
| 59 | + sys_user: [{ id: KEY_OWNER }, { id: COOKIE_USER }], |
| 60 | + sys_user_permission_set: [], |
| 61 | + sys_permission_set: [], |
| 62 | + }; |
| 63 | + return { |
| 64 | + find: async (object: string, q: any = {}) => { |
| 65 | + if (object === 'sys_api_key' && keyRead === 'rejects') throw new Error('connection terminated unexpectedly'); |
| 66 | + if (object === 'sys_api_key' && keyRead === 'unprovisioned') throw new Error('no such table: sys_api_key'); |
| 67 | + const rows = (tables[object] ?? []).filter((row: any) => matchesWhere(row, q?.where)); |
| 68 | + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; |
| 69 | + }, |
| 70 | + update: async () => ({}), |
| 71 | + }; |
| 72 | +} |
| 73 | + |
| 74 | +/** The single-kernel wiring: an auth provider whose session read answers the cookie's user, and the objectql provider. */ |
| 75 | +function setup(keyRead: KeyRead) { |
| 76 | + const servedAs: Array<string | undefined> = []; |
| 77 | + const protocol: any = { |
| 78 | + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), |
| 79 | + getMetaTypes: vi.fn().mockResolvedValue([]), |
| 80 | + getMetaItems: vi.fn().mockResolvedValue([]), |
| 81 | + getMetaItem: vi.fn().mockResolvedValue({}), |
| 82 | + findData: vi.fn(async (r: any) => { servedAs.push(r?.context?.userId); return { value: [], total: 0 }; }), |
| 83 | + }; |
| 84 | + const server: any = { |
| 85 | + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), |
| 86 | + listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), |
| 87 | + }; |
| 88 | + const authServiceProvider = async () => ({ |
| 89 | + api: { |
| 90 | + getSession: async ({ headers }: { headers: Headers }) => ( |
| 91 | + headers.get('cookie') ? { user: { id: COOKIE_USER }, session: { userId: COOKIE_USER } } : null |
| 92 | + ), |
| 93 | + }, |
| 94 | + }); |
| 95 | + const ql = makeQl(keyRead); |
| 96 | + const rest = new RestServer(server, protocol, {} as any, undefined, undefined, undefined, authServiceProvider, async () => ql); |
| 97 | + rest.registerRoutes(); |
| 98 | + return { rest, servedAs }; |
| 99 | +} |
| 100 | + |
| 101 | +async function get(rest: any, headers: Record<string, string>) { |
| 102 | + const res: any = { statusCode: 200, body: undefined }; |
| 103 | + res.status = (c: number) => { res.statusCode = c; return res; }; |
| 104 | + res.json = (b: any) => { res.body = b; return res; }; |
| 105 | + res.header = () => res; res.setHeader = () => {}; res.write = () => {}; res.end = () => {}; res.send = () => {}; |
| 106 | + const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === DATA_COLLECTION); |
| 107 | + if (!route) throw new Error(`GET ${DATA_COLLECTION} route not registered`); |
| 108 | + await route.handler({ method: 'GET', path: '/api/v1/data/account', params: { object: 'account' }, query: {}, headers }, res); |
| 109 | + return { status: res.statusCode as number, body: res.body }; |
| 110 | +} |
| 111 | + |
| 112 | +// This file silences the REST fault log it does not assert on, so it declares the level it runs at. |
| 113 | +beforeAll(() => { vi.stubEnv('OS_REST_LOG', 'info'); }); |
| 114 | +afterAll(() => { vi.unstubAllEnvs(); }); |
| 115 | + |
| 116 | +let errorSpy: ReturnType<typeof vi.spyOn>; |
| 117 | +let warnSpy: ReturnType<typeof vi.spyOn>; |
| 118 | +beforeEach(() => { |
| 119 | + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 120 | + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 121 | +}); |
| 122 | +afterEach(() => { errorSpy.mockRestore(); warnSpy.mockRestore(); }); |
| 123 | + |
| 124 | +describe('[#24299] REST data door — a rejecting sys_api_key read is the store outage', () => { |
| 125 | + it('key only: 503 SERVICE_UNAVAILABLE, not the anonymous floor\'s 401', async () => { |
| 126 | + const { rest, servedAs } = setup('rejects'); |
| 127 | + const { status, body } = await get(rest, { 'x-api-key': KEY }); |
| 128 | + expect(status).toBe(503); |
| 129 | + expect(body?.code).toBe('SERVICE_UNAVAILABLE'); |
| 130 | + expect(servedAs).toEqual([]); |
| 131 | + }); |
| 132 | + |
| 133 | + it('key + another user\'s cookie: 503, and the request is never served as the cookie\'s user', async () => { |
| 134 | + const { rest, servedAs } = setup('rejects'); |
| 135 | + const { status, body } = await get(rest, { 'x-api-key': KEY, cookie: 'session=other-user' }); |
| 136 | + expect(status).toBe(503); |
| 137 | + expect(body?.code).toBe('SERVICE_UNAVAILABLE'); |
| 138 | + expect(servedAs, 'the data service was called — a credential the caller did not lead with answered').toEqual([]); |
| 139 | + }); |
| 140 | + |
| 141 | + it('session only: unchanged — the same fault does not touch a caller who sends no key', async () => { |
| 142 | + const { rest, servedAs } = setup('rejects'); |
| 143 | + const { status } = await get(rest, { cookie: 'session=other-user' }); |
| 144 | + expect(status).toBe(200); |
| 145 | + expect(servedAs).toEqual([COOKIE_USER]); |
| 146 | + }); |
| 147 | + |
| 148 | + it('control: a healthy key read is served as the key\'s owner, cookie or not', async () => { |
| 149 | + const { rest, servedAs } = setup('healthy'); |
| 150 | + expect((await get(rest, { 'x-api-key': KEY })).status).toBe(200); |
| 151 | + expect((await get(rest, { 'x-api-key': KEY, cookie: 'session=other-user' })).status).toBe(200); |
| 152 | + expect(servedAs).toEqual([KEY_OWNER, KEY_OWNER]); |
| 153 | + }); |
| 154 | + |
| 155 | + it('control: a never-provisioned sys_api_key is still "no key" — the anonymous floor\'s 401', async () => { |
| 156 | + const { rest, servedAs } = setup('unprovisioned'); |
| 157 | + const { status, body } = await get(rest, { 'x-api-key': KEY }); |
| 158 | + expect(status).toBe(401); |
| 159 | + expect(body?.code).toBe('UNAUTHENTICATED'); |
| 160 | + expect(servedAs).toEqual([]); |
| 161 | + }); |
| 162 | +}); |
0 commit comments