Skip to content

Commit 73ec085

Browse files
fix(analytics): an empty or blank where key answers 400 INVALID_FIELD on all three analytics doors (#38218)
Fixes #35543 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:通过接口或 AI 助手做统计查询时,筛选条件里写了空的或只有空格的字段名,现在会直接得到「字段名无效」的明确提示,不再报服务器内部错误或无权限。 - 为什么做:让统计查询对这种写错的请求和普通数据查询给出同一种答复,调用方能看懂错在哪里。 - 出错会怎样:最坏情况是某个本来能用的统计筛选被误拒,调用方会看到明确的拒绝提示;改动只有一处检查,可以直接撤回。 - 要你做什么:无。 ## What changes An empty filter key (`{"": "z"}`) on `POST /api/v1/analytics/query`, as the dataset `runtimeFilter` on `POST /api/v1/analytics/dataset/query`, and through MCP `query_dataset` reached SQLite as `WHERE = ?` and answered `500 DATABASE_ERROR`. A blank key (`" "`) answered `403 PERMISSION_DENIED` from the field-read gate. Both now answer `400 INVALID_FIELD` (`field`, `param: 'where'`), as `/data` answers the same body. The engine is never reached. The mechanism: every analytics gate passes the empty key by. `namedQueryFields` skips `member === ''` outright, and `resolveMemberSource` answers `source: null` (a stand-down) for any spelling that is not a bare identifier. So nothing judged it before the strategy compiled it. The fix is one check, `assertWhereMemberIsFieldName`, at the top of the `where` source-field gate (`assertWhereFields`, #5669). That gate runs on every path out of `ensureCube` and on the dataset draft-preview path, so all three doors share it. The check needs no field probe. It runs before the gate's three probe stand-downs, because no object has a field with an empty name. `/data`'s validator (`assertFilterFieldsExist`, `@objectstack/metadata-protocol`) is not reused. It answers "is this a field of the object". The analytics question is "does this member resolve to a column", and the existing `where` gate already asks it in the analytics vocabulary (cube members, the cube qualifier, relationship paths). Taking a dependency on the protocol package for an emptiness check would add a second reader of the filter tree. Deliberately narrow: only whitespace-only keys. A key that is text but no column reference (`amount + 1`, `foo bar`) keeps the #21156 member-shape gate's `PERMISSION_DENIED` / 403. That verdict is pinned "in every tier" by `caller-member-column-reference-gate.test.ts`, which this PR's first, wider draft turned red (8 cases). Changing that verdict is a contract question and is out of scope here. ## Tests `src/__tests__/where-member-field-name-35543.test.ts` uses the plugin-wired service (`AnalyticsServicePlugin` over an engine double), with all three doors called as their callers call them: `service.query`, `service.queryDataset` and `datasetTools().queryDataset`. - An empty key, a blank key and a tab-only key on each door: `code: 'INVALID_FIELD'`, `status: 400`, `field`, `param: 'where'`. The engine saw no statement. - An empty key nested under `$or`: refused the same way. - `amount + 1` keeps `PERMISSION_DENIED` / 403. This is the #21156 boundary. - CONTROL: `{status: 'paid'}` answers on all three doors. Ablation through `scripts/ablation-replace.mjs`, which deleted the gate's call line (anchor 1 to 0, restored blob == HEAD, `git diff HEAD` empty). 10 failed, 1 passed (the control). The red set was every refusal case on all three doors. Live re-measure on the stock showcase (`--fresh`, admin), before at `7605e0c9c` and after at `c79abcb26`: | body | before | after | |:--|:--|:--| | `/analytics/query` `where {"": "z"}` | 500 DATABASE_ERROR | 400 INVALID_FIELD | | `/analytics/dataset/query` `runtimeFilter {"": "z"}` | 500 DATABASE_ERROR | 400 INVALID_FIELD | | MCP `query_dataset` `runtimeFilter {"": "z"}` | isError DATABASE_ERROR / 500 | isError INVALID_FIELD / 400 | | the same three with `{" ": "z"}` | 403 PERMISSION_DENIED | 400 INVALID_FIELD | | CONTROL `{"status": "paid"}` on all three | 200 | 200 | | `/data/showcase_invoice/query` `where {"": "z"}` | 400 INVALID_FIELD | 400 INVALID_FIELD | <details><summary>Package run at c79abcb</summary> `pnpm --filter @objectstack/service-analytics typecheck && … build && … test` under the verify lock: `VERDICT command-exit 0`, `Test Files 228 passed (228)`, `Tests 5914 passed | 345 skipped (6259)`. `tsc --listFiles` includes the new test file. </details> ## Acceptance notes - The card's second "also seen" row is a separate mechanism and is not fixed here. `where {"account.a.b.c.d": "z"}` still answers `403 PERMISSION_DENIED` naming the synthesized alias `account__a`. The two-hop `account.nope` answers `400 INVALID_FIELD` naming `showcase_account`. It is a relationship-path resolution question, not an empty key, and is reported for the seat to file. - A key with a space in it (`foo bar`) still answers 403 under #21156, where `/data` answers 400. See the narrowing above. - `/data`'s empty-key envelope omits `field`, where its blank-key envelope carries `field: " "`. This is an observation only. ## Verification Read first: `assertWhereMemberIsFieldName` and its call at the top of `assertWhereFields` (`packages/services/service-analytics/src/analytics-service.ts`). The risk hunk is the move of the three probe stand-downs below the member collection. The second file is the new test. Two-minute check: `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/where-member-field-name-35543.test.ts`. Expect 12 passed. Gates at `c79abcb26`: `dispatch-gates --ran` accounts for 71 derived families. 69 ran with exit 0. 2 are NOT MEASURED (exit 3, prerequisite not met): `check:dual-build-cjs-loads` needs a full workspace build, and `check:type-check-debt` could not get a turn on the verify lock. CI runs both. --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSAaBEfQpU2yJexSJ8)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e65fb3 commit 73ec085

3 files changed

Lines changed: 186 additions & 8 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(analytics): an empty or blank `where` key answers 400 INVALID_FIELD on all three analytics doors
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
An empty filter key (`{"": "z"}`) on `POST /api/v1/analytics/query`, as a dataset's `runtimeFilter` on `POST /api/v1/analytics/dataset/query`, or through the MCP `query_dataset` tool reached the database as `WHERE = ?` and answered `500 DATABASE_ERROR`. A blank or whitespace-only key (`" "`, a tab) answered `403 PERMISSION_DENIED` from the field-read gate. Both now answer `400 INVALID_FIELD` with `field` and `param: 'where'` on those three doors, as `/data` answers the same body, and nothing reaches the database. A key that is text but no column reference, such as `amount + 1` or `foo bar`, is unchanged: it still answers `403 PERMISSION_DENIED` from the #21156 member-shape gate. Nothing to migrate.
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #35543 — an empty or blank (whitespace-only) `where` key is refused
5+
* `INVALID_FIELD` / 400 on all three analytics doors, as `/data` answers the
6+
* same body. Non-identifier text (`amount + 1`, `foo bar`) keeps the #21156
7+
* member-shape gate's 403.
8+
*
9+
* Measured on the stock showcase at `7605e0c9c` before the fix:
10+
*
11+
* ```
12+
* POST /analytics/query where {"": "z"} -> 500 DATABASE_ERROR (near "=": syntax error)
13+
* POST /analytics/dataset/query runtimeFilter {"": "z"} -> 500 DATABASE_ERROR
14+
* MCP query_dataset runtimeFilter {"": "z"} -> isError, DATABASE_ERROR
15+
* the same three with {" ": "z"} -> 403 PERMISSION_DENIED (field-read gate)
16+
* POST /data/showcase_invoice/query where {"": "z"} -> 400 INVALID_FIELD
17+
* ```
18+
*
19+
* The harness is the plugin-wired service over an engine double that runs any
20+
* statement, so before the fix the empty key RESOLVED here (the double has no
21+
* SQL parser to fail) and the blank key was refused 403: both cases below read
22+
* red without the fix. `statements` stays empty on every refusal: the body
23+
* never reached the engine.
24+
*/
25+
26+
import { describe, it, expect, vi } from 'vitest';
27+
import type { ExecutionContext } from '@objectstack/spec/kernel';
28+
import { AnalyticsServicePlugin } from '../plugin.js';
29+
import type { AnalyticsService } from '../analytics-service.js';
30+
31+
const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext;
32+
33+
const FIELDS: Record<string, Record<string, unknown>> = {
34+
id: { type: 'text' },
35+
status: { type: 'text' },
36+
amount: { type: 'number' },
37+
};
38+
39+
const INVOICE_METRICS = {
40+
name: 'invoice_metrics',
41+
label: 'Invoice metrics',
42+
object: 'inv_invoice',
43+
dimensions: [{ name: 'status', label: 'Status', field: 'status', type: 'string' }],
44+
measures: [{ name: 'invoice_count', label: 'Invoices', aggregate: 'count' }],
45+
};
46+
47+
const security = {
48+
getReadFilter: async () => undefined,
49+
canReadObject: () => true,
50+
getReadableFields: async () => Object.keys(FIELDS),
51+
getQueryableFields: async () => Object.keys(FIELDS),
52+
};
53+
54+
async function boot() {
55+
const statements: string[] = [];
56+
const engine = {
57+
execute: async (sql: unknown) => {
58+
statements.push(String((sql as { sql?: string })?.sql ?? sql));
59+
return { rows: [{ invoice_count: 1, 'inv_invoice.count': 1 }] };
60+
},
61+
hasObjectMiddleware: () => false,
62+
getObject: (name: string) => (name === 'inv_invoice' ? { fields: FIELDS } : undefined),
63+
resolveEffectiveDatasource: () => undefined,
64+
};
65+
const registered: Record<string, unknown> = {};
66+
const ctx = {
67+
getService: (name: string) => (name === 'security' ? security : name === 'data' ? engine : registered[name]),
68+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
69+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
70+
logger: { info() {}, warn() {}, error() {}, debug() {} },
71+
};
72+
await new AnalyticsServicePlugin({
73+
queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }),
74+
}).init(ctx as never);
75+
const service = registered.analytics as AnalyticsService;
76+
const tools = service.datasetTools({ loadDatasets: vi.fn(async () => [INVOICE_METRICS]) });
77+
return { service, tools, statements };
78+
}
79+
80+
type Door = (filter: Record<string, unknown>) => Promise<unknown>;
81+
82+
/** The three doors, each handed the same filter where its caller puts it. */
83+
function doors(b: Awaited<ReturnType<typeof boot>>): Array<[string, Door]> {
84+
return [
85+
['/analytics/query', (where) => b.service.query({ cube: 'inv_invoice', measures: ['inv_invoice.count'], where } as never, ADMIN)],
86+
['/analytics/dataset/query', (runtimeFilter) =>
87+
b.service.queryDataset(INVOICE_METRICS as never, { measures: ['invoice_count'], runtimeFilter } as never, ADMIN)],
88+
['MCP query_dataset', (runtimeFilter) =>
89+
b.tools.queryDataset({ datasetName: 'invoice_metrics', selection: { measures: ['invoice_count'], runtimeFilter } }, ADMIN)],
90+
];
91+
}
92+
93+
const DOOR_NAMES = ['/analytics/query', '/analytics/dataset/query', 'MCP query_dataset'];
94+
95+
const REFUSED = { code: 'INVALID_FIELD', status: 400 };
96+
97+
describe('[#35543] a where key that names no field is INVALID_FIELD / 400 on every analytics door', () => {
98+
for (const [label, key] of [
99+
['an empty key', ''],
100+
['a blank key', ' '],
101+
['a tab-only key', '\t'],
102+
] as const) {
103+
for (const index of [0, 1, 2]) {
104+
it(`${label} on ${DOOR_NAMES[index]} is refused before the engine is reached`, async () => {
105+
const b = await boot();
106+
const [, door] = doors(b)[index];
107+
await expect(door({ [key]: 'z' })).rejects.toMatchObject({ ...REFUSED, field: key, param: 'where' });
108+
expect(b.statements).toEqual([]);
109+
});
110+
}
111+
}
112+
113+
it('an empty key nested under $or is refused the same way', async () => {
114+
const b = await boot();
115+
const [, door] = doors(b)[0];
116+
await expect(door({ $or: [{ status: 'paid' }, { '': 'z' }] })).rejects.toMatchObject(REFUSED);
117+
expect(b.statements).toEqual([]);
118+
});
119+
120+
it('a key that is text but no column reference keeps the #21156 shape verdict, 403', async () => {
121+
const b = await boot();
122+
const [, door] = doors(b)[0];
123+
await expect(door({ 'amount + 1': 'z' })).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
124+
expect(b.statements).toEqual([]);
125+
});
126+
127+
it('CONTROL: a valid filter answers on all three doors', async () => {
128+
for (const [label, door] of doors(await boot())) {
129+
await expect(door({ status: 'paid' }), label).resolves.toBeDefined();
130+
}
131+
});
132+
});

