Skip to content

Commit 9010861

Browse files
committed
test(objectql): pin the queryable-field search narrowing
1 parent 7e37c11 commit 9010861

2 files changed

Lines changed: 216 additions & 0 deletions

File tree

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25672] A `search` resolves only over fields the caller may QUERY.
5+
*
6+
* The field-read predicate guard (plugin-security) runs after the expansion and
7+
* judges the expanded `$or` as the caller's own predicate, so one hidden column
8+
* in the server-resolved set refused the whole search with 403: `sys_user`
9+
* searches `role` / `ban_reason` / `last_login_ip`, and every user picker broke
10+
* for members. The engine now asks the registered `security` service's
11+
* `getQueryableFields` (the complement of what that guard refuses) and
12+
* withholds the rest from the RESOLVED set.
13+
*
14+
* Pinned beside the narrowing, so a fix that over-reaches goes red here too: a
15+
* field the caller NAMES in `searchFields` is never withheld (the guard refuses
16+
* it loudly); a context-less read, an absent service and an `undefined` answer
17+
* narrow nothing; a declaration whose fields are all hidden does not fall
18+
* through to the auto-default; and a set withheld down to nothing is the
19+
* #24284 refusal, not every row.
20+
*/
21+
22+
import { describe, it, expect, beforeEach } from 'vitest';
23+
import { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js';
24+
25+
type Row = Record<string, unknown>;
26+
27+
const MEMBER = { userId: 'u_member', organizationId: 'org_1' };
28+
29+
function makeDriver() {
30+
const seen: Array<{ verb: string; object: string; where: unknown }> = [];
31+
const record = (verb: string) => async (object: string, ast: any) => {
32+
seen.push({ verb, object, where: ast?.where });
33+
return verb === 'count' ? 0 : verb === 'findOne' ? null : [];
34+
};
35+
const driver: any = {
36+
name: 'mem', version: '0.0.0', supports: {},
37+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
38+
find: record('find'),
39+
findOne: record('findOne'),
40+
count: record('count'),
41+
async create(_o: string, d: any) { return d; },
42+
async update(_o: string, _id: string, d: any) { return d; },
43+
async delete() { return true; },
44+
async bulkCreate(_o: string, r: any[]) { return r; },
45+
async bulkUpdate() { return []; }, async bulkDelete() {},
46+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
47+
async commit() {}, async rollback() {},
48+
};
49+
return { driver, seen };
50+
}
51+
52+
/** Every field name a filter tree mentions as a key. */
53+
function fieldsOf(where: unknown, out: Set<string> = new Set()): Set<string> {
54+
if (Array.isArray(where)) { for (const w of where) fieldsOf(w, out); return out; }
55+
if (!where || typeof where !== 'object') return out;
56+
for (const [k, v] of Object.entries(where as Row)) {
57+
if (k.startsWith('$')) fieldsOf(v, out);
58+
else out.add(k);
59+
}
60+
return out;
61+
}
62+
63+
describe('[#25672] search resolves only over the fields the caller may query', () => {
64+
let engine: ObjectQL;
65+
let seen: ReturnType<typeof makeDriver>['seen'];
66+
let asked: Array<{ object: string; context: unknown }>;
67+
let queryable: Record<string, string[] | undefined>;
68+
69+
const wire = (svc: unknown) => {
70+
(engine as unknown as Record<symbol, unknown>)[SECURITY_SERVICE_SOURCE_SLOT] = () => svc;
71+
};
72+
73+
beforeEach(async () => {
74+
const made = makeDriver();
75+
seen = made.seen;
76+
engine = new ObjectQL();
77+
engine.registerDriver(made.driver, true);
78+
await engine.init();
79+
const registry = engine.registry as any;
80+
// The `sys_user` shape: a declared search set holding admin-only columns.
81+
registry.registerObject({
82+
name: 'app_person',
83+
nameField: 'name',
84+
searchableFields: ['name', 'email', 'role', 'ban_reason'],
85+
fields: {
86+
name: { type: 'text' },
87+
email: { type: 'email' },
88+
role: { type: 'text' },
89+
ban_reason: { type: 'text' },
90+
},
91+
}, 'test');
92+
// A second shape: the auto-default set, one textual column hidden.
93+
registry.registerObject({
94+
name: 'app_ticket',
95+
fields: { subject: { type: 'text' }, private_note: { type: 'textarea' } },
96+
}, 'test');
97+
// Every declared search field hidden from the member.
98+
registry.registerObject({
99+
name: 'app_secret',
100+
searchableFields: ['code'],
101+
fields: { code: { type: 'text' }, label: { type: 'text' } },
102+
}, 'test');
103+
asked = [];
104+
queryable = {
105+
app_person: ['id', 'name', 'email'],
106+
app_ticket: ['id', 'subject'],
107+
app_secret: ['id', 'label'],
108+
};
109+
wire({
110+
async getQueryableFields(object: string, context: unknown) {
111+
asked.push({ object, context });
112+
return queryable[object];
113+
},
114+
});
115+
});
116+
117+
const lastWhere = () => seen[seen.length - 1]?.where;
118+
119+
it.each([
120+
['find', (e: ObjectQL) => e.find('app_person', { search: 'ann', context: MEMBER as any })],
121+
['findOne', (e: ObjectQL) => e.findOne('app_person', { search: 'ann', context: MEMBER as any })],
122+
['count', (e: ObjectQL) => e.count('app_person', { search: 'ann', context: MEMBER as any })],
123+
] as const)('%s searches only the queryable declared fields, asked with the caller context', async (_verb, run) => {
124+
await run(engine);
125+
expect([...fieldsOf(lastWhere())].sort()).toEqual(['email', 'name']);
126+
expect(asked).toEqual([{ object: 'app_person', context: expect.objectContaining(MEMBER) }]);
127+
});
128+
129+
it('aggregate searches the same narrowed set', async () => {
130+
const where: unknown[] = [];
131+
(engine as any).getDriver('app_person').aggregate = async (_o: string, ast: any) => { where.push(ast?.where); return []; };
132+
await engine.aggregate('app_person', {
133+
search: 'ann', groupBy: ['name'], aggregations: [{ function: 'count', alias: 'n' }], context: MEMBER as any,
134+
}).catch(() => undefined);
135+
const named = new Set([...where, lastWhere()].flatMap((w) => [...fieldsOf(w)]));
136+
expect(named.has('role')).toBe(false);
137+
expect(named.has('ban_reason')).toBe(false);
138+
expect(named.has('name')).toBe(true);
139+
});
140+
141+
it('is general: an auto-default set loses its hidden column on another object', async () => {
142+
await engine.find('app_ticket', { search: 'printer', context: MEMBER as any });
143+
expect([...fieldsOf(lastWhere())]).toEqual(['subject']);
144+
});
145+
146+
it('a field the caller NAMES in searchFields is not withheld — the guard judges it', async () => {
147+
await engine.find('app_person', { search: 'spam', searchFields: ['name', 'ban_reason'], context: MEMBER as any });
148+
expect([...fieldsOf(lastWhere())].sort()).toEqual(['ban_reason', 'name']);
149+
});
150+
151+
it('a caller who may query every field gets the full declared set', async () => {
152+
queryable.app_person = ['id', 'name', 'email', 'role', 'ban_reason'];
153+
await engine.find('app_person', { search: 'ann', context: { userId: 'u_admin' } as any });
154+
expect([...fieldsOf(lastWhere())].sort()).toEqual(['ban_reason', 'email', 'name', 'role']);
155+
});
156+
157+
it('narrows nothing without an answer: no context, no service, no method, or undefined', async () => {
158+
const full = ['ban_reason', 'email', 'name', 'role'];
159+
await engine.find('app_person', { search: 'ann' });
160+
expect([...fieldsOf(lastWhere())].sort()).toEqual(full);
161+
expect(asked).toEqual([]);
162+
163+
queryable.app_person = undefined;
164+
await engine.find('app_person', { search: 'ann', context: MEMBER as any });
165+
expect([...fieldsOf(lastWhere())].sort()).toEqual(full);
166+
167+
wire({});
168+
await engine.find('app_person', { search: 'ann', context: MEMBER as any });
169+
expect([...fieldsOf(lastWhere())].sort()).toEqual(full);
170+
171+
(engine as unknown as Record<symbol, unknown>)[SECURITY_SERVICE_SOURCE_SLOT] = () => { throw new Error('not registered'); };
172+
await engine.find('app_person', { search: 'ann', context: MEMBER as any });
173+
expect([...fieldsOf(lastWhere())].sort()).toEqual(full);
174+
});
175+
176+
it('a blank term asks nothing and adds no predicate', async () => {
177+
await engine.find('app_person', { search: ' ', context: MEMBER as any });
178+
expect(asked).toEqual([]);
179+
expect(lastWhere()).toBeUndefined();
180+
});
181+
182+
it('a declared set withheld to nothing is the #24284 refusal, never every row nor the auto-default', async () => {
183+
const err: any = await engine.find('app_secret', { search: 'x', context: MEMBER as any }).then(() => null, (e) => e);
184+
expect(err).toMatchObject({ code: 'INVALID_FIELD', status: 400, object: 'app_secret', param: 'search' });
185+
expect(String(err.message)).toMatch(/^Object 'app_secret' has no field this caller may search/);
186+
expect(seen.filter((s) => s.object === 'app_secret')).toEqual([]);
187+
});
188+
});

‎packages/objectql/src/search-filter.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,31 @@ describe('expandSearchToFilter', () => {
249249
});
250250
});
251251
});
252+
253+
describe('[#25672] queryableFields withholds what the caller may not query', () => {
254+
const fields = { name: { type: 'text' }, email: { type: 'email' }, ban_reason: { type: 'text' } };
255+
const searchableFields = ['name', 'email', 'ban_reason'];
256+
const queryableFields = new Set(['name', 'email']);
257+
const named = (f: unknown) => (f as { $or: Array<Record<string, unknown>> }).$or.map((c) => Object.keys(c)[0]);
258+
259+
it('withholds a resolved field outside the set', () => {
260+
expect(named(expandSearchToFilter('ann', { fields, searchableFields, queryableFields }))).toEqual(['name', 'email']);
261+
});
262+
263+
it('keeps a field the caller named, in either spelling', () => {
264+
expect(named(expandSearchToFilter('x', { fields, searchableFields, queryableFields, requestedFields: ['ban_reason'] })))
265+
.toEqual(['ban_reason']);
266+
expect(named(expandSearchToFilter('x', { fields, searchableFields, queryableFields, requestedFields: 'name, ban_reason' })))
267+
.toEqual(['name', 'ban_reason']);
268+
expect(named(expandSearchToFilter({ query: 'x', fields: ['ban_reason'] }, { fields, searchableFields, queryableFields })))
269+
.toEqual(['ban_reason']);
270+
});
271+
272+
it('answers null when it withholds every declared field — never the auto-default', () => {
273+
expect(expandSearchToFilter('x', { fields, searchableFields: ['ban_reason'], queryableFields })).toBeNull();
274+
});
275+
276+
it('is a no-op when absent', () => {
277+
expect(named(expandSearchToFilter('ann', { fields, searchableFields }))).toEqual(['name', 'email', 'ban_reason']);
278+
});
279+
});

0 commit comments

Comments
 (0)