|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #4371 — a direct engine call carrying a wire-only alias spelling |
| 5 | + * (`sort`/`select`/`skip`/`populate`) is REJECTED, not silently dropped. |
| 6 | + * |
| 7 | + * Regression: #4346 folds `filter`→`where` and `top`→`limit` on every engine |
| 8 | + * entry point, but the other four pairs in `RPC_QUERY_ALIAS_SLOTS` fold at the |
| 9 | + * RPC/protocol layer only (their value shapes need lowering that belongs |
| 10 | + * there). A direct `engine.find()` never crosses that layer, so the alias key |
| 11 | + * rode the AST verbatim, drivers read only the canonical name, and the request |
| 12 | + * SUCCEEDED with the parameter discarded — `sort` + `limit` ("the latest N") |
| 13 | + * silently returning an arbitrary N. Three shipped instances were fixed in |
| 14 | + * #4370; a fourth sat in the engine's own `seedAutonumber`. The engine now |
| 15 | + * throws at the boundary, naming the canonical key and shape, while the |
| 16 | + * RPC/wire path keeps folding exactly as before — the fold must NOT move. |
| 17 | + */ |
| 18 | + |
| 19 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 20 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 21 | +import { ObjectQL } from './engine.js'; |
| 22 | + |
| 23 | +const task = { |
| 24 | + name: 'task', |
| 25 | + label: 'Task', |
| 26 | + fields: { |
| 27 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 28 | + title: { name: 'title', type: 'text' as const }, |
| 29 | + status: { name: 'status', type: 'text' as const }, |
| 30 | + }, |
| 31 | +}; |
| 32 | + |
| 33 | +/** Memory driver that records every AST handed to find/findOne. */ |
| 34 | +function makeRecordingDriver() { |
| 35 | + const stores = new Map<string, Map<string, Record<string, unknown>>>(); |
| 36 | + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; |
| 37 | + const finds: any[] = []; |
| 38 | + let nextId = 0; |
| 39 | + const matches = (row: Record<string, unknown>, where: any): boolean => { |
| 40 | + if (!where || typeof where !== 'object') return true; |
| 41 | + for (const [k, v] of Object.entries(where)) { |
| 42 | + if (k.startsWith('$')) continue; |
| 43 | + const exp = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; |
| 44 | + if ((row[k] ?? null) !== (exp ?? null)) return false; |
| 45 | + } |
| 46 | + return true; |
| 47 | + }; |
| 48 | + const run = (o: string, ast: any) => { |
| 49 | + let rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); |
| 50 | + const ord = Array.isArray(ast?.orderBy) ? ast.orderBy : []; |
| 51 | + if (ord.length > 0) { |
| 52 | + rows = [...rows].sort((a: any, b: any) => { |
| 53 | + for (const { field, order } of ord) { |
| 54 | + const cmp = String(a?.[field] ?? '').localeCompare(String(b?.[field] ?? '')); |
| 55 | + if (cmp !== 0) return order === 'desc' ? -cmp : cmp; |
| 56 | + } |
| 57 | + return 0; |
| 58 | + }); |
| 59 | + } |
| 60 | + if (typeof ast?.offset === 'number' && ast.offset > 0) rows = rows.slice(ast.offset); |
| 61 | + return typeof ast?.limit === 'number' && ast.limit > 0 ? rows.slice(0, ast.limit) : rows; |
| 62 | + }; |
| 63 | + const driver: any = { |
| 64 | + name: 'memory', version: '0.0.0', supports: {}, |
| 65 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 66 | + async find(o: string, ast: any) { finds.push(ast); return run(o, ast); }, |
| 67 | + findStream() { throw new Error('ns'); }, |
| 68 | + async findOne(o: string, ast: any) { finds.push(ast); return run(o, ast)[0] ?? null; }, |
| 69 | + async create(o: string, data: Record<string, unknown>) { |
| 70 | + nextId += 1; const id = (data.id as string) ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; |
| 71 | + }, |
| 72 | + async update(o: string, id: string, data: Record<string, unknown>) { |
| 73 | + const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error(`nf ${o}/${id}`); |
| 74 | + const up = { ...cur, ...data, id }; s.set(id, up); return up; |
| 75 | + }, |
| 76 | + async delete(o: string, id: string) { return storeFor(o).delete(id); }, |
| 77 | + async count(o: string, ast: any) { return run(o, ast).length; }, |
| 78 | + async bulkCreate(o: string, rows: Record<string, unknown>[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, |
| 79 | + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, async commit() {}, async rollback() {}, |
| 80 | + }; |
| 81 | + return { driver, stores, finds }; |
| 82 | +} |
| 83 | + |
| 84 | +describe('wire-only alias spellings are rejected on direct engine calls (#4371)', () => { |
| 85 | + let engine: ObjectQL; |
| 86 | + let finds: any[]; |
| 87 | + |
| 88 | + beforeEach(async () => { |
| 89 | + engine = new ObjectQL(); |
| 90 | + const mem = makeRecordingDriver(); |
| 91 | + finds = mem.finds; |
| 92 | + engine.registerDriver(mem.driver, true); |
| 93 | + await engine.init(); |
| 94 | + engine.registry.registerObject(task as any); |
| 95 | + await engine.insert('task', { title: 'B', status: 'done' }); |
| 96 | + await engine.insert('task', { title: 'A', status: 'open' }); |
| 97 | + await engine.insert('task', { title: 'C', status: 'done' }); |
| 98 | + finds.length = 0; // drop insert-path reads; the pins below own this log |
| 99 | + }); |
| 100 | + |
| 101 | + // ── each wire spelling throws before the driver sees anything ────── |
| 102 | + |
| 103 | + it.each([ |
| 104 | + ['sort', { created_at: 'asc' }, 'orderBy'], |
| 105 | + ['select', ['id', 'title'], 'fields'], |
| 106 | + ['skip', 10, 'offset'], |
| 107 | + ['populate', ['owner'], 'expand'], |
| 108 | + ])('find({%s}) is refused, naming the canonical key', async (alias, value, canonical) => { |
| 109 | + await expect(engine.find('task', { [alias]: value } as any)).rejects.toThrow( |
| 110 | + new RegExp(`wire spelling of '${canonical}'.*Pass '${canonical}'`, 's'), |
| 111 | + ); |
| 112 | + expect(finds).toHaveLength(0); |
| 113 | + }); |
| 114 | + |
| 115 | + it('findOne({sort}) is refused too — "first row of THIS order" degrades the same way', async () => { |
| 116 | + await expect(engine.findOne('task', { sort: { title: 'asc' } } as any)) |
| 117 | + .rejects.toThrow(/findOne\('task'\) does not accept 'sort'/); |
| 118 | + expect(finds).toHaveLength(0); |
| 119 | + }); |
| 120 | + |
| 121 | + it('a sort already in SortNode[] shape is still refused — the KEY is the contract', async () => { |
| 122 | + await expect(engine.find('task', { sort: [{ field: 'title', order: 'asc' }] } as any)) |
| 123 | + .rejects.toThrow(/wire spelling of 'orderBy'/); |
| 124 | + }); |
| 125 | + |
| 126 | + it('several wire spellings at once are reported in ONE rejection', async () => { |
| 127 | + await expect( |
| 128 | + engine.find('task', { sort: { title: 'asc' }, populate: ['owner'] } as any), |
| 129 | + ).rejects.toThrow(/'sort'.*'populate'|'populate'.*'sort'/s); |
| 130 | + }); |
| 131 | + |
| 132 | + // ── the canonical spellings all work — the migration target is real ─ |
| 133 | + |
| 134 | + it('find({where, fields, orderBy, offset, limit}) reaches the driver canonically', async () => { |
| 135 | + const rows = await engine.find('task', { |
| 136 | + where: { status: 'done' }, |
| 137 | + fields: ['id', 'title'], |
| 138 | + orderBy: [{ field: 'title', order: 'desc' }], |
| 139 | + offset: 0, |
| 140 | + limit: 10, |
| 141 | + }); |
| 142 | + expect(rows.map((r: any) => r.title)).toEqual(['C', 'B']); |
| 143 | + expect(finds).toHaveLength(1); |
| 144 | + expect(finds[0].orderBy).toEqual([{ field: 'title', order: 'desc' }]); |
| 145 | + expect(finds[0].sort).toBeUndefined(); |
| 146 | + }); |
| 147 | + |
| 148 | + // ── null stays a withdrawal, exactly like the folded slots ────────── |
| 149 | + |
| 150 | + it('an explicit null wire spelling is a withdrawal, not a rejection', async () => { |
| 151 | + const rows = await engine.find('task', { sort: null } as any); |
| 152 | + expect(rows).toHaveLength(3); |
| 153 | + }); |
| 154 | + |
| 155 | + // ── the folded pairs did not regress behind the new parameter ────── |
| 156 | + |
| 157 | + it('find({filter, top}) still folds (#4346) with the rejection guard in place', async () => { |
| 158 | + const rows = await engine.find('task', { filter: { status: 'done' }, top: 1 } as any); |
| 159 | + expect(rows).toHaveLength(1); |
| 160 | + expect(finds[0].where).toEqual({ status: 'done' }); |
| 161 | + expect(finds[0].limit).toBe(1); |
| 162 | + }); |
| 163 | + |
| 164 | + // ── the RPC/wire path still folds — the fold must NOT move (#4371 pin 3) ─ |
| 165 | + |
| 166 | + it('wire `sort` through the protocol layer folds to orderBy and passes the guard', async () => { |
| 167 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 168 | + const out: any = await protocol.findData({ object: 'task', query: { sort: '-title' } }); |
| 169 | + expect(out.records.map((r: any) => r.title)).toEqual(['C', 'B', 'A']); |
| 170 | + expect(finds).toHaveLength(1); |
| 171 | + expect(finds[0].orderBy).toEqual([{ field: 'title', order: 'desc' }]); |
| 172 | + expect(finds[0].sort).toBeUndefined(); |
| 173 | + }); |
| 174 | + |
| 175 | + it('wire `select`/`skip`/`populate` through the protocol layer pass the guard as canonical keys', async () => { |
| 176 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 177 | + const out: any = await protocol.findData({ |
| 178 | + object: 'task', |
| 179 | + query: { select: 'id,title', skip: 1, sort: 'title' }, |
| 180 | + }); |
| 181 | + expect(out.records.map((r: any) => r.title)).toEqual(['B', 'C']); |
| 182 | + expect(finds[0].fields).toEqual(expect.arrayContaining(['id', 'title'])); |
| 183 | + expect(finds[0].offset).toBe(1); |
| 184 | + expect(finds[0].select).toBeUndefined(); |
| 185 | + expect(finds[0].skip).toBeUndefined(); |
| 186 | + }); |
| 187 | +}); |
0 commit comments