‎packages/services/service-analytics/src/analytics-service.ts‎

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,35 @@ function resolveMemberSource(
448448
return { key: member, source: BARE_IDENTIFIER.test(member) ? member : null };
449449
}
450450

451+
/**
452+
* [#35543] Refuse a `where` member that is empty or blank — `INVALID_FIELD` /
453+
* 400, the answer `/data` gives the same body — before any strategy compiles it.
454+
*
455+
* Such a key names no field and no expression: there is nothing in it for a
456+
* field gate to judge, which is why every other gate passes it by
457+
* ({@link namedQueryFields} skips the empty member outright). The empty key
458+
* then compiled `WHERE = ?` (500 DATABASE_ERROR) and the blank one reached
459+
* the field-read gate as an expression (403 PERMISSION_DENIED).
460+
*
461+
* ⛔ Only whitespace-only text. A key that is text but no column reference
462+
* (`amount + 1`) keeps the #21156 shape gate's `PERMISSION_DENIED` / 403: it
463+
* could read fields, and that gate's verdict is one answer in every tier.
464+
*/
465+
function assertWhereMemberIsFieldName(cube: Cube, member: string): void {
466+
if (member.trim() !== '') return;
467+
const err = new Error(
468+
`Filter member '${member}' in 'where' on cube '${cube.name}' is ${member === '' ? 'an empty' : 'a blank'} key, ` +
469+
`which names no field. A filter key is a field name or a relationship path ending in one ` +
470+
`(such as 'account.name'). The query was refused before it reached the database.`,
471+
) as Error & { code?: string; status?: number; field?: string; param?: string; member?: string };
472+
err.code = 'INVALID_FIELD';
473+
err.status = 400;
474+
err.field = member;
475+
err.param = 'where';
476+
err.member = member;
477+
throw err;
478+
}
479+
451480
/** [#20917] A dotted identifier path: relationship hops, then one column — `NativeSQLStrategy`'s own test. */
452481
const IDENTIFIER_PATH = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)+$/;
453482

