Skip to content

Commit 1d7816d

Browse files
fix(rest): GET /data/:object/:id answers a malformed query 400, not 404 (#26895)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XWgL6EWwuEAw4Nr2sBGh9VT)_ Fixes #26816 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`GET /api/v1/data/:object/:id` 遇到写错的查询参数(`?select=nope`、空的 `?select=`、`?expand=nope`)现在回 400,不再回 404;回包内容不变。 - 为什么改:404 让调用方(包括 AI)以为记录不存在而放弃,实际错在自己的查询串;运行时 dispatcher 的同名路由早就回 400,两个入口答案不一致。 - 风险与回滚:只影响这条路由的错误状态码;记录不存在、或调用方无权读取的记录,仍然回 404 `RECORD_NOT_FOUND`,且 400 不会泄露记录是否存在。回滚即 revert 本 PR。 - 先看:`packages/rest/src/crud-routes.ts`(by-id 的 catch)、`packages/rest/src/data-record-read-malformed-query-door.test.ts`、`packages/runtime/src/domains/data-record-read-status-parity.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run src/data-record-read-malformed-query-door.test.ts`,预期 12 个用例全绿;对一条存在的记录请求 `?select=nope` 应看到 400 `INVALID_FIELD`。 - 需要你做的:无,席位落地。 ## What changes `RestServer`'s `GET /api/v1/data/:object/:id` catch answered every mapped `400` as `404` (`res.status(mapped.status === 400 ? 404 : mapped.status)`). It now answers the mapped status, like every other Data API route in `crud-routes.ts` and like the runtime dispatcher's twin route. | request | before | after | |:--|:--|:--| | own record, `?select=nope` | 404 `INVALID_FIELD` | 400 `INVALID_FIELD`, same body | | own record, `?select=` / `?select=,` | 404 `VALIDATION_ERROR` | 400 `VALIDATION_ERROR`, same body | | own record, `?expand=nope` | 404 `INVALID_FIELD` | 400 `INVALID_FIELD`, same body | | missing id | 404 `RECORD_NOT_FOUND` | unchanged | | a row the caller's row scope hides | 404 `RECORD_NOT_FOUND` | unchanged | ### Why the rewrite existed, and why removing it keeps the existence guarantee The order asked to find this first. `git log -S` on a full-history checkout: - `1d884a5d31` (2026-01-30, the first REST server) answered **every** error on this route `404` (`res.status(404).json({ error: error.message })`). - `867ad87e5e` (2026-04-30) introduced `mapDataError`, whose fallback was then "anything else becomes a 400 (bad request) preserving prior behavior". To keep this route's old blanket 404, the catch folded that 400 band back to 404. The commit is a feature commit (audit objects); nothing in it is about hiding whether a record exists. - `bb7ccde666` (2026-10-17) moved the line into `crud-routes.ts` unchanged. So it was compatibility with a blanket 404, not an existence guard. The existence property still holds without it, for two reasons the new tests pin: 1. **Missing or unreadable is one answer by construction.** Row scope makes the read return no row; `getData` then throws `RECORD_NOT_FOUND`, which declares `404` (`@objectstack/core` `recordNotFoundError`). Neither case ever went through the rewrite. 2. **A 400 says nothing about existence.** Every `400` `getData` raises on this route (unknown `select` / `expand` entry, empty projection) is raised before the record is read, so the body is byte-identical for the caller's row, a hidden row and an id that exists nowhere. Which errors still map to `404` on this route: `RECORD_NOT_FOUND` (missing id, and a row the caller may not read), `OBJECT_NOT_FOUND` (unregistered object), and the `OBJECT_API_DISABLED` exposure refusal. Each declares its own `404`; none depended on the rewrite. ### Other by-id routes Re-checked on `main` at `5787df4d4b`: `PATCH` and `DELETE /data/:object/:id` in `crud-routes.ts` already answer `mapped.status`. `git grep` for the rewrite across `packages/rest/src` and `packages/runtime/src` finds only this line. Nothing else changed. ### Departure from the order The order asked the green pin to carry "the error code and `param` the dispatcher gives". Measured: neither host puts `param` on the wire. The dispatcher's envelope carries `code`, `message`, and for `INVALID_FIELD` a `details.field` / `details.object`; REST's flat body carries `code`, `error`, `field`, `object`. The parameter is named only in the sentence. So the tests pin the code, the field, and that the sentence names the parameter, and that the two hosts give the same sentence. Putting `param` on the wire would be a change to the shared classifier in `@objectstack/types`, outside this card's file surface. ### Comments updated - The `[#7606]` note above `refuseUnknownQueryParams` on this route said the gate responds because the catch rewrites 400 to 404; it now says that was the reason until this change. - `rest-server-closed-query-params.test.ts` and `data-empty-projection-count-door.test.ts` described the rewrite as current; both now say it is gone, and the latter also asserts the 400. ## Tests - New `packages/rest/src/data-record-read-malformed-query-door.test.ts`: the REST door over a real `ObjectQL`, `SqlDriver` (SQLite) and the real `SecurityPlugin` with a row-scope rule. Pins the four malformed queries at 400 with their body; the same bytes for the caller's, a hidden and a missing id; the missing-id and hidden-row 404 controls; the served 200s. - New `packages/runtime/src/domains/data-record-read-status-parity.test.ts`: one store, both hosts (`RestServer` and `HttpDispatcher`, through both host exits), eleven requests, the same status, code, field and sentence on each. Red first on `main` (`5787df4d4b`, tests only, fix not applied): - REST door: 4 failed, 8 passed. Each failure is `expected 404 to be 400` for `?select=nope`, `?select=`, `?select=,`, `?expand=nope`. - Parity: 6 failed, 5 passed. Each failure is `RestServer: expected { status: 404 } to deeply equal { status: 400 }`. The five controls (missing id, hidden row, hidden row with `?select=title`, two 200s) already agreed. Green on the fix: both files pass (12/12 and 11/11), with `data-empty-projection-count-door.test.ts`, `rest-server-closed-query-params.test.ts` and `data-empty-projection-count.test.ts`. The red run is the ablation: the base code is the mutation, and the same tests go red on it. ## Acceptance notes - No `packages/spec/**` and no `ui/**`. - The rewrite touched the 400 band only, so every other answer on this route is byte-for-byte what it was: a 403 permission refusal, the declared 404s, 409s and the 5xx fault terminals. - The hidden-row 404 pinned here is the row-scope case, the one where a 400 could have mattered for existence. ## Verification All local readings are on head `a9c1ef10ae`. The test and typecheck runs were on `f17981e56a`; the only later commit adds the changeset file. - `pnpm --filter @objectstack/rest typecheck && pnpm --filter @objectstack/rest test`: VERDICT command-exit 0. Test Files 329 passed, Tests 6525 passed, 326 skipped. - `pnpm --filter @objectstack/runtime typecheck`: VERDICT command-exit 0. `pnpm --filter @objectstack/runtime test`: VERDICT command-exit 0. Test Files 461 passed, Tests 7468 passed, 19 skipped. - `pnpm exec eslint --no-inline-config packages/rest packages/runtime`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 59 commands. Each ran with its exit code captured by redirect before any pipe. 58 exited 0. - `pnpm check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET: some package has no `dist/`; this container built only the runtime closure). It is NOT MEASURED locally, and CI runs it. - `--ran`: "59 derived, 58 run, 1 NOT-MEASURED, 0 UNRUN", exit 0. - Also run: `check-platform-checklist.mjs --changed-from origin/main` exit 0, `check-commit-card-trailers.mjs --range origin/main..HEAD` exit 0. - `test:repo` (the vitest `repo` project) is CI's: the diff adds no file it lists. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The six-line maintainer brief above is Chinese, as the dispatch contract asks.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5md6KXHiW13KzwWFDG --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8a218fc commit 1d7816d

6 files changed

Lines changed: 480 additions & 18 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): `GET /api/v1/data/:object/:id` answers a malformed query `400`, not `404`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The by-id route answered every refusal in the `400` band as `404`, so a malformed query on a record that exists read as "no such record": `?select=nope` and `?expand=nope` answered `404 INVALID_FIELD`, and a blank `?select=` (or `?select=,`) answered `404 VALIDATION_ERROR`. A client, or an AI agent, told `404` concludes the record is missing and stops, when the fault is its own query string. The runtime dispatcher's twin route already answered the same requests `400`.
11+
12+
The route now answers the mapped status, as every other Data API route does. The body is unchanged: the same `code`, `error`, `field` and `object` the `404` carried.
13+
14+
What still answers `404 RECORD_NOT_FOUND`, unchanged: an id that names no record, and a record the caller's row scope hides. Those two are the same answer by construction (a read that returns no row), and neither ever went through the rewrite. A `400` does not reveal whether a record exists: each one is raised before the record is read, so it is the same for any id.

