|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #4371 option (2) — an engine option-bag key the engine does not execute is |
| 5 | + * REJECTED at the entry point instead of silently ignored. |
| 6 | + * |
| 7 | + * The engine declares a query contract (`Engine*OptionsSchema`) but never |
| 8 | + * parses it at runtime, so before this gate ANY key outside the contract — |
| 9 | + * a typo (`orderby`), a retired key (`cursor`), a wire-protocol leftover |
| 10 | + * (`object`, `count`), a key that only works on OTHER methods (`tenantId` on |
| 11 | + * `count`) — rode along and was dropped without a trace. The per-method legal |
| 12 | + * sets mirror the schemas plus the documented extras (`searchFields`, |
| 13 | + * `onFieldsDropped`, the driver pass-through keys); the drift pin at the |
| 14 | + * bottom keeps them from falling out of step with the spec. |
| 15 | + */ |
| 16 | + |
| 17 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 18 | +import { |
| 19 | + EngineQueryOptionsSchema, |
| 20 | + EngineUpdateOptionsSchema, |
| 21 | + EngineDeleteOptionsSchema, |
| 22 | + EngineCountOptionsSchema, |
| 23 | + EngineAggregateOptionsSchema, |
| 24 | +} from '@objectstack/spec/data'; |
| 25 | +import { ObjectQL, ENGINE_OPTION_KEY_SETS } from './engine.js'; |
| 26 | + |
| 27 | +const task = { |
| 28 | + name: 'task', |
| 29 | + label: 'Task', |
| 30 | + fields: { |
| 31 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 32 | + title: { name: 'title', type: 'text' as const }, |
| 33 | + status: { name: 'status', type: 'text' as const }, |
| 34 | + owner: { name: 'owner', type: 'lookup' as const, reference: 'person' }, |
| 35 | + }, |
| 36 | +}; |
| 37 | +const person = { |
| 38 | + name: 'person', |
| 39 | + label: 'Person', |
| 40 | + fields: { |
| 41 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 42 | + name: { name: 'name', type: 'text' as const }, |
| 43 | + }, |
| 44 | +}; |
| 45 | + |
| 46 | +function makeDriver() { |
| 47 | + const stores = new Map<string, Map<string, Record<string, unknown>>>(); |
| 48 | + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; |
| 49 | + const finds: any[] = []; |
| 50 | + let nextId = 0; |
| 51 | + const matches = (row: any, where: any): boolean => { |
| 52 | + if (!where || typeof where !== 'object') return true; |
| 53 | + for (const [k, v] of Object.entries(where)) { |
| 54 | + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); |
| 55 | + if (k.startsWith('$')) continue; |
| 56 | + const exp = (v && typeof v === 'object' && '$in' in (v as any)) ? (v as any).$in : v; |
| 57 | + if (Array.isArray(exp)) { if (!exp.includes(row[k])) return false; } |
| 58 | + else if ((row[k] ?? null) !== (exp ?? null)) return false; |
| 59 | + } |
| 60 | + return true; |
| 61 | + }; |
| 62 | + const run = (o: string, ast: any) => { |
| 63 | + let rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); |
| 64 | + if (Array.isArray(ast?.orderBy) && ast.orderBy.length > 0) { |
| 65 | + rows = [...rows].sort((a: any, b: any) => { |
| 66 | + for (const { field, order } of ast.orderBy) { |
| 67 | + const cmp = String(a?.[field] ?? '').localeCompare(String(b?.[field] ?? '')); |
| 68 | + if (cmp !== 0) return order === 'desc' ? -cmp : cmp; |
| 69 | + } |
| 70 | + return 0; |
| 71 | + }); |
| 72 | + } |
| 73 | + return typeof ast?.limit === 'number' && ast.limit > 0 ? rows.slice(0, ast.limit) : rows; |
| 74 | + }; |
| 75 | + const driver: any = { |
| 76 | + name: 'memory', version: '0.0.0', supports: {}, |
| 77 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 78 | + async find(o: string, ast: any) { finds.push(ast); return run(o, ast); }, |
| 79 | + async findOne(o: string, ast: any) { finds.push(ast); return run(o, ast)[0] ?? null; }, |
| 80 | + findStream() { throw new Error('ns'); }, |
| 81 | + async create(o: string, data: any) { nextId += 1; const id = data.id ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; }, |
| 82 | + async update(o: string, id: string, data: any) { const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error('nf'); const up = { ...cur, ...data, id }; s.set(id, up); return up; }, |
| 83 | + async updateMany(o: string, ast: any, data: any) { let n = 0; for (const [id, row] of storeFor(o)) { if (!matches(row, ast?.where)) continue; storeFor(o).set(id, { ...row, ...data, id }); n += 1; } return n; }, |
| 84 | + async delete(o: string, id: string) { return storeFor(o).delete(id); }, |
| 85 | + async deleteMany(o: string, ast: any) { let n = 0; for (const [id, row] of [...storeFor(o)]) { if (!matches(row, ast?.where)) continue; storeFor(o).delete(id); n += 1; } return n; }, |
| 86 | + async count(o: string, ast: any) { return run(o, ast).length; }, |
| 87 | + async aggregate(o: string, ast: any) { return [{ n: run(o, ast).length }]; }, |
| 88 | + async bulkCreate(o: string, rows: any[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, |
| 89 | + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, async commit() {}, async rollback() {}, |
| 90 | + }; |
| 91 | + return { driver, stores, finds }; |
| 92 | +} |
| 93 | + |
| 94 | +describe('unknown engine option keys are rejected (#4371 option 2)', () => { |
| 95 | + let engine: ObjectQL; |
| 96 | + let finds: any[]; |
| 97 | + let a: any; |
| 98 | + |
| 99 | + beforeEach(async () => { |
| 100 | + engine = new ObjectQL(); |
| 101 | + const mem = makeDriver(); |
| 102 | + finds = mem.finds; |
| 103 | + engine.registerDriver(mem.driver, true); |
| 104 | + await engine.init(); |
| 105 | + engine.registry.registerObject(task as any); |
| 106 | + engine.registry.registerObject(person as any); |
| 107 | + await engine.insert('person', { id: 'p1', name: 'P' }); |
| 108 | + a = await engine.insert('task', { title: 'A', status: 'open', owner: 'p1' }); |
| 109 | + await engine.insert('task', { title: 'B', status: 'done', owner: 'p1' }); |
| 110 | + finds.length = 0; |
| 111 | + }); |
| 112 | + |
| 113 | + // ── each method refuses a key it does not execute ─────────────────── |
| 114 | + |
| 115 | + it.each([ |
| 116 | + ['find', () => engine.find('task', { bogus: 1 } as any)], |
| 117 | + ['findOne', () => engine.findOne('task', { bogus: 1 } as any)], |
| 118 | + ['update', () => engine.update('task', { title: 'Z' }, { where: { id: 'x' }, bogus: 1 } as any)], |
| 119 | + ['delete', () => engine.delete('task', { where: { id: 'x' }, bogus: 1 } as any)], |
| 120 | + ['count', () => engine.count('task', { bogus: 1 } as any)], |
| 121 | + ['aggregate', () => engine.aggregate('task', { aggregations: [{ function: 'count', alias: 'n' }], bogus: 1 } as any)], |
| 122 | + ])('%s rejects an unknown option, naming the legal set', async (method, call) => { |
| 123 | + await expect(call()).rejects.toThrow( |
| 124 | + new RegExp(`${method}\\('task'\\) does not recognise option 'bogus'.*Legal keys for ${method}:`, 's'), |
| 125 | + ); |
| 126 | + }); |
| 127 | + |
| 128 | + it('a typo like `orderby` is caught, not silently unsorted', async () => { |
| 129 | + await expect(engine.find('task', { orderby: [{ field: 'title', order: 'asc' }] } as any)) |
| 130 | + .rejects.toThrow(/'orderby'/); |
| 131 | + expect(finds).toHaveLength(0); |
| 132 | + }); |
| 133 | + |
| 134 | + it('several unknown keys are reported in ONE rejection', async () => { |
| 135 | + await expect(engine.find('task', { bogus: 1, extra: 2 } as any)) |
| 136 | + .rejects.toThrow(/options 'bogus'; 'extra'/); |
| 137 | + }); |
| 138 | + |
| 139 | + // ── retired keys quote their tombstone ────────────────────────────── |
| 140 | + |
| 141 | + it.each(['cursor', 'distinct'])('%s is rejected with its #4286 tombstone', async (key) => { |
| 142 | + await expect(engine.find('task', { [key]: 'x' } as any)) |
| 143 | + .rejects.toThrow(/#4286, ADR-0049/); |
| 144 | + }); |
| 145 | + |
| 146 | + // ── null stays a withdrawal ───────────────────────────────────────── |
| 147 | + |
| 148 | + it('a null-valued unknown key is a withdrawal, not a rejection', async () => { |
| 149 | + const rows = await engine.find('task', { bogus: null } as any); |
| 150 | + expect(rows).toHaveLength(2); |
| 151 | + }); |
| 152 | + |
| 153 | + // ── the documented extras stay legal where they work ──────────────── |
| 154 | + |
| 155 | + it('driver pass-through keys (tenantId, bypassTenantAudit) pass on find/update/delete', async () => { |
| 156 | + await engine.find('task', { tenantId: 't1', bypassTenantAudit: true } as any); |
| 157 | + await engine.update('task', { title: 'A2' }, { where: { id: a.id }, tenantId: 't1' } as any); |
| 158 | + await engine.delete('task', { where: { id: a.id }, bypassTenantAudit: true } as any); |
| 159 | + }); |
| 160 | + |
| 161 | + it.each([ |
| 162 | + ['count', () => engine.count('task', { tenantId: 't1' } as any)], |
| 163 | + ['aggregate', () => engine.aggregate('task', { aggregations: [{ function: 'count', alias: 'n' }], tenantId: 't1' } as any)], |
| 164 | + ])('%s rejects driver pass-through keys — its bag never reaches the driver options', async (_m, call) => { |
| 165 | + await expect(call()).rejects.toThrow(/'tenantId'/); |
| 166 | + }); |
| 167 | + |
| 168 | + it('onFieldsDropped passes on update (contract-declared write observability)', async () => { |
| 169 | + await engine.update('task', { title: 'A3' }, { where: { id: a.id }, onFieldsDropped: () => {} } as any); |
| 170 | + }); |
| 171 | + |
| 172 | + it('searchFields passes on find (read by the $search expansion)', async () => { |
| 173 | + // Legality pin only — the $or/$contains expansion itself is covered by |
| 174 | + // the search-filter tests; this mock driver does not evaluate it. |
| 175 | + await expect(engine.find('task', { search: 'A', searchFields: ['title'] } as any)) |
| 176 | + .resolves.toBeDefined(); |
| 177 | + }); |
| 178 | + |
| 179 | + it('the OData spellings $search/$searchFields are unknown keys — wire-only, protocol folds them', async () => { |
| 180 | + await expect(engine.find('task', { $search: 'A' } as any)).rejects.toThrow(/'\$search'/); |
| 181 | + }); |
| 182 | + |
| 183 | + it('a stray `object` key is refused — it used to OVERRIDE the resolved object on the AST', async () => { |
| 184 | + await expect(engine.find('task', { object: 'person' } as any)).rejects.toThrow(/'object'/); |
| 185 | + expect(finds).toHaveLength(0); |
| 186 | + }); |
| 187 | + |
| 188 | + // ── expand nested ASTs reject wire spellings too ──────────────────── |
| 189 | + |
| 190 | + it("expand: { owner: { sort } } is refused — nested wire spellings were silently dropped", async () => { |
| 191 | + await expect( |
| 192 | + engine.find('task', { expand: { owner: { object: 'person', sort: { name: 'asc' } } } } as any), |
| 193 | + ).rejects.toThrow(/expand\['owner'\] on 'task' does not accept 'sort'.*Pass 'orderBy'/s); |
| 194 | + }); |
| 195 | + |
| 196 | + it('expand with canonical nested keys works', async () => { |
| 197 | + const rows = await engine.find('task', { |
| 198 | + where: { id: a.id }, |
| 199 | + expand: { owner: { object: 'person', fields: ['id', 'name'] } }, |
| 200 | + } as any); |
| 201 | + expect(rows[0].owner).toMatchObject({ id: 'p1', name: 'P' }); |
| 202 | + }); |
| 203 | + |
| 204 | + // ── drift pin: legal sets stay glued to the spec schemas ──────────── |
| 205 | + |
| 206 | + it('each legal set covers its schema shape (minus tombstones) and only the documented extras', () => { |
| 207 | + const TOMBSTONES = new Set(['cursor', 'distinct']); |
| 208 | + const PASSTHROUGH = ['transaction', 'tenantId', 'tenantIds', 'timezone', 'bypassTenantAudit', 'preserveAudit']; |
| 209 | + const expectSetMatches = ( |
| 210 | + setName: string, |
| 211 | + schema: { shape: Record<string, unknown> }, |
| 212 | + extras: string[], |
| 213 | + ) => { |
| 214 | + const legal = ENGINE_OPTION_KEY_SETS[setName]; |
| 215 | + const schemaKeys = Object.keys(schema.shape).filter((k) => !TOMBSTONES.has(k)); |
| 216 | + for (const k of schemaKeys) { |
| 217 | + // `top` folds into `limit` before the gate and never reaches it. |
| 218 | + if (k === 'top') continue; |
| 219 | + expect(legal.has(k), `${setName} must accept schema key '${k}'`).toBe(true); |
| 220 | + } |
| 221 | + const documented = new Set([...schemaKeys, ...extras]); |
| 222 | + for (const k of legal) { |
| 223 | + expect(documented.has(k), `${setName} accepts '${k}' which neither the schema nor the documented extras declare`).toBe(true); |
| 224 | + } |
| 225 | + }; |
| 226 | + expectSetMatches('find', EngineQueryOptionsSchema as any, PASSTHROUGH); |
| 227 | + expectSetMatches('findOne', EngineQueryOptionsSchema as any, PASSTHROUGH); |
| 228 | + expectSetMatches('update', EngineUpdateOptionsSchema as any, ['onFieldsDropped', ...PASSTHROUGH]); |
| 229 | + expectSetMatches('delete', EngineDeleteOptionsSchema as any, PASSTHROUGH); |
| 230 | + expectSetMatches('count', EngineCountOptionsSchema as any, []); |
| 231 | + expectSetMatches('aggregate', EngineAggregateOptionsSchema as any, []); |
| 232 | + }); |
| 233 | +}); |
0 commit comments