@@ -5045,17 +5074,9 @@ export class AnalyticsService implements IAnalyticsService {
50455074
* for both spellings of one filter.
50465075
*/
50475076
private assertWhereFields(query: AnalyticsQuery, cube: Cube, declaredDimensions: string[]): void {
5048-
const probe = this.getObjectFieldNames;
5049-
if (!probe) return;
50505077
const where = (query as { where?: unknown }).where;
50515078
if (!where || typeof where !== 'object') return;
50525079

5053-
const object = typeof cube.sql === 'string' ? cube.sql.trim() : '';
5054-
if (!object || !BARE_IDENTIFIER.test(object)) return;
5055-
const fieldNames = probe(object);
5056-
if (!fieldNames || fieldNames.length === 0) return;
5057-
const known = new Set<string>([...fieldNames, 'id', 'created_at', 'updated_at']);
5058-
50595080
/** Every member the compiled predicate will bind against, structure discarded. */
50605081
let members: string[];
50615082
try {
@@ -5071,6 +5092,21 @@ export class AnalyticsService implements IAnalyticsService {
50715092
}
50725093
if (members.length === 0) return;
50735094

5095+
// [#35543] An empty or blank filter key is refused first. It needs no
5096+
// field probe: no object has such a field. Before, the empty key compiled
5097+
// `WHERE = $1` (500 DATABASE_ERROR) and the blank one reached the
5098+
// field-read gate (403 PERMISSION_DENIED), where `/data` answers both
5099+
// `400 INVALID_FIELD`.
5100+
for (const member of members) assertWhereMemberIsFieldName(cube, member);
5101+
5102+
const probe = this.getObjectFieldNames;
5103+
if (!probe) return;
5104+
const object = typeof cube.sql === 'string' ? cube.sql.trim() : '';
5105+
if (!object || !BARE_IDENTIFIER.test(object)) return;
5106+
const fieldNames = probe(object);
5107+
if (!fieldNames || fieldNames.length === 0) return;
5108+
const known = new Set<string>([...fieldNames, 'id', 'created_at', 'updated_at']);
5109+
50745110
// Two passes, for the reason the measure and dimension gates have two: on the
50755111
// auto-inference path `inferCubeFromQuery` mints the `where`'s own field keys
50765112
// into `cube.dimensions` — since #5353 for the array spelling too — so

0 commit comments

Comments
 (0)