Skip to content

Commit 41bae08

Browse files
committed
test(service-datasource): pin route-shadowed datasource names (red first)
Adds the reserved-name list derived against the admin registrar's literal siblings of /:name, a drift pin over the registrar's mounts, and door cases over the real Hono server: creating `drivers` must answer 400. Claude-Session: https://claude.ai/code/session_01ADHkmPjMhxWBYAk48z4Mam Co-authored-by: Claude <noreply@anthropic.com>
1 parent dedc350 commit 41bae08

2 files changed

Lines changed: 245 additions & 0 deletions

File tree

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
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.status).toBe(200);
205+
expect(records.some((r) => r.name === 'drivers')).toBe(false);
206+
});
207+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Datasource names the admin route family can never serve by name (#29164).
5+
*
6+
* `registerDatasourceAdminRoutes` mounts the by-name doors at
7+
* `/datasources/:name` and, beside them, literal single-segment routes under
8+
* the same root. Where a literal shares a METHOD with a `/:name` route it is
9+
* registered first and captures the path: `GET /datasources/drivers` answers
10+
* the driver catalog, so a datasource named `drivers` could be created and
11+
* listed while its detail read — the load of its edit form — was never
12+
* reached. Each such literal is therefore a reserved datasource name, refused
13+
* at create the same way the host-owned `default` is.
14+
*
15+
* A literal that shares no method with a `/:name` route captures no name, and
16+
* is not reserved: `POST /datasources/test` (the unsaved-draft probe) sits
17+
* beside no `POST /datasources/:name`, so a datasource named `test` is read,
18+
* patched, removed and probed (`POST /datasources/test/test`) through its own
19+
* doors.
20+
*
21+
* ONE list for both halves. The registrar mounts each shadowing literal from
22+
* the constant below, and `DatasourceAdminService` refuses each name in
23+
* {@link ROUTE_SHADOWED_DATASOURCE_NAMES}. The drift pin
24+
* (`__tests__/datasource-route-reserved-names.test.ts`) enumerates what the
25+
* registrar actually mounts and fails both ways: a literal sibling of a
26+
* same-method `/:name` route that is not listed here, and a listed name that
27+
* no longer shadows anything.
28+
*/
29+
30+
/** The driver-catalog literal: `GET /datasources/drivers`, mounted beside `GET /datasources/:name`. */
31+
export const DRIVER_CATALOG_SEGMENT = 'drivers';
32+
33+
/**
34+
* Every literal segment the admin registrar mounts beside a same-method
35+
* `/datasources/:name` route — a datasource of one of these names could never
36+
* be reached through that by-name door.
37+
*/
38+
export const ROUTE_SHADOWED_DATASOURCE_NAMES: readonly string[] = Object.freeze([DRIVER_CATALOG_SEGMENT]);

0 commit comments

Comments
 (0)