Skip to content

Commit 0b44a20

Browse files
committed
fix(rest): parse the declared api config at the RestServer seam instead of casting to it
`RestApiConfigSchema` constrains `api.version` with `.regex(/^[a-zA-Z0-9_\-\.]+$/)`, and `version` becomes a path segment in every route `getApiBasePath()` mounts. Nothing ran the regex: both hops into `@objectstack/rest` are casts, the plugin declares no `configSchema`, and `PluginLoader` calls its own `validatePluginConfig(metadata)` with no config argument. `??` was the only guard left, so `api.version: ''` mounted the whole API at `/api//` and `'v1/beta'` spliced a segment into every route. `normalizeConfig` now runs the declared contract before the cast. Validation only: the parsed output is discarded so the undeclared `enableSearch` is not silently stripped, and the retired `api.requireAuth` tombstone is omitted so #3963's warn-and-ignore posture is preserved. Part of #11637 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019siH5jDmk5hrayvfyojUqR
1 parent 7899f57 commit 0b44a20

4 files changed

Lines changed: 364 additions & 21 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
'@objectstack/rest': minor
3+
---
4+
5+
**BREAKING (accept-set tightening)**: `RestServer` now parses `config.api`
6+
against `RestApiConfigSchema` at construction instead of casting to it, so a
7+
deployment whose `api` config the spec rejects fails loudly at boot rather than
8+
booting into a structurally broken URL space (#11637).
9+
10+
The regex was always declared. `packages/spec/src/api/rest-server.zod.ts`
11+
constrains `version: z.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default('v1')`, and
12+
`version` is spliced into `getApiBasePath()` — the base of **every** route this
13+
server mounts. Nothing ran it: both hops into `@objectstack/rest` are casts
14+
(`config.api as any` in `rest-api-plugin.ts`, then `as Partial<RestApiConfig>`
15+
in `normalizeConfig`), the plugin declares no `configSchema`, and the kernel's
16+
`PluginConfigValidator` could not have covered it either — `PluginLoader`
17+
invokes its own `validatePluginConfig(metadata)` with **no config argument** and
18+
returns early, and `createRestApiPlugin` closes over its config so the kernel
19+
never receives it. `??` was the only guard left, and `??` substitutes
20+
`null`/`undefined` only. Measured on the pre-fix code: `api.version: ''`
21+
constructed happily and mounted the whole API — `/data`, `/meta`, `/discovery`,
22+
`openapi.json` — under `/api//`.
23+
24+
**Newly refused, all at `new RestServer(...)` / `createRestApiPlugin().start()`:**
25+
26+
- `api.version: ''` — the reported case. Refused with
27+
`Invalid string: must match pattern /^[a-zA-Z0-9_\-\.]+$/`.
28+
- `api.version` carrying any character outside `[a-zA-Z0-9_-.]` — `'v1/beta'`
29+
(which spliced an extra path segment into every route), `'v1 beta'`, `'v1%2F'`
30+
and so on.
31+
- `api.projectResolution` outside `'required' | 'optional' | 'auto'` — same
32+
seam, same cast, equally unenforced until now.
33+
- A declared key written with the wrong type: `api.enableCrud: 'yes'`,
34+
`api.basePath: 42`, a malformed `api.documentation` / `api.responseFormat`.
35+
36+
**Deliberately NOT refused** — the narrowing is exactly what the schema
37+
declares, and no more:
38+
39+
- `api.requireAuth`. The retired key (#3963) is `.omit()`ed from the
40+
validation: it keeps the warn-and-ignore posture `rest-api-plugin.ts` gives
41+
it, and `tsc` still refuses it at any typed authoring site. Converting that
42+
warn into a boot failure is #3963's decision to make, not this seam's.
43+
- Keys no schema in `packages/spec` declares, `api.enableSearch` first among
44+
them. The parse is run for its verdict only and its output is **discarded** —
45+
`RestApiConfigSchema` is not `.strict()`, so a non-strict `z.object()` strips
46+
what it does not declare, and consuming the parsed value would have silently
47+
turned search back on for a deployment that turned it off.
48+
- `api.basePath: ''` — a bare `z.string()` with no declared constraint stays
49+
accepted.
50+
- `crud`, `metadata`, `batch` and `routes`. Those sub-objects are still cast,
51+
not parsed, and carry unenforced constraints of their own
52+
(`batch.maxBatchSize: z.number().int().min(1).max(1000)`, the
53+
`routes.nameTransform` enum). Same defect class, filed separately — this
54+
change deliberately puts one narrowing in front of contract review, not five.
55+
56+
**Migration.** Delete or correct the offending key; the refusal names the path,
57+
the declared rule that rejected it, and why an empty version is not survivable.
58+
A deployment that meant "no version segment" wants `api.apiPath: '/api'`, which
59+
sets the base outright and is unconstrained.
60+
61+
**In-repo blast radius, measured before shipping:** exactly one in-repo site
62+
constructed a server this parse refuses — the `rest-openapi-route.test.ts` pin
63+
for a falsy `api.version`, which carried its own written instruction to retire
64+
if normalization ever started rejecting it, and is replaced here by a pin on the
65+
refusal. The 96 fixtures passing the retired `api.requireAuth` are unaffected by
66+
design, as are `packages/cli`'s `os serve` composition and the `@objectstack/client`
67+
integration boots. Full `@objectstack/rest` suite: 146 files, 2354 tests, green.
68+
69+
<!-- adr-0087: not-required (no-migration-prescription) Nothing authorable is removed or renamed — no spec key, export or config field changes spelling, and `RestApiConfigSchema` itself is untouched. What changes is that the schema already declaring `api.version` is finally executed at the consumption seam, so `objectstack migrate meta` has no mechanical rewrite to list: a config carrying `version: ''` or `'v1/beta'` states an intent (which path segment did you mean?) that no conversion can decide for the author, and the refusal text names the fix at the call site. -->
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#11637] The REST server runs the config contract it declares.
5+
*
6+
* `RestApiConfigSchema` (`packages/spec/src/api/rest-server.zod.ts`) constrains
7+
* `api.version` with `z.string().regex(/^[a-zA-Z0-9_\-\.]+$/)`, which refuses
8+
* `''`. Nothing ever ran it. Both hops into this package were casts —
9+
* `config.api as any` in `rest-api-plugin.ts`, then `as Partial<RestApiConfig>`
10+
* in `RestServer.normalizeConfig` — the plugin declares no `configSchema`, and
11+
* the kernel's `PluginConfigValidator` could not have covered it anyway
12+
* (`PluginLoader.loadPlugin` calls its own `validatePluginConfig(metadata)`
13+
* with NO config argument and returns early, and `createRestApiPlugin` closes
14+
* over its config so the kernel never receives it). `??` was the only guard
15+
* left, and `??` substitutes `null`/`undefined` only.
16+
*
17+
* Measured on the pre-fix code: `api.version: ''` constructed happily and
18+
* `getApiBasePath()` returned `/api/`, so the whole surface — `/data`, `/meta`,
19+
* `/discovery`, `openapi.json` — mounted under a doubled slash, and
20+
* `'v1/beta'` spliced an extra path segment into every route.
21+
*
22+
* ⛔ ANTI-VACUITY. A pin asserting that *the schema* refuses `''` would be
23+
* green before this change too — the schema always refused it. Every pin below
24+
* drives the REAL server construction (and, in §B, the real plugin
25+
* composition), so what it measures is whether the SERVER refuses.
26+
*
27+
* §C is explicitly a set of REGRESSION GUARDS: green before this change and
28+
* green after. They are here to bound the narrowing — to show it refuses
29+
* exactly what the schema declares and nothing this seam invented.
30+
*/
31+
32+
import { describe, it, expect, vi } from 'vitest';
33+
import { RestServer } from './rest-server';
34+
import { createRestApiPlugin } from './rest-api-plugin';
35+
36+
function makeServer() {
37+
return {
38+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
39+
use: vi.fn(), listen: vi.fn(), close: vi.fn(),
40+
} as any;
41+
}
42+
43+
function makeProtocol() {
44+
return {
45+
getMetaItems: vi.fn(async ({ type }: { type: string }) => ({ type, items: [] })),
46+
} as any;
47+
}
48+
49+
/** Construct the real server with `api` as given — the seam under test. */
50+
function construct(api: Record<string, unknown>) {
51+
return new RestServer(makeServer(), makeProtocol(), { api } as any);
52+
}
53+
54+
// ---------------------------------------------------------------------------
55+
// §A — the server refuses what the schema declares invalid
56+
// ---------------------------------------------------------------------------
57+
58+
describe('[#11637] §A RestServer construction runs RestApiConfigSchema', () => {
59+
it('refuses `api.version: ""` — the value that mounted the whole API at /api//', () => {
60+
expect(() => construct({ version: '' })).toThrow(/api\.version/);
61+
});
62+
63+
it('names the declared contract and the pattern it failed, not a bare "invalid"', () => {
64+
let message = '';
65+
try {
66+
construct({ version: '' });
67+
} catch (err: any) {
68+
message = String(err?.message ?? err);
69+
}
70+
// The prescription is the payload: an operator reading this must be
71+
// able to find the rule without reading our source.
72+
expect(message, 'the refusal must name the schema that declares the rule').toContain('RestApiConfigSchema');
73+
expect(message, "zod's own issue message carries the declared pattern").toContain('must match pattern');
74+
expect(message, 'and it must say why an empty version is not survivable').toContain('/api//');
75+
});
76+
77+
it('refuses `api.version: "v1/beta"` — a version that splices a path segment into every route', () => {
78+
expect(() => construct({ version: 'v1/beta' })).toThrow(/api\.version/);
79+
});
80+
81+
it('refuses a version carrying whitespace', () => {
82+
expect(() => construct({ version: 'v1 beta' })).toThrow(/api\.version/);
83+
});
84+
85+
it('refuses a declared-enum violation on the same object (`projectResolution`)', () => {
86+
// Same seam, same mechanism: the cast admitted any string here too.
87+
expect(() => construct({ projectResolution: 'whenever' })).toThrow(/api\.projectResolution/);
88+
});
89+
90+
it('no constructed server can carry a doubled slash in its mount', () => {
91+
// The defect stated as the operator sees it. Pre-fix this server
92+
// existed and `getApiBasePath()` answered `/api/`; now the
93+
// construction itself is refused, so the broken mount is unreachable.
94+
expect(() => construct({ version: '' })).toThrow();
95+
const ok = construct({ version: 'v1' });
96+
expect(ok.getApiBasePath()).toBe('/api/v1');
97+
expect(ok.getApiBasePath()).not.toContain('//');
98+
});
99+
});
100+
101+
// ---------------------------------------------------------------------------
102+
// §B — the real plugin composition, i.e. BOTH cast hops
103+
// ---------------------------------------------------------------------------
104+
105+
function createCtx(services: Record<string, unknown>) {
106+
return {
107+
registerService: vi.fn(),
108+
getService: vi.fn((name: string) => {
109+
if (name in services) return services[name];
110+
throw new Error(`Service '${name}' not found`);
111+
}),
112+
getServices: vi.fn(() => new Map(Object.entries(services))),
113+
hook: vi.fn(),
114+
trigger: vi.fn().mockResolvedValue(undefined),
115+
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
116+
getKernel: vi.fn(),
117+
} as any;
118+
}
119+
120+
function bootCtx() {
121+
return createCtx({ 'http.server': makeServer(), protocol: makeProtocol() });
122+
}
123+
124+
describe('[#11637] §B the refusal survives the plugin path', () => {
125+
it('CONTROL: this ctx really does boot a REST server', async () => {
126+
// Not decoration. `createRestApiPlugin.start()` returns quietly when
127+
// `http.server` or `protocol` is missing, so a rejection below could
128+
// otherwise be attributed to a thin ctx rather than to the config.
129+
// This case is what makes the next one attributable.
130+
const ctx = bootCtx();
131+
await expect(createRestApiPlugin({ api: { api: { version: 'v1' } } as any }).start!(ctx)).resolves.toBeUndefined();
132+
expect(ctx.logger.error).not.toHaveBeenCalled();
133+
});
134+
135+
it('rejects `createRestApiPlugin({ api: { api: { version: "" } } }).start()`', async () => {
136+
const ctx = bootCtx();
137+
await expect(
138+
createRestApiPlugin({ api: { api: { version: '' } } as any }).start!(ctx),
139+
).rejects.toThrow(/api\.version/);
140+
});
141+
});
142+
143+
// ---------------------------------------------------------------------------
144+
// §C — REGRESSION GUARDS (green BEFORE this change and after)
145+
// ---------------------------------------------------------------------------
146+
147+
describe('[#11637] §C regression guards — the narrowing is exactly the declared one', () => {
148+
it('a conventional config still boots and still mounts at /api/v1', () => {
149+
expect(construct({}).getApiBasePath()).toBe('/api/v1');
150+
expect(construct({ version: 'v1' }).getApiBasePath()).toBe('/api/v1');
151+
});
152+
153+
it('accepts every spelling the declared pattern allows', () => {
154+
expect(construct({ version: 'v2' }).getApiBasePath()).toBe('/api/v2');
155+
expect(construct({ version: '2024-01' }).getApiBasePath()).toBe('/api/2024-01');
156+
expect(construct({ version: 'v1.2' }).getApiBasePath()).toBe('/api/v1.2');
157+
expect(construct({ version: 'v1_beta' }).getApiBasePath()).toBe('/api/v1_beta');
158+
});
159+
160+
it('still accepts `basePath: ""` — the schema declares NO constraint there', () => {
161+
// The narrowing follows the contract, it does not extend it. `basePath`
162+
// is a bare `z.string()`, so an empty one stays this seam's business
163+
// to accept (`direct-mount-base-follows-apipath.test.ts` boots one).
164+
expect(construct({ basePath: '', version: 'v1' }).getApiBasePath()).toBe('/v1');
165+
});
166+
167+
it('`apiPath` still overrides the composed base', () => {
168+
expect(construct({ apiPath: '/backend/api/v9' }).getApiBasePath()).toBe('/backend/api/v9');
169+
});
170+
171+
it('KEEPS `enableSearch`, which no schema in packages/spec declares', () => {
172+
// The reason the seam validates but does NOT consume the parsed output.
173+
// `RestApiConfigSchema` is not `.strict()`, so a non-strict `z.object()`
174+
// STRIPS this key (measured). Consuming the parse would silently turn
175+
// search back ON for a deployment that turned it off.
176+
const rest = construct({ version: 'v1', enableSearch: false });
177+
expect((rest as any).config.api.enableSearch).toBe(false);
178+
});
179+
180+
it('KEEPS the retired `api.requireAuth` warn-and-ignore posture (#3963)', () => {
181+
// The tombstone is `.omit()`ed from the validation on purpose: #3963
182+
// chose warn-and-ignore for this key, and converting that into a boot
183+
// failure is that decision's to make. 96 in-repo fixtures still pass it.
184+
expect(() => construct({ requireAuth: false, version: 'v1' })).not.toThrow();
185+
});
186+
});

‎packages/rest/src/rest-openapi-route.test.ts‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -426,27 +426,20 @@ describe('GET /openapi.json — what `info.version` carries (#11546)', () => {
426426
}
427427
});
428428

429-
it('serves a falsy `api.version` as itself rather than falling back to the artifact', async () => {
430-
// The removed `|| enriched.info.version` was reachable, not dead — though
431-
// not because the contract permits `''`. `RestApiConfigSchema` refuses it
432-
// (`z.string().regex(/^[a-zA-Z0-9_\-\.]+$/)`); nothing parses this config
433-
// against that schema, so `??` is the only guard and `''` walks past it.
434-
// Measured on the pre-fix code this served the spec package's compile-time
435-
// version — the exact value the old comment said the line existed to keep
436-
// off the wire.
429+
it('refuses a falsy `api.version` at construction — there is no such server to ask [#11637]', () => {
430+
// RETIRED AND REPLACED, on this pin's own instruction ("if normalization
431+
// starts rejecting it, retire the pin"). It used to assert that a server
432+
// built with `version: ''` mounted at `/api/` and published
433+
// `info.version: ''` — observable only because nothing ran
434+
// `RestApiConfigSchema` against this config. #11637 made the seam parse
435+
// instead of cast, so `RestServer` refuses the construction and the
436+
// doubled-slash mount is unreachable.
437437
//
438-
// An empty version is a broken deployment either way (the mount doubles its
439-
// slash, below). The point of the pin is that it stays visibly broken
440-
// instead of quietly publishing a different kind of fact.
441-
const rest = makeRest(makeProtocol({ object: [], api: [] }).protocol, { version: '' });
442-
expect(
443-
(rest as any).getApiBasePath(),
444-
'this pin describes the empty-version mount — if normalization starts rejecting it, retire the pin',
445-
).toBe('/api/');
446-
447-
const artifact = await (rest as any).loadOpenApiSpec();
448-
const { body } = await serveOpenApiFrom(rest, '/api/');
449-
expect(body.info.version).toBe('');
450-
expect(body.info.version).not.toBe(artifact.info.version);
438+
// The fact the old pin protected is unchanged and still covered above:
439+
// there is still NO `|| enriched.info.version` fallback, so a configured
440+
// version is served as itself. What changed is that `''` is no longer a
441+
// configurable version.
442+
expect(() => makeRest(makeProtocol({ object: [], api: [] }).protocol, { version: '' }))
443+
.toThrow(/api\.version/);
451444
});
452445
});

0 commit comments

Comments
 (0)