Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/21177-analytics-inline-dataset-field-admission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/service-analytics': minor
---

fix(service-analytics)!: a dataset's own `field` text that is not a column reference is refused at the analytics dataset door, inline or saved

Clause-②: no (narrowing)

<!-- adr-0087: not-required (no-migration-prescription) a dataset's own dimension or measure `field` text that is not a column reference (a field, a relationship path ending in one, or `*`) is refused at the analytics dataset door — whichever branch supplied the dataset, an inline `body.dataset` or a saved `body.datasetName` — before the dataset is compiled and before any strategy runs, for every caller and whether or not a security service is wired, through the field-read gate's existing judge and envelope (`PERMISSION_DENIED` / 403). No authorable key, spelling, export or stored shape moves, and no stored row is read differently by any metadata consumer; the published surface gains and loses nothing. The other categories are closed on facts: the package publishes (not `unpublished`); no ADR-0087 id covers a dataset `field` (not `registered` / `already-registered`); and the change is runtime behaviour, not a declaration (not `runtime-interface-only` / `type-surface-only`). A dataset names a column instead of writing an expression, which is ADR-0021's author surface already ("zero raw expressions"), so there is no FROM → TO mapping to carry. -->

**BREAKING**: this narrows what the analytics dataset door accepts. A dataset whose dimension or measure `field` is not a column reference is now refused with `403 PERMISSION_DENIED` instead of being evaluated — an inline dataset and a saved dataset queried by name alike, since both reach the same door. No shipped dataset carries a non-column `field`. It ships as `minor` under the launch-window convention for accept-set narrowings. No export or published type changes.

**What changes.** The service compiles a dataset into a cube whose members read as declared, so a dimension or measure whose `field` was a raw expression resolved to a declared cube member and was left to the field-level read gate, which stands down with no security service and on an object its reader answers `undefined` for; in those tiers the expression reached the native statement as written. The dataset's own `field` text is now judged at the dataset door, before compile and before any strategy runs, through the field-read gate's existing judge (`PERMISSION_DENIED` / 403, naming the member and never the expression text), for every caller, admin included, and with or without a security service. There is no new error code and no new admission module.

