|
| 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 | +}); |
0 commit comments