Skip to content

Commit 5a21e58

Browse files
committed
fix(objectql): the engine refuses an empty projection, as every published declaration does
ObjectQL.find / findOne read fields: [] as every column, and an expand entry's fields: [] the same way, while the HTTP doors and EngineQueryOptionsSchema.fields refuse it. The entry now refuses it with the declaration's own words and the doors' 400 VALIDATION_ERROR, before any driver read. An absent fields still reads every column. Claude-Session: https://claude.ai/code/session_01FEkQ5mbUpy4ebfWUHxAv87 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 07d18e6 commit 5a21e58

3 files changed

Lines changed: 315 additions & 0 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#27008] An empty projection — `fields: []` — is refused by the engine's
5+
* `find` and `findOne` with `VALIDATION_ERROR` / 400, before any driver is
6+
* asked. So is an empty projection on an `expand` entry, at any depth.
7+
*
8+
* ## One rule
9+
*
10+
* #26817, #26909 and #26954 settled it: an empty projection is refused, never
11+
* read as every column. The HTTP doors refuse `select: []`
12+
* (`projectionFieldsValue` in `@objectstack/metadata-protocol`, `400
13+
* VALIDATION_ERROR`), and every published declaration of a read's projection
14+
* refuses it too, `EngineQueryOptionsSchema.fields` included. The engine never
15+
* parses its options with that schema, and its projection guards ran only when
16+
* `ast.fields.length > 0`, so `fields: []` reached the driver. Every driver
17+
* serves an empty projection as none: a plugin, a hook through `ctx.api` or a
18+
* flow that built an empty list by mistake got owner, organization and audit
19+
* columns back, and was not told. Measured on `origin/main` `07d18e69` with
20+
* `engine.find(obj, { fields: [] })`, `findOne` and an
21+
* `expand: { rel: { fields: [] } }` entry: every column, under no error.
22+
*
23+
* ## Same refusal as the doors
24+
*
25+
* The words are the declaration's own, read off the published
26+
* `EngineQueryOptionsSchema.fields` rather than copied, and the error carries
27+
* the status and code the door's does, so `mapDataError` answers an
28+
* in-process caller and a REST caller with the same `400 VALIDATION_ERROR`.
29+
* The rule is about the shape, not the caller: a system-context read is
30+
* refused too. An absent (or `null`) `fields` still means every column.
31+
*
32+
* ## Why `expand` is judged at the entry
33+
*
34+
* An `expand` entry's projection is forwarded to the related object's own
35+
* `find`, so that sub-read would refuse it — but `expandRelatedRecords` keeps
36+
* the bare foreign key when a sub-read throws, so the refusal would reach the
37+
* caller as a silently unexpanded field. Judged here, before the parent read,
38+
* it reaches the caller as a refusal.
39+
*/
40+
41+
import { EngineQueryOptionsSchema } from '@objectstack/spec/data';
42+
43+
let declaredRefusal: string | undefined;
44+
45+
/** The declaration's own words for a projection naming no field. */
46+
function projectionNamesNoField(): string | undefined {
47+
declaredRefusal ??= EngineQueryOptionsSchema.shape.fields.safeParse([]).error?.issues[0]?.message;
48+
return declaredRefusal;
49+
}
50+
51+
function refuseEmptyProjection(object: string, operation: 'find' | 'findOne', param: string): never {
52+
const err: any = new Error(
53+
`ObjectQL.${operation}('${object}') names no field in ${param}: got []. The query was not run: `
54+
+ 'an empty projection was read as no projection, which answers every column. '
55+
+ `${projectionNamesNoField()}, or leave the projection out to read every column.`,
56+
);
57+
// The status and code `projectionFieldsValue` throws at the HTTP doors, so
58+
// a host surfacing engine errors answers the same envelope on both.
59+
err.status = 400;
60+
err.code = 'VALIDATION_ERROR';
61+
err.param = param;
62+
err.object = object;
63+
throw err;
64+
}
65+
66+
function assertExpandProjections(
67+
object: string,
68+
operation: 'find' | 'findOne',
69+
expand: unknown,
70+
prefix: string,
71+
): void {
72+
if (expand == null || typeof expand !== 'object') return;
73+
for (const [relation, nested] of Object.entries(expand)) {
74+
if (nested == null || typeof nested !== 'object') continue;
75+
const at = `${prefix}expand['${relation}']`;
76+
const fields = (nested as { fields?: unknown }).fields;
77+
if (Array.isArray(fields) && fields.length === 0) refuseEmptyProjection(object, operation, `${at}.fields`);
78+
assertExpandProjections(object, operation, (nested as { expand?: unknown }).expand, `${at}.`);
79+
}
80+
}
81+
82+
/**
83+
* Refuse a read whose projection, or any `expand` entry's projection, names
84+
* no field. Runs at the entry of `find` / `findOne`, after the option-key
85+
* gate, before any driver call.
86+
*/
87+
export function assertProjectionNamesAField(
88+
object: string,
89+
operation: 'find' | 'findOne',
90+
query: { fields?: unknown; expand?: unknown } | undefined,
91+
): void {
92+
if (!query) return;
93+
if (Array.isArray(query.fields) && query.fields.length === 0) refuseEmptyProjection(object, operation, "'fields'");
94+
assertExpandProjections(object, operation, query.expand, '');
95+
}
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#27008] The in-process engine refuses an empty projection, as every
5+
* published declaration of a read's projection does.
6+
*
7+
* #26817, #26909 and #26954 settled one rule: an empty projection is refused,
8+
* never read as every column. The HTTP doors refuse `select: []`
9+
* (`projectionFieldsValue`, `400 VALIDATION_ERROR`) and
10+
* `EngineQueryOptionsSchema.fields` declares the same refusal, but
11+
* `ObjectQL.find` / `findOne` never parse their options with that schema. Their
12+
* projection guards ran only when `ast.fields.length > 0`, so `fields: []`
13+
* reached the driver, and every driver serves an empty projection as none:
14+
* owner, organization and audit columns came back, and the caller was not told.
15+
*
16+
* Driven against a REAL {@link ObjectQL} engine over a driver double that
17+
* projects exactly (an empty list answers every column, as `SqlDriver` and
18+
* `InMemoryDriver` do) and counts its reads, so "refused before any driver
19+
* call" is measured rather than assumed.
20+
*/
21+
22+
import { describe, it, expect, beforeEach } from 'vitest';
23+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
24+
import { EngineQueryOptionsSchema } from '@objectstack/spec/data';
25+
import { mapDataError } from '@objectstack/types';
26+
import { ObjectQL } from './engine.js';
27+
28+
const projectObject = {
29+
name: 'proj_27008',
30+
label: 'Project',
31+
fields: {
32+
id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true },
33+
name: { name: 'name', label: 'Name', type: 'text' as const },
34+
},
35+
};
36+
37+
const taskObject = {
38+
name: 'task_27008',
39+
label: 'Task',
40+
fields: {
41+
id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true },
42+
title: { name: 'title', label: 'Title', type: 'text' as const },
43+
project_id: { name: 'project_id', label: 'Project', type: 'lookup' as const, reference: 'proj_27008' },
44+
},
45+
};
46+
47+
/** The declarations' own refusal words, read off the published schema. */
48+
const declaredRefusal = (): string => {
49+
const parsed = EngineQueryOptionsSchema.shape.fields.safeParse([]);
50+
expect(parsed.success).toBe(false);
51+
return parsed.error!.issues[0].message;
52+
};
53+
54+
function makeDriver() {
55+
const rows: Record<string, Record<string, unknown>[]> = {
56+
proj_27008: [{ id: 'p1', name: 'Apollo', owner_id: 'usr_1', organization_id: 'org_1' }],
57+
task_27008: [{
58+
id: 't1', title: 'Ship', project_id: 'p1',
59+
owner_id: 'usr_1', organization_id: 'org_1', created_at: '2026-10-28T00:00:00.000Z',
60+
}],
61+
};
62+
const reads: Array<{ object: string; fields: unknown }> = [];
63+
const project = (row: Record<string, unknown>, fields: unknown) =>
64+
Array.isArray(fields) && fields.length > 0
65+
? Object.fromEntries(fields.map((f: string) => [f, row[f]]))
66+
: { ...row };
67+
const matches = (row: Record<string, unknown>, where: any): boolean => {
68+
if (!where || typeof where !== 'object') return true;
69+
for (const [k, v] of Object.entries(where)) {
70+
if (k === '$and' && Array.isArray(v)) {
71+
if (!v.every((arm) => matches(row, arm))) return false;
72+
continue;
73+
}
74+
if (v && typeof v === 'object' && '$in' in (v as any)) {
75+
if (!(v as any).$in.map(String).includes(String(row[k]))) return false;
76+
continue;
77+
}
78+
const expected = v && typeof v === 'object' && '$eq' in (v as any) ? (v as any).$eq : v;
79+
if (row[k] !== expected) return false;
80+
}
81+
return true;
82+
};
83+
const driver: any = {
84+
name: 'memory',
85+
version: '0.0.0',
86+
supports: {},
87+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
88+
async find(object: string, ast: any) {
89+
reads.push({ object, fields: ast?.fields });
90+
return (rows[object] ?? []).filter((r) => matches(r, ast?.where)).map((r) => project(r, ast?.fields));
91+
},
92+
async findOne(object: string, ast: any) {
93+
reads.push({ object, fields: ast?.fields });
94+
const hit = (rows[object] ?? []).find((r) => matches(r, ast?.where));
95+
return hit ? project(hit, ast?.fields) : null;
96+
},
97+
async create(_o: string, d: any) { return d; },
98+
async update(_o: string, _id: string, d: any) { return d; },
99+
async delete() { return true; },
100+
async count(object: string) { return (rows[object] ?? []).length; },
101+
async bulkCreate(_o: string, r: any[]) { return r; },
102+
async bulkUpdate() { return []; }, async bulkDelete() {},
103+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
104+
async commit() {}, async rollback() {},
105+
};
106+
return { driver, reads };
107+
}
108+
109+
/** The refusal as the REST door would answer it: `mapDataError`'s status and code. */
110+
async function wireAnswer(read: Promise<unknown>) {
111+
const err = await read.then(
112+
() => { throw new Error('expected a refusal, got an answer'); },
113+
(e: unknown) => e,
114+
);
115+
const mapped = mapDataError(err);
116+
return { status: mapped.status, code: mapped.body.code, message: (err as Error).message };
117+
}
118+
119+
describe('[#27008] the in-process engine refuses an empty projection', () => {
120+
let engine: ObjectQL;
121+
let reads: Array<{ object: string; fields: unknown }>;
122+
123+
beforeEach(async () => {
124+
engine = new ObjectQL();
125+
const made = makeDriver();
126+
reads = made.reads;
127+
engine.registerDriver(made.driver, true);
128+
await engine.init();
129+
engine.registry.registerObject(projectObject, 'test-package');
130+
engine.registry.registerObject(taskObject, 'test-package');
131+
});
132+
133+
it('find with fields: [] is refused 400 VALIDATION_ERROR in the declarations\' words, before any driver read', async () => {
134+
const answer = await wireAnswer(engine.find('task_27008', { fields: [] }));
135+
expect(answer).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
136+
expect(answer.message).toContain(declaredRefusal());
137+
expect(answer.message).toMatch(/^ObjectQL\.find\('task_27008'\) names no field in 'fields'/);
138+
expect(reads).toEqual([]);
139+
});
140+
141+
it('findOne with fields: [] is refused the same way, before any driver read', async () => {
142+
const answer = await wireAnswer(engine.findOne('task_27008', { where: { id: 't1' }, fields: [] }));
143+
expect(answer).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
144+
expect(answer.message).toContain(declaredRefusal());
145+
expect(answer.message).toMatch(/^ObjectQL\.findOne\('task_27008'\)/);
146+
expect(reads).toEqual([]);
147+
});
148+
149+
it('a system-context read is refused too: the rule is about the shape, not the caller', async () => {
150+
const answer = await wireAnswer(engine.find('task_27008', { fields: [], context: { isSystem: true } }));
151+
expect(answer).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
152+
expect(reads).toEqual([]);
153+
});
154+
155+
it('an expand sub-read with fields: [] is refused at the entry, not swallowed into a bare foreign key', async () => {
156+
// The expansion's own `catch` keeps the foreign key on a sub-read failure,
157+
// so a refusal raised only inside the sub-read would degrade silently. The
158+
// entry judges the nested projection before the parent row is read.
159+
const answer = await wireAnswer(engine.find('task_27008', {
160+
expand: { project_id: { object: 'proj_27008', fields: [] } },
161+
}));
162+
expect(answer).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
163+
expect(answer.message).toContain(declaredRefusal());
164+
expect(answer.message).toContain("expand['project_id']");
165+
expect(reads).toEqual([]);
166+
});
167+
168+
it('a deeper expand level is judged too', async () => {
169+
const answer = await wireAnswer(engine.findOne('task_27008', {
170+
where: { id: 't1' },
171+
expand: { project_id: { object: 'proj_27008', fields: ['name'], expand: { owner: { object: 'sys_user', fields: [] } } } },
172+
}));
173+
expect(answer).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
174+
expect(answer.message).toContain("expand['project_id'].expand['owner']");
175+
expect(reads).toEqual([]);
176+
});
177+
178+
it('the REST door answers the same status and code for the same projection', async () => {
179+
const protocol = new ObjectStackProtocolImplementation(engine);
180+
const door = await wireAnswer(protocol.findData({ object: 'task_27008', query: { select: [] } }));
181+
const inProcess = await wireAnswer(engine.find('task_27008', { fields: [] }));
182+
expect({ status: inProcess.status, code: inProcess.code }).toEqual({ status: door.status, code: door.code });
183+
expect(door).toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
184+
expect(door.message).toContain(declaredRefusal());
185+
expect(reads).toEqual([]);
186+
});
187+
188+
// ─── Controls ────────────────────────────────────────────────────
189+
190+
it('CONTROL: an absent fields still reads every column', async () => {
191+
const [row] = await engine.find('task_27008', {});
192+
expect(row).toMatchObject({ id: 't1', title: 'Ship', owner_id: 'usr_1', organization_id: 'org_1' });
193+
expect(reads).toHaveLength(1);
194+
});
195+
196+
it('CONTROL: fields: null is a withdrawal and reads every column', async () => {
197+
const [row] = await engine.find('task_27008', { fields: null as unknown as string[] });
198+
expect(row).toMatchObject({ id: 't1', title: 'Ship', owner_id: 'usr_1' });
199+
});
200+
201+
it('CONTROL: a named projection projects', async () => {
202+
const [row] = await engine.find('task_27008', { fields: ['title'] });
203+
expect(row).toEqual({ title: 'Ship' });
204+
const one = await engine.findOne('task_27008', { where: { id: 't1' }, fields: ['title'] });
205+
expect(one).toEqual({ title: 'Ship' });
206+
});
207+
208+
it('CONTROL: an expand with a named nested projection still expands', async () => {
209+
const [row] = await engine.find('task_27008', {
210+
fields: ['title', 'project_id'],
211+
expand: { project_id: { object: 'proj_27008', fields: ['name'] } },
212+
});
213+
expect(row).toEqual({ title: 'Ship', project_id: { name: 'Apollo' } });
214+
});
215+
});