**What stays answerable.** Every dataset whose fields are columns or relationship paths is unchanged, inline or saved. A saved dataset whose `field` is an expression is refused the same way as an inline one; refusing such a `field` when it is authored belongs to the dataset schema's own retirement of expression fields, not to this door. The dataset's own filter, the selection's runtime filter and cube-query members are lowered into the compiled query and already judged on the query path, so they are unchanged.
164 changes: 96 additions & 68 deletions packages/rest/src/analytics-16019-driver-declared-fault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,31 @@
* reaches the caller by DECLARATION, and the declaration wins over the
* phrasing heuristic.
*
* ## The two shapes, and why this file drives the real driver
* ## The ruling, and where each half is proved
*
* The card was filed on a hand-made `Error('no such function: translate')` and
* re-scoped when the Clause-② review of PR #16020 measured the shape production
* actually raises — knex's `<statement> - no such function: translate` — and
* found it withheld already, by accident: `looksLikeInternalErrorLeak` fires on
* the `select ` prefix, never on the phrase. On `origin/main`:
* Under the 2026-09-06 ruling (decision batch #57, option 3) `SqlDriver.execute()`
* declares the fault — `DATABASE_ERROR`/500, the dialect error under a
* non-enumerable `cause` — and this door's ③a arm relays a declared 5xx with the
* producer's code and `INTERNAL_ERROR_MESSAGE`. The two halves are proved
* separately: `driver-sql`'s `sql-driver-16019-raw-statement-fault-envelope.test.ts`
* proves `SqlDriver.execute` declares the fault, and the SECOND block here proves
* this route relays a declared `DATABASE_ERROR`/500 with the prose withheld (a
* throwing double hands the door the exact declared shape).
*
* | shape reaching the door | body |
* |-----------------------------------------------|-------------------------------------------------------|
* | bare `Error('no such function: translate')` | `500 ANALYTICS_QUERY_FAILED`, raw engine text |
* | knex-shaped — what `SqlDriver.execute` raised | `500 ANALYTICS_QUERY_FAILED`, `Internal server error` |
*
* Both were UNDECLARED. Under the 2026-09-06 ruling (decision batch #57,
* option 3) `SqlDriver.execute()` declares the fault — `DATABASE_ERROR`/500,
* the dialect error under a non-enumerable `cause` — and this door's ③a arm
* relays a declared 5xx with the producer's code and `INTERNAL_ERROR_MESSAGE`.
* The first block drives that END TO END: a real `AnalyticsService` on the
* native-SQL strategy, a real better-sqlite3 `SqlDriver` behind the exact
* bridge `service-analytics`'s plugin wires (`engine.execute` → `driver.execute`),
* and a dataset dimension whose expression calls `translate()` — the function
* SQLite lacks, the #16028 fault verbatim — so the refusal is the ENGINE's,
* not a fixture's, and the compiled statement is the real one.
* [#21177] This file once drove the two halves END TO END through one call — a
* real `AnalyticsService` on the native-SQL strategy over a real better-sqlite3
* `SqlDriver`, fed a dataset dimension whose expression called `translate()`, the
* function SQLite lacks. That path is gone: #21177 refuses a caller-supplied
* inline-dataset dimension/measure `field` that is not a column reference at the
* analytics door, before any strategy or driver runs, so a raw `translate(...)`
* can no longer reach the engine from caller content. The FIRST block now pins
* THAT — the door refuses the expression `PERMISSION_DENIED` / 403, the one
* judge #21156 reaches (no new error code) — beside a positive control that a
* legitimate dataset on declared fields is still served 200 by the real driver.
* It pins the route's SAVED branch (`body.datasetName`) the same way: that branch
* loads the dataset from metadata and calls the same `queryDataset`, so a saved
* dataset whose `field` is not a column reference is refused too, and a saved
* plain-column dataset is still served.
*
* The second block pins the ordering the ruling's execution notes name. A
* DECLARED fault is withheld even when its text is one the heuristic does not
Expand All @@ -44,19 +46,14 @@
*
* ## Reverse verification, direction predicted BEFORE running
*
* Restore the bare `await builder` in `SqlDriver.execute()` and REBUILD
* driver-sql: the first block's `DATABASE_ERROR` assertions go RED
* (`ANALYTICS_QUERY_FAILED` returns) while its `INTERNAL_ERROR_MESSAGE`
* assertion stays GREEN — the accident the re-scope measured, the heuristic's
* `select ` limb — and the driver-log assertion goes RED (the driver no longer
* logs; the route's `logError` becomes the only copy). The second block stays
* GREEN throughout: it hands the door shapes that never touch the driver.
*
* The ORDERING pin in block 2 has its own leg: gate the door's ③a relay
* behind `looksLikeInternalErrorLeak` being false (i.e. consult the heuristic
* first) and only that case goes RED (`ANALYTICS_QUERY_FAILED` in place of the
* producer's code); the neighbouring "phrase the heuristic does not know"
* case stays GREEN, which is precisely why it could not stand in for this one.
* The first block's leg: remove the caller-content gate and the expression
* reaches the real driver again — the refusal flips from `403 PERMISSION_DENIED`
* to the `500 DATABASE_ERROR` relay this file once asserted.
*/

import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
Expand All @@ -82,11 +79,12 @@ function mockServer() {
use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
};
}
function mockProtocol() {
/** `savedDatasets` is what the route's `body.datasetName` branch loads from metadata. */
function mockProtocol(savedDatasets: unknown[] = []) {
return {
getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }),
getMetaTypes: vi.fn().mockResolvedValue([]),
getMetaItems: vi.fn().mockResolvedValue([]),
getMetaItems: vi.fn().mockResolvedValue(savedDatasets),
};
}
function mockRes() {
Expand All @@ -97,9 +95,9 @@ function mockRes() {
return res;
}

function buildRoute(analyticsProvider?: any) {
function buildRoute(analyticsProvider?: any, savedDatasets: unknown[] = []) {
const rest = new RestServer(
mockServer() as any, mockProtocol() as any, { api: { requireAuth: false } } as any,
mockServer() as any, mockProtocol(savedDatasets) as any, { api: { requireAuth: false } } as any,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined,
analyticsProvider,
Expand All @@ -123,23 +121,39 @@ async function post(route: any, body: unknown) {
const ACCOUNT_FIELDS = ['id', 'name', 'industry'];

/**
* One plain dimension for the control, and one whose expression calls the
* function SQLite lacks. The compiler passes an expression through verbatim
* (`qualifyAndRegisterJoin` leaves anything that is not a bare identifier or
* a dotted path alone) and the source-field gate judges bare identifiers only,
* so this is the real statement the strategy emits, refused by the real engine.
* A legitimate dataset on declared fields — the positive control, and the body
* block 2 posts to the throwing double (whose `queryDataset` is mocked, so the
* definition never reaches the real door).
*/
const dataset = {
name: 'account_metrics',
label: 'Account metrics',
object: 'crm_account',
dimensions: [
{ name: 'industry', field: 'industry', type: 'string' },
{ name: 'folded_name', field: "translate(name, 'ABC', 'abc')", type: 'string' },
],
measures: [{ name: 'account_count', aggregate: 'count' }],
};

/**
* [#21177] A caller-supplied inline dataset whose dimension `field` is a raw
* expression. Until #21177 the compiler passed it through verbatim and the real
* engine ran it (the #16028 `translate()` fault this file once drove end to end);
* now the caller-content gate refuses it at the door, before any strategy or
* driver runs. The real-driver declaration and the door relay it once proved
* jointly are each covered on their own: `driver-sql`'s
* `sql-driver-16019-raw-statement-fault-envelope.test.ts` proves `SqlDriver`
* declares the fault, and block 2 below proves this route relays a declared
* `DATABASE_ERROR` / 500 with the prose withheld.
*/
const expressionDataset = {
...dataset,
dimensions: [
{ name: 'industry', field: 'industry', type: 'string' },
{ name: 'folded_name', field: "translate(name, 'ABC', 'abc')", type: 'string' },
],
};

async function realDriver(): Promise<SqlDriver> {
const driver = new SqlDriver({
client: 'better-sqlite3',
Expand Down Expand Up @@ -208,48 +222,62 @@ describe('[#16019] a driver fault on the raw-SQL path reaches the caller by decl
await driver.disconnect();
});

it('the statement SQLite refuses answers 500 DATABASE_ERROR with the prose withheld — the ③a relay, not ③b', async () => {
it('[#21177] a caller-supplied dimension-field expression is refused 403 PERMISSION_DENIED at the door — before any strategy or driver runs', async () => {
const route = buildRoute(async () => realAnalytics(driver));
const res = await post(route, { dataset, selection: { measures: ['account_count'], dimensions: ['folded_name'] } });

expect(res.statusCode).toBe(500);
// The producer's code, relayed — where an undeclared fault answered the
// route's generic one.
expect(res.body.code).toBe('DATABASE_ERROR');
expect(res.body.code).not.toBe('ANALYTICS_QUERY_FAILED');
expect(res.body.error).toBe(INTERNAL_ERROR_MESSAGE);
const res = await post(route, { dataset: expressionDataset, selection: { measures: ['account_count'], dimensions: ['folded_name'] } });

expect(res.statusCode).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
// Caller text that names no attributable field is refused at the door,
// not evaluated — the driver never ran, so there is no driver fault line.
expect(warned.filter((m) => m.includes('[sql-driver] DATABASE_ERROR'))).toHaveLength(0);
// ⛔ The refusal names the member and its object (both the caller's own
// input), never the caller's `field` expression text or the compiled statement.
const body = JSON.stringify(res.body);
expect(body).not.toMatch(/translate/i);
expect(body).not.toMatch(/no such function/i);
expect(body).not.toMatch(/SELECT|GROUP BY|crm_account/i);
expect(body).not.toMatch(/SELECT|GROUP BY/i);
});

it('the operator keeps the whole diagnostic: the driver logged the statement and the engine text, the route logged the envelope', async () => {
const route = buildRoute(async () => realAnalytics(driver));
await post(route, { dataset, selection: { measures: ['account_count'], dimensions: ['folded_name'] } });

// The driver's warn line is now the only copy of the dialect text.
const driverLine = warned.find((m) => m.includes('[sql-driver] DATABASE_ERROR'));
expect(driverLine).toBeDefined();
expect(driverLine).toContain('no such function: translate');
expect(driverLine).toMatch(/translate\(name, 'ABC', 'abc'\)/i);
// The route still logs the fault it relayed — the composed envelope, which
// names no statement (`logError` prints `error.message`).
const routeLine = errored.find((m) => m.includes('[REST] Analytics dataset query error'));
expect(routeLine).toBeDefined();
expect(routeLine).toContain('refused to run a raw statement');
expect(routeLine).not.toContain('no such function');
});

it('POSITIVE CONTROL: the same wiring with the plain dimension → 200 with rows', async () => {
it('POSITIVE CONTROL: a legitimate dataset on declared fields → 200 with rows', async () => {
const route = buildRoute(async () => realAnalytics(driver));
const res = await post(route, { dataset, selection: { measures: ['account_count'], dimensions: ['industry'] } });

expect(res.statusCode).toBe(200);
expect(res.body.rows).toEqual([{ industry: 'tech', account_count: 1 }]);
expect(warned.filter((m) => m.includes('[sql-driver] DATABASE_ERROR'))).toHaveLength(0);
});

// [#21177] The route's SAVED branch: `body.datasetName` loads the dataset from
// metadata and calls the same `queryDataset`, so the door judges a saved
// dataset's own `field` text exactly as it judges an inline one. The expression
// here is one SQLite can run, so without the door it would be served (200).
it('[#21177] a SAVED dataset (body.datasetName) whose dimension field is not a column reference is refused 403 PERMISSION_DENIED — nothing executed', async () => {
const saved = {
...dataset,
name: 'account_metrics_saved_expr',
dimensions: [{ name: 'lowered_name', field: 'lower(name)', type: 'string' }],
};
const execute = vi.spyOn(driver, 'execute');
const route = buildRoute(async () => realAnalytics(driver), [saved]);
const res = await post(route, { datasetName: saved.name, selection: { measures: ['account_count'], dimensions: ['lowered_name'] } });

expect(res.statusCode).toBe(403);
expect(res.body.code).toBe('PERMISSION_DENIED');
expect(execute).not.toHaveBeenCalled();
const body = JSON.stringify(res.body);
expect(body).toContain('lowered_name');
expect(body).not.toMatch(/lower\(name\)/i);
});

it('[#21177] CONTROL: a SAVED plain-column dataset (body.datasetName) → 200 with rows', async () => {
const execute = vi.spyOn(driver, 'execute');
const route = buildRoute(async () => realAnalytics(driver), [dataset]);
const res = await post(route, { datasetName: dataset.name, selection: { measures: ['account_count'], dimensions: ['industry'] } });

expect(res.statusCode).toBe(200);
expect(res.body.rows).toEqual([{ industry: 'tech', account_count: 1 }]);
expect(execute).toHaveBeenCalled();
});
});

describe('[#16019] at the door: a declaration wins over the heuristic, and the heuristic stays as the fallback', () => {
Expand Down
Loading
Loading