‎packages/rest/src/crud-routes.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,12 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo
205205
// caller who may not read this object should not learn
206206
// the shape of its ingress before being refused.
207207
//
208-
// This gate RESPONDS rather than throwing, which on this
209-
// route is load-bearing and not a style choice: the catch
210-
// below rewrites every 400 into a 404 (a bad id is a
211-
// miss, not a malformed request). A refusal routed
212-
// through it would reach the caller as "no such record"
213-
// — the silent-drop defect wearing a different status.
208+
// This gate RESPONDS rather than throwing, as every
209+
// `refuseUnknownQueryParams` door does. That was
210+
// load-bearing here while the catch below rewrote every
211+
// 400 into a 404; since #26816 it answers the mapped
212+
// status, so the catch no longer turns a refusal into
213+
// "no such record" either way.
214214
if (refuseUnknownQueryParams(req, res, DATA_RECORD_READ_PARAMS)) return;
215215
const { select, expand } = req.query || {};
216216
const getRequest: ServerScopedDataRequest<GetDataRequest> = {
@@ -224,9 +224,21 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo
224224
const result = await p.getData(getRequest);
225225
res.json(result);
226226
} catch (error: any) {
227+
// [#26816] The mapped status, as on every other data route
228+
// and on the dispatcher's twin. This catch used to answer
229+
// every mapped 400 as 404 — a rewrite kept from the days
230+
// it answered EVERY error 404 (867ad87e5e), not an
231+
// existence guard — so a malformed query on a real record
232+
// (`?select=nope`, a blank `?select=`) read as "no such
233+
// record". The 404s need no rewrite: a missing id and a
234+
// row the caller may not read are the same no-row read,
235+
// which `getData` answers `RECORD_NOT_FOUND`, declared
236+
// 404. And a 400 says nothing about existence: each one
237+
// `getData` raises comes before the read, byte-identical
238+
// for any id (`data-record-read-malformed-query-door.test.ts`).
227239
const mapped = mapDataError(error, req.params?.object);
228240
logUnexpectedRouteError(error, mapped);
229-
res.status(mapped.status === 400 ? 404 : mapped.status).json(mapped.body);
241+
res.status(mapped.status).json(mapped.body);
230242
}
231243
},
232244
metadata: {

‎packages/rest/src/data-empty-projection-count-door.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
* | `GET ?$count=maybe`, `?$count=1`, `?count=` (with `$top`) | 200, `total` reported | 400 naming the spelling |
1616
* | `POST {"select":""}`, `{"fields":[]}` | 200, every column | 400 naming the key |
1717
* | `POST {"count":"maybe"}` | 400 `VALIDATION_FAILED` (the body schema) | unchanged |
18-
* | `GET /:id?select=`, `?select=,` | 200, every column | `VALIDATION_ERROR` naming `select`, at this route's 404 (it rewrites every 400, as for `?select=nope`) |
18+
* | `GET /:id?select=`, `?select=,` | 200, every column | `VALIDATION_ERROR` naming `select`, at this route's 404 (it rewrote every 400, as for `?select=nope`); 400 since #26816 |
1919
* | `GET ?$select=label`, `?$count=true` / `false`, absent; `GET /:id?select=label` | 200 | unchanged |
2020
*
2121
* The per-spelling pin with a recording engine is `metadata-protocol`'s
@@ -168,12 +168,12 @@ describe('[#26644] an empty projection and an unrecognised count flag on the Dat
168168
});
169169