‎packages/objectql/src/engine.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ import {
303303
// each body the members it reads (`CountAggregateHost`).
304304
import { count, rejectCredentialAggregation } from './engine-count-aggregate.js';
305305
import { assertGroupByNamesNoJsonStoredField } from './group-by-structured-json-door.js';
306+
import { assertProjectionNamesAField } from './empty-projection-door.js';
306307
import { assertAggregationFieldTypesAccepted } from './aggregate-field-type-door.js';
307308
import { assertAggregatedColumnsAreDistinct, assertDateBucketTargetsAreTemporal } from './aggregate-query-shape-door.js';
308309
import { applyProtection, pluralToSingular, ExternalWriteForbiddenError } from '@objectstack/spec/shared';
@@ -13519,6 +13520,8 @@ export class ObjectQL implements IObjectQLEngine {
1351913520
// (#4371, three shipped instances in #4370).
1352013521
query = foldEngineOptionAliases(object, 'find', query, ENGINE_QUERY_SLOTS, ENGINE_WIRE_ONLY_SLOTS);
1352113522
rejectUnknownEngineOptions(object, 'find', query, ENGINE_FIND_OPTION_KEYS);
13523+
// [#27008] An empty projection is refused, never read as every column.
13524+
assertProjectionNamesAField(object, 'find', query);
1352213525
query = lowerWhereFilterArray(object, 'find', query, this._registry.getObject(object), this.relatedSchemaOf);
1352313526
this.logger.debug('Find operation starting', { object, query });
1352413527
const driver = this.getDriver(object);
@@ -13847,6 +13850,8 @@ export class ObjectQL implements IObjectQLEngine {
1384713850
// matters here too: findOne({ sort }) means "first row of THIS order".
1384813851
query = foldEngineOptionAliases(objectName, 'findOne', query, ENGINE_QUERY_SLOTS, ENGINE_WIRE_ONLY_SLOTS);
1384913852
rejectUnknownEngineOptions(objectName, 'findOne', query, ENGINE_FIND_OPTION_KEYS);
13853+
// [#27008] Same refusal as find().
13854+
assertProjectionNamesAField(objectName, 'findOne', query);
1385013855
query = lowerWhereFilterArray(objectName, 'findOne', query, this._registry.getObject(objectName), this.relatedSchemaOf);
1385113856
this.logger.debug('FindOne operation', { objectName });
1385213857
const driver = this.getDriver(objectName);

0 commit comments

Comments
 (0)