|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Route-shadowed datasource names (#29164). |
| 5 | + * |
| 6 | + * `GET /datasources/drivers` is the driver catalog, mounted before |
| 7 | + * `GET /datasources/:name`, so a runtime datasource named `drivers` was |
| 8 | + * created (201) and listed while its detail read — the edit form's load — |
| 9 | + * always answered the catalog. Create now refuses every literal the registrar |
| 10 | + * mounts beside a same-method `/:name` route, the way it refuses the |
| 11 | + * host-owned `default`. |
| 12 | + * |
| 13 | + * Two halves: |
| 14 | + * - the DRIFT PIN derives the shadowing literals from what |
| 15 | + * `registerDatasourceAdminRoutes` actually mounts (a capturing mock |
| 16 | + * `IHttpServer`, the route-ledger conformance seam) and holds the reserved |
| 17 | + * list equal to them, so a new literal sibling of `/:name` mounted without |
| 18 | + * a reservation fails here; |
| 19 | + * - the DOOR cases run the real `HonoHttpServer` over a real |
| 20 | + * `DatasourceAdminService`: the refusal envelope, the service never |
| 21 | + * writing, `default` unchanged, and the names that stay creatable. |
| 22 | + */ |
| 23 | + |
| 24 | +import { describe, it, expect, vi } from 'vitest'; |
| 25 | +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; |
| 26 | +import { registerDatasourceAdminRoutes } from '../admin-routes.js'; |
| 27 | +import { |
| 28 | + DatasourceAdminService, |
| 29 | + type DatasourceAdminServiceConfig, |
| 30 | + type StoredDatasource, |
| 31 | +} from '../datasource-admin-service.js'; |
| 32 | +import { ROUTE_SHADOWED_DATASOURCE_NAMES } from '../datasource-route-reserved-names.js'; |
| 33 | +import { |
| 34 | + ENTITLED_CREDENTIAL, |
| 35 | + createSessionAuthService, |
| 36 | + createGrantsEngine, |
| 37 | +} from './entitled-caller.fixture.js'; |
| 38 | + |
| 39 | +const BASE = '/api/v1'; |
| 40 | +const ROOT = `${BASE}/datasources`; |
| 41 | +const VERBS = ['get', 'post', 'put', 'patch', 'delete'] as const; |
| 42 | + |
| 43 | +/** Every `[VERB, path]` the registrar mounts at the default base. */ |
| 44 | +function enumerateMounts(): Array<[string, string]> { |
| 45 | + const server = Object.fromEntries([ |
| 46 | + ...VERBS.map((v) => [v, vi.fn()]), |
| 47 | + ['use', vi.fn()], |
| 48 | + ['listen', vi.fn().mockResolvedValue(undefined)], |
| 49 | + ['close', vi.fn().mockResolvedValue(undefined)], |
| 50 | + ]) as Record<(typeof VERBS)[number], ReturnType<typeof vi.fn>>; |
| 51 | + const ctx = { getService: () => undefined, logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() } }; |
| 52 | + registerDatasourceAdminRoutes(server as never, ctx as never, BASE); |
| 53 | + return VERBS.flatMap((v) => server[v].mock.calls.map((c): [string, string] => [v.toUpperCase(), String(c[0])])); |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * The literal single segments under the root that share a method with a |
| 58 | + * `/:name` route — the names that route would never see. |
| 59 | + */ |
| 60 | +function shadowingLiterals(mounts: Array<[string, string]>): string[] { |
| 61 | + const byNameMethods = new Set(mounts.filter(([, p]) => p === `${ROOT}/:name`).map(([m]) => m)); |
| 62 | + const literals = new Set<string>(); |
| 63 | + for (const [method, path] of mounts) { |
| 64 | + if (!path.startsWith(`${ROOT}/`)) continue; |
| 65 | + const rest = path.slice(ROOT.length + 1); |
| 66 | + if (rest.includes('/') || rest.startsWith(':')) continue; |
| 67 | + if (byNameMethods.has(method)) literals.add(rest); |
| 68 | + } |
| 69 | + return [...literals].sort(); |
| 70 | +} |
| 71 | + |
| 72 | +describe('reserved datasource names ↔ the registrar\'s literal siblings of /:name', () => { |
| 73 | + it('reserves exactly the literals that shadow a same-method /:name route', () => { |
| 74 | + const mounts = enumerateMounts(); |
| 75 | + // Control: the enumeration saw the by-name read and a literal at all, so |
| 76 | + // an empty answer below could not be a silent nothing-enumerated. |
| 77 | + expect(mounts).toContainEqual(['GET', `${ROOT}/:name`]); |
| 78 | + expect(mounts).toContainEqual(['POST', `${ROOT}/test`]); |
| 79 | + |
| 80 | + expect([...ROUTE_SHADOWED_DATASOURCE_NAMES].sort()).toEqual(shadowingLiterals(mounts)); |
| 81 | + }); |
| 82 | + |
| 83 | + it('a literal beside a /:name route of ANOTHER method is not a shadowing one', () => { |
| 84 | + // `POST /datasources/test` shares no method with a `/:name` route; were a |
| 85 | + // `GET /datasources/test` mounted, `test` would join the derived set and |
| 86 | + // the pin above would fail until it is reserved. |
| 87 | + expect(shadowingLiterals([['POST', `${ROOT}/test`], ['GET', `${ROOT}/:name`]])).toEqual([]); |
| 88 | + expect(shadowingLiterals([['GET', `${ROOT}/test`], ['GET', `${ROOT}/:name`]])).toEqual(['test']); |
| 89 | + }); |
| 90 | +}); |
| 91 | + |
| 92 | +// --------------------------------------------------------------------------- |
| 93 | +// The create door, end to end. |
| 94 | + |
| 95 | +function harness(seed: StoredDatasource[] = []) { |
| 96 | + const records: StoredDatasource[] = seed.map((r) => ({ ...r })); |
| 97 | + const puts: string[] = []; |
| 98 | + const config: DatasourceAdminServiceConfig = { |
| 99 | + probe: async () => ({ ok: true, latencyMs: 1 }), |
| 100 | + listDatasourceRecords: async () => records.map((r) => ({ ...r })), |
| 101 | + getDatasourceRecord: async (n) => { |
| 102 | + const r = records.find((x) => x.name === n); |
| 103 | + return r ? { ...r } : undefined; |
| 104 | + }, |
| 105 | + putDatasourceRecord: async (record) => { |
| 106 | + puts.push(record.name); |
| 107 | + const i = records.findIndex((r) => r.name === record.name); |
| 108 | + if (i >= 0) records[i] = { ...record }; |
| 109 | + else records.push({ ...record }); |
| 110 | + }, |
| 111 | + deleteDatasourceRecord: async (n) => { |
| 112 | + const i = records.findIndex((r) => r.name === n); |
| 113 | + if (i >= 0) records.splice(i, 1); |
| 114 | + }, |
| 115 | + writeSecret: async (_input, hint) => `sys_secret://datasource/${hint.name}`, |
| 116 | + countBoundObjects: async () => 0, |
| 117 | + listObjectsBoundTo: async () => [], |
| 118 | + }; |
| 119 | + const service = new DatasourceAdminService(config); |
| 120 | + const authService = createSessionAuthService(); |
| 121 | + const grantsEngine = createGrantsEngine(); |
| 122 | + const server = new HonoHttpServer(0); |
| 123 | + const ctx = { |
| 124 | + getService: (name: string) => |
| 125 | + name === 'auth' |
| 126 | + ? authService |
| 127 | + : name === 'objectql' || name === 'data' |
| 128 | + ? grantsEngine |
| 129 | + : name === 'datasource-admin' |
| 130 | + ? service |
| 131 | + : undefined, |
| 132 | + }; |
| 133 | + registerDatasourceAdminRoutes(server, ctx as never, BASE); |
| 134 | + const app = server.getRawApp(); |
| 135 | + const call = (path: string, method = 'GET', body?: unknown) => |
| 136 | + app.fetch( |
| 137 | + new Request(`http://local${path}`, { |
| 138 | + method, |
| 139 | + headers: { 'content-type': 'application/json', authorization: ENTITLED_CREDENTIAL }, |
| 140 | + ...(body === undefined ? {} : { body: JSON.stringify(body) }), |
| 141 | + }), |
| 142 | + ); |
| 143 | + return { call, puts, records }; |
| 144 | +} |
| 145 | + |
| 146 | +const draft = (name: string) => ({ name, driver: 'postgres', config: { database: 'analytics' } }); |
| 147 | + |
| 148 | +describe('POST /api/v1/datasources — route-shadowed names', () => { |
| 149 | + it('refuses `drivers` with the 400 DATASOURCE_ADMIN_ERROR naming the segment, and writes nothing', async () => { |
| 150 | + const { call, puts, records } = harness(); |
| 151 | + const res = await call(ROOT, 'POST', draft('drivers')); |
| 152 | + expect(res.status).toBe(400); |
| 153 | + const body = (await res.json()) as { error: { code: string; message: string } }; |
| 154 | + expect(body.error.code).toBe('DATASOURCE_ADMIN_ERROR'); |
| 155 | + expect(body.error.message).toContain("'drivers'"); |
| 156 | + expect(puts).toEqual([]); |
| 157 | + expect(records).toEqual([]); |
| 158 | + }); |
| 159 | + |
| 160 | + it('keeps refusing the host-owned `default` the same way', async () => { |
| 161 | + const { call, puts } = harness(); |
| 162 | + const res = await call(ROOT, 'POST', draft('default')); |
| 163 | + expect(res.status).toBe(400); |
| 164 | + const body = (await res.json()) as { error: { code: string; message: string } }; |
| 165 | + expect(body.error.code).toBe('DATASOURCE_ADMIN_ERROR'); |
| 166 | + expect(body.error.message).toContain("'default'"); |
| 167 | + expect(puts).toEqual([]); |
| 168 | + }); |
| 169 | + |
| 170 | + it('still creates an ordinary name (201) and reads it back by name', async () => { |
| 171 | + const { call, puts } = harness(); |
| 172 | + const res = await call(ROOT, 'POST', draft('reporting')); |
| 173 | + expect(res.status).toBe(201); |
| 174 | + expect(puts).toEqual(['reporting']); |
| 175 | + const read = await call(`${ROOT}/reporting`); |
| 176 | + expect(read.status).toBe(200); |
| 177 | + expect(((await read.json()) as any).data.datasource.name).toBe('reporting'); |
| 178 | + }); |
| 179 | + |
| 180 | + it('still creates `test` — the draft-probe literal shadows no by-name door', async () => { |
| 181 | + const { call, puts } = harness(); |
| 182 | + const res = await call(ROOT, 'POST', draft('test')); |
| 183 | + expect(res.status).toBe(201); |
| 184 | + expect(puts).toEqual(['test']); |
| 185 | + const read = await call(`${ROOT}/test`); |
| 186 | + expect(read.status).toBe(200); |
| 187 | + expect(((await read.json()) as any).data.datasource.name).toBe('test'); |
| 188 | + }); |
| 189 | +}); |
| 190 | + |
| 191 | +describe('a stored `drivers` row written before the refusal', () => { |
| 192 | + it('stays listed, patchable and removable — the refusal is at create only', async () => { |
| 193 | + const { call, records } = harness([{ name: 'drivers', driver: 'postgres', config: { database: 'a' }, origin: 'runtime' }]); |
| 194 | + |
| 195 | + const list = await call(ROOT); |
| 196 | + expect(list.status).toBe(200); |
| 197 | + expect(((await list.json()) as any).data.datasources.map((d: { name: string }) => d.name)).toContain('drivers'); |
| 198 | + |
| 199 | + const patched = await call(`${ROOT}/drivers`, 'PATCH', { label: 'Old drivers' }); |
| 200 | + expect(patched.status).toBe(200); |
| 201 | + expect(records.find((r) => r.name === 'drivers')?.label).toBe('Old drivers'); |
| 202 | + |
| 203 | + const removed = await call(`${ROOT}/drivers`, 'DELETE'); |
| 204 | + expect(removed.ok).toBe(true); |
| 205 | + expect(records.some((r) => r.name === 'drivers')).toBe(false); |
| 206 | + }); |
| 207 | +}); |
0 commit comments