From 4cdb3b2df52425803b6a60c1890d44e86486db14 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:49:57 +0000 Subject: [PATCH 01/10] test(plugin-audit,rest): pin one dataset_query row per opted-in dataset query, none when refused before the read Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/dataset-query-audit.test.ts | 242 ++++++++++++++++++ .../src/analytics-dataset-query-audit.test.ts | 159 ++++++++++++ 2 files changed, 401 insertions(+) create mode 100644 packages/plugins/plugin-audit/src/dataset-query-audit.test.ts create mode 100644 packages/rest/src/analytics-dataset-query-audit.test.ts diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts new file mode 100644 index 00000000000..3b9f9820ee5 --- /dev/null +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts @@ -0,0 +1,242 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `dataset_query` writer stores a REAL, READ-BACK ledger row for each + * dataset query of an opted-in dataset, and never a filtered value. + * + * The cases boot the real composition this package ships in + * (`ObjectQLPlugin` + `AuditPlugin` on a sqlite driver). Every assertion reads + * the row back through the engine, for the reason `data-export-audit.test.ts` + * records: every `sys_audit_log` field is `readonly` and `validateRecord` + * skips readonly fields, so "the call did not throw" is equally true when the + * row landed right, landed wrong, or was never attempted. The door side (the + * analytics dataset door hands one event per query that reached the read, and + * none for a refused one) is pinned in `@objectstack/rest`'s + * `analytics-dataset-query-audit.test.ts`. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; + +import { AuditPlugin } from './audit-plugin.js'; +import { + DATASET_QUERY_AUDIT_ACTION, + createDatasetQueryAuditWriter, + type DatasetQueryAuditEvent, +} from './dataset-query-audit.js'; + +const LEDGER = 'sys_audit_log'; +const SYS = { isSystem: true } as const; + +/** A value no field name, operator or code in this file spells. */ +const SECRET = 'Zq7-dataset-filter-value-5521'; + +/** A query as the door hands it, completed; each case overrides what it is about. */ +function queryEvent(overrides: Partial = {}): DatasetQueryAuditEvent { + return { + context: { userId: 'u_analyst', tenantId: 'org_a' }, + datasetName: 'sales', + objectName: 'opportunity', + dimensions: ['region'], + measures: ['revenue'], + readQuery: { filter: { stage: SECRET, amount: { $gte: 1000 } } }, + rowCount: 3, + outcome: 'succeeded', + ...overrides, + }; +} + +const metadataOf = (row: Record): Record => JSON.parse(String(row.metadata)); + +async function bootKernel(plugin: AuditPlugin): Promise<{ kernel: ObjectKernel; engine: ObjectQL }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(plugin); + await kernel.bootstrap(); + const engine = kernel.getService('objectql'); + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + engine.registerDriver(driver, true); + await engine.syncSchemas(); + return { kernel, engine }; +} + +const queryRows = async (engine: ObjectQL): Promise>> => + (await engine.find(LEDGER, { + where: { action: DATASET_QUERY_AUDIT_ACTION }, + orderBy: [{ field: 'created_at', order: 'asc' }], + context: SYS, + })) as Array>; + +describe('the dataset_query writer over the real ledger', () => { + let kernel: ObjectKernel; + let engine: ObjectQL; + + beforeAll(async () => { + ({ kernel, engine } = await bootKernel(new AuditPlugin())); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('one query of an opted-in dataset writes ONE run-level row naming who, which dataset, the selection and the row count', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'] }); + const before = (await queryRows(engine)).length; + writer.recordDatasetQuery(queryEvent()); + await writer.flush(); + const rows = await queryRows(engine); + expect(rows).toHaveLength(before + 1); + const row = rows[rows.length - 1]; + expect(row).toMatchObject({ + action: 'dataset_query', + object_name: 'opportunity', + record_id: null, + user_id: 'u_analyst', + actor: 'u_analyst', + tenant_id: 'org_a', + }); + expect(row.old_value ?? null).toBeNull(); + expect(row.new_value ?? null).toBeNull(); + expect(metadataOf(row)).toEqual({ + dataset: 'sales', + dimensions: ['region'], + measures: ['revenue'], + filter: [ + { field: 'stage', op: '$eq' }, + { field: 'amount', op: '$gte' }, + ], + row_count: 3, + outcome: 'succeeded', + }); + await writer.stop(); + }); + + it('a dataset that is not opted in writes no row', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['pipeline'] }); + const before = (await queryRows(engine)).length; + writer.recordDatasetQuery(queryEvent({ datasetName: 'sales' })); + await writer.flush(); + expect(writer.pending()).toBe(0); + expect(await queryRows(engine)).toHaveLength(before); + await writer.stop(); + }); + + it('with no dataset opted in (the default) a query writes no row and the writer buffers nothing', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: [] }); + const before = (await queryRows(engine)).length; + writer.recordDatasetQuery(queryEvent()); + expect(writer.pending()).toBe(0); + await writer.flush(); + expect(await queryRows(engine)).toHaveLength(before); + expect(writer.auditedDatasets).toEqual([]); + }); + + it('a query that failed after the read started writes ONE row with outcome failed, its status and machine code', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'] }); + const before = (await queryRows(engine)).length; + writer.recordDatasetQuery(queryEvent({ outcome: 'failed', rowCount: 0, status: 503, errorCode: 'SERVICE_UNAVAILABLE' })); + await writer.flush(); + const rows = await queryRows(engine); + expect(rows).toHaveLength(before + 1); + expect(metadataOf(rows[rows.length - 1])).toMatchObject({ + dataset: 'sales', + row_count: 0, + outcome: 'failed', + status: 503, + error_code: 'SERVICE_UNAVAILABLE', + }); + await writer.stop(); + }); + + it('records no filtered value: every comparand position of the filter is dropped unread', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'] }); + writer.recordDatasetQuery(queryEvent({ + readQuery: { + filter: { + $or: [{ stage: { $in: [SECRET, `${SECRET}-2`] } }, { name: { $contains: SECRET } }], + owner: { name: SECRET }, + }, + }, + })); + await writer.flush(); + const rows = await queryRows(engine); + const row = rows[rows.length - 1]; + expect(JSON.stringify(row)).not.toContain(SECRET); + expect(metadataOf(row).filter).toEqual([ + { field: 'stage', op: '$in' }, + { field: 'name', op: '$contains' }, + { field: 'owner.name', op: '$eq' }, + ]); + await writer.stop(); + }); + + it('stamps the QUERY instant, not the flush instant', async () => { + const queriedAt = new Date('2026-01-02T03:04:05.000Z'); + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'], now: () => queriedAt }); + writer.recordDatasetQuery(queryEvent({ datasetName: 'sales', rowCount: 9 })); + await writer.flush(); + const rows = await queryRows(engine); + const row = rows.find((r) => metadataOf(r).row_count === 9)!; + expect(new Date(row.created_at).toISOString()).toBe(queriedAt.toISOString()); + await writer.stop(); + }); + + it('enqueue returns before the ledger write: the row lands on the flush, off the request path', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'] }); + const before = (await queryRows(engine)).length; + const returned = writer.recordDatasetQuery(queryEvent({ rowCount: 11 })); + expect(returned).toBeUndefined(); + expect(writer.pending()).toBe(1); + expect(await queryRows(engine)).toHaveLength(before); + await writer.flush(); + expect(await queryRows(engine)).toHaveLength(before + 1); + await writer.stop(); + }); + + it('a lost batch is reported at error once per cause and never throws to the caller', async () => { + const logger = { error: vi.fn(), warn: vi.fn(), debug: vi.fn() }; + const failing = { insert: async () => { throw Object.assign(new Error('disk full'), { code: 'SQLITE_FULL' }); } } as any; + const writer = createDatasetQueryAuditWriter({ getEngine: () => failing, datasets: ['sales'], logger }); + writer.recordDatasetQuery(queryEvent()); + await writer.flush(); + writer.recordDatasetQuery(queryEvent()); + await writer.flush(); + expect(logger.error).toHaveBeenCalledTimes(1); + expect(String(logger.error.mock.calls[0][0])).toMatch(/Dataset-query audit write FAILED/); + await writer.stop(); + }); +}); + +describe('the dataset_query opt-in through AuditPlugin and the `audit` slot', () => { + it('a dataset named in datasetQueryAudit.datasets writes its row through the slot; another dataset writes none', async () => { + const { kernel, engine } = await bootKernel( + new AuditPlugin({ datasetQueryAudit: { datasets: ['sales'], flushIntervalMs: 1 } }), + ); + try { + const audit = kernel.getService<{ recordDatasetQuery(e: DatasetQueryAuditEvent): void }>('audit'); + expect(typeof audit.recordDatasetQuery).toBe('function'); + audit.recordDatasetQuery(queryEvent({ datasetName: 'pipeline', rowCount: 21 })); + audit.recordDatasetQuery(queryEvent({ datasetName: 'sales', rowCount: 22 })); + await vi.waitFor(async () => { + expect((await queryRows(engine)).map((r) => metadataOf(r).dataset)).toEqual(['sales']); + }, { timeout: 5_000 }); + } finally { + await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + } + }, 120_000); + + it('an AuditPlugin with no datasetQueryAudit option writes no dataset_query row', async () => { + const { kernel, engine } = await bootKernel(new AuditPlugin()); + try { + const audit = kernel.getService<{ recordDatasetQuery(e: DatasetQueryAuditEvent): void }>('audit'); + audit.recordDatasetQuery(queryEvent()); + await new Promise((r) => setTimeout(r, 50)); + expect(await queryRows(engine)).toHaveLength(0); + } finally { + await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + } + }, 120_000); +}); diff --git a/packages/rest/src/analytics-dataset-query-audit.test.ts b/packages/rest/src/analytics-dataset-query-audit.test.ts new file mode 100644 index 00000000000..81b066f2900 --- /dev/null +++ b/packages/rest/src/analytics-dataset-query-audit.test.ts @@ -0,0 +1,159 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The analytics dataset door's half of the ledger's `dataset_query` row: one + * event per saved-dataset query that reached the read, handed to the `audit` + * slot's `recordDatasetQuery` (plugin-audit's `dataset-query-audit.ts` owns + * the row, the per-dataset opt-in and the batching, pinned there). + * + * The rules are the export door's: a query the door refused before the read + * hands no event; a query that failed after the read started hands one event + * with outcome `failed`, its status and machine code. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { RestServer } from './rest-server'; + +function mockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), + use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; +} + +function mockRes() { + const res: any = { statusCode: 200, body: undefined }; + res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); + res.json = vi.fn((b: any) => { res.body = b; return res; }); + res.end = vi.fn(() => res); + return res; +} + +const SALES = { + name: 'sales', label: 'Sales', object: 'opportunity', + dimensions: [{ name: 'region', field: 'region', type: 'string' }], + measures: [{ name: 'revenue', aggregate: 'sum', field: 'amount' }], +}; + +/** A value no field name, operator or code in this file spells. */ +const SECRET = 'Zq7-door-filter-value-8830'; + +function protocolWith(items: any[]) { + return { + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn().mockResolvedValue([]), + getMetaItem: vi.fn(async ({ name }: { name: string }) => ({ type: 'dataset', name, item: items.find((d) => d?.name === name) })), + }; +} + +function boot(opts: { queryDataset?: (...a: any[]) => Promise; sink?: Record } = {}) { + const events: any[] = []; + const sink = opts.sink ?? { recordDatasetQuery: (event: any) => { events.push(event); } }; + const queryDataset = vi.fn(opts.queryDataset ?? (async () => ({ rows: [{ region: 'NA', revenue: 1 }, { region: 'EU', revenue: 2 }], fields: [] }))); + const rest = new RestServer( + mockServer() as any, protocolWith([SALES]) as any, { api: { requireAuth: false } } as any, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, undefined, + async () => ({ queryDataset }), // analyticsServiceProvider + undefined, // settingsServiceProvider + undefined, // serviceExistsProvider + undefined, // securityServiceProvider + undefined, // requestEnvResolver + undefined, // metadataServiceProvider + undefined, // tenancyServiceProvider + async () => sink, // auditServiceProvider + ); + (rest as any).resolveExecCtx = async () => ({ userId: 'u_analyst', tenantId: 'org_a' }); + rest.registerRoutes(); + const single = rest.getRoutes().find((r) => r.method === 'POST' && r.path.endsWith('/analytics/dataset/query'))!; + const batch = rest.getRoutes().find((r) => r.method === 'POST' && r.path.endsWith('/analytics/dataset/query/batch'))!; + const post = async (body: unknown) => { + const res = mockRes(); + await single.handler({ method: 'POST', params: {}, query: {}, headers: {}, body } as any, res); + return res; + }; + const postBatch = async (queries: unknown[]) => { + const res = mockRes(); + await batch.handler({ method: 'POST', params: {}, query: {}, headers: {}, body: { queries } } as any, res); + return res; + }; + return { events, queryDataset, post, postBatch }; +} + +const selection = { + dimensions: ['region'], + measures: ['revenue'], + runtimeFilter: { region: SECRET, amount: { $gte: 5 } }, +}; + +describe('POST /analytics/dataset/query hands the ledger one event per query that reached the read', () => { + it('a saved-dataset query that answered hands ONE event: caller, dataset, selection names, the filter as read, the row count', async () => { + const { events, post } = boot(); + const res = await post({ datasetName: 'sales', selection }); + expect(res.statusCode).toBe(200); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + context: { userId: 'u_analyst', tenantId: 'org_a' }, + datasetName: 'sales', + objectName: 'opportunity', + dimensions: ['region'], + measures: ['revenue'], + readQuery: { filter: selection.runtimeFilter }, + rowCount: 2, + outcome: 'succeeded', + }); + }); + + it('a query refused before the read hands no event', async () => { + const { events, post, queryDataset } = boot(); + // No measures: the door's selection check refuses it. + expect((await post({ datasetName: 'sales', selection: { dimensions: ['region'], measures: [] } })).statusCode).toBe(400); + // A dataset the resolver does not find. + expect((await post({ datasetName: 'nope', selection })).statusCode).toBe(404); + // An unknown body key: the body door refuses it. + expect((await post({ datasetName: 'sales', selection, runtimeFilter: {} })).statusCode).toBe(400); + expect(queryDataset).not.toHaveBeenCalled(); + expect(events).toEqual([]); + }); + + it('a query that failed after the read started hands ONE event with outcome failed, its status and machine code', async () => { + const { events, post } = boot({ + queryDataset: async () => { throw Object.assign(new Error(`driver said ${SECRET}`), { code: 'SERVICE_UNAVAILABLE', status: 503 }); }, + }); + const res = await post({ datasetName: 'sales', selection }); + expect(res.statusCode).toBe(503); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ datasetName: 'sales', outcome: 'failed', rowCount: 0, status: 503, errorCode: 'SERVICE_UNAVAILABLE' }); + // The error's text, which a driver can fill with a comparand, never travels. + expect(JSON.stringify({ ...events[0], readQuery: undefined })).not.toContain(SECRET); + }); + + it('an inline dataset definition hands no event: the opt-in is per saved dataset, and an inline name is the caller\'s text', async () => { + const { events, post } = boot(); + const res = await post({ dataset: SALES, selection }); + expect(res.statusCode).toBe(200); + expect(events).toEqual([]); + }); + + it('the batch door hands one event per query that reached the read, and none for an entry refused before it', async () => { + const { events, postBatch } = boot(); + const res = await postBatch([ + { datasetName: 'sales', selection }, + { datasetName: 'nope', selection }, + { datasetName: 'sales', selection: { measures: ['revenue'] } }, + ]); + expect(res.statusCode).toBe(200); + expect(events.map((e) => [e.datasetName, e.outcome])).toEqual([ + ['sales', 'succeeded'], + ['sales', 'succeeded'], + ]); + }); + + it('a ledger sink that throws never changes the answer', async () => { + const { post } = boot({ sink: { recordDatasetQuery: () => { throw new Error('ledger down'); } } }); + const res = await post({ datasetName: 'sales', selection }); + expect(res.statusCode).toBe(200); + expect(res.body.rows).toHaveLength(2); + }); +}); From 7b6980cf3a6faac9aecc81e75cde2e6ce35c9cd0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:53:39 +0000 Subject: [PATCH 02/10] feat(plugin-audit,rest): one dataset_query ledger row per query of an opted-in saved dataset The analytics dataset door hands the audit slot one event per saved-dataset query that reached the read, answered or failed; a request refused before the read hands none. plugin-audit records only the datasets named in AuditPlugin's datasetQueryAudit.datasets (off by default), batched off the request path with the record-view writer's batcher, and keeps the filter's field names and operators, never its values. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../plugins/plugin-audit/src/audit-plugin.ts | 49 +++ .../plugin-audit/src/data-export-audit.ts | 7 +- .../plugin-audit/src/dataset-query-audit.ts | 364 ++++++++++++++++++ packages/plugins/plugin-audit/src/index.ts | 13 + .../sys-audit-log-action-labels.test.ts | 2 + .../sys-audit-log-retired-actions.test.ts | 6 + .../src/objects/sys-audit-log.object.ts | 14 + .../plugins/plugin-audit/src/read-audit.ts | 22 +- .../src/translations/ar.objects.generated.ts | 3 +- .../ar.source-hashes.generated.ts | 1 + .../src/translations/de.objects.generated.ts | 3 +- .../de.source-hashes.generated.ts | 1 + .../src/translations/en.objects.generated.ts | 3 +- .../translations/es-ES.objects.generated.ts | 3 +- .../es-ES.source-hashes.generated.ts | 1 + .../src/translations/fr.objects.generated.ts | 3 +- .../fr.source-hashes.generated.ts | 1 + .../translations/ja-JP.objects.generated.ts | 3 +- .../ja-JP.source-hashes.generated.ts | 1 + .../src/translations/ko.objects.generated.ts | 3 +- .../ko.source-hashes.generated.ts | 1 + .../translations/pt-BR.objects.generated.ts | 3 +- .../pt-BR.source-hashes.generated.ts | 1 + .../src/translations/ru.objects.generated.ts | 3 +- .../ru.source-hashes.generated.ts | 1 + .../translations/zh-CN.objects.generated.ts | 3 +- .../zh-CN.source-hashes.generated.ts | 1 + .../translations/zh-Hant.objects.generated.ts | 3 +- .../zh-Hant.source-hashes.generated.ts | 1 + .../rest/src/analytics-dataset-query-audit.ts | 157 ++++++++ packages/rest/src/analytics-routes.ts | 12 +- packages/rest/src/rest-server.ts | 1 + ...check-durability-degradation-log-level.mjs | 4 + scripts/measure-durability-swallow-family.mjs | 1 + 34 files changed, 674 insertions(+), 21 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/dataset-query-audit.ts create mode 100644 packages/rest/src/analytics-dataset-query-audit.ts diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 543a893a11c..1245d47b563 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -47,6 +47,7 @@ import { installReadAuditWriter, type ReadAuditWriterHandle } from './read-audit import { createAuthEventAuditSink } from './auth-event-audit.js'; import { createActionInvocationAuditWriter } from './action-invocation-audit.js'; import { createDataExportAuditWriter } from './data-export-audit.js'; +import { createDatasetQueryAuditWriter, type DatasetQueryAuditWriter } from './dataset-query-audit.js'; import { createPackageLifecycleAuditWriter } from './package-lifecycle-audit.js'; import { createCredentialUseAuditWriter, @@ -99,10 +100,32 @@ export interface AuditPluginReadAuditOptions { flushIntervalMs?: number; } +/** + * Dataset-query auditing configuration — the per-dataset opt-in, closed, with + * the record-view writer's shape and for its reasons + * ({@link AuditPluginReadAuditOptions}). + */ +export interface AuditPluginDatasetQueryAuditOptions { + /** + * Saved datasets whose queries through the analytics dataset door are + * recorded as `dataset_query` rows in `sys_audit_log`: who, which dataset, + * the dimensions and measures selected, the filtered field names (never the + * values), the row count and the outcome. Absent or empty records nothing + * and buffers nothing. + */ + datasets?: readonly string[]; + /** Flush once this many rows are buffered. Default 50. */ + maxBatchSize?: number; + /** Flush this long after the first row of a batch. Default 2000ms. */ + flushIntervalMs?: number; +} + /** Constructor options for {@link AuditPlugin}. */ export interface AuditPluginOptions { /** [#8992] Record-view auditing. Off unless objects are named. */ readAudit?: AuditPluginReadAuditOptions; + /** Dataset-query auditing (`dataset_query` rows). Off unless datasets are named. */ + datasetQueryAudit?: AuditPluginDatasetQueryAuditOptions; /** * Host locale resolver: the language this plugin writes the title of the * @mention notification it emits in. Called with the write's organization @@ -311,6 +334,7 @@ export class AuditPlugin implements Plugin { * succeeded. */ private readAuditWriter: ReadAuditWriterHandle | null = null; + private datasetQueryWriter: DatasetQueryAuditWriter | null = null; /** [ADR-0154 D3] The sealer, started at `kernel:ready` and stopped by `destroy()`. */ private sealer: AuditSealer | null = null; @@ -435,6 +459,27 @@ export class AuditPlugin implements Plugin { // this slot, from plugin-auth's OAuth stamp point // (`credential-use-audit.ts`). this.credentialUseWriter = createCredentialUseAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }); + // + // And the dataset-query writer (`recordDatasetQuery`): the analytics + // dataset door hands it one event per saved-dataset query that reached + // the read; it records only the datasets named in + // `datasetQueryAudit.datasets`, batched off the request path + // (`dataset-query-audit.ts`). Named nothing, it records nothing. + const datasetQueryAudit = this.options.datasetQueryAudit; + const datasetQueryWriter = createDatasetQueryAuditWriter({ + getEngine: getLedgerEngine, + logger: ctx.logger, + datasets: datasetQueryAudit?.datasets ?? [], + ...(datasetQueryAudit?.maxBatchSize !== undefined ? { maxBatchSize: datasetQueryAudit.maxBatchSize } : {}), + ...(datasetQueryAudit?.flushIntervalMs !== undefined ? { flushIntervalMs: datasetQueryAudit.flushIntervalMs } : {}), + }); + this.datasetQueryWriter = datasetQueryWriter; + if (datasetQueryWriter.auditedDatasets.length > 0) { + ctx.logger.info( + `AuditPlugin: dataset-query auditing on ${datasetQueryWriter.auditedDatasets.length} dataset(s) — ` + + `${datasetQueryWriter.auditedDatasets.join(', ')}`, + ); + } ctx.registerService('audit', { ...createAuthEventAuditSink({ getEngine: getLedgerEngine, logger: ctx.logger }), ...createActionInvocationAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }), @@ -442,6 +487,7 @@ export class AuditPlugin implements Plugin { ...createPackageLifecycleAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }), ...this.credentialUseWriter, ...createScimRefusalAuditWriter({ getEngine: getLedgerEngine, logger: ctx.logger }), + recordDatasetQuery: datasetQueryWriter.recordDatasetQuery, // The activity door's writer: one timeline entry an app adds through // `ctx.activity.append` (`app-activity-door.ts`). ...createAppActivityWriter({ getEngine: getLedgerEngine, getActorSnapshot: () => this.actorSnapshotOf }), @@ -1009,6 +1055,9 @@ export class AuditPlugin implements Plugin { const writer = this.readAuditWriter; this.readAuditWriter = null; if (writer) await writer.stop(); + const datasetQueryWriter = this.datasetQueryWriter; + this.datasetQueryWriter = null; + if (datasetQueryWriter) await datasetQueryWriter.stop(); } } diff --git a/packages/plugins/plugin-audit/src/data-export-audit.ts b/packages/plugins/plugin-audit/src/data-export-audit.ts index 39820af56f1..1b12f1ab44a 100644 --- a/packages/plugins/plugin-audit/src/data-export-audit.ts +++ b/packages/plugins/plugin-audit/src/data-export-audit.ts @@ -166,7 +166,12 @@ export interface ExportFilterSummary { omitted: number; } -function recordedField(path: string): string { +/** + * A field path as the ledger records it: the path when it is a machine-name + * path, else `?`. Shared with the `dataset_query` writer, which records the + * selection's dimension and measure names under the same rule. + */ +export function recordedField(path: string): string { return FIELD_PATH.test(path) ? path : '?'; } diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.ts new file mode 100644 index 00000000000..aad1f254df2 --- /dev/null +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.ts @@ -0,0 +1,364 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `dataset_query` row in the compliance ledger: one durable, run-level row + * per query of an opted-in saved dataset that the analytics dataset door + * (`POST /analytics/dataset/query`, and each query of its batch door) handed + * to the read. + * + * ## What it answers + * + * 「who read which dataset, under which filter, and how many rows came back」. + * A report or a dashboard is composed in the browser and reaches the server + * only as dataset queries, so this row is the server's own fact about what was + * read: it covers reports and dashboards alike, and it does NOT name a report, + * which the server never sees. The action is named for what the row records. + * + * ## The scope pins (the follow-up the record-view writer reserved) + * + * The same three pins `read-audit.ts` carries, each a line of code here: + * + * - **Per-dataset opt-in, closed, off by default.** The writer takes the + * opted-in dataset names ({@link DatasetQueryAuditWriterOptions.datasets}, + * wired from `AuditPlugin`'s `datasetQueryAudit.datasets`). A query of any + * other dataset is dropped before anything is buffered, and an empty list + * builds no batcher at all. There is no global flag and no exception list, + * for the reason `read-audit.ts` gives for its install-time list. + * - **Saved datasets only.** The opt-in names a saved dataset; an inline + * definition (the Studio preview) carries a name the caller chose, so the + * door hands no event for one. That edge is a declared narrowing. + * - **Async batched writes off the request path.** `recordDatasetQuery` + * enqueues and returns; the rows land on a later tick through + * `createReadAuditBatcher`, the record-view writer's batcher. The query + * that produced the row never awaits its write. + * + * ## Refused and failed queries (the export door's rules) + * + * The door hands an event only once the query reached the read + * (`queryDataset`): a request it refused first (identity, the body and + * selection doors, the dataset's resolution, its parse) is no read and writes + * no row. A query that failed after the read started writes one row with + * outcome `failed`, the HTTP status and the error's machine code, never the + * error's text. + * + * ## No queried value, ever + * + * The row records WHAT was asked, never what was in it: the filter is reduced + * to its field names and operators by the export writer's own + * `summarizeExportFilter` (every comparand dropped unread), the selection to + * its dimension and measure names, and the answer to its row count. Nothing + * here reads a row of the result. + */ + +import type { IDataEngine } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { isMissingTableError } from '@objectstack/types'; +import { + auditFailureCauseKey, + auditFailureCauseSummary, + createFieldPresenceProbe, +} from './audit-writers.js'; +import { recordedField, summarizeExportFilter } from './data-export-audit.js'; +import { IMPERSONATED_BY_KEY, impersonatorOf } from './impersonation-attribution.js'; +import { + createReadAuditBatcher, + type ReadAuditBatcher, + type ReadAuditLogger, + type ReadAuditTimers, +} from './read-audit.js'; + +/** The `sys_audit_log.action` value this writer emits. */ +export const DATASET_QUERY_AUDIT_ACTION = 'dataset_query' as const; + +/** How the query ended: it answered, or it failed after the read started. */ +export type DatasetQueryOutcome = 'succeeded' | 'failed'; + +/** + * One dataset query, in the vocabulary of what HAPPENED. The door builds it; + * this writer turns it into a row. + */ +export interface DatasetQueryAuditEvent { + /** + * The caller's envelope. Read for `userId`, `actor`, `tenantId`, + * `performedBy` and `impersonatedBy` — nothing else. + */ + context: + | Pick + | undefined; + /** The saved dataset's name, as the door resolved it. The opt-in is keyed on it. */ + datasetName: string; + /** The dataset's base object. */ + objectName?: string; + /** The selection's dimension names. */ + dimensions?: unknown; + /** The selection's measure names. */ + measures?: unknown; + /** The selection's time-dimension names (never their date ranges). */ + timeDimensions?: unknown; + /** + * The query's filter as the door read it. Reduced to names and operators + * before it reaches the row: the comparands are never recorded. + */ + readQuery?: { filter?: unknown }; + /** Rows the answer carried (0 on a failure). */ + rowCount: number; + outcome: DatasetQueryOutcome; + /** On a failure: the HTTP status the door answered. */ + status?: number; + /** On a failure: the error's machine code, as the door answered it. */ + errorCode?: string; +} + +/** What {@link createDatasetQueryAuditWriter} returns; `recordDatasetQuery` goes on the `audit` slot. */ +export interface DatasetQueryAuditWriter { + /** The datasets this writer records — the closed opt-in set. */ + readonly auditedDatasets: readonly string[]; + /** + * Record one query. Returns immediately — never awaits the ledger write, + * never throws. A dataset outside the opt-in is dropped here. + */ + recordDatasetQuery(event: DatasetQueryAuditEvent): void; + /** Persist every buffered row now. */ + flush(): Promise; + /** Rows buffered and not yet persisted. */ + pending(): number; + /** Cancel the timer and flush the tail. */ + stop(): Promise; +} + +export interface DatasetQueryAuditWriterOptions { + /** Resolve the data engine at FLUSH time — see `AuthEventAuditSinkOptions.getEngine`. */ + getEngine(): IDataEngine | undefined; + /** + * The per-dataset opt-in — the closed set of saved dataset names whose + * queries are recorded. Empty (the default) records nothing and buffers + * nothing. + */ + datasets?: readonly string[]; + logger?: ReadAuditLogger; + /** Flush as soon as this many rows are buffered. Default 50. */ + maxBatchSize?: number; + /** Flush this long after the first row of a batch. Default 2000ms. */ + flushIntervalMs?: number; + /** Hard ceiling on the buffer. Default 10000. */ + maxBufferedEvents?: number; + timers?: ReadAuditTimers; + /** Clock seam — the query instant stamped on the row. Defaults to `Date`. */ + now?: () => Date; +} + +/** The most dimension, measure or time-dimension names a row keeps, each. */ +const DATASET_QUERY_NAMES_MAX = 32; + +function nonEmpty(v: unknown): string | undefined { + return typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined; +} + +function wholeNumber(v: unknown): number | undefined { + return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.trunc(v) : undefined; +} + +/** A list of selection names, each a field path or `?`, bounded. */ +function selectionNames(v: unknown): string[] { + if (!Array.isArray(v)) return []; + return v + .filter((s): s is string => typeof s === 'string' && s.length > 0) + .slice(0, DATASET_QUERY_NAMES_MAX) + .map(recordedField); +} + +/** JSON that cannot throw on a cyclic/odd value — same rule as the CRUD writer. */ +function safeStringify(v: unknown): string { + try { + return JSON.stringify(v); + } catch { + return String(v); + } +} + +/** + * The row for one query, without the conditionally-present `actor` column — + * exported so the shape is pinned without an engine. Built at ENQUEUE time, so + * the buffer holds names and counts only, never the caller's filter. + */ +export function buildDatasetQueryAuditRow(event: DatasetQueryAuditEvent, queriedAt: Date): Record { + const ctx = event.context ?? {}; + const userId = nonEmpty(ctx.userId); + const performedBy = nonEmpty(ctx.performedBy?.clientId); + + const metadata: Record = { + dataset: recordedField(String(event.datasetName ?? '')), + dimensions: selectionNames(event.dimensions), + measures: selectionNames(event.measures), + }; + const timeDimensions = selectionNames(event.timeDimensions); + if (timeDimensions.length > 0) metadata.time_dimensions = timeDimensions; + const filter = event.readQuery?.filter; + if (filter !== undefined && filter !== null) { + const summary = summarizeExportFilter(filter); + metadata.filter = summary.terms; + if (summary.omitted > 0) metadata.filter_terms_omitted = summary.omitted; + } + metadata.row_count = wholeNumber(event.rowCount) ?? 0; + metadata.outcome = event.outcome === 'failed' ? 'failed' : 'succeeded'; + if (event.outcome === 'failed') { + if (typeof event.status === 'number') metadata.status = event.status; + const errorCode = nonEmpty(event.errorCode); + if (errorCode) metadata.error_code = errorCode; + } + // [ADR-0090 D10 rule 4] The delegated-call pair, as the CRUD mirror and the + // export row write it — present only when an agent performed the call. + if (performedBy) { + metadata.performed_by = performedBy; + metadata.on_behalf_of = userId ?? null; + } + const impersonatedBy = impersonatorOf(ctx); + if (impersonatedBy) metadata[IMPERSONATED_BY_KEY] = impersonatedBy; + + return { + action: DATASET_QUERY_AUDIT_ACTION, + // The QUERY instant, not the flush instant: batching moves the INSERT off + // the request path, and `persistDatasetQueryAuditRows` writes with + // `preserveAudit` so the stamp hook keeps it (`read-audit.ts` `buildRow` + // carries the full reasoning). + created_at: queriedAt, + user_id: userId ?? null, + object_name: nonEmpty(event.objectName) ?? null, + // Run-level: a query is about a set of rows, so it names no record. + record_id: null, + old_value: null, + new_value: null, + // [ADR-0131 D7] The organization the query ran in. + tenant_id: nonEmpty(ctx.tenantId) ?? null, + metadata: safeStringify(metadata), + }; +} + +/** The principal label the `actor` column takes (ADR-0014 D2), by the CRUD mirror's rule. */ +function actorOf(event: DatasetQueryAuditEvent): string | null { + const ctx = event.context ?? {}; + return nonEmpty(ctx.userId) ?? nonEmpty(ctx.actor) ?? null; +} + +interface PendingDatasetQueryRow { + row: Record; + actor: string | null; +} + +/** Create the `dataset_query` writer; `AuditPlugin` puts its `recordDatasetQuery` on the `audit` slot. */ +export function createDatasetQueryAuditWriter(opts: DatasetQueryAuditWriterOptions): DatasetQueryAuditWriter { + const { getEngine, logger, now = () => new Date() } = opts; + + const auditedDatasets = [...new Set(opts.datasets ?? [])].filter( + (name): name is string => typeof name === 'string' && name.trim().length > 0, + ); + const opted = new Set(auditedDatasets); + + let probe: ((objectName: string, field: string) => boolean) | undefined; + let probedEngine: IDataEngine | undefined; + + /** + * Write one batch of ledger rows. A NAMED callee so + * `pnpm check:durability-log-level` anchors on it + * (`DURABILITY_CRITICAL_CALLEES`). The two context keys are the record-view + * writer's, for its reasons (`persistReadAuditRows`): `isSystem` for the + * readonly strip, `preserveAudit` so the stamp hook keeps the query instant. + */ + const persistDatasetQueryAuditRows = async ( + engine: IDataEngine, + rows: Record[], + ): Promise => { + await engine.insert('sys_audit_log', rows as any, { context: { isSystem: true, preserveAudit: true } } as any); + }; + + /** + * Report a lost batch — once per CAUSE (`auditFailureCauseKey`), the rule + * every writer in this package follows. A durability degradation, so + * `error`, falling back to `warn`, never to silence. Names the count and the + * cause; never a query. + */ + const reportedCauses = new Set(); + const reportWriteFailure = (count: number, err: unknown): void => { + const detail = String((err as any)?.message ?? err); + try { + const cause = auditFailureCauseKey('sys_audit_log', err); + if (reportedCauses.has(cause)) { + logger?.debug?.('Dataset-query audit write failed (already reported)', { count, err: detail, cause }); + return; + } + reportedCauses.add(cause); + const message = + `Dataset-query audit write FAILED (${auditFailureCauseSummary(err, detail)}) — ${count} dataset_query ` + + 'row(s) were LOST and the compliance trail is now INCOMPLETE. The queries themselves were answered ' + + 'exactly as they would have been without the ledger, so every report, dashboard and counter reads ' + + 'clean; only the `sys_audit_log` rows recording WHO read WHICH dataset, under which filter and how many ' + + 'rows, never landed, and nothing retries them. Every later batch failing THIS WAY is lost the same way ' + + '(this CAUSE is reported ONCE — raise the log level to `debug` to see the rest; a DIFFERENT cause gets ' + + 'its own `error` line). ' + + (isMissingTableError(err, 'sys_audit_log') + ? 'Fix: confirm `sys_audit_log` is reachable from the connection this write ran on — its ADR-0057 ' + + '§3.6 lifecycle class routes it to the dedicated `telemetry` datasource whenever one is registered, ' + + 'so a "no such table" here usually means the write ran against a DIFFERENT datasource than the ' + + 'one the table was created in. Set `OS_TELEMETRY_DB=0` to keep every lifecycle-classed object on ' + + 'the primary datasource.' + : 'Fix: resolve the driver fault quoted at the head of this line on the connection this write ran ' + + 'on — every batch that hits it loses its rows until it is resolved.'); + if (logger?.error) { + logger.error(message, err instanceof Error ? err : new Error(detail), { count }); + } else { + logger?.warn?.(message, { count, err: detail }); + } + } catch { + /* logging must never break a query's answer */ + } + }; + + const batcher: ReadAuditBatcher | null = auditedDatasets.length === 0 + ? null + : createReadAuditBatcher({ + async persist(pending) { + const engine = getEngine(); + if (!engine) return; + try { + if (probe === undefined || probedEngine !== engine) { + probe = createFieldPresenceProbe(engine); + probedEngine = engine; + } + const hasActor = probe('sys_audit_log', 'actor'); + const rows = pending.map(({ row, actor }) => (hasActor ? { ...row, actor } : row)); + await persistDatasetQueryAuditRows(engine, rows); + } catch (err) { + reportWriteFailure(pending.length, err); + } + }, + overflowMessage: + 'Dataset-query audit buffer OVERFLOWED — dataset_query rows are being DROPPED, so the compliance trail ' + + 'now has holes that no error anywhere else will show: every query still answered. The buffer only ' + + 'grows this far when ledger writes are not draining (an unreachable `sys_audit_log`, or a query rate ' + + 'above what the datasource can absorb). This is reported ONCE — raise the log level to `debug` to see ' + + 'the rest. Fix: confirm `sys_audit_log` is writable from this process, then lower `flushIntervalMs` or ' + + 'raise `maxBatchSize` so batches drain faster than queries arrive.', + ...(opts.maxBatchSize !== undefined ? { maxBatchSize: opts.maxBatchSize } : {}), + ...(opts.flushIntervalMs !== undefined ? { flushIntervalMs: opts.flushIntervalMs } : {}), + ...(opts.maxBufferedEvents !== undefined ? { maxBufferedEvents: opts.maxBufferedEvents } : {}), + ...(logger !== undefined ? { logger } : {}), + ...(opts.timers !== undefined ? { timers: opts.timers } : {}), + }); + + return { + auditedDatasets, + recordDatasetQuery(event: DatasetQueryAuditEvent): void { + if (!batcher) return; + try { + if (!event || typeof event.datasetName !== 'string' || !opted.has(event.datasetName)) return; + batcher.enqueue({ row: buildDatasetQueryAuditRow(event, now()), actor: actorOf(event) }); + } catch (err) { + // A row that cannot be built is a row that does not land: reported as one. + reportWriteFailure(1, err); + } + }, + flush: () => batcher?.flush() ?? Promise.resolve(), + pending: () => batcher?.pending() ?? 0, + stop: () => batcher?.stop() ?? Promise.resolve(), + }; +} diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index b362d4f5430..8476e22a271 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -73,6 +73,19 @@ export type { PackageLifecycleAuditWriter, PackageLifecycleAuditWriterOptions, } from './package-lifecycle-audit.js'; +// The `dataset_query` row writer the analytics dataset door reaches through +// the `audit` slot, opted in per dataset. +export { + buildDatasetQueryAuditRow, + createDatasetQueryAuditWriter, + DATASET_QUERY_AUDIT_ACTION, +} from './dataset-query-audit.js'; +export type { + DatasetQueryAuditEvent, + DatasetQueryAuditWriter, + DatasetQueryAuditWriterOptions, + DatasetQueryOutcome, +} from './dataset-query-audit.js'; export { createReadAuditBatcher, extractDetailReadId, diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts index c8462a14a69..af94bb790e1 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-log-action-labels.test.ts @@ -41,6 +41,8 @@ describe('sys_audit_log.action option labels', () => { 'scim_refused', // #31908: a new value, added writer-first; no existing value moved. 'audit_signing_key_change', + // A new value, added writer-first; no existing value moved. + 'dataset_query', ]); }); diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts index a6d536151e5..e4bba748850 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-log-retired-actions.test.ts @@ -137,6 +137,12 @@ const ACTIONS_WITH_WRITERS: ReadonlyArray { /** Record a view. Returns immediately — never awaits the ledger write. */ - enqueue(event: ReadAuditEvent): void; + enqueue(event: E): void; /** Persist everything buffered right now. */ flush(): Promise; /** How many views are buffered and not yet persisted. */ @@ -190,9 +190,9 @@ const DEFAULT_TIMERS: ReadAuditTimers = { }, }; -export interface ReadAuditBatcherOptions { +export interface ReadAuditBatcherOptions { /** Persist one drained batch. Must not be called concurrently with itself. */ - persist(events: ReadAuditEvent[]): Promise; + persist(events: E[]): Promise; /** Flush as soon as this many views are buffered. Default 50. */ maxBatchSize?: number; /** Flush this long after the first view of a batch. Default 2000ms. */ @@ -206,6 +206,12 @@ export interface ReadAuditBatcherOptions { maxBufferedEvents?: number; logger?: ReadAuditLogger; timers?: ReadAuditTimers; + /** + * The overflow warning's text, for a batcher that buffers another kind of + * row (the `dataset_query` writer, `dataset-query-audit.ts`). Absent, the + * record-view sentence below. + */ + overflowMessage?: string; } /** @@ -221,7 +227,7 @@ export interface ReadAuditBatcherOptions { * turn a valid read into an error, and a retry storm against an unreachable * table is the shape that turns a degradation into an outage. */ -export function createReadAuditBatcher(opts: ReadAuditBatcherOptions): ReadAuditBatcher { +export function createReadAuditBatcher(opts: ReadAuditBatcherOptions): ReadAuditBatcher { const { persist, maxBatchSize = 50, @@ -229,9 +235,10 @@ export function createReadAuditBatcher(opts: ReadAuditBatcherOptions): ReadAudit maxBufferedEvents = 10_000, logger, timers = DEFAULT_TIMERS, + overflowMessage, } = opts; - let buffer: ReadAuditEvent[] = []; + let buffer: E[] = []; let timer: unknown = null; /** Serializes flushes so two never interleave against the same driver. */ let inFlight: Promise = Promise.resolve(); @@ -245,6 +252,7 @@ export function createReadAuditBatcher(opts: ReadAuditBatcherOptions): ReadAudit } overflowReported = true; logger?.warn?.( + overflowMessage ?? 'Read-audit buffer OVERFLOWED — record-view rows are being DROPPED, so the compliance trail now has ' + 'holes that no error anywhere else will show: every read still succeeded and returned 200. The buffer ' + 'only grows this far when ledger writes are not draining (an unreachable `sys_audit_log`, or a view rate ' + @@ -287,7 +295,7 @@ export function createReadAuditBatcher(opts: ReadAuditBatcherOptions): ReadAudit }; return { - enqueue(event: ReadAuditEvent): void { + enqueue(event: E): void { if (stopped) return; buffer.push(event); if (buffer.length > maxBufferedEvents) { diff --git a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts index 47ac16a6ffb..d981e5c06b9 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts @@ -44,7 +44,8 @@ export const arObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts index d522f37ec99..e1602631a00 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const arGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts index 0725a5e71dc..591f061b53e 100644 --- a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts @@ -44,7 +44,8 @@ export const deObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts index 1814d471e76..2f248d310f5 100644 --- a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.export": "cdfbf4ace38f5a21", "objects.sys_audit_log.fields.action.options.import": "05c80d3a61ec3290", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", diff --git a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts index c1a082de590..c9e26ab966b 100644 --- a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts @@ -44,7 +44,8 @@ export const enObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts index 9d5c070662d..b98dc99e4c7 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts @@ -44,7 +44,8 @@ export const esESObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts index 71aa5710371..681d64e4f7e 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts @@ -93,6 +93,7 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_log.fields.actor.label": "b155813f8a7f06e3", diff --git a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts index 27e32b6c708..f8537f3bbf9 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts @@ -44,7 +44,8 @@ export const frObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts index 2de189384cb..fc3fc48aae5 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts @@ -93,6 +93,7 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_audit_log.fields.action.label": "a36bba313a7aa9ab", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.export": "cdfbf4ace38f5a21", "objects.sys_audit_log.fields.action.options.import": "05c80d3a61ec3290", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts index 72b0316c262..45a46342ba7 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts @@ -44,7 +44,8 @@ export const jaJPObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts index 1f01fb8981b..46ba9ae38fc 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts @@ -92,6 +92,7 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts index 7f833047ed1..177f2808757 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts @@ -44,7 +44,8 @@ export const koObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts index b3eb442b766..d537eeeb984 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts index 5513611c149..42ea8a1ffb7 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts @@ -44,7 +44,8 @@ export const ptBRObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts index 03b424f62a3..e4892929219 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts index ab5582b88b8..e63717ea193 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts @@ -44,7 +44,8 @@ export const ruObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts index d28c39ad2c6..65a725eaa8c 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts index b649ae4ae23..50e55bd8f39 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts @@ -44,7 +44,8 @@ export const zhCNObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts index e5e21a0d8a6..1eef8db5fc6 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts @@ -92,6 +92,7 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts index 3d3dfead628..06a6b24da85 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts @@ -44,7 +44,8 @@ export const zhHantObjects: NonNullable = { package_unmanaged_import: "Package Unmanaged Import", credential_use: "Credential Use", scim_refused: "SCIM Refused", - audit_signing_key_change: "Audit Signing Key Change" + audit_signing_key_change: "Audit Signing Key Change", + dataset_query: "Dataset Query" } }, user_id: { diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts index a09d064c7e8..271fe17738b 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts @@ -91,6 +91,7 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.pluralLabel": "9f6cf60d97382872", "objects.sys_audit_log.fields.action.options.audit_signing_key_change": "3d3ea51b5e14e16f", "objects.sys_audit_log.fields.action.options.credential_use": "68af3e0d078292d7", + "objects.sys_audit_log.fields.action.options.dataset_query": "1654e463eefcc0e4", "objects.sys_audit_log.fields.action.options.package_unmanaged_import": "676d7ce8c9d1fda4", "objects.sys_audit_log.fields.action.options.scim_refused": "2f27dc90233914f7", "objects.sys_audit_signing_key.description": "211b2fe44c08ada5", diff --git a/packages/rest/src/analytics-dataset-query-audit.ts b/packages/rest/src/analytics-dataset-query-audit.ts new file mode 100644 index 00000000000..54a32459239 --- /dev/null +++ b/packages/rest/src/analytics-dataset-query-audit.ts @@ -0,0 +1,157 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The analytics dataset door's half of the ledger's `dataset_query` row: the + * event this door hands the `audit` slot's `recordDatasetQuery` + * (plugin-audit's `dataset-query-audit.ts`, which owns the row, the + * per-dataset opt-in and the batching, and declares the same shape). + * Declared here structurally, so neither package depends on the other — the + * export door's `recordDataExport` reaches the same slot the same way + * (`data-action-routes.ts`). + * + * ## Which queries hand an event + * + * One event per query of a SAVED dataset that reached the read + * (`queryDataset`), whether it answered or failed; the export door's rules: + * + * - a request the door refused before the read (identity, the body and + * selection doors, the dataset's resolution, its parse) is no read and + * hands none — {@link runAuditedDatasetQuery} only wraps the read itself; + * - a read that threw hands one event with outcome `failed`, the status and + * machine code the shared resolver reads off the error, never its text, + * which a driver can fill with a comparand; + * - an inline definition (the Studio preview) hands none: the opt-in names a + * saved dataset, and an inline definition's name is the caller's text. + * + * `readQuery` is the filter AS READ: the writer reduces it to field names and + * operators before anything reaches the ledger. It is not spelled `query` for + * the reason `data-action-routes.ts` gives. + * + * Whether the dataset is audited at all is the writer's to answer (its + * opt-in list); the door hands every saved-dataset query and the writer drops + * the ones it was not asked to record, before buffering anything. + */ + +import { resolveThrownHttpError } from '@objectstack/types'; + +/** One dataset query, as the door hands it to the `audit` slot. */ +interface DatasetQueryAuditEvent { + context: unknown; + datasetName: string; + objectName?: string; + dimensions?: unknown; + measures?: unknown; + timeDimensions?: unknown; + readQuery: { filter?: unknown }; + rowCount: number; + outcome: 'succeeded' | 'failed'; + status?: number; + errorCode?: string; +} + +/** The `audit` slot member this door calls — declared locally, structurally. */ +interface DatasetQueryAuditSurface { + recordDatasetQuery(event: DatasetQueryAuditEvent): void | Promise; +} + +/** What {@link runAuditedDatasetQuery} reads from the server: the audit slot's resolver. */ +export interface DatasetQueryAuditHost { + resolveAuditService(environmentId?: string, req?: any): Promise; +} + +/** The query being read, as the door judged it. */ +export interface AuditedDatasetQuery { + readonly req: unknown; + readonly environmentId: string | undefined; + readonly context: unknown; + /** The saved dataset's name; `undefined` for an inline definition, which hands no event. */ + readonly datasetName: string | undefined; + /** The parsed dataset definition (read for its base object). */ + readonly dataset: unknown; + /** The caller's selection (read for its names and its filter). */ + readonly selection: unknown; +} + +const asRecord = (v: unknown): Record => + v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : {}; + +/** The selection's time-dimension names, never their date ranges. */ +function timeDimensionNames(v: unknown): string[] | undefined { + if (!Array.isArray(v)) return undefined; + return v.map((t) => asRecord(t).dimension).filter((d): d is string => typeof d === 'string'); +} + +/** + * Hand one query to the `audit` slot. Never throws and never waits for the + * ledger write — the writer enqueues and returns, and reports its own lost + * rows. A host with no audit plugin has no ledger, so the call is skipped. + */ +async function recordDatasetQuery( + host: DatasetQueryAuditHost, + query: AuditedDatasetQuery, + event: DatasetQueryAuditEvent, +): Promise { + let sink: Partial | undefined; + try { + sink = (await host.resolveAuditService(query.environmentId, query.req)) as Partial | undefined; + } catch { + return; // no audit slot on this kernel: no ledger to write to + } + if (!sink || typeof sink.recordDatasetQuery !== 'function') return; + try { + const pending = sink.recordDatasetQuery(event); + // A host's own sink that answers a promise is not awaited: the + // ledger write stays off the request path, and its rejection is + // never the caller's. + if (pending && typeof (pending as Promise).catch === 'function') { + (pending as Promise).catch(() => undefined); + } + } catch { + // The writer never throws by contract; a sink that does must not turn + // an answered query into a failed request. + } +} + +/** + * Run the dataset read and hand the ledger its event: one per saved-dataset + * query that reached the read, answered or failed. The read's own answer and + * its own throw pass through unchanged. + */ +export async function runAuditedDatasetQuery( + host: DatasetQueryAuditHost, + query: AuditedDatasetQuery, + read: () => Promise, +): Promise { + if (typeof query.datasetName !== 'string' || query.datasetName === '') return read(); + const selection = asRecord(query.selection); + const base = { + context: query.context, + datasetName: query.datasetName, + ...(typeof asRecord(query.dataset).object === 'string' ? { objectName: asRecord(query.dataset).object as string } : {}), + dimensions: selection.dimensions, + measures: selection.measures, + ...(selection.timeDimensions !== undefined ? { timeDimensions: timeDimensionNames(selection.timeDimensions) } : {}), + readQuery: { filter: selection.runtimeFilter }, + }; + let result: T; + try { + result = await read(); + } catch (error) { + const { status, code } = resolveThrownHttpError(error, 500); + await recordDatasetQuery(host, query, { + ...base, + rowCount: 0, + outcome: 'failed', + status, + ...(typeof code === 'string' && code.length > 0 ? { errorCode: code } : {}), + }); + throw error; + } + const rows = asRecord(result).rows; + await recordDatasetQuery(host, query, { + ...base, + rowCount: Array.isArray(rows) ? rows.length : 0, + outcome: 'succeeded', + }); + return result; +} diff --git a/packages/rest/src/analytics-routes.ts b/packages/rest/src/analytics-routes.ts index 662e822c455..856ac5e50d3 100644 --- a/packages/rest/src/analytics-routes.ts +++ b/packages/rest/src/analytics-routes.ts @@ -83,6 +83,8 @@ import { refuseRepeatedQueryParams } from './query-multiplicity.js'; import { mayReadPendingDrafts, metaItemPackageBinding, type RestServer } from './rest-server.js'; import { metaCallerPackageQuery, metaItemCallerPackageRefusalMessage } from './meta-item-read-gate.js'; import { admitRefusedDatasetHolders } from './analytics-dataset-admission-order.js'; +// The ledger's `dataset_query` row: one per saved-dataset query that reached the read. +import { runAuditedDatasetQuery } from './analytics-dataset-query-audit.js'; /** * The `RestServer` members {@link registerAnalyticsEndpoints} reads — every @@ -100,6 +102,8 @@ export interface AnalyticsRouteHost { enforceAuth: RestServer['enforceAuth']; resolveProtocol: RestServer['resolveProtocol']; translateMetaItem: RestServer['translateMetaItem']; + /** The `audit` slot, for the ledger's `dataset_query` row ({@link runAuditedDatasetQuery}). */ + resolveAuditService: RestServer['resolveAuditService']; } /** @@ -768,12 +772,16 @@ async function answerDatasetQuery( }; } - const result = await svc.queryDataset( + // The read. A saved dataset's query hands the ledger one + // `dataset_query` event here, answered or failed; every refusal above + // returned before it and hands none ({@link runAuditedDatasetQuery}). + const queried = { req, environmentId, context, dataset, selection, datasetName: body.dataset ? undefined : body.datasetName }; + const result = await runAuditedDatasetQuery(this, queried, () => svc.queryDataset( dataset, selection, context ?? undefined, previewDrafts ? { previewDrafts: true } : undefined, - ); + )); return { status: 200, body: result }; } catch (error: any) { return datasetQueryFaultAnswer(error); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 1eee701a012..244bca4ec64 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -6342,6 +6342,7 @@ export class RestServer { enforceAuth: (...a) => this.enforceAuth(...a), resolveProtocol: (...a) => this.resolveProtocol(...a), translateMetaItem: (...a) => this.translateMetaItem(...a), + resolveAuditService: (...a) => this.resolveAuditService(...a), }; registerAnalyticsEndpoints.call(host, basePath); } diff --git a/scripts/check-durability-degradation-log-level.mjs b/scripts/check-durability-degradation-log-level.mjs index 32fbdff856d..1580658b0a0 100644 --- a/scripts/check-durability-degradation-log-level.mjs +++ b/scripts/check-durability-degradation-log-level.mjs @@ -422,6 +422,10 @@ const DURABILITY_CRITICAL_CALLEES = new Map([ 'persistScimRefusalAuditRow', 'The compliance audit row for a refused SCIM request was never written — the identity provider was answered its refusal exactly as it would have been without the ledger, so the API and every counter read clean, while the `sys_audit_log` row recording WHICH connection was refused, and why, is simply absent and nothing retries it. A SCIM console or SIEM feed reading `scim_refused` rows keeps showing a connection with no errors (#31829, the #5226 shape on the SCIM door).', ], + [ + 'persistDatasetQueryAuditRows', + 'A batch of compliance `dataset_query` rows was never written — the dataset queries themselves were answered, so every report, dashboard and counter read clean, while the `sys_audit_log` rows recording WHO read WHICH dataset, under which filter and how many rows, are simply absent and nothing retries them. Written from a BUFFER off the request path, so no request is left to notice, and a SIEM feed reading `dataset_query` rows answers who read the data with a confident, short list (the #5226 shape on the analytics dataset door).', + ], [ 'deleteMetaItemFromLoader', 'The metadata definition was never deleted from the authoritative store — `unregister()` still resolves and still announces `deleted`, the in-memory registry entry is gone, and the surviving row is read straight back out of storage by the very next `list()`/`get()`, so the "deleted" item reappears and survives every restart. Nothing retries it (#5259).', diff --git a/scripts/measure-durability-swallow-family.mjs b/scripts/measure-durability-swallow-family.mjs index 7c7309fb33a..8b9cf82ada4 100644 --- a/scripts/measure-durability-swallow-family.mjs +++ b/scripts/measure-durability-swallow-family.mjs @@ -332,6 +332,7 @@ const WRITE_SHAPED_CALLEES = new Map([ ['persistPackageLifecycleAuditRow', 'gate-vocabulary'], ['persistCredentialUseAuditRow', 'gate-vocabulary'], ['persistScimRefusalAuditRow', 'gate-vocabulary'], + ['persistDatasetQueryAuditRows', 'gate-vocabulary'], ['deleteMetaItemFromLoader', 'gate-vocabulary'], ['persistPackageCommitRow', 'gate-vocabulary'], ['persistSeedTenancyReceiptRow', 'gate-vocabulary'], From 3d982b0ac0435c7ff3bd02257534a7057d679560 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:54:16 +0000 Subject: [PATCH 03/10] docs(plugin-audit): the dataset_query row, its opt-in and its edges; changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/31797-dataset-query-audit-row.md | 14 ++++++++ .../docs/permissions/record-view-auditing.mdx | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 .changeset/31797-dataset-query-audit-row.md diff --git a/.changeset/31797-dataset-query-audit-row.md b/.changeset/31797-dataset-query-audit-row.md new file mode 100644 index 00000000000..c696d81b1ad --- /dev/null +++ b/.changeset/31797-dataset-query-audit-row.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/rest': patch +--- + +feat(plugin-audit, rest): a query of an opted-in saved dataset writes one `dataset_query` row in `sys_audit_log` (#31797) + +Clause-②: yes (widening) — a new `sys_audit_log.action` value, `dataset_query`, with its writer; a new `AuditPlugin` option, `datasetQueryAudit` (`datasets`, `maxBatchSize`, `flushIntervalMs`); a new `recordDatasetQuery` member on the `audit` service slot; and new exports from `@objectstack/plugin-audit` (`createDatasetQueryAuditWriter`, `buildDatasetQueryAuditRow`, `DATASET_QUERY_AUDIT_ACTION` and their types). `createReadAuditBatcher` takes an optional event type parameter and an optional `overflowMessage`, both defaulting to what it did before. No door answers differently: with no dataset named, nothing is recorded or buffered. +Metadata-protocol: none +Skills-docs: none — no file under `skills/**` teaches the audit ledger's actions or `AuditPlugin`'s options; `content/docs/permissions/record-view-auditing.mdx` gains a "Dataset queries" section. + +**What a deployment gets.** Name saved datasets in `new AuditPlugin({ datasetQueryAudit: { datasets: [...] } })` and each query of one through `POST /analytics/dataset/query`, or through each query of its batch door, writes one run-level row: the caller (`user_id`, `actor`, `tenant_id`), the dataset's base object in `object_name`, and in `metadata` the dataset name, the dimensions and measures selected, the filtered field names and operators (never the values), the row count and the outcome. A report or dashboard is composed in the browser, so the row names the dataset, not a report. + +**The rules.** Off by default and opted in per saved dataset; an inline definition (the Studio preview) writes no row. A request the door refuses before the read writes no row; a query that fails after the read started writes one row with outcome `failed`, the HTTP status and the error's machine code, never the error's text. Rows are written in batches off the request path, stamped with the query's instant, and a lost batch is reported at `error` once per cause. diff --git a/content/docs/permissions/record-view-auditing.mdx b/content/docs/permissions/record-view-auditing.mdx index fa1539d6fb6..2cee9db05f9 100644 --- a/content/docs/permissions/record-view-auditing.mdx +++ b/content/docs/permissions/record-view-auditing.mdx @@ -272,6 +272,39 @@ datasource whenever one is registered, and `os dev` provisions one by default as a sibling SQLite file. +## Dataset queries + +A report or a dashboard reads its data through the analytics dataset door, +`POST /analytics/dataset/query` (and its batch door), one query per block or +widget. The same plugin can record each of those queries as a `dataset_query` +row: **who** ran it, **which dataset** (its base object in `object_name`), the +**dimensions and measures** selected, the **filtered field names and +operators** (never the values), the **row count** and the **outcome**. It is +opted in per saved dataset and off by default: + +```typescript +new AuditPlugin({ + datasetQueryAudit: { + datasets: ['sales_pipeline', 'support_backlog'], + // maxBatchSize: 50, // flush once this many rows are buffered + // flushIntervalMs: 2000, // flush this long after a batch's first row + }, +}); +``` + +The rows are written in batches off the request path, stamped with the query's +own instant, by the same batcher as record views. The edges: + +- **Saved datasets only.** A query that posts an inline definition (the Studio + preview) writes no row: the opt-in names a saved dataset, and an inline + definition's name is the caller's own text. +- **A refused query writes no row.** A request the door refuses before the + read (sign-in, a malformed body or selection, a dataset it cannot find or + parse) is not a read. A query that fails after the read started writes one + row with outcome `failed`, the HTTP status and the error's machine code. +- **No report name.** A report is composed in the browser, so the server sees + its queries, not the report: one opened report can write one row per block. + ## Not this - **[`services.audit`](/docs/kernel/runtime-services/audit-service)** is the From f2f0ca6e49fa1ebbb9ede7d011b81c69c501053e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:01:59 +0000 Subject: [PATCH 04/10] test(rest): the dataset-query audit pins pay the objectql load at collection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- packages/rest/src/analytics-dataset-query-audit.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/rest/src/analytics-dataset-query-audit.test.ts b/packages/rest/src/analytics-dataset-query-audit.test.ts index 81b066f2900..e0665735791 100644 --- a/packages/rest/src/analytics-dataset-query-audit.test.ts +++ b/packages/rest/src/analytics-dataset-query-audit.test.ts @@ -13,6 +13,10 @@ import { describe, it, expect, vi } from 'vitest'; import { RestServer } from './rest-server'; +// The server under test reaches `@objectstack/objectql` only through a dynamic +// import inside a handler, so this module-top import pays that module graph's +// load during collection rather than inside a case's clocked window. +import '@objectstack/objectql'; function mockServer() { return { From 0f3569f234507b8a90f6762fc35597944ee9ebb1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:03:26 +0000 Subject: [PATCH 05/10] refactor(rest): keep the dataset-query audit import clear of the admission import Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- packages/rest/src/analytics-routes.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rest/src/analytics-routes.ts b/packages/rest/src/analytics-routes.ts index 856ac5e50d3..4a12c13ce09 100644 --- a/packages/rest/src/analytics-routes.ts +++ b/packages/rest/src/analytics-routes.ts @@ -65,6 +65,8 @@ import { PackageScopedNameRefusedError } from '@objectstack/core'; import type { ApiError, DatasetQueryBatchEntry, GetMetaItemRequest } from '@objectstack/spec/api'; import { DATASET_QUERY_BATCH_MAX_QUERIES, DatasetQueryBatchRequestSchema } from '@objectstack/spec/api'; import { stripReadDecorations } from '@objectstack/spec/kernel'; +// The ledger's `dataset_query` row: one per saved-dataset query that reached the read. +import { runAuditedDatasetQuery } from './analytics-dataset-query-audit.js'; import { boundedDeclaredUserMessage, classifiedRefusalAnswer, @@ -83,8 +85,6 @@ import { refuseRepeatedQueryParams } from './query-multiplicity.js'; import { mayReadPendingDrafts, metaItemPackageBinding, type RestServer } from './rest-server.js'; import { metaCallerPackageQuery, metaItemCallerPackageRefusalMessage } from './meta-item-read-gate.js'; import { admitRefusedDatasetHolders } from './analytics-dataset-admission-order.js'; -// The ledger's `dataset_query` row: one per saved-dataset query that reached the read. -import { runAuditedDatasetQuery } from './analytics-dataset-query-audit.js'; /** * The `RestServer` members {@link registerAnalyticsEndpoints} reads — every From 1f741879a98e944a648aad37e953a2c9674dbffc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:15:30 +0000 Subject: [PATCH 06/10] fix(plugin-audit): the dataset_query insert states its elevated context readably; the tenant audit census counts the new site Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../docs/permissions/tenant-audit-census.mdx | 34 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 19 ++++++----- .../plugin-audit/src/dataset-query-audit.ts | 2 +- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 7d99b4620a1..0f3cecfb451 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 314 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 315 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **314** | +| 175 write call sites | quoted in the merged changeset | **315** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **219 of 314** decidable, **95** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 177 decidably elevated, 0 decidably not, 125 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **220 of 315** decidable, **95** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 178 decidably elevated, 0 decidably not, 125 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -217,11 +217,11 @@ would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -177 of 314 (56%) as decidably elevated, with 125 more whose elevation is a +178 of 315 (57%) as decidably elevated, with 125 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 314`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 315`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,28 +233,28 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **314** | -| …whose object name is statically decidable | 219 | +| write call sites on the application surface | **315** | +| …whose object name is statically decidable | 220 | | …whose object name is chosen at run time | 95 | -| …against an object with tenancy ENABLED | 212 | +| …against an object with tenancy ENABLED | 213 | | …against an object that declares tenancy off | 7 | -| threading a tenant context | 243 | +| threading a tenant context | 244 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | -| threading a decidably ELEVATED (`isSystem`) context | 177 | +| threading a decidably ELEVATED (`isSystem`) context | 178 | | threading a context that is decidably NOT elevated | 0 | | threading a context whose elevation is a run-time fact | 125 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 252 | +| receiver carried a readable engine type | 253 | | receiver erased, placed by the object NAME | 52 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | -| object name spelled inline | 133 | +| object name spelled inline | 134 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | | object name is some other run-time expression | 85 | @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-14 at `aad3132fa`. +Measured on 2026-11-15 at `0f3569f23`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1160 | -| engine-shaped types recognised | 138 | +| tracked non-test sources scanned | 1169 | +| engine-shaped types recognised | 139 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 298 | +| same-named calls subtracted as non-engine | 308 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index a04b66af036..54b8bb52a63 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 314 | -| Object name statically decidable | 219 | +| Write call sites | 315 | +| Object name statically decidable | 220 | | Object name chosen at run time | 95 | -| Against a tenancy-enabled object | 212 | +| Against a tenancy-enabled object | 213 | | Against an object declaring tenancy off | 7 | -| Threading a tenant context | 243 | +| Threading a tenant context | 244 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | -| Threading a decidably elevated context | 177 | +| Threading a decidably elevated context | 178 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 125 | @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-14 at `aad3132fa`. +Measured on 2026-11-15 at `0f3569f23`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1160 | -| engine-shaped types recognised | 138 | +| tracked non-test sources scanned | 1169 | +| engine-shaped types recognised | 139 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 298 | +| same-named calls subtracted as non-engine | 308 | ## Every site @@ -129,6 +129,7 @@ Measured on 2026-11-14 at `aad3132fa`. | `packages/plugins/plugin-audit/src/comment-parent-pair-backfill.ts` | `update` | `sys_comment` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/credential-use-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/data-export-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | +| `packages/plugins/plugin-audit/src/dataset-query-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | | `packages/plugins/plugin-audit/src/mail-log-body-migration.ts` | `update` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-audit/src/mail-log-body-migration.ts` | `update` | `object` | undecidable | options unreadable | 1 | | `packages/plugins/plugin-audit/src/package-lifecycle-audit.ts` | `insert` | `sys_audit_log` | enabled | elevated | 1 | diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.ts index aad1f254df2..f115100eaf9 100644 --- a/packages/plugins/plugin-audit/src/dataset-query-audit.ts +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.ts @@ -268,7 +268,7 @@ export function createDatasetQueryAuditWriter(opts: DatasetQueryAuditWriterOptio engine: IDataEngine, rows: Record[], ): Promise => { - await engine.insert('sys_audit_log', rows as any, { context: { isSystem: true, preserveAudit: true } } as any); + await engine.insert('sys_audit_log', rows, { context: { isSystem: true, preserveAudit: true } }); }; /** From 9a1778154fe40922fa4a9859f885da5f21b5d0a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 01:52:56 +0000 Subject: [PATCH 07/10] test(plugin-audit,rest): pin the holder package and a served draft on the dataset_query row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/dataset-query-audit.test.ts | 14 +++++++ .../src/analytics-dataset-query-audit.test.ts | 41 ++++++++++++++++--- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts index 3b9f9820ee5..846bfb6eacd 100644 --- a/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts @@ -102,6 +102,7 @@ describe('the dataset_query writer over the real ledger', () => { expect(row.new_value ?? null).toBeNull(); expect(metadataOf(row)).toEqual({ dataset: 'sales', + dataset_package: null, dimensions: ['region'], measures: ['revenue'], filter: [ @@ -114,6 +115,19 @@ describe('the dataset_query writer over the real ledger', () => { await writer.stop(); }); + it('names the package holding the dataset, and a served draft, so two holders of one name are two different rows', async () => { + const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['sales'] }); + writer.recordDatasetQuery(queryEvent({ datasetPackage: 'com.acme.crm', rowCount: 31 })); + writer.recordDatasetQuery(queryEvent({ datasetPackage: 'com.acme.ops', preview: true, rowCount: 32 })); + await writer.flush(); + const rows = (await queryRows(engine)).map(metadataOf).filter((m) => m.row_count === 31 || m.row_count === 32); + expect(rows.map((m) => [m.dataset, m.dataset_package, m.preview])).toEqual([ + ['sales', 'com.acme.crm', undefined], + ['sales', 'com.acme.ops', true], + ]); + await writer.stop(); + }); + it('a dataset that is not opted in writes no row', async () => { const writer = createDatasetQueryAuditWriter({ getEngine: () => engine, datasets: ['pipeline'] }); const before = (await queryRows(engine)).length; diff --git a/packages/rest/src/analytics-dataset-query-audit.test.ts b/packages/rest/src/analytics-dataset-query-audit.test.ts index e0665735791..b70f8a3891b 100644 --- a/packages/rest/src/analytics-dataset-query-audit.test.ts +++ b/packages/rest/src/analytics-dataset-query-audit.test.ts @@ -47,16 +47,22 @@ function protocolWith(items: any[]) { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), getMetaTypes: vi.fn().mockResolvedValue([]), getMetaItems: vi.fn().mockResolvedValue([]), - getMetaItem: vi.fn(async ({ name }: { name: string }) => ({ type: 'dataset', name, item: items.find((d) => d?.name === name) })), + // A `packageId` reads that holder's item (the exact qualifier `?package=` + // resolves to); none reads the first item of the name. + getMetaItem: vi.fn(async ({ name, packageId }: { name: string; packageId?: string }) => ({ + type: 'dataset', + name, + item: items.find((d) => d?.name === name && (packageId === undefined || d?._packageId === packageId)), + })), }; } -function boot(opts: { queryDataset?: (...a: any[]) => Promise; sink?: Record } = {}) { +function boot(opts: { queryDataset?: (...a: any[]) => Promise; sink?: Record; datasets?: any[] } = {}) { const events: any[] = []; const sink = opts.sink ?? { recordDatasetQuery: (event: any) => { events.push(event); } }; const queryDataset = vi.fn(opts.queryDataset ?? (async () => ({ rows: [{ region: 'NA', revenue: 1 }, { region: 'EU', revenue: 2 }], fields: [] }))); const rest = new RestServer( - mockServer() as any, protocolWith([SALES]) as any, { api: { requireAuth: false } } as any, + mockServer() as any, protocolWith(opts.datasets ?? [SALES]) as any, { api: { requireAuth: false } } as any, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, async () => ({ queryDataset }), // analyticsServiceProvider @@ -72,9 +78,9 @@ function boot(opts: { queryDataset?: (...a: any[]) => Promise; sink?: Recor rest.registerRoutes(); const single = rest.getRoutes().find((r) => r.method === 'POST' && r.path.endsWith('/analytics/dataset/query'))!; const batch = rest.getRoutes().find((r) => r.method === 'POST' && r.path.endsWith('/analytics/dataset/query/batch'))!; - const post = async (body: unknown) => { + const post = async (body: unknown, query: Record = {}) => { const res = mockRes(); - await single.handler({ method: 'POST', params: {}, query: {}, headers: {}, body } as any, res); + await single.handler({ method: 'POST', params: {}, query, headers: {}, body } as any, res); return res; }; const postBatch = async (queries: unknown[]) => { @@ -154,6 +160,31 @@ describe('POST /analytics/dataset/query hands the ledger one event per query tha ]); }); + it('two packages holding one name: the event names the holder the door read, so ?package=A and ?package=B are two different rows', async () => { + const { events, post } = boot({ + datasets: [ + { ...SALES, _packageId: 'com.acme.crm' }, + { ...SALES, _packageId: 'com.acme.ops' }, + ], + }); + expect((await post({ datasetName: 'sales', selection }, { package: 'com.acme.crm' })).statusCode).toBe(200); + expect((await post({ datasetName: 'sales', selection }, { package: 'com.acme.ops' })).statusCode).toBe(200); + expect(events.map((e) => [e.datasetName, e.datasetPackage])).toEqual([ + ['sales', 'com.acme.crm'], + ['sales', 'com.acme.ops'], + ]); + }); + + it("the environment's own definition names no holder package, and a served draft says so", async () => { + const { events, post } = boot({ + datasets: [{ ...SALES, _packageId: 'sys_metadata', _draft: true }], + }); + expect((await post({ datasetName: 'sales', selection })).statusCode).toBe(200); + expect(events).toHaveLength(1); + expect(events[0].datasetPackage).toBeNull(); + expect(events[0].preview).toBe(true); + }); + it('a ledger sink that throws never changes the answer', async () => { const { post } = boot({ sink: { recordDatasetQuery: () => { throw new Error('ledger down'); } } }); const res = await post({ datasetName: 'sales', selection }); From 37cead9ab5d3937d481310983a49172639880586 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 01:54:30 +0000 Subject: [PATCH 08/10] fix(plugin-audit,rest): the dataset_query row names the package holding the dataset it read, and a served draft Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/31797-dataset-query-audit-row.md | 2 +- .../docs/permissions/record-view-auditing.mdx | 5 +++++ .../plugins/plugin-audit/src/audit-plugin.ts | 4 +++- .../plugin-audit/src/dataset-query-audit.ts | 22 ++++++++++++++++++- .../rest/src/analytics-dataset-query-audit.ts | 20 +++++++++++++++++ packages/rest/src/analytics-routes.ts | 5 ++++- 6 files changed, 54 insertions(+), 4 deletions(-) diff --git a/.changeset/31797-dataset-query-audit-row.md b/.changeset/31797-dataset-query-audit-row.md index c696d81b1ad..1776ad9bb00 100644 --- a/.changeset/31797-dataset-query-audit-row.md +++ b/.changeset/31797-dataset-query-audit-row.md @@ -9,6 +9,6 @@ Clause-②: yes (widening) — a new `sys_audit_log.action` value, `dataset_quer Metadata-protocol: none Skills-docs: none — no file under `skills/**` teaches the audit ledger's actions or `AuditPlugin`'s options; `content/docs/permissions/record-view-auditing.mdx` gains a "Dataset queries" section. -**What a deployment gets.** Name saved datasets in `new AuditPlugin({ datasetQueryAudit: { datasets: [...] } })` and each query of one through `POST /analytics/dataset/query`, or through each query of its batch door, writes one run-level row: the caller (`user_id`, `actor`, `tenant_id`), the dataset's base object in `object_name`, and in `metadata` the dataset name, the dimensions and measures selected, the filtered field names and operators (never the values), the row count and the outcome. A report or dashboard is composed in the browser, so the row names the dataset, not a report. +**What a deployment gets.** Name saved datasets in `new AuditPlugin({ datasetQueryAudit: { datasets: [...] } })` and each query of one through `POST /analytics/dataset/query`, or through each query of its batch door, writes one run-level row: the caller (`user_id`, `actor`, `tenant_id`), the dataset's base object in `object_name`, and in `metadata` the dataset name, the package holding it (`dataset_package`, `null` for the environment's own definition; a name in `datasets` covers every holder of that name), `preview: true` when a draft definition was read, the dimensions and measures selected, the filtered field names and operators (never the values), the row count and the outcome. A report or dashboard is composed in the browser, so the row names the dataset, not a report. **The rules.** Off by default and opted in per saved dataset; an inline definition (the Studio preview) writes no row. A request the door refuses before the read writes no row; a query that fails after the read started writes one row with outcome `failed`, the HTTP status and the error's machine code, never the error's text. Rows are written in batches off the request path, stamped with the query's instant, and a lost batch is reported at `error` once per cause. diff --git a/content/docs/permissions/record-view-auditing.mdx b/content/docs/permissions/record-view-auditing.mdx index 2cee9db05f9..43b83629ae3 100644 --- a/content/docs/permissions/record-view-auditing.mdx +++ b/content/docs/permissions/record-view-auditing.mdx @@ -302,6 +302,11 @@ own instant, by the same batcher as record views. The edges: read (sign-in, a malformed body or selection, a dataset it cannot find or parse) is not a read. A query that fails after the read started writes one row with outcome `failed`, the HTTP status and the error's machine code. +- **A name covers every holder.** Two packages can each hold a dataset of the + same name. A name in `datasets` audits every one of them, and each row names + the package it read in `metadata.dataset_package` (`null` for the + environment's own definition). A query that read a draft definition carries + `preview: true`. - **No report name.** A report is composed in the browser, so the server sees its queries, not the report: one opened report can write one row per block. diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 1245d47b563..85555b71a64 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -111,7 +111,9 @@ export interface AuditPluginDatasetQueryAuditOptions { * recorded as `dataset_query` rows in `sys_audit_log`: who, which dataset, * the dimensions and measures selected, the filtered field names (never the * values), the row count and the outcome. Absent or empty records nothing - * and buffers nothing. + * and buffers nothing. A name covers every package that holds a dataset of + * that name (ADR-0150 D3); each row records the holder it read in + * `metadata.dataset_package`. */ datasets?: readonly string[]; /** Flush once this many rows are buffered. Default 50. */ diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.ts index f115100eaf9..6034ef313b1 100644 --- a/packages/plugins/plugin-audit/src/dataset-query-audit.ts +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.ts @@ -85,8 +85,19 @@ export interface DatasetQueryAuditEvent { context: | Pick | undefined; - /** The saved dataset's name, as the door resolved it. The opt-in is keyed on it. */ + /** + * The saved dataset's name, as the door resolved it. The opt-in is keyed on + * it, so a name covers every package that holds a dataset of that name. + */ datasetName: string; + /** + * The package holding the dataset the door read (ADR-0150 D3: two packages + * can hold one name), or `null` for the environment's own definition. This + * is what tells two holders' rows apart. + */ + datasetPackage?: string | null; + /** The door served a draft definition (a preview read), not the published one. */ + preview?: boolean; /** The dataset's base object. */ objectName?: string; /** The selection's dimension names. */ @@ -167,6 +178,13 @@ function selectionNames(v: unknown): string[] { .map(recordedField); } +/** A package id the row records: the id when it has a package id's shape, else `?`; absent is `null`. */ +const PACKAGE_ID = /^[A-Za-z0-9@][A-Za-z0-9@._\/-]{0,127}$/; +function recordedPackage(v: unknown): string | null { + if (typeof v !== 'string' || v === '') return null; + return PACKAGE_ID.test(v) ? v : '?'; +} + /** JSON that cannot throw on a cyclic/odd value — same rule as the CRUD writer. */ function safeStringify(v: unknown): string { try { @@ -188,9 +206,11 @@ export function buildDatasetQueryAuditRow(event: DatasetQueryAuditEvent, queried const metadata: Record = { dataset: recordedField(String(event.datasetName ?? '')), + dataset_package: recordedPackage(event.datasetPackage), dimensions: selectionNames(event.dimensions), measures: selectionNames(event.measures), }; + if (event.preview === true) metadata.preview = true; const timeDimensions = selectionNames(event.timeDimensions); if (timeDimensions.length > 0) metadata.time_dimensions = timeDimensions; const filter = event.readQuery?.filter; diff --git a/packages/rest/src/analytics-dataset-query-audit.ts b/packages/rest/src/analytics-dataset-query-audit.ts index 54a32459239..636858d770a 100644 --- a/packages/rest/src/analytics-dataset-query-audit.ts +++ b/packages/rest/src/analytics-dataset-query-audit.ts @@ -38,6 +38,8 @@ import { resolveThrownHttpError } from '@objectstack/types'; interface DatasetQueryAuditEvent { context: unknown; datasetName: string; + datasetPackage: string | null; + preview?: true; objectName?: string; dimensions?: unknown; measures?: unknown; @@ -68,6 +70,12 @@ export interface AuditedDatasetQuery { readonly datasetName: string | undefined; /** The parsed dataset definition (read for its base object). */ readonly dataset: unknown; + /** + * The item the by-name read served, before any strip: read for its package + * stamp (`_packageId`, the holder the door resolved; `sys_metadata` is the + * environment's own definition) and its draft badge (`_draft`). + */ + readonly served?: unknown; /** The caller's selection (read for its names and its filter). */ readonly selection: unknown; } @@ -75,6 +83,15 @@ export interface AuditedDatasetQuery { const asRecord = (v: unknown): Record => v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : {}; +/** The environment's own definition's package stamp: it names no holder package. */ +const ENVIRONMENT_PACKAGE_STAMP = 'sys_metadata'; + +/** The package holding the served dataset, or `null` for the environment's own definition. */ +function holderPackageOf(served: unknown): string | null { + const stamp = asRecord(served)._packageId; + return typeof stamp === 'string' && stamp !== '' && stamp !== ENVIRONMENT_PACKAGE_STAMP ? stamp : null; +} + /** The selection's time-dimension names, never their date ranges. */ function timeDimensionNames(v: unknown): string[] | undefined { if (!Array.isArray(v)) return undefined; @@ -127,6 +144,9 @@ export async function runAuditedDatasetQuery( const base = { context: query.context, datasetName: query.datasetName, + // Two packages can hold one name (ADR-0150 D3): the row names the one read. + datasetPackage: holderPackageOf(query.served), + ...(asRecord(query.served)._draft === true ? { preview: true as const } : {}), ...(typeof asRecord(query.dataset).object === 'string' ? { objectName: asRecord(query.dataset).object as string } : {}), dimensions: selection.dimensions, measures: selection.measures, diff --git a/packages/rest/src/analytics-routes.ts b/packages/rest/src/analytics-routes.ts index 4a12c13ce09..9323dc593c4 100644 --- a/packages/rest/src/analytics-routes.ts +++ b/packages/rest/src/analytics-routes.ts @@ -567,6 +567,8 @@ async function answerDatasetQuery( // Resolve the dataset definition: inline draft (Studio // preview) or a saved dataset by name. let dataset = body.dataset; + // The item the by-name read served, for the ledger row's holder package. + let served: unknown; if (!dataset && body.datasetName) { const p = await this.resolveProtocol(environmentId, req); // [#32072, ADR-0150 D3/D5] The saved dataset is read BY @@ -708,6 +710,7 @@ async function answerDatasetQuery( read = judged.read; } dataset = read?.item; + served = read?.item; if (!dataset) { return datasetNotFoundAnswer(body.datasetName); } @@ -775,7 +778,7 @@ async function answerDatasetQuery( // The read. A saved dataset's query hands the ledger one // `dataset_query` event here, answered or failed; every refusal above // returned before it and hands none ({@link runAuditedDatasetQuery}). - const queried = { req, environmentId, context, dataset, selection, datasetName: body.dataset ? undefined : body.datasetName }; + const queried = { req, environmentId, context, dataset, served, selection, datasetName: body.dataset ? undefined : body.datasetName }; const result = await runAuditedDatasetQuery(this, queried, () => svc.queryDataset( dataset, selection, From 99e4217bd87db1e3a90d51f5a2dbb9fd61935a0a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 01:59:51 +0000 Subject: [PATCH 09/10] test(plugin-audit): order the two-holder pin by row count, not by insert order within one batch Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- packages/plugins/plugin-audit/src/dataset-query-audit.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts index 846bfb6eacd..5653646940a 100644 --- a/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts +++ b/packages/plugins/plugin-audit/src/dataset-query-audit.test.ts @@ -120,7 +120,9 @@ describe('the dataset_query writer over the real ledger', () => { writer.recordDatasetQuery(queryEvent({ datasetPackage: 'com.acme.crm', rowCount: 31 })); writer.recordDatasetQuery(queryEvent({ datasetPackage: 'com.acme.ops', preview: true, rowCount: 32 })); await writer.flush(); - const rows = (await queryRows(engine)).map(metadataOf).filter((m) => m.row_count === 31 || m.row_count === 32); + const rows = (await queryRows(engine)).map(metadataOf).filter((m) => m.row_count === 31 || m.row_count === 32) + // One batch, one instant: ordered by what each query returned, not by insert order. + .sort((a, b) => a.row_count - b.row_count); expect(rows.map((m) => [m.dataset, m.dataset_package, m.preview])).toEqual([ ['sales', 'com.acme.crm', undefined], ['sales', 'com.acme.ops', true], From be4a48ae3044fd52058048c8508b3d5fc877c57c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 02:00:56 +0000 Subject: [PATCH 10/10] docs(audits): re-measure the tenant audit census on the merged main Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- content/docs/permissions/tenant-audit-census.mdx | 6 +++--- docs/audits/2026-08-tenant-audit-write-call-sites.counts.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 0f3cecfb451..3bbcac10fcd 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `0f3569f23`. +Measured on 2026-11-15 at `c1014aa8e`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1169 | +| tracked non-test sources scanned | 1170 | | engine-shaped types recognised | 139 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 308 | +| same-named calls subtracted as non-engine | 309 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index 54b8bb52a63..98a68b76d73 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `0f3569f23`. +Measured on 2026-11-15 at `c1014aa8e`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1169 | +| tracked non-test sources scanned | 1170 | | engine-shaped types recognised | 139 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 308 | +| same-named calls subtracted as non-engine | 309 | ## Every site