170170
it("GET by id: VALIDATION_ERROR naming `select`, at the status this route gives every projection refusal — no read", async () => {
171-
// This route's catch rewrites every 400 into a 404 (`crud-routes.ts`: "a
172-
// bad id is a miss"), so its projection refusals already answer 404 — an
173-
// unknown `select` field included. The empty projection joins that answer
174-
// rather than inventing a second one here; the code is what differs.
171+
// The same status as an unknown `select` field; the code is what differs.
172+
// That status is 400 since #26816 (the catch used to rewrite every 400
173+
// into a 404; `data-record-read-malformed-query-door.test.ts`).
175174
const unknownField = await byId({ select: 'nope' });
176175
expect(unknownField.body.code, JSON.stringify(unknownField.body)).toBe('INVALID_FIELD');
176+
expect(unknownField.status).toBe(400);
177177
const before = reads.n;
178178
for (const select of ['', ',']) {
179179
const res = await byId({ select });
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26816] `GET /api/v1/data/:object/:id` answers a malformed query at its own
5+
* status, `400`, and keeps `404` for a record that is missing or that the
6+
* caller may not read — with the REAL security layer (`SecurityPlugin` on a
7+
* real `ObjectQL` over a real `SqlDriver`).
8+
*
9+
* The route's catch used to answer every mapped `400` as `404`. That rewrite
10+
* was not an existence guard: until 867ad87e5e (2026-04-30) the catch answered
11+
* EVERY error `404`, and the rewrite kept that answer for the mapper's `400`
12+
* band when the mapper arrived. What it hid since is the request-shape
13+
* refusals `getData` raises before it reads anything — an unknown `select` or
14+
* `expand` entry (`INVALID_FIELD`) and an empty projection (`VALIDATION_ERROR`,
15+
* #26644) — so a caller was told "no such record" about its own query string,
16+
* while the runtime dispatcher's twin route answered the same request `400`.
17+
*
18+
* Measured on the base (`5787df4d4b`), and again on the fix:
19+
*
20+
* | request | base | fix |
21+
* |:--|:--|:--|
22+
* | own record, `?select=nope` | 404 `INVALID_FIELD` | 400, the same body |
23+
* | own record, `?select=`, `?select=,` | 404 `VALIDATION_ERROR` | 400, the same body |
24+
* | own record, `?expand=nope` | 404 `INVALID_FIELD` | 400, the same body |
25+
* | missing id | 404 `RECORD_NOT_FOUND` | unchanged |
26+
* | a row the caller's row scope hides | 404 `RECORD_NOT_FOUND` | unchanged |
27+
* | own record, `?select=title` / no query | 200 | unchanged |
28+
*
29+
* Why the `404`s need no rewrite: a missing row and a row the caller may not
30+
* read are one answer by construction — row scope makes the read return no
31+
* row, and `getData` then throws `RECORD_NOT_FOUND`, which DECLARES `404`.
32+
* And why the `400` leaks nothing about existence: every one of them is raised
33+
* before the read, so it is byte-identical whether the id names the caller's
34+
* row, a hidden row or no row at all — pinned below.
35+
*
36+
* The dispatcher's half, and the two hosts compared request for request, is
37+
* `packages/runtime/src/domains/data-record-read-status-parity.test.ts`.
38+
*/
39+
40+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
41+
import { PermissionSetSchema } from '@objectstack/spec/security';
42+
import { ObjectQL } from '@objectstack/objectql';
43+
import { SqlDriver } from '@objectstack/driver-sql';
44+
import { SecurityPlugin } from '@objectstack/plugin-security';
45+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
46+
import { RestServer } from './rest-server';
47+
import { installDefaultOrganization } from './default-organization.testkit.js';
48+
49+
const OBJECT = 'rest_by_id_query_26816';
50+
const ME = 'usr_26816_member';
51+
const OTHER = 'usr_26816_other';
52+
const SYS_CTX = { isSystem: true, userId: 'usr_system' };
53+
54+
const MEMBER_SET = PermissionSetSchema.parse({
55+
name: 'member_default',
56+
label: 'Member',
57+
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
58+
// The caller reads its own rows only.
59+
rowLevelSecurity: [{ name: 'own_rows', object: OBJECT, operation: 'select', using: 'record.owner == current_user.id' }],
60+
});
61+
const MEMBER_CTX = { userId: ME, positions: [], permissions: [MEMBER_SET.name], posture: 'MEMBER' };
62+
63+
/** The caller's row, a row its row scope hides, and an id no row has. */
64+
const MINE = 'r_mine';
65+
const HIDDEN = 'r_hidden';
66+
const NOWHERE = 'r_nowhere';
67+
68+
/**
69+
* name · the querystring · the code · the field the body names (an unknown
70+
* entry only) · the parameter its sentence names.
71+
*/
72+
const MALFORMED: ReadonlyArray<readonly [string, Record<string, string>, string, string | undefined, string]> = [
73+
['?select=nope (the card)', { select: 'nope' }, 'INVALID_FIELD', 'nope', 'select'],
74+
['?select= blank (the card)', { select: '' }, 'VALIDATION_ERROR', undefined, 'select'],
75+
['?select=, comma-only', { select: ',' }, 'VALIDATION_ERROR', undefined, 'select'],
76+
['?expand=nope', { expand: 'nope' }, 'INVALID_FIELD', 'nope', 'expand'],
77+
];
78+
79+
function createMockServer() {
80+
const noop = () => {};
81+
return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
82+
}
83+
84+
function makeRes() {
85+
const res: any = {
86+
write: () => true, end: () => {},
87+
header: () => res,
88+
status: (code: number) => { res._status = code; return res; },
89+
json: (body: any) => { res._json = body; return res; },
90+
};
91+
return res;
92+
}
93+
94+
describe('[#26816] GET /data/:object/:id — a malformed query is a 400, a missing or unreadable record a 404', () => {
95+
let engine: ObjectQL;
96+
let byId: (id: string, query: Record<string, string>) => Promise<{ status: number; body: any }>;
97+
98+
beforeAll(async () => {
99+
engine = new ObjectQL();
100+
engine.registerDriver(
101+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any),
102+
true,
103+
);
104+
await engine.init();
105+
engine.registerApp({
106+
id: 'com.objectstack.qa.by-id-malformed-query-26816',
107+
name: 'By-id read: a malformed query is not a missing record',
108+
version: '1.0.0',
109+
type: 'plugin',
110+
scope: 'system',
111+
objects: [
112+
{
113+
name: OBJECT,
114+
label: 'Ledger',
115+
sharingModel: 'public_read_write',
116+
fields: {
117+
title: { name: 'title', type: 'text' },
118+
owner: { name: 'owner', type: 'text' },
119+
},
120+
},
121+
],
122+
} as never);
123+
await engine.syncSchemas();
124+
// A real `single` install's Default Organization: the system writes below
125+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
126+
await installDefaultOrganization(engine);
127+
128+
const services: Record<string, unknown> = {
129+
manifest: { register: vi.fn() },
130+
objectql: engine,
131+
metadata: {
132+
get: async (_type: string, name: string) => engine.getSchema(name) ?? null,
133+
list: async () => [MEMBER_SET],
134+
},
135+
};
136+
const ctx = {
137+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
138+
registerService: vi.fn(),
139+
getService: (name: string) => {
140+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
141+
return services[name];
142+
},
143+
};
144+
const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
145+
await plugin.init(ctx as never);
146+
await plugin.start(ctx as never);
147+
148+
await engine.insert(OBJECT, [
149+
{ id: MINE, title: 'mine', owner: ME },
150+
{ id: HIDDEN, title: 'theirs', owner: OTHER },
151+
], { context: SYS_CTX } as never);
152+
153+
const protocol = new ObjectStackProtocolImplementation(engine as any);
154+
const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any);
155+
(rest as any).resolveExecCtx = async () => ({ ...MEMBER_CTX });
156+
rest.registerRoutes();
157+
const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/:id');
158+
expect(route).toBeDefined();
159+
byId = async (id, query) => {
160+
const res = makeRes();
161+
await route!.handler({ params: { object: OBJECT, id }, query, headers: {} } as any, res);
162+
return { status: res._status ?? 200, body: res._json };
163+
};
164+
});
165+
166+
afterAll(async () => {
167+
try { await engine?.destroy(); } catch { /* noop */ }
168+
});
169+
170+
it('precondition: the caller reads its own row and its row scope hides the other one', async () => {
171+
const read = (id: string) => engine.findOne(OBJECT, { where: { id }, context: { ...MEMBER_CTX } } as never);
172+
expect((await read(MINE) as any)?.title).toBe('mine');
173+
expect(await read(HIDDEN)).toBeNull();
174+
});
175+
176+
it.each(MALFORMED)('%s on the caller\'s own record: 400 with the mapped body — its code, and the field and parameter it names', async (_name, query, code, field, param) => {
177+
const res = await byId(MINE, query);
178+
expect(res.status, JSON.stringify(res.body)).toBe(400);
179+
expect(res.body.code).toBe(code);
180+
expect(res.body.field).toBe(field);
181+
expect(res.body.object).toBe(OBJECT);
182+
// The parameter is named in the sentence only: the thrown error's `param`
183+
// reaches neither host's wire body.
184+
expect(res.body.error).toContain(`'${param}'`);
185+
});
186+
187+
it.each(MALFORMED)('%s answers the same bytes whether the id is the caller\'s, hidden, or nowhere — the 400 says nothing about existence', async (_name, query) => {
188+
const mine = await byId(MINE, query);
189+
expect(await byId(HIDDEN, query)).toEqual(mine);
190+
expect(await byId(NOWHERE, query)).toEqual(mine);
191+
});
192+
193+
it('CONTROL a missing id is 404 RECORD_NOT_FOUND', async () => {
194+
const res = await byId(NOWHERE, {});
195+
expect(res.status, JSON.stringify(res.body)).toBe(404);
196+
expect(res.body.code).toBe('RECORD_NOT_FOUND');
197+
});
198+
199+
it('CONTROL a row the caller may not read is the missing id\'s 404 — the same answer, but for the id', async () => {
200+
const hidden = await byId(HIDDEN, {});
201+
const missing = await byId(NOWHERE, {});
202+
expect(hidden.status, JSON.stringify(hidden.body)).toBe(404);
203+
expect(hidden.body.code).toBe('RECORD_NOT_FOUND');
204+
expect(JSON.stringify(hidden).split(HIDDEN).join('ID')).toBe(JSON.stringify(missing).split(NOWHERE).join('ID'));
205+
// …and a well-formed projection does not tell them apart either.
206+
const hiddenProjected = await byId(HIDDEN, { select: 'title' });
207+
expect(hiddenProjected.status, JSON.stringify(hiddenProjected.body)).toBe(404);
208+
expect(hiddenProjected.body.code).toBe('RECORD_NOT_FOUND');
209+
});
210+
211+
it('CONTROL the caller\'s own record is served, projected or whole', async () => {
212+
const projected = await byId(MINE, { select: 'title' });
213+
expect(projected.status, JSON.stringify(projected.body)).toBe(200);
214+
expect(projected.body.record.title).toBe('mine');
215+
expect('owner' in projected.body.record).toBe(false);
216+
217+
const whole = await byId(MINE, {});
218+
expect(whole.status, JSON.stringify(whole.body)).toBe(200);
219+
expect(whole.body.record.owner).toBe(ME);
220+
});
221+
});

‎packages/rest/src/rest-server-closed-query-params.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,12 +188,12 @@ describe('#7606 §1 — GET /data/:object/:id refuses what it would have dropped
188188
expect(getData).not.toHaveBeenCalled();
189189
});
190190

191-
it('the refusal stays a 400 — the catch that rewrites 400→404 must not swallow it', async () => {
192-
// This route's catch turns every 400 into a 404 (a bad id is a miss,
193-
// not a malformed request). The gate RESPONDS rather than throwing
194-
// precisely so a refusal cannot reach the caller as "no such record" —
195-
// the silent-drop defect wearing a different status. If someone later
196-
// converts the gate to `throw`, this is the test that goes red.
191+
it('the refusal is a 400 — never "no such record"', async () => {
192+
// This route's catch used to turn every 400 into a 404, and the gate
193+
// RESPONDED rather than throwing so a refusal could not reach the
194+
// caller as "no such record". Since #26816 the catch answers the
195+
// mapped status; the pin stays, so a refusal reading as a miss — by
196+
// either road — is still the test that goes red.
197197
const { readRecord } = boot();
198198
const answer = await readRecord({ nope: '1' }, { object: 'task', id: '1' });
199199
expect(answer.status).toBe(400);

0 commit comments

Comments
 (0)