feat(analytics): BI-P017 — analyst SQL contract, proven against live ClickHouse with the guard removed
CI (SIAX Cloud) / quality (push) Successful in 50s
CI (SIAX Cloud) / integration (push) Successful in 35s
CI (SIAX Cloud) / security (push) Successful in 21s
Security Scan (SIAX Cloud) / security (push) Successful in 26s
CI (SIAX Cloud) / quality (pull_request) Successful in 46s
CI (SIAX Cloud) / integration (pull_request) Successful in 35s
CI (SIAX Cloud) / security (pull_request) Successful in 19s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s

AnalyticsSQLSession is a SEPARATE class, not a method on SiaxAnalyticsEngine.
executeMetric has no raw-SQL surface at all; on the same object the closed DSL
would be one refactor away from growing one. ClickHouseAnalyticsEngine
.executeQuery stays a documented refusal.

FOUR LAYERS, and the guard is deliberately called the weakest:
  1 role   — the CL0UD analyst role is checked when the SESSION IS OPENED, so
             a caller without it never obtains an object that can run SQL.
  2 guard  — statement admission. Comments and literals removed with
             ClickHouse's own lexical rules, ASCII-only outside literals, one
             statement, SELECT/WITH only, and every table reference POSITIVELY
             resolved against the tenant's catalog. Deny-lists are a second
             opinion, never the mechanism.
  3 grants — a per-tenant ClickHouse user with SELECT on that tenant's catalog
             alone, plus a restrictive row policy on the base tables.
  4 views  — the tenant catalog holds only VIEWS, each baking
             `WHERE tenant_id = '<tenant>'`, and tenant_id is not projected.

61 bypass attempts, in one shared corpus, run TWICE: against the guard, and
against a live ClickHouse 24.8.14.39 with LAYER 2 REMOVED. The live assertion
is not "the engine errored" — it is "no canary came back", with BETA_CANARY
seeded into the other tenant's rows and SECRET_CANARY into an ungranted table.
The counterfactual runs first: as admin the same base table returns 100 rows
and BETA_CANARY IS readable, so the isolation numbers mean something.
Result: 0 of 61 leaked. Evidence: evidence/bi-p017/analyst-sql-live-bypass.json.

FOUR DEFECTS FOUND BY WRITING TESTS THAT CAN FAIL — three of them mine:

  * `CREATE ROW POLICY IF NOT EXISTS` is a SILENT NO-OP on re-provisioning.
    Dropping the user empties the policy's apply-to list; the next run skips
    re-creation, so the policy survives with `apply_to_list = []`, applying to
    nobody, while `system.row_policies` still shows the correct select_filter.
    The restricted user read 100 of 100 rows — BOTH TENANTS — from the base
    table. Fixed with OR REPLACE + `rowPolicyVerificationSql`, which turns
    "the policy is applied" from an assumption into a query, and a test that
    asserts applied_to_user = 1 per object.

  * `CREATE SETTINGS PROFILE IF NOT EXISTS` has the identical shape: a changed
    budget never lands. A stale 60-row ceiling survived re-provisioning and
    starved every legitimate statement, with the DDL reporting success
    throughout. Also OR REPLACE now.

  * `describe.skipIf(!reachable)` where `reachable` is set in `beforeAll`
    skips ALWAYS — vitest evaluates skipIf at collection time. Ten tests
    reported green while skipping against a live, reachable server. Replaced
    with the repo's existing env-var gate, which FAILS when CLICKHOUSE_URL is
    set and the server is down rather than degrading to a skip.

  * MEASURED, and it changes the design: a ClickHouse user whose profile
    carries `readonly = 1` cannot have ANY setting changed from the request
    (Code: 164). The BI-P012 ceilings therefore cannot travel with an analyst
    statement; they are baked into the user's SETTINGS PROFILE at provisioning.
    Proven both ways: over-budget scan fails with code 158 from the profile
    with no setting sent, and an attempt to raise it from the request fails
    with code 164.

Honest about what the guard does NOT catch: `SELECT tenant_id FROM
t_alpha_sql.sales` is structurally legitimate and IS admitted. It fails at the
engine because the view does not project the column. Recorded in its own
GUARD_ADMITS_ENGINE_REFUSES list and asserted live, rather than deleted from
the corpus.

evidence/bi-p017 is pinned by tests/analytics/analyst-sql-evidence.test.ts,
which never skips: adding an attack without re-running the live suite breaks
the build, and the pin also checks the counterfactual numbers so the evidence
cannot be a recording of an empty database.

246 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Claude Opus 5
2026-09-07 02:17:07 +02:00
parent b1884a89a5
commit d9c8f7190b
29 changed files with 4460 additions and 934 deletions
+2 -2
View File
@@ -148,14 +148,14 @@ export class FlatBufferBuilder {
}
startObject(numFields: number): void {
if (this.inObject) throw new Error("nested startObject");
if (this.inObject) throw new Error('nested startObject');
this.vtable = new Array<number>(numFields).fill(0);
this.objectStart = this.used;
this.inObject = true;
}
endObject(): Offset {
if (!this.inObject) throw new Error("endObject outside an object");
if (!this.inObject) throw new Error('endObject outside an object');
this.prep(SIZEOF_INT);
this.writeInt32(0); // soffset placeholder, patched below
const objectOffset = this.used;
+63 -55
View File
@@ -29,8 +29,8 @@
* padded so the body starts 8-byte aligned, then the body buffers.
* Terminated by 0xFFFFFFFF 0x00000000.
*/
import { FlatBufferBuilder, type Offset } from "./flatbuffer-builder";
import { SiaxError } from "../../platform/errors";
import { FlatBufferBuilder, type Offset } from './flatbuffer-builder';
import { SiaxError } from '../../platform/errors';
// ── FlatBuffer enum values from org.apache.arrow.flatbuf ────────────────────
@@ -51,13 +51,13 @@ const PRECISION_DOUBLE = 2;
// every 64-bit constant is built with BigInt(...) instead. Behaviour is
// identical — this is a compiler-target accommodation, not a semantic choice.
const BIG_ZERO = BigInt(0);
const INT64_MAX = BigInt("9223372036854775807");
const INT64_MIN = BigInt("-9223372036854775808");
const INT64_MAX = BigInt('9223372036854775807');
const INT64_MIN = BigInt('-9223372036854775808');
const TIME_UNIT_MILLISECOND = 1;
// ── public column model ────────────────────────────────────────────────────
export type ArrowColumnType = "int64" | "float64" | "utf8" | "bool" | "timestamp_ms";
export type ArrowColumnType = 'int64' | 'float64' | 'utf8' | 'bool' | 'timestamp_ms';
export interface ArrowColumn {
name: string;
@@ -78,39 +78,39 @@ export const ARROW_TYPE_SUPPORT: {
note: string;
}[] = [
{
clickhouse: "Int64 / UInt32 / Int32",
arrow: "int64",
duckdb: "BIGINT",
python: "int",
note: "exact; UInt64 above 2^63 is NOT supported and is rejected rather than silently wrapped",
clickhouse: 'Int64 / UInt32 / Int32',
arrow: 'int64',
duckdb: 'BIGINT',
python: 'int',
note: 'exact; UInt64 above 2^63 is NOT supported and is rejected rather than silently wrapped',
},
{
clickhouse: "Float64",
arrow: "float64",
duckdb: "DOUBLE",
python: "float",
note: "exact IEEE-754 round trip",
clickhouse: 'Float64',
arrow: 'float64',
duckdb: 'DOUBLE',
python: 'float',
note: 'exact IEEE-754 round trip',
},
{
clickhouse: "String / LowCardinality(String)",
arrow: "utf8",
duckdb: "VARCHAR",
python: "str",
note: "LowCardinality is decoded to plain utf8 — dictionary encoding is lost, values are not",
clickhouse: 'String / LowCardinality(String)',
arrow: 'utf8',
duckdb: 'VARCHAR',
python: 'str',
note: 'LowCardinality is decoded to plain utf8 — dictionary encoding is lost, values are not',
},
{
clickhouse: "Bool / UInt8(0|1)",
arrow: "bool",
duckdb: "BOOLEAN",
python: "bool",
note: "bit-packed one bit per value; ClickHouse UInt8 other than 0/1 is NOT a bool and must be sent as int64",
clickhouse: 'Bool / UInt8(0|1)',
arrow: 'bool',
duckdb: 'BOOLEAN',
python: 'bool',
note: 'bit-packed one bit per value; ClickHouse UInt8 other than 0/1 is NOT a bool and must be sent as int64',
},
{
clickhouse: "DateTime64(3,'UTC')",
arrow: "timestamp_ms",
duckdb: "TIMESTAMP",
python: "datetime",
note: "millisecond precision; DateTime64(6/9) loses sub-ms and is therefore NOT in the supported set",
arrow: 'timestamp_ms',
duckdb: 'TIMESTAMP',
python: 'datetime',
note: 'millisecond precision; DateTime64(6/9) loses sub-ms and is therefore NOT in the supported set',
},
];
@@ -118,7 +118,7 @@ export const ARROW_TYPE_SUPPORT: {
/** ClickHouse output format producing an Arrow IPC *stream*. */
export function clickhouseArrowStreamFormat(): string {
return "ArrowStream";
return 'ArrowStream';
}
/**
@@ -129,8 +129,8 @@ export function clickhouseArrowStreamFormat(): string {
*/
export function arrowStreamSettings(): Record<string, string> {
return {
output_format_arrow_string_as_string: "1",
output_format_arrow_low_cardinality_as_dictionary: "0",
output_format_arrow_string_as_string: '1',
output_format_arrow_low_cardinality_as_dictionary: '0',
};
}
@@ -165,20 +165,24 @@ function encodeColumn(col: ArrowColumn): { buffers: EncodedBuffer[]; nullCount:
const n = col.values.length;
switch (col.type) {
case "int64": {
case 'int64': {
const data = new Uint8Array(alignTo8(n * 8));
const dv = new DataView(data.buffer);
col.values.forEach((v, i) => {
if (v === null || v === undefined) return;
const b = typeof v === "bigint" ? v : BigInt(Math.trunc(Number(v)));
const b = typeof v === 'bigint' ? v : BigInt(Math.trunc(Number(v)));
if (b > INT64_MAX || b < INT64_MIN) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `value out of int64 range in column "${col.name}"`);
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`value out of int64 range in column "${col.name}"`,
);
}
dv.setBigInt64(i * 8, b, true);
});
return { buffers: [validity, { bytes: data, length: n * 8 }], nullCount };
}
case "float64": {
case 'float64': {
const data = new Uint8Array(alignTo8(n * 8));
const dv = new DataView(data.buffer);
col.values.forEach((v, i) => {
@@ -187,17 +191,17 @@ function encodeColumn(col: ArrowColumn): { buffers: EncodedBuffer[]; nullCount:
});
return { buffers: [validity, { bytes: data, length: n * 8 }], nullCount };
}
case "timestamp_ms": {
case 'timestamp_ms': {
const data = new Uint8Array(alignTo8(n * 8));
const dv = new DataView(data.buffer);
col.values.forEach((v, i) => {
if (v === null || v === undefined) return;
const ms = v instanceof Date ? v.getTime() : typeof v === "bigint" ? Number(v) : Number(v);
const ms = v instanceof Date ? v.getTime() : typeof v === 'bigint' ? Number(v) : Number(v);
dv.setBigInt64(i * 8, BigInt(Math.trunc(ms)), true);
});
return { buffers: [validity, { bytes: data, length: n * 8 }], nullCount };
}
case "bool": {
case 'bool': {
const byteLen = Math.ceil(n / 8);
const data = new Uint8Array(alignTo8(byteLen));
col.values.forEach((v, i) => {
@@ -206,7 +210,7 @@ function encodeColumn(col: ArrowColumn): { buffers: EncodedBuffer[]; nullCount:
});
return { buffers: [validity, { bytes: data, length: byteLen }], nullCount };
}
case "utf8": {
case 'utf8': {
const encoded = col.values.map((v) =>
v === null || v === undefined ? new Uint8Array(0) : new TextEncoder().encode(String(v)),
);
@@ -228,36 +232,36 @@ function encodeColumn(col: ArrowColumn): { buffers: EncodedBuffer[]; nullCount:
}
default: {
const never: never = col.type;
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unsupported arrow type ${String(never)}`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unsupported arrow type ${String(never)}`);
}
}
}
function buildTypeTable(b: FlatBufferBuilder, type: ArrowColumnType): { typeType: number; offset: Offset } {
switch (type) {
case "int64": {
case 'int64': {
b.startObject(2);
b.addInt32(0, 64, 0); // bitWidth
b.addInt8(1, 1, 0); // is_signed
return { typeType: TYPE_INT, offset: b.endObject() };
}
case "float64": {
case 'float64': {
b.startObject(1);
b.addInt16(0, PRECISION_DOUBLE, 0); // precision = DOUBLE
return { typeType: TYPE_FLOATING_POINT, offset: b.endObject() };
}
case "utf8": {
case 'utf8': {
b.startObject(0);
return { typeType: TYPE_UTF8, offset: b.endObject() };
}
case "bool": {
case 'bool': {
b.startObject(0);
return { typeType: TYPE_BOOL, offset: b.endObject() };
}
case "timestamp_ms": {
case 'timestamp_ms': {
// Build the timezone string BEFORE startObject — FlatBuffers forbids
// creating a nested object while a table is open.
const tz = b.createString("UTC");
const tz = b.createString('UTC');
b.startObject(2);
b.addInt16(0, TIME_UNIT_MILLISECOND, 0);
b.addOffset(1, tz, 0);
@@ -265,7 +269,7 @@ function buildTypeTable(b: FlatBufferBuilder, type: ArrowColumnType): { typeType
}
default: {
const never: never = type;
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unsupported arrow type ${String(never)}`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unsupported arrow type ${String(never)}`);
}
}
}
@@ -361,14 +365,14 @@ function framedMessage(metadata: Uint8Array, body: Uint8Array): Uint8Array {
*/
export function encodeArrowStream(columns: readonly ArrowColumn[]): Uint8Array {
if (columns.length === 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "an Arrow stream needs at least one column");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'an Arrow stream needs at least one column');
}
const rowCount = columns[0].values.length;
for (const c of columns) {
if (c.values.length !== rowCount) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`column "${c.name}" has ${c.values.length} values, expected ${rowCount}`,
);
}
@@ -496,7 +500,11 @@ export function decodeArrowStream(bytes: Uint8Array): ArrowStreamInfo {
while (pos + 8 <= bytes.byteLength) {
const continuation = dv.getUint32(pos, true);
if (continuation !== 0xffffffff) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "not an Arrow IPC stream (missing continuation marker)");
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
'not an Arrow IPC stream (missing continuation marker)',
);
}
const metaLen = dv.getInt32(pos + 4, true);
if (metaLen === 0) break; // end of stream
@@ -513,7 +521,7 @@ export function decodeArrowStream(bytes: Uint8Array): ArrowStreamInfo {
fields = [];
for (let i = 0; i < n; i++) {
const f = schema.vectorElementTable(1, i);
fields.push({ name: f.readString(0) ?? "", typeType: f.readInt8(2, 0) });
fields.push({ name: f.readString(0) ?? '', typeType: f.readInt8(2, 0) });
}
}
} else if (headerType === MESSAGE_HEADER_RECORD_BATCH) {
@@ -538,8 +546,8 @@ export function assertArrowWithinResultBudget(bytes: Uint8Array, maxResultRows:
const info = decodeArrowStream(bytes);
if (info.rowCount > maxResultRows) {
throw new SiaxError(
"QUOTA_EXCEEDED",
"0pt.analytics",
'QUOTA_EXCEEDED',
'0pt.analytics',
`Arrow result has ${info.rowCount} rows, over the ${maxResultRows}-row budget`,
);
}
+35 -36
View File
@@ -25,7 +25,7 @@
*
* Retention: tables are created WITH TTL (event_time + INTERVAL n DAY).
*/
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors";
import { SiaxError, siaxErrorCodeForUpstreamStatus } from '../platform/errors';
export interface ClickHouseAnalyticsOptions {
baseUrl: string;
@@ -52,7 +52,7 @@ export interface MetricQuery {
tenant_id: string;
dataset_id?: string;
metric: string;
aggregate: "sum" | "avg" | "min" | "max" | "count";
aggregate: 'sum' | 'avg' | 'min' | 'max' | 'count';
/** Group by one dimension key (validated identifier). */
group_by?: string;
from_time?: string;
@@ -77,9 +77,9 @@ export class ClickHouseAnalytics {
private readonly maxResultRows: number;
constructor(opts: ClickHouseAnalyticsOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString("base64")}` : undefined;
this.database = opts.database ?? "opt_analytics";
this.baseUrl = opts.baseUrl.replace(/\/+$/, '');
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString('base64')}` : undefined;
this.database = opts.database ?? 'opt_analytics';
this.timeoutMs = opts.timeoutMs ?? 30_000;
this.maxExecutionTimeSec = opts.maxExecutionTimeSec ?? 10;
this.maxResultRows = opts.maxResultRows ?? 10_000;
@@ -100,7 +100,7 @@ export class ClickHouseAnalytics {
ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_time)
ORDER BY (tenant_id, metric, dataset_id, event_time)
TTL toDateTime(event_time) + INTERVAL ${Math.floor(retentionDays)} DAY`
TTL toDateTime(event_time) + INTERVAL ${Math.floor(retentionDays)} DAY`,
);
}
@@ -109,10 +109,14 @@ export class ClickHouseAnalytics {
if (events.length === 0) return { ingested: 0 };
for (const e of events) {
if (!e.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "every analytics event needs tenant_id");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'every analytics event needs tenant_id');
}
if (!Number.isFinite(e.value)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `metric value for "${e.metric}" must be finite`);
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`metric value for "${e.metric}" must be finite`,
);
}
}
const rows = events
@@ -122,11 +126,11 @@ export class ClickHouseAnalytics {
dataset_id: e.dataset_id,
metric: e.metric,
value: e.value,
event_time: (e.event_time ?? new Date().toISOString()).replace("T", " ").replace(/Z$/, ""),
event_time: (e.event_time ?? new Date().toISOString()).replace('T', ' ').replace(/Z$/, ''),
dimensions: e.dimensions ?? {},
})
}),
)
.join("\n");
.join('\n');
await this.exec(`INSERT INTO ${this.database}.opt_metric_events FORMAT JSONEachRow`, rows);
return { ingested: events.length };
}
@@ -134,41 +138,40 @@ export class ClickHouseAnalytics {
/** Closed metric-query DSL — compiled with a FORCED tenant predicate. */
async queryMetric(q: MetricQuery): Promise<MetricQueryRow[]> {
if (!q.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every metric query");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'tenant_id is required on every metric query');
}
if (q.group_by !== undefined && !IDENT_RE.test(q.group_by)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `invalid group_by identifier`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `invalid group_by identifier`);
}
const agg =
q.aggregate === "count" ? "count()" : `${q.aggregate}(value)`;
const agg = q.aggregate === 'count' ? 'count()' : `${q.aggregate}(value)`;
const groupExpr = q.group_by ? `dimensions['${q.group_by}']` : undefined;
const limit = Math.min(q.limit ?? 1000, this.maxResultRows);
// Parameterized query — values travel as HTTP params, never spliced.
const conditions = ["tenant_id = {tenant:String}", "metric = {metric:String}"];
const conditions = ['tenant_id = {tenant:String}', 'metric = {metric:String}'];
const params: Record<string, string> = { param_tenant: q.tenant_id, param_metric: q.metric };
if (q.dataset_id) {
conditions.push("dataset_id = {dataset:String}");
conditions.push('dataset_id = {dataset:String}');
params.param_dataset = q.dataset_id;
}
if (q.from_time) {
conditions.push("event_time >= parseDateTime64BestEffort({fromTime:String})");
conditions.push('event_time >= parseDateTime64BestEffort({fromTime:String})');
params.param_fromTime = q.from_time;
}
if (q.to_time) {
conditions.push("event_time < parseDateTime64BestEffort({toTime:String})");
conditions.push('event_time < parseDateTime64BestEffort({toTime:String})');
params.param_toTime = q.to_time;
}
const sql =
`SELECT ${groupExpr ? `${groupExpr} AS grp, ` : ""}${agg} AS value ` +
`SELECT ${groupExpr ? `${groupExpr} AS grp, ` : ''}${agg} AS value ` +
`FROM ${this.database}.opt_metric_events ` +
`WHERE ${conditions.join(" AND ")} ` +
(groupExpr ? `GROUP BY grp ORDER BY value DESC ` : "") +
`WHERE ${conditions.join(' AND ')} ` +
(groupExpr ? `GROUP BY grp ORDER BY value DESC ` : '') +
`LIMIT ${limit} FORMAT JSON`;
const json = (await this.exec(sql, undefined, {
readonly: "1",
readonly: '1',
max_execution_time: String(this.maxExecutionTimeSec),
max_result_rows: String(this.maxResultRows),
...params,
@@ -182,7 +185,7 @@ export class ClickHouseAnalytics {
async health(): Promise<boolean> {
try {
await this.exec("SELECT 1 FORMAT JSON");
await this.exec('SELECT 1 FORMAT JSON');
return true;
} catch {
return false;
@@ -190,28 +193,24 @@ export class ClickHouseAnalytics {
}
// -----------------------------------------------------------------------
private async exec(
sql: string,
body?: string,
settings?: Record<string, string>
): Promise<unknown> {
private async exec(sql: string, body?: string, settings?: Record<string, string>): Promise<unknown> {
const url = new URL(this.baseUrl);
url.searchParams.set("query", sql);
url.searchParams.set('query', sql);
for (const [k, v] of Object.entries(settings ?? {})) url.searchParams.set(k, v);
const headers: Record<string, string> = {};
if (this.authHeader) headers["Authorization"] = this.authHeader;
if (this.authHeader) headers['Authorization'] = this.authHeader;
let res: Response;
try {
res = await fetch(url.toString(), {
method: "POST",
method: 'POST',
headers,
body: body ?? "",
body: body ?? '',
signal: AbortSignal.timeout(this.timeoutMs),
});
} catch (cause) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "clickhouse", "clickhouse unreachable", { cause });
throw new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'clickhouse unreachable', { cause });
}
const text = await res.text();
if (!res.ok) {
@@ -219,8 +218,8 @@ export class ClickHouseAnalytics {
const code = /Code: (\d+)/.exec(text)?.[1] ?? String(res.status);
throw new SiaxError(
siaxErrorCodeForUpstreamStatus(res.status),
"clickhouse",
`query failed (CH code ${code})`
'clickhouse',
`query failed (CH code ${code})`,
);
}
if (!text) return undefined;
+110 -66
View File
@@ -18,10 +18,10 @@
* shipped under a minor bump is exactly the failure this gate exists to
* catch, so it is reported as a violation rather than tolerated.
*/
import crypto from "node:crypto";
import { SiaxError } from "../../platform/errors";
import type { AnalyticsFieldType, FieldRole, PiiClassification } from "./entities";
import type { AnalyticsTier } from "./tiers";
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { AnalyticsFieldType, FieldRole, PiiClassification } from './entities';
import type { AnalyticsTier } from './tiers';
export interface ContractField {
name: string;
@@ -38,7 +38,7 @@ export interface ContractQualityRule {
rule_id: string;
kind: string;
field_name?: string;
severity: "warn" | "block";
severity: 'warn' | 'block';
}
/** BI-P004's named contents, one field each. */
@@ -77,14 +77,18 @@ const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)$/;
export function parseSemVer(v: string): SemVer {
const m = SEMVER_RE.exec(v);
if (!m) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `contract version "${v}" is not major.minor.patch`);
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`contract version "${v}" is not major.minor.patch`,
);
}
return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) };
}
// ── change classification ──────────────────────────────────────────────────
export type ChangeSeverity = "compatible" | "breaking";
export type ChangeSeverity = 'compatible' | 'breaking';
export interface ContractChange {
severity: ChangeSeverity;
@@ -100,7 +104,7 @@ export interface ContractChange {
* Everything absent from this table is breaking.
*/
const SAFE_TYPE_WIDENING: Partial<Record<AnalyticsFieldType, readonly AnalyticsFieldType[]>> = {
date: ["timestamp"],
date: ['timestamp'],
};
function typeChangeIsCompatible(from: AnalyticsFieldType, to: AnalyticsFieldType): boolean {
@@ -132,9 +136,9 @@ function typeChangeIsCompatible(from: AnalyticsFieldType, to: AnalyticsFieldType
export function diffContracts(previous: DatasetContract, next: DatasetContract): ContractChange[] {
if (previous.dataset_id !== next.dataset_id) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
"contract compatibility is only defined between versions of the SAME dataset",
'INVALID_REQUEST',
'0pt.analytics',
'contract compatibility is only defined between versions of the SAME dataset',
);
}
const changes: ContractChange[] = [];
@@ -144,44 +148,49 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
for (const [name, pf] of prevFields) {
const nf = nextFields.get(name);
if (!nf) {
changes.push({ severity: "breaking", code: "field_removed", field: name, detail: `field "${name}" removed` });
changes.push({
severity: 'breaking',
code: 'field_removed',
field: name,
detail: `field "${name}" removed`,
});
continue;
}
if (!typeChangeIsCompatible(pf.type, nf.type)) {
changes.push({
severity: "breaking",
code: "field_type_changed",
severity: 'breaking',
code: 'field_type_changed',
field: name,
detail: `field "${name}" type ${pf.type} -> ${nf.type}`,
});
} else if (pf.type !== nf.type) {
changes.push({
severity: "compatible",
code: "field_type_widened",
severity: 'compatible',
code: 'field_type_widened',
field: name,
detail: `field "${name}" widened ${pf.type} -> ${nf.type}`,
});
}
if (!pf.nullable && nf.nullable) {
changes.push({
severity: "breaking",
code: "field_became_nullable",
severity: 'breaking',
code: 'field_became_nullable',
field: name,
detail: `field "${name}" became nullable`,
});
}
if (pf.nullable && !nf.nullable) {
changes.push({
severity: "compatible",
code: "field_became_required",
severity: 'compatible',
code: 'field_became_required',
field: name,
detail: `field "${name}" is no longer nullable`,
});
}
if (pf.role !== nf.role) {
changes.push({
severity: "breaking",
code: "field_role_changed",
severity: 'breaking',
code: 'field_role_changed',
field: name,
detail: `field "${name}" role ${pf.role} -> ${nf.role}`,
});
@@ -192,8 +201,8 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
if (prevFields.has(name)) continue;
if (nf.nullable) {
changes.push({
severity: "compatible",
code: "nullable_field_added",
severity: 'compatible',
code: 'nullable_field_added',
field: name,
detail: `nullable field "${name}" added`,
});
@@ -201,8 +210,8 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
// A required new field breaks producers, and breaks readers that
// reconstruct rows (they now have no value to supply).
changes.push({
severity: "breaking",
code: "required_field_added",
severity: 'breaking',
code: 'required_field_added',
field: name,
detail: `required (non-nullable) field "${name}" added`,
});
@@ -214,51 +223,75 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
previous.primary_identifiers.every((v, i) => next.primary_identifiers[i] === v);
if (!idsEqual) {
changes.push({
severity: "breaking",
code: "primary_identifier_changed",
detail: `primary identifier [${previous.primary_identifiers.join(",")}] -> [${next.primary_identifiers.join(",")}]`,
severity: 'breaking',
code: 'primary_identifier_changed',
detail: `primary identifier [${previous.primary_identifiers.join(',')}] -> [${next.primary_identifiers.join(',')}]`,
});
}
for (const d of previous.dimensions) {
if (!next.dimensions.includes(d)) {
changes.push({ severity: "breaking", code: "dimension_removed", field: d, detail: `dimension "${d}" removed` });
changes.push({
severity: 'breaking',
code: 'dimension_removed',
field: d,
detail: `dimension "${d}" removed`,
});
}
}
for (const d of next.dimensions) {
if (!previous.dimensions.includes(d)) {
changes.push({ severity: "compatible", code: "dimension_added", field: d, detail: `dimension "${d}" added` });
changes.push({
severity: 'compatible',
code: 'dimension_added',
field: d,
detail: `dimension "${d}" added`,
});
}
}
for (const m of previous.measures) {
if (!next.measures.includes(m)) {
changes.push({ severity: "breaking", code: "measure_removed", field: m, detail: `measure "${m}" removed` });
changes.push({
severity: 'breaking',
code: 'measure_removed',
field: m,
detail: `measure "${m}" removed`,
});
}
}
for (const m of next.measures) {
if (!previous.measures.includes(m)) {
changes.push({ severity: "compatible", code: "measure_added", field: m, detail: `measure "${m}" added` });
changes.push({
severity: 'compatible',
code: 'measure_added',
field: m,
detail: `measure "${m}" added`,
});
}
}
if (next.freshness_slo_seconds > previous.freshness_slo_seconds) {
changes.push({
severity: "breaking",
code: "freshness_slo_loosened",
severity: 'breaking',
code: 'freshness_slo_loosened',
detail: `freshness SLO ${previous.freshness_slo_seconds}s -> ${next.freshness_slo_seconds}s`,
});
}
if (next.retention_days < previous.retention_days) {
changes.push({
severity: "breaking",
code: "retention_shortened",
severity: 'breaking',
code: 'retention_shortened',
detail: `retention ${previous.retention_days}d -> ${next.retention_days}d`,
});
}
for (const p of previous.allowed_purposes) {
if (!next.allowed_purposes.includes(p)) {
changes.push({ severity: "breaking", code: "purpose_removed", detail: `allowed purpose "${p}" removed` });
changes.push({
severity: 'breaking',
code: 'purpose_removed',
detail: `allowed purpose "${p}" removed`,
});
}
}
@@ -270,8 +303,8 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
};
if (PII_RANK[next.pii_classification] > PII_RANK[previous.pii_classification]) {
changes.push({
severity: "breaking",
code: "pii_classification_raised",
severity: 'breaking',
code: 'pii_classification_raised',
detail: `PII classification ${previous.pii_classification} -> ${next.pii_classification}`,
});
}
@@ -279,16 +312,16 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
const prevRules = new Map(previous.quality_rules.map((r) => [r.rule_id, r]));
for (const [id, pr] of prevRules) {
const nr = next.quality_rules.find((r) => r.rule_id === id);
if (!nr && pr.severity === "block") {
if (!nr && pr.severity === 'block') {
changes.push({
severity: "breaking",
code: "blocking_quality_rule_removed",
severity: 'breaking',
code: 'blocking_quality_rule_removed',
detail: `blocking quality rule "${id}" removed`,
});
} else if (nr && pr.severity === "block" && nr.severity === "warn") {
} else if (nr && pr.severity === 'block' && nr.severity === 'warn') {
changes.push({
severity: "breaking",
code: "blocking_quality_rule_downgraded",
severity: 'breaking',
code: 'blocking_quality_rule_downgraded',
detail: `quality rule "${id}" downgraded block -> warn`,
});
}
@@ -296,8 +329,8 @@ export function diffContracts(previous: DatasetContract, next: DatasetContract):
if (previous.tier !== next.tier) {
changes.push({
severity: "breaking",
code: "tier_changed",
severity: 'breaking',
code: 'tier_changed',
detail: `tier ${previous.tier} -> ${next.tier}`,
});
}
@@ -334,7 +367,7 @@ export function checkContractCompatibility(
const pv = parseSemVer(previous.version);
const nv = parseSemVer(next.version);
const changes = diffContracts(previous, next);
const breaking = changes.filter((c) => c.severity === "breaking");
const breaking = changes.filter((c) => c.severity === 'breaking');
const forward =
nv.major > pv.major ||
@@ -364,7 +397,7 @@ export function checkContractCompatibility(
reason:
`${breaking.length} breaking change(s) require a MAJOR version bump ` +
`(${previous.version} -> ${next.version} is not one): ` +
breaking.map((b) => b.code).join(", "),
breaking.map((b) => b.code).join(', '),
};
}
@@ -379,10 +412,17 @@ export function checkContractCompatibility(
}
/** Throwing form for call sites that treat incompatibility as a failure. */
export function assertContractCompatible(previous: DatasetContract, next: DatasetContract): CompatibilityVerdict {
export function assertContractCompatible(
previous: DatasetContract,
next: DatasetContract,
): CompatibilityVerdict {
const verdict = checkContractCompatibility(previous, next);
if (!verdict.compatible) {
throw new SiaxError("CONFLICT", "0pt.analytics", verdict.reason ?? "dataset contract compatibility gate failed");
throw new SiaxError(
'CONFLICT',
'0pt.analytics',
verdict.reason ?? 'dataset contract compatibility gate failed',
);
}
return verdict;
}
@@ -395,24 +435,28 @@ export function assertContractCompatible(previous: DatasetContract, next: Datase
export function validateContract(contract: DatasetContract): void {
parseSemVer(contract.version);
if (!contract.dataset_id.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "contract needs a dataset_id");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'contract needs a dataset_id');
}
if (contract.fields.length === 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `contract ${contract.dataset_id} declares no fields`);
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
`contract ${contract.dataset_id} declares no fields`,
);
}
const names = new Set<string>();
for (const f of contract.fields) {
if (names.has(f.name)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `duplicate field "${f.name}"`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `duplicate field "${f.name}"`);
}
names.add(f.name);
}
for (const label of ["primary_identifiers", "dimensions", "measures"] as const) {
for (const label of ['primary_identifiers', 'dimensions', 'measures'] as const) {
for (const n of contract[label]) {
if (!names.has(n)) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`${label} references unknown field "${n}" in ${contract.dataset_id}`,
);
}
@@ -420,23 +464,23 @@ export function validateContract(contract: DatasetContract): void {
}
if (contract.primary_identifiers.length === 0) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`contract ${contract.dataset_id} declares no primary identifier`,
);
}
if (contract.allowed_purposes.length === 0) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`contract ${contract.dataset_id} declares no allowed_purposes (purpose limitation is not optional)`,
);
}
if (contract.freshness_slo_seconds <= 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "freshness_slo_seconds must be positive");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'freshness_slo_seconds must be positive');
}
if (contract.retention_days < 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "retention_days must not be negative");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'retention_days must not be negative');
}
}
@@ -457,7 +501,7 @@ export function contractHash(contract: DatasetContract): string {
nullable: f.nullable,
role: f.role,
primary_identifier: f.primary_identifier ?? false,
classification: f.classification ?? "none",
classification: f.classification ?? 'none',
}))
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)),
primary_identifiers: contract.primary_identifiers,
@@ -470,5 +514,5 @@ export function contractHash(contract: DatasetContract): string {
quality_rules: [...contract.quality_rules].sort((a, b) => (a.rule_id < b.rule_id ? -1 : 1)),
allowed_purposes: [...contract.allowed_purposes].sort(),
};
return crypto.createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
return crypto.createHash('sha256').update(JSON.stringify(canonical)).digest('hex');
}
+85 -85
View File
@@ -35,7 +35,7 @@
* defines its own copies of these tables and never receives engine
* credentials.
*/
import type { AnalyticsTier } from "./tiers";
import type { AnalyticsTier } from './tiers';
/** Every tenant-owned analytics record. */
export interface TenantScoped {
@@ -46,28 +46,28 @@ export interface TenantScoped {
// ── field/typing vocabulary ────────────────────────────────────────────────
export const ANALYTICS_FIELD_TYPES = [
"string",
"int64",
"float64",
"bool",
"date",
"timestamp",
"decimal",
"json",
'string',
'int64',
'float64',
'bool',
'date',
'timestamp',
'decimal',
'json',
] as const;
export type AnalyticsFieldType = (typeof ANALYTICS_FIELD_TYPES)[number];
/** A field's analytical role. Measures aggregate; dimensions group. */
export const FIELD_ROLES = ["identifier", "dimension", "measure", "attribute"] as const;
export const FIELD_ROLES = ['identifier', 'dimension', 'measure', 'attribute'] as const;
export type FieldRole = (typeof FIELD_ROLES)[number];
/** PII classification, aligned with the SIAX risk vocabulary (L0 = none). */
export const PII_CLASSIFICATIONS = ["none", "pseudonymous", "personal", "sensitive"] as const;
export const PII_CLASSIFICATIONS = ['none', 'pseudonymous', 'personal', 'sensitive'] as const;
export type PiiClassification = (typeof PII_CLASSIFICATIONS)[number];
// ── 1. AnalyticsDataset ────────────────────────────────────────────────────
export const DATASET_STATUSES = ["draft", "active", "deprecated", "retired"] as const;
export const DATASET_STATUSES = ['draft', 'active', 'deprecated', 'retired'] as const;
export type AnalyticsDatasetStatus = (typeof DATASET_STATUSES)[number];
/**
@@ -137,7 +137,7 @@ export interface DatasetField extends TenantScoped {
// ── 4. DatasetGrant ────────────────────────────────────────────────────────
export const GRANT_LEVELS = ["read", "query", "export", "admin"] as const;
export const GRANT_LEVELS = ['read', 'query', 'export', 'admin'] as const;
export type GrantLevel = (typeof GRANT_LEVELS)[number];
/**
@@ -150,7 +150,7 @@ export interface DatasetGrant extends TenantScoped {
dataset_id: string;
/** Subject: a CL0UD principal, role, or BI application binding id. */
subject_id: string;
subject_type: "user" | "role" | "service" | "bi_application";
subject_type: 'user' | 'role' | 'service' | 'bi_application';
level: GrantLevel;
allowed_purposes: string[];
expires_at?: string;
@@ -161,14 +161,14 @@ export interface DatasetGrant extends TenantScoped {
// ── 5. MetricDefinition ────────────────────────────────────────────────────
export const METRIC_AGGREGATIONS = [
"sum",
"avg",
"min",
"max",
"count",
"count_distinct",
"ratio",
"derived",
'sum',
'avg',
'min',
'max',
'count',
'count_distinct',
'ratio',
'derived',
] as const;
export type MetricAggregation = (typeof METRIC_AGGREGATIONS)[number];
@@ -244,7 +244,7 @@ export interface SemanticModel extends TenantScoped {
// ── 9. AnalyticsQuery ──────────────────────────────────────────────────────
export const QUERY_SURFACES = ["metric", "sql", "projection"] as const;
export const QUERY_SURFACES = ['metric', 'sql', 'projection'] as const;
export type QuerySurface = (typeof QUERY_SURFACES)[number];
/**
@@ -268,12 +268,12 @@ export interface AnalyticsQuery extends TenantScoped {
// ── 10. QueryExecution ─────────────────────────────────────────────────────
export const EXECUTION_STATES = [
"queued",
"running",
"succeeded",
"failed",
"cancelled",
"rejected",
'queued',
'running',
'succeeded',
'failed',
'cancelled',
'rejected',
] as const;
export type ExecutionState = (typeof EXECUTION_STATES)[number];
@@ -299,7 +299,7 @@ export interface QueryExecution extends TenantScoped {
// ── 11. QueryResult ────────────────────────────────────────────────────────
export const RESULT_ENCODINGS = ["json", "arrow_ipc"] as const;
export const RESULT_ENCODINGS = ['json', 'arrow_ipc'] as const;
export type ResultEncoding = (typeof RESULT_ENCODINGS)[number];
export interface QueryResult extends TenantScoped {
@@ -345,7 +345,7 @@ export interface DashboardVersion extends TenantScoped {
// ── 14. ReportDefinition ───────────────────────────────────────────────────
export const REPORT_FORMATS = ["pdf", "csv", "xlsx", "parquet", "arrow_ipc"] as const;
export const REPORT_FORMATS = ['pdf', 'csv', 'xlsx', 'parquet', 'arrow_ipc'] as const;
export type ReportFormat = (typeof REPORT_FORMATS)[number];
export interface ReportDefinition extends TenantScoped {
@@ -378,18 +378,18 @@ export interface ReportRun extends TenantScoped {
// ── 16. DataQualityRule ────────────────────────────────────────────────────
export const QUALITY_RULE_KINDS = [
"not_null",
"unique",
"accepted_values",
"range",
"freshness",
"row_count",
"referential",
"custom",
'not_null',
'unique',
'accepted_values',
'range',
'freshness',
'row_count',
'referential',
'custom',
] as const;
export type QualityRuleKind = (typeof QUALITY_RULE_KINDS)[number];
export const QUALITY_SEVERITIES = ["warn", "block"] as const;
export const QUALITY_SEVERITIES = ['warn', 'block'] as const;
export type QualitySeverity = (typeof QUALITY_SEVERITIES)[number];
export interface DataQualityRule extends TenantScoped {
@@ -423,7 +423,7 @@ export interface DataQualityRun extends TenantScoped {
// ── 18. LineageReference ───────────────────────────────────────────────────
export const LINEAGE_DIRECTIONS = ["input", "output"] as const;
export const LINEAGE_DIRECTIONS = ['input', 'output'] as const;
export type LineageDirection = (typeof LINEAGE_DIRECTIONS)[number];
/**
@@ -438,7 +438,7 @@ export interface LineageReference extends TenantScoped {
job_name: string;
direction: LineageDirection;
/** The analytics entity this edge touches. */
entity_type: "dataset" | "metric" | "dashboard" | "report";
entity_type: 'dataset' | 'metric' | 'dashboard' | 'report';
entity_id: string;
/** Namespaced dataset name on the other side of the edge. */
counterpart_ref: string;
@@ -447,7 +447,7 @@ export interface LineageReference extends TenantScoped {
// ── 19. BIApplicationBinding ───────────────────────────────────────────────
export const BI_APPLICATION_KINDS = ["superset", "evidence", "des1gn", "notebook", "custom"] as const;
export const BI_APPLICATION_KINDS = ['superset', 'evidence', 'des1gn', 'notebook', 'custom'] as const;
export type BiApplicationKind = (typeof BI_APPLICATION_KINDS)[number];
/**
@@ -482,55 +482,55 @@ export interface BIApplicationBinding extends TenantScoped {
* or omission is a test failure rather than drift.
*/
export const ANALYTICS_DOMAIN_ENTITIES = [
"AnalyticsDataset",
"DatasetVersion",
"DatasetField",
"DatasetGrant",
"MetricDefinition",
"MetricVersion",
"DimensionDefinition",
"SemanticModel",
"AnalyticsQuery",
"QueryExecution",
"QueryResult",
"DashboardDefinition",
"DashboardVersion",
"ReportDefinition",
"ReportRun",
"DataQualityRule",
"DataQualityRun",
"LineageReference",
"BIApplicationBinding",
'AnalyticsDataset',
'DatasetVersion',
'DatasetField',
'DatasetGrant',
'MetricDefinition',
'MetricVersion',
'DimensionDefinition',
'SemanticModel',
'AnalyticsQuery',
'QueryExecution',
'QueryResult',
'DashboardDefinition',
'DashboardVersion',
'ReportDefinition',
'ReportRun',
'DataQualityRule',
'DataQualityRun',
'LineageReference',
'BIApplicationBinding',
] as const;
export type AnalyticsDomainEntity = (typeof ANALYTICS_DOMAIN_ENTITIES)[number];
/** Entity -> physical table in sql/008_analytics_domain_model.sql. */
export const ANALYTICS_ENTITY_TABLES: Record<AnalyticsDomainEntity, string> = {
AnalyticsDataset: "opt_analytics_dataset",
DatasetVersion: "opt_analytics_dataset_version",
DatasetField: "opt_analytics_dataset_field",
DatasetGrant: "opt_analytics_dataset_grant",
MetricDefinition: "opt_analytics_metric_definition",
MetricVersion: "opt_analytics_metric_version",
DimensionDefinition: "opt_analytics_dimension_definition",
SemanticModel: "opt_analytics_semantic_model",
AnalyticsQuery: "opt_analytics_query",
QueryExecution: "opt_analytics_query_execution",
QueryResult: "opt_analytics_query_result",
DashboardDefinition: "opt_analytics_dashboard_definition",
DashboardVersion: "opt_analytics_dashboard_version",
ReportDefinition: "opt_analytics_report_definition",
ReportRun: "opt_analytics_report_run",
DataQualityRule: "opt_analytics_data_quality_rule",
DataQualityRun: "opt_analytics_data_quality_run",
LineageReference: "opt_analytics_lineage_reference",
BIApplicationBinding: "opt_analytics_bi_application_binding",
AnalyticsDataset: 'opt_analytics_dataset',
DatasetVersion: 'opt_analytics_dataset_version',
DatasetField: 'opt_analytics_dataset_field',
DatasetGrant: 'opt_analytics_dataset_grant',
MetricDefinition: 'opt_analytics_metric_definition',
MetricVersion: 'opt_analytics_metric_version',
DimensionDefinition: 'opt_analytics_dimension_definition',
SemanticModel: 'opt_analytics_semantic_model',
AnalyticsQuery: 'opt_analytics_query',
QueryExecution: 'opt_analytics_query_execution',
QueryResult: 'opt_analytics_query_result',
DashboardDefinition: 'opt_analytics_dashboard_definition',
DashboardVersion: 'opt_analytics_dashboard_version',
ReportDefinition: 'opt_analytics_report_definition',
ReportRun: 'opt_analytics_report_run',
DataQualityRule: 'opt_analytics_data_quality_rule',
DataQualityRun: 'opt_analytics_data_quality_run',
LineageReference: 'opt_analytics_lineage_reference',
BIApplicationBinding: 'opt_analytics_bi_application_binding',
};
/** The four entities BI-P002 requires to be immutable once written. */
export const IMMUTABLE_VERSION_ENTITIES: readonly AnalyticsDomainEntity[] = [
"DatasetVersion",
"MetricVersion",
"SemanticModel",
"DashboardVersion",
'DatasetVersion',
'MetricVersion',
'SemanticModel',
'DashboardVersion',
];
+12 -12
View File
@@ -21,24 +21,24 @@
* ARCHITECTURE BOUNDARY (BI program §0): 0pt owns tier semantics. Product
* repos (VehIQ et al) own what the rows MEAN; they never re-declare tiers.
*/
import { SiaxError } from "../../platform/errors";
import { SiaxError } from '../../platform/errors';
export const ANALYTICS_TIERS = ["RAW", "NORMALIZED", "CURATED", "SERVING"] as const;
export const ANALYTICS_TIERS = ['RAW', 'NORMALIZED', 'CURATED', 'SERVING'] as const;
export type AnalyticsTier = (typeof ANALYTICS_TIERS)[number];
/** Physical home a tier is expected to live in (BI-P003 "suggested" mapping). */
export const TIER_PHYSICAL_HOME: Record<AnalyticsTier, string> = {
RAW: "st0re:iceberg|parquet",
NORMALIZED: "st0re:iceberg",
CURATED: "st0re:iceberg",
SERVING: "clickhouse:projection",
RAW: 'st0re:iceberg|parquet',
NORMALIZED: 'st0re:iceberg',
CURATED: 'st0re:iceberg',
SERVING: 'clickhouse:projection',
};
/** Tiers a BI presentation surface may read without an explicit exception. */
export const BI_READABLE_TIERS: readonly AnalyticsTier[] = ["SERVING", "CURATED"];
export const BI_READABLE_TIERS: readonly AnalyticsTier[] = ['SERVING', 'CURATED'];
export function isAnalyticsTier(v: unknown): v is AnalyticsTier {
return typeof v === "string" && (ANALYTICS_TIERS as readonly string[]).includes(v);
return typeof v === 'string' && (ANALYTICS_TIERS as readonly string[]).includes(v);
}
/**
@@ -64,8 +64,8 @@ export function assertReadableByBiSurface(
if (BI_READABLE_TIERS.includes(dataset.tier)) return;
if (dataset.raw_access_exception && dataset.raw_access_exception.trim().length > 0) return;
throw new SiaxError(
"AUTHORIZATION_DENIED",
"0pt.analytics",
'AUTHORIZATION_DENIED',
'0pt.analytics',
`BI surface "${surface}" may not read ${dataset.tier} dataset ${dataset.dataset_id} ` +
`without a recorded raw_access_exception (BI-P003)`,
);
@@ -75,8 +75,8 @@ export function assertReadableByBiSurface(
export function assertTierLineageSane(datasetTier: AnalyticsTier, sourceTier: AnalyticsTier): void {
if (TIER_RANK[sourceTier] > TIER_RANK[datasetTier]) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`a ${datasetTier} dataset cannot be built from a ${sourceTier} dataset (BI-P003 tier order)`,
);
}
+62 -55
View File
@@ -26,17 +26,17 @@
* LEGAL BOUNDARY (inherited): generic 0pt analytics only. Never the b0ts
* ClickHouse pipelines, never quarantined market data.
*/
import crypto from "node:crypto";
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../../platform/errors";
import { ClickHouseAnalytics } from "../clickhouse-analytics";
import crypto from 'node:crypto';
import { SiaxError, siaxErrorCodeForUpstreamStatus } from '../../platform/errors';
import { ClickHouseAnalytics } from '../clickhouse-analytics';
import {
compileMetricQuery,
compileProjectionQuery,
dimensionCatalogFrom,
FORCED_TENANT_PREDICATE,
type DimensionCatalog,
} from "./query-compiler";
import { analyticsSchemaDdl, type AnalyticsSchemaOptions } from "./schema";
} from './query-compiler';
import { analyticsSchemaDdl, type AnalyticsSchemaOptions } from './schema';
import {
applyQuota,
clickhouseSettings,
@@ -44,7 +44,7 @@ import {
DEFAULT_BUDGETS,
planningSettings,
type ResourceBudget,
} from "./resource-governance";
} from './resource-governance';
import type {
AnalystQueryRequest,
AnalyticsIdentity,
@@ -56,7 +56,7 @@ import type {
QueryEstimate,
QueryExplanation,
SiaxAnalyticsEngine,
} from "./siax-analytics-engine";
} from './siax-analytics-engine';
export interface ClickHouseEngineOptions {
baseUrl: string;
@@ -66,13 +66,13 @@ export interface ClickHouseEngineOptions {
timeoutMs?: number;
/** Dimension allow-list per tenant. Absent tenant = no dimensions allowed. */
dimensionCatalogs?: Record<string, Record<string, string>>;
schema?: Omit<AnalyticsSchemaOptions, "database">;
schema?: Omit<AnalyticsSchemaOptions, 'database'>;
}
const EMPTY_CATALOG: DimensionCatalog = { resolve: () => undefined };
export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
readonly provider = "clickhouse";
readonly provider = 'clickhouse';
/** PRESERVED pre-existing implementation, composed not replaced. */
private readonly legacy: ClickHouseAnalytics;
@@ -81,15 +81,15 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
private readonly database: string;
private readonly timeoutMs: number;
private readonly dimensionCatalogs: Record<string, Record<string, string>>;
private readonly schemaOpts: Omit<AnalyticsSchemaOptions, "database">;
private readonly schemaOpts: Omit<AnalyticsSchemaOptions, 'database'>;
private readonly gate: ConcurrencyGate;
/** query_id -> AbortController, so cancelQuery can stop the client side too. */
private readonly inFlight = new Map<string, AbortController>();
constructor(opts: ClickHouseEngineOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString("base64")}` : undefined;
this.database = opts.database ?? "opt_analytics";
this.baseUrl = opts.baseUrl.replace(/\/+$/, '');
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString('base64')}` : undefined;
this.database = opts.database ?? 'opt_analytics';
this.timeoutMs = opts.timeoutMs ?? 30_000;
this.dimensionCatalogs = opts.dimensionCatalogs ?? {};
this.schemaOpts = opts.schema ?? {};
@@ -112,7 +112,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
}
private budgetFor(identity: AnalyticsIdentity): ResourceBudget {
const tier = identity.budget_tier ?? "INTERACTIVE";
const tier = identity.budget_tier ?? 'INTERACTIVE';
return applyQuota(DEFAULT_BUDGETS[tier], identity.quota);
}
@@ -125,13 +125,13 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
private assertIdentity(identity: AnalyticsIdentity): void {
if (!identity?.tenant_id || !identity.tenant_id.trim()) {
throw new SiaxError(
"UNAUTHENTICATED",
"0pt.analytics",
"analytics requires a verified CL0UD identity carrying tenant_id",
'UNAUTHENTICATED',
'0pt.analytics',
'analytics requires a verified CL0UD identity carrying tenant_id',
);
}
if (!identity.principal_id || !identity.principal_id.trim()) {
throw new SiaxError("UNAUTHENTICATED", "0pt.analytics", "analytics requires a verified principal_id");
throw new SiaxError('UNAUTHENTICATED', '0pt.analytics', 'analytics requires a verified principal_id');
}
}
@@ -150,15 +150,16 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
async health(): Promise<HealthReport> {
try {
const legacyOk = await this.legacy.health();
if (!legacyOk) return { healthy: false, provider: this.provider, detail: "legacy health probe returned false" };
const v = await this.raw("SELECT version() AS v FORMAT JSON", {}, {});
if (!legacyOk)
return { healthy: false, provider: this.provider, detail: 'legacy health probe returned false' };
const v = await this.raw('SELECT version() AS v FORMAT JSON', {}, {});
const version = (v as { data?: { v?: string }[] })?.data?.[0]?.v;
return { healthy: true, provider: this.provider, version };
} catch (err) {
return {
healthy: false,
provider: this.provider,
detail: err instanceof SiaxError ? err.code : "unreachable",
detail: err instanceof SiaxError ? err.code : 'unreachable',
};
}
}
@@ -191,14 +192,13 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
budget.maxResultRows,
);
const json = (await this.raw(compiled.sql, compiled.params, clickhouseSettings(budget), queryId)) as
| ClickHouseJsonResponse
| undefined;
ClickHouseJsonResponse | undefined;
const groupNames = request.group_by ?? [];
const rows = (json?.data ?? []).map((r) => {
const groups: Record<string, string> = {};
groupNames.forEach((name, i) => {
const v = (r as Record<string, unknown>)[`grp${i}`];
groups[name] = v === undefined || v === null ? "" : String(v);
groups[name] = v === undefined || v === null ? '' : String(v);
});
return {
...(groupNames.length ? { groups } : {}),
@@ -230,7 +230,15 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
*/
async executeLegacyMetric(
identity: AnalyticsIdentity,
request: { metric: string; aggregate: "sum" | "avg" | "min" | "max" | "count"; dataset_id?: string; group_by?: string; from_time?: string; to_time?: string; limit?: number },
request: {
metric: string;
aggregate: 'sum' | 'avg' | 'min' | 'max' | 'count';
dataset_id?: string;
group_by?: string;
from_time?: string;
to_time?: string;
limit?: number;
},
): Promise<EngineResult> {
this.assertIdentity(identity);
const started = Date.now();
@@ -264,9 +272,9 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
// BI-P033 (analytics authorization) exist would create precisely the
// "raw SQL attempt" hole BI-P011's adversarial list enumerates.
throw new SiaxError(
"CAPABILITY_UNAVAILABLE",
"0pt.analytics",
"analyst SQL is not enabled on the ClickHouse provider until BI-P017/BI-P033 land",
'CAPABILITY_UNAVAILABLE',
'0pt.analytics',
'analyst SQL is not enabled on the ClickHouse provider until BI-P017/BI-P033 land',
);
}
@@ -296,7 +304,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
// `EXPLAIN ESTIMATE` reports the parts/rows/marks the planner will read
// AFTER primary-key pruning — which is why tenant_id leads every ORDER BY
// in schema.ts: the estimate for one tenant does not include everyone.
const estimateSql = compiled.sql.replace(/ FORMAT JSON$/, "");
const estimateSql = compiled.sql.replace(/ FORMAT JSON$/, '');
let rowsToRead = 0;
let partsRead = 0;
try {
@@ -313,7 +321,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
// An estimate that cannot be produced must not read as "cheap".
throw err instanceof SiaxError
? err
: new SiaxError("DEPENDENCY_UNAVAILABLE", "clickhouse", "could not estimate query");
: new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'could not estimate query');
}
// Rough byte estimate: ClickHouse's ESTIMATE reports rows, not bytes.
// 128 B/row is a deliberately PESSIMISTIC constant for these tables
@@ -347,7 +355,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
async cancelQuery(identity: AnalyticsIdentity, queryId: string): Promise<boolean> {
this.assertIdentity(identity);
if (!queryId.startsWith(this.queryIdPrefix(identity))) {
throw new SiaxError("AUTHORIZATION_DENIED", "0pt.analytics", "query does not belong to this tenant");
throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics', 'query does not belong to this tenant');
}
this.inFlight.get(queryId)?.abort();
this.inFlight.delete(queryId);
@@ -357,7 +365,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
await this.raw(
`KILL QUERY WHERE query_id = {killId:String} SYNC FORMAT JSON`,
{ param_killId: queryId },
{ max_execution_time: "10" },
{ max_execution_time: '10' },
);
return true;
} catch {
@@ -388,14 +396,14 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
this.catalogFor(identity),
budget.maxResultRows,
);
const sql = compiled.sql.replace(/ FORMAT JSON$/, "");
const sql = compiled.sql.replace(/ FORMAT JSON$/, '');
const res = (await this.raw(
`EXPLAIN PLAN indexes = 1 ${sql} FORMAT TSVRaw`,
compiled.params,
planningSettings(budget),
)) as string | undefined;
return {
plan: typeof res === "string" ? res : JSON.stringify(res ?? ""),
plan: typeof res === 'string' ? res : JSON.stringify(res ?? ''),
forced_tenant_predicate: FORCED_TENANT_PREDICATE,
table: compiled.table,
};
@@ -414,22 +422,22 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
const body = request.rows
.map((r) => {
if (!r.entity_key || !r.entity_key.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "every projection row needs an entity_key");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'every projection row needs an entity_key');
}
return JSON.stringify({
// tenant/project come from the VERIFIED identity, never the row —
// a row-supplied tenant_id is the INF0 Wave-2 bug class.
tenant_id: identity.tenant_id,
project_id: identity.project_id ?? "",
project_id: identity.project_id ?? '',
dataset_id: request.dataset_id,
entity_key: r.entity_key,
as_of: (r.as_of ?? now.toISOString()).replace("T", " ").replace(/Z$/, ""),
as_of: (r.as_of ?? now.toISOString()).replace('T', ' ').replace(/Z$/, ''),
version: r.version ?? version,
attributes: r.attributes ?? {},
measures: r.measures ?? {},
});
})
.join("\n");
.join('\n');
await this.raw(
`INSERT INTO ${this.database}.opt_dataset_projection FORMAT JSONEachRow`,
{},
@@ -455,7 +463,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
await this.raw(
`OPTIMIZE TABLE ${this.database}.opt_dataset_projection PARTITION {tenant:String} FINAL`,
{ param_tenant: identity.tenant_id },
{ max_execution_time: "120" },
{ max_execution_time: '120' },
);
const compiled = compileProjectionQuery(
{ tenant_id: identity.tenant_id, project_id: identity.project_id, dataset_id, limit: 1 },
@@ -466,8 +474,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
`SELECT count() AS value FROM ${this.database}.opt_dataset_projection FINAL ` +
`WHERE ${FORCED_TENANT_PREDICATE} AND dataset_id = {dataset:String} FORMAT JSON`;
const res = (await this.raw(countSql, compiled.params, clickhouseSettings(this.budgetFor(identity)))) as
| { data?: { value: number | string }[] }
| undefined;
{ data?: { value: number | string }[] } | undefined;
return {
dataset_id,
row_count: Number(res?.data?.[0]?.value ?? 0),
@@ -478,16 +485,16 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
// ── transport ────────────────────────────────────────────────────────────
private queryIdPrefix(identity: AnalyticsIdentity): string {
return `opt_${crypto.createHash("sha256").update(identity.tenant_id).digest("hex").slice(0, 12)}_`;
return `opt_${crypto.createHash('sha256').update(identity.tenant_id).digest('hex').slice(0, 12)}_`;
}
private newQueryId(identity: AnalyticsIdentity): string {
return `${this.queryIdPrefix(identity)}${crypto.randomUUID().replace(/-/g, "")}`;
return `${this.queryIdPrefix(identity)}${crypto.randomUUID().replace(/-/g, '')}`;
}
/** DDL path: no readonly, no result parsing beyond errors. */
private async ddl(sql: string): Promise<void> {
await this.raw(sql, {}, { max_execution_time: "60" });
await this.raw(sql, {}, { max_execution_time: '60' });
}
private async raw(
@@ -498,13 +505,13 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
body?: string,
): Promise<unknown> {
const url = new URL(this.baseUrl);
url.searchParams.set("query", sql);
url.searchParams.set('query', sql);
for (const [k, v] of Object.entries(settings)) url.searchParams.set(k, v);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
if (queryId) url.searchParams.set("query_id", queryId);
if (queryId) url.searchParams.set('query_id', queryId);
const headers: Record<string, string> = {};
if (this.authHeader) headers["Authorization"] = this.authHeader;
if (this.authHeader) headers['Authorization'] = this.authHeader;
const controller = new AbortController();
if (queryId) this.inFlight.set(queryId, controller);
@@ -513,13 +520,13 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
let res: Response;
try {
res = await fetch(url.toString(), {
method: "POST",
method: 'POST',
headers,
body: body ?? "",
body: body ?? '',
signal: controller.signal,
});
} catch (cause) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "clickhouse", "clickhouse unreachable", { cause });
throw new SiaxError('DEPENDENCY_UNAVAILABLE', 'clickhouse', 'clickhouse unreachable', { cause });
} finally {
clearTimeout(timeout);
}
@@ -530,7 +537,7 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
const code = /Code: (\d+)/.exec(text)?.[1] ?? String(res.status);
throw new SiaxError(
siaxErrorCodeForUpstreamStatus(res.status),
"clickhouse",
'clickhouse',
`query failed (CH code ${code})`,
);
}
@@ -548,10 +555,10 @@ export class ClickHouseAnalyticsEngine implements SiaxAnalyticsEngine {
// have already been flushed, the JSON body can carry an `exception` key
// under a 200 — a truncated answer indistinguishable from a whole one.
// Treat any body carrying an exception as a failure, whatever the status.
if (parsed && typeof parsed === "object" && "exception" in parsed) {
const ex = String((parsed as { exception?: unknown }).exception ?? "");
const code = /Code: (\d+)/.exec(ex)?.[1] ?? "unknown";
throw new SiaxError("PERMANENT_FAILURE", "clickhouse", `query failed mid-stream (CH code ${code})`);
if (parsed && typeof parsed === 'object' && 'exception' in parsed) {
const ex = String((parsed as { exception?: unknown }).exception ?? '');
const code = /Code: (\d+)/.exec(ex)?.[1] ?? 'unknown';
throw new SiaxError('PERMANENT_FAILURE', 'clickhouse', `query failed mid-stream (CH code ${code})`);
}
return parsed;
}
+49 -47
View File
@@ -27,20 +27,20 @@
* the guarantee rather than replacing it, and
* tests/analytics/tenant-predicate-regression.test.ts asserts BOTH.
*/
import { SiaxError } from "../../platform/errors";
import type { AnalyticsTable } from "./schema";
import { SiaxError } from '../../platform/errors';
import type { AnalyticsTable } from './schema';
/** A physical identifier that has been VALIDATED, not merely received. */
const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
export function assertSafeIdentifier(value: string, what: string): string {
if (!IDENT_RE.test(value)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `invalid ${what} identifier`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `invalid ${what} identifier`);
}
return value;
}
export const METRIC_AGGREGATES = ["sum", "avg", "min", "max", "count", "count_distinct"] as const;
export const METRIC_AGGREGATES = ['sum', 'avg', 'min', 'max', 'count', 'count_distinct'] as const;
export type MetricAggregate = (typeof METRIC_AGGREGATES)[number];
/**
@@ -97,15 +97,15 @@ export interface CompiledQuery {
* forcing, the test fails on a missing substring rather than on a subtle
* behavioural difference that a mocked engine would happily hide.
*/
export const FORCED_TENANT_PREDICATE = "tenant_id = {tenant:String}";
export const FORCED_TENANT_PREDICATE = 'tenant_id = {tenant:String}';
const AGG_SQL: Record<MetricAggregate, string> = {
sum: "sum(value)",
avg: "avg(value)",
min: "min(value)",
max: "max(value)",
count: "count()",
count_distinct: "uniqExact(event_id)",
sum: 'sum(value)',
avg: 'avg(value)',
min: 'min(value)',
max: 'max(value)',
count: 'count()',
count_distinct: 'uniqExact(event_id)',
};
const MAX_GROUP_BY = 8;
@@ -126,13 +126,13 @@ export function compileMetricQuery(
): CompiledQuery {
if (!req.tenant_id || !req.tenant_id.trim()) {
// Fail closed. A blank tenant must never compile to "no predicate".
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every analytics query");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'tenant_id is required on every analytics query');
}
assertSafeIdentifier(db, "database");
const table: AnalyticsTable = req.table ?? "opt_analytics_event";
assertSafeIdentifier(table, "table");
assertSafeIdentifier(db, 'database');
const table: AnalyticsTable = req.table ?? 'opt_analytics_event';
assertSafeIdentifier(table, 'table');
if (!METRIC_AGGREGATES.includes(req.aggregate)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "unsupported aggregate");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'unsupported aggregate');
}
const params: Record<string, string> = {
@@ -141,22 +141,22 @@ export function compileMetricQuery(
};
// ── the forced predicate. First condition, always, no branch. ─────────
const conditions: string[] = [FORCED_TENANT_PREDICATE, "metric = {metric:String}"];
const conditions: string[] = [FORCED_TENANT_PREDICATE, 'metric = {metric:String}'];
if (req.project_id) {
conditions.push("project_id = {project:String}");
conditions.push('project_id = {project:String}');
params.param_project = req.project_id;
}
if (req.dataset_id) {
conditions.push("dataset_id = {dataset:String}");
conditions.push('dataset_id = {dataset:String}');
params.param_dataset = req.dataset_id;
}
if (req.from_time) {
conditions.push("event_time >= parseDateTime64BestEffort({fromTime:String})");
conditions.push('event_time >= parseDateTime64BestEffort({fromTime:String})');
params.param_fromTime = req.from_time;
}
if (req.to_time) {
conditions.push("event_time < parseDateTime64BestEffort({toTime:String})");
conditions.push('event_time < parseDateTime64BestEffort({toTime:String})');
params.param_toTime = req.to_time;
}
@@ -165,16 +165,14 @@ export function compileMetricQuery(
for (const [name, value] of Object.entries(req.filters ?? {})) {
const physical = catalog.resolve(name);
if (physical === undefined) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unknown filter dimension "${name}"`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unknown filter dimension "${name}"`);
}
// `physical` came from the catalog, but validate anyway: a corrupted or
// hostile catalog row must not become an injection vector either.
assertSafeIdentifier(physical, "dimension");
assertSafeIdentifier(physical, 'dimension');
const nameKey = `f${filterIdx}n`;
const valKey = `f${filterIdx}v`;
conditions.push(
`dim_values[indexOf(dim_names, {${nameKey}:String})] = {${valKey}:String}`,
);
conditions.push(`dim_values[indexOf(dim_names, {${nameKey}:String})] = {${valKey}:String}`);
params[`param_${nameKey}`] = physical;
params[`param_${valKey}`] = value;
filterIdx += 1;
@@ -184,8 +182,8 @@ export function compileMetricQuery(
const groupBy = req.group_by ?? [];
if (groupBy.length > MAX_GROUP_BY) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.analytics",
'INVALID_REQUEST',
'0pt.analytics',
`at most ${MAX_GROUP_BY} group-by dimensions (got ${groupBy.length})`,
);
}
@@ -194,9 +192,9 @@ export function compileMetricQuery(
groupBy.forEach((name, i) => {
const physical = catalog.resolve(name);
if (physical === undefined) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", `unknown group_by dimension "${name}"`);
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unknown group_by dimension "${name}"`);
}
assertSafeIdentifier(physical, "dimension");
assertSafeIdentifier(physical, 'dimension');
const key = `g${i}`;
// The ALIAS is compiler-generated (`grp0`, `grp1`), never caller text.
selectParts.push(`dim_values[indexOf(dim_names, {${key}:String})] AS grp${i}`);
@@ -207,10 +205,10 @@ export function compileMetricQuery(
const limit = Math.max(1, Math.min(Math.floor(req.limit ?? 1000), maxResultRows));
const sql =
`SELECT ${selectParts.length ? selectParts.join(", ") + ", " : ""}${AGG_SQL[req.aggregate]} AS value ` +
`SELECT ${selectParts.length ? selectParts.join(', ') + ', ' : ''}${AGG_SQL[req.aggregate]} AS value ` +
`FROM ${db}.${table} ` +
`WHERE ${conditions.join(" AND ")} ` +
(groupParts.length ? `GROUP BY ${groupParts.join(", ")} ORDER BY value DESC ` : "") +
`WHERE ${conditions.join(' AND ')} ` +
(groupParts.length ? `GROUP BY ${groupParts.join(', ')} ORDER BY value DESC ` : '') +
`LIMIT ${limit} FORMAT JSON`;
return { sql, params, forcedTenantPredicate: FORCED_TENANT_PREDICATE, table };
@@ -226,29 +224,29 @@ export function compileProjectionQuery(
maxResultRows: number,
): CompiledQuery {
if (!req.tenant_id || !req.tenant_id.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant_id is required on every analytics query");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'tenant_id is required on every analytics query');
}
assertSafeIdentifier(db, "database");
assertSafeIdentifier(db, 'database');
const params: Record<string, string> = {
param_tenant: req.tenant_id,
param_dataset: req.dataset_id,
};
const conditions = [FORCED_TENANT_PREDICATE, "dataset_id = {dataset:String}"];
const conditions = [FORCED_TENANT_PREDICATE, 'dataset_id = {dataset:String}'];
if (req.project_id) {
conditions.push("project_id = {project:String}");
conditions.push('project_id = {project:String}');
params.param_project = req.project_id;
}
if (req.entity_keys && req.entity_keys.length > 0) {
conditions.push("has({entityKeys:Array(String)}, entity_key)");
conditions.push('has({entityKeys:Array(String)}, entity_key)');
params.param_entityKeys = JSON.stringify(req.entity_keys);
}
const limit = Math.max(1, Math.min(Math.floor(req.limit ?? 1000), maxResultRows));
const sql =
`SELECT entity_key, as_of, version, attributes, measures ` +
`FROM ${db}.opt_dataset_projection ` +
`WHERE ${conditions.join(" AND ")} ` +
`WHERE ${conditions.join(' AND ')} ` +
`ORDER BY entity_key LIMIT ${limit} FORMAT JSON`;
return { sql, params, forcedTenantPredicate: FORCED_TENANT_PREDICATE, table: "opt_dataset_projection" };
return { sql, params, forcedTenantPredicate: FORCED_TENANT_PREDICATE, table: 'opt_dataset_projection' };
}
/**
@@ -275,25 +273,29 @@ export function restrictedTenantUserDdl(args: {
tables: readonly string[];
settingsProfile?: string;
}): string[] {
assertSafeIdentifier(args.db, "database");
assertSafeIdentifier(args.userName, "user");
assertSafeIdentifier(args.db, 'database');
assertSafeIdentifier(args.userName, 'user');
// A tenant id is `t_<slug>` in this estate; enforce that shape strictly
// rather than trusting the caller.
if (!/^[A-Za-z0-9_-]{1,64}$/.test(args.tenantId)) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "tenant id is not policy-safe");
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', 'tenant id is not policy-safe');
}
if (args.password.includes("'") || args.password.includes("\\")) {
throw new SiaxError("INVALID_REQUEST", "0pt.analytics", "password contains characters that cannot be embedded");
if (args.password.includes("'") || args.password.includes('\\')) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics',
'password contains characters that cannot be embedded',
);
}
const profile = args.settingsProfile;
if (profile) assertSafeIdentifier(profile, "settings profile");
if (profile) assertSafeIdentifier(profile, 'settings profile');
const stmts: string[] = [
`CREATE USER IF NOT EXISTS ${args.userName} IDENTIFIED WITH sha256_password BY '${args.password}'` +
(profile ? ` SETTINGS PROFILE ${profile}` : ` SETTINGS readonly = 1`),
];
for (const table of args.tables) {
assertSafeIdentifier(table, "table");
assertSafeIdentifier(table, 'table');
stmts.push(
`CREATE ROW POLICY IF NOT EXISTS ${args.userName}_${table}_rp ON ${args.db}.${table} ` +
`FOR SELECT USING tenant_id = '${args.tenantId}' TO ${args.userName}`,
+17 -17
View File
@@ -30,7 +30,7 @@
* subsidises a query bomb. `INTERACTIVE` is the dashboard default and is
* deliberately mean.
*/
import { SiaxError } from "../../platform/errors";
import { SiaxError } from '../../platform/errors';
export interface ResourceBudget {
/** Seconds. ClickHouse `max_execution_time`. */
@@ -47,7 +47,7 @@ export interface ResourceBudget {
maxConcurrentQueries: number;
}
export const BUDGET_TIERS = ["INTERACTIVE", "ANALYTICAL", "BATCH"] as const;
export const BUDGET_TIERS = ['INTERACTIVE', 'ANALYTICAL', 'BATCH'] as const;
export type BudgetTier = (typeof BUDGET_TIERS)[number];
/**
@@ -91,7 +91,7 @@ export const DEFAULT_BUDGETS: Record<BudgetTier, ResourceBudget> = {
export function applyQuota(base: ResourceBudget, quota: Partial<ResourceBudget> | undefined): ResourceBudget {
if (!quota) return { ...base };
const pick = (b: number, q: number | undefined): number =>
typeof q === "number" && Number.isFinite(q) && q > 0 ? Math.min(b, q) : b;
typeof q === 'number' && Number.isFinite(q) && q > 0 ? Math.min(b, q) : b;
return {
maxExecutionTimeSec: pick(base.maxExecutionTimeSec, quota.maxExecutionTimeSec),
maxResultRows: pick(base.maxResultRows, quota.maxResultRows),
@@ -114,14 +114,14 @@ export function applyQuota(base: ResourceBudget, quota: Partial<ResourceBudget>
*/
export function clickhouseSettings(budget: ResourceBudget): Record<string, string> {
return {
readonly: "1",
readonly: '1',
max_execution_time: String(budget.maxExecutionTimeSec),
timeout_overflow_mode: "throw",
timeout_overflow_mode: 'throw',
max_result_rows: String(budget.maxResultRows),
result_overflow_mode: "throw",
result_overflow_mode: 'throw',
max_rows_to_read: String(budget.maxRowsToRead),
max_bytes_to_read: String(budget.maxBytesToRead),
read_overflow_mode: "throw",
read_overflow_mode: 'throw',
max_memory_usage: String(budget.maxMemoryUsageBytes),
};
}
@@ -139,21 +139,21 @@ export function clickhouseSettings(budget: ResourceBudget): Record<string, strin
*/
export function planningSettings(budget: ResourceBudget): Record<string, string> {
return {
readonly: "1",
readonly: '1',
max_execution_time: String(Math.min(budget.maxExecutionTimeSec, 15)),
timeout_overflow_mode: "throw",
timeout_overflow_mode: 'throw',
max_memory_usage: String(budget.maxMemoryUsageBytes),
};
}
/** Every setting name BI-P012 requires, for the DoD assertion. */
export const REQUIRED_GOVERNANCE_SETTINGS = [
"max_execution_time",
"max_result_rows",
"max_rows_to_read",
"max_bytes_to_read",
"max_memory_usage",
"max_concurrent_queries",
'max_execution_time',
'max_result_rows',
'max_rows_to_read',
'max_bytes_to_read',
'max_memory_usage',
'max_concurrent_queries',
] as const;
/**
@@ -192,8 +192,8 @@ export class ConcurrencyGate {
const current = this.inFlight.get(tenantId) ?? 0;
if (current >= limit) {
throw new SiaxError(
"RATE_LIMITED",
"0pt.analytics",
'RATE_LIMITED',
'0pt.analytics',
`tenant already has ${current} analytics queries in flight (limit ${limit})`,
);
}
+5 -6
View File
@@ -55,14 +55,14 @@ export interface AnalyticsSchemaOptions {
/** Physical tables this module owns (opt_metric_events is NOT one of them). */
export const ANALYTICS_TABLES = [
"opt_analytics_event",
"opt_metric_daily",
"opt_dataset_projection",
'opt_analytics_event',
'opt_metric_daily',
'opt_dataset_projection',
] as const;
export type AnalyticsTable = (typeof ANALYTICS_TABLES)[number];
/** The materialized view wiring opt_analytics_event -> opt_metric_daily. */
export const ANALYTICS_MATERIALIZED_VIEWS = ["opt_metric_daily_mv"] as const;
export const ANALYTICS_MATERIALIZED_VIEWS = ['opt_metric_daily_mv'] as const;
/**
* DDL, in dependency order. Every statement is CREATE ... IF NOT EXISTS so
@@ -163,7 +163,6 @@ export function analyticsSchemaDdl(opts: AnalyticsSchemaOptions): string[] {
*/
export function sortingKeySql(db: string, table: string): string {
return (
`SELECT sorting_key FROM system.tables ` +
`WHERE database = '${db}' AND name = '${table}' FORMAT TSV`
`SELECT sorting_key FROM system.tables ` + `WHERE database = '${db}' AND name = '${table}' FORMAT TSV`
);
}
+15 -12
View File
@@ -19,9 +19,9 @@
* (VehIQ) call an API in front of this interface; they never hold a provider
* credential and never construct an engine.
*/
import type { CompiledQuery, MetricAggregate } from "./query-compiler";
import type { AnalyticsTable } from "./schema";
import type { BudgetTier, ResourceBudget } from "./resource-governance";
import type { CompiledQuery, MetricAggregate } from './query-compiler';
import type { AnalyticsTable } from './schema';
import type { BudgetTier, ResourceBudget } from './resource-governance';
/**
* The VERIFIED caller. `tenant_id` here is the one the engine forces into
@@ -158,21 +158,24 @@ export interface SiaxAnalyticsEngine {
explain(identity: AnalyticsIdentity, request: MetricRequest): Promise<QueryExplanation>;
ingestProjection(identity: AnalyticsIdentity, request: ProjectionIngestRequest): Promise<{ ingested: number }>;
ingestProjection(
identity: AnalyticsIdentity,
request: ProjectionIngestRequest,
): Promise<{ ingested: number }>;
refreshProjection(identity: AnalyticsIdentity, dataset_id: string): Promise<ProjectionRefreshResult>;
}
/** The eight capability names, for the provider contract test. */
export const SIAX_ANALYTICS_ENGINE_CAPABILITIES = [
"health",
"executeMetric",
"executeQuery",
"estimateQuery",
"cancelQuery",
"explain",
"ingestProjection",
"refreshProjection",
'health',
'executeMetric',
'executeQuery',
'estimateQuery',
'cancelQuery',
'explain',
'ingestProjection',
'refreshProjection',
] as const;
export type SiaxAnalyticsEngineCapability = (typeof SIAX_ANALYTICS_ENGINE_CAPABILITIES)[number];
@@ -19,9 +19,9 @@
* Uses postgres.js through `RepositorySql`, the same connection type the other
* P0 repositories take (src/repositories/db.ts).
*/
import crypto from "node:crypto";
import { SiaxError } from "../../platform/errors";
import type { RepositorySql } from "../../repositories/db";
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { RepositorySql } from '../../repositories/db';
import type {
AnalyticsDataset,
DatasetVersion,
@@ -29,8 +29,8 @@ import type {
MetricDefinition,
MetricVersion,
PiiClassification,
} from "../domain/entities";
import type { AnalyticsTier } from "../domain/tiers";
} from '../domain/entities';
import type { AnalyticsTier } from '../domain/tiers';
/** The verified tenant scope every call must present. */
export interface TenantScope {
@@ -41,9 +41,9 @@ export interface TenantScope {
function assertScope(scope: TenantScope): void {
if (!scope?.tenant_id?.trim() || !scope?.project_id?.trim()) {
throw new SiaxError(
"UNAUTHENTICATED",
"0pt.analytics",
"analytics persistence requires a verified tenant_id + project_id",
'UNAUTHENTICATED',
'0pt.analytics',
'analytics persistence requires a verified tenant_id + project_id',
);
}
}
@@ -90,7 +90,7 @@ function toDataset(r: DatasetRow): AnalyticsDataset {
quality_rule_ids: r.quality_rule_ids ?? [],
retention_days: Number(r.retention_days),
classification: r.classification as PiiClassification,
status: r.status as AnalyticsDataset["status"],
status: r.status as AnalyticsDataset['status'],
...(r.raw_access_exception ? { raw_access_exception: r.raw_access_exception } : {}),
...(r.description ? { description: r.description } : {}),
created_at: iso(r.created_at)!,
@@ -104,7 +104,10 @@ export class AnalyticsDomainRepository {
// ── AnalyticsDataset ─────────────────────────────────────────────────────
async createDataset(scope: TenantScope, input: Omit<AnalyticsDataset, "tenant_id" | "project_id" | "created_at" | "updated_at">): Promise<AnalyticsDataset> {
async createDataset(
scope: TenantScope,
input: Omit<AnalyticsDataset, 'tenant_id' | 'project_id' | 'created_at' | 'updated_at'>,
): Promise<AnalyticsDataset> {
assertScope(scope);
const rows = await this.sql<DatasetRow[]>`
INSERT INTO opt_analytics_dataset
@@ -133,7 +136,10 @@ export class AnalyticsDomainRepository {
return rows[0] ? toDataset(rows[0]) : undefined;
}
async listDatasets(scope: TenantScope, filter?: { tier?: AnalyticsTier; status?: string }): Promise<AnalyticsDataset[]> {
async listDatasets(
scope: TenantScope,
filter?: { tier?: AnalyticsTier; status?: string },
): Promise<AnalyticsDataset[]> {
assertScope(scope);
const rows = await this.sql<DatasetRow[]>`
SELECT * FROM opt_analytics_dataset
@@ -155,14 +161,20 @@ export class AnalyticsDomainRepository {
*/
async createDatasetVersion(
scope: TenantScope,
input: { dataset_id: string; contract_hash: string; schema_contract_version: string; record_count?: number; created_by?: string },
input: {
dataset_id: string;
contract_hash: string;
schema_contract_version: string;
record_count?: number;
created_by?: string;
},
): Promise<DatasetVersion> {
assertScope(scope);
const owner = await this.getDataset(scope, input.dataset_id);
if (!owner) {
throw new SiaxError("NOT_FOUND", "0pt.analytics", "dataset not found in this tenant");
throw new SiaxError('NOT_FOUND', '0pt.analytics', 'dataset not found in this tenant');
}
const id = `dsv_${crypto.randomUUID().replace(/-/g, "")}`;
const id = `dsv_${crypto.randomUUID().replace(/-/g, '')}`;
try {
const rows = await this.sql<
{
@@ -202,8 +214,8 @@ export class AnalyticsDomainRepository {
...(r.created_by ? { created_by: r.created_by } : {}),
};
} catch (err) {
if (String(err).includes("duplicate key")) {
throw new SiaxError("CONFLICT", "0pt.analytics", "a concurrent writer minted this dataset version");
if (String(err).includes('duplicate key')) {
throw new SiaxError('CONFLICT', '0pt.analytics', 'a concurrent writer minted this dataset version');
}
throw err;
}
@@ -212,7 +224,18 @@ export class AnalyticsDomainRepository {
async listDatasetVersions(scope: TenantScope, datasetId: string): Promise<DatasetVersion[]> {
assertScope(scope);
const rows = await this.sql<
{ dataset_version_id: string; dataset_id: string; tenant_id: string; project_id: string; version: number; contract_hash: string; schema_contract_version: string; record_count: string | number | null; created_at: string | Date; created_by: string | null }[]
{
dataset_version_id: string;
dataset_id: string;
tenant_id: string;
project_id: string;
version: number;
contract_hash: string;
schema_contract_version: string;
record_count: string | number | null;
created_at: string | Date;
created_by: string | null;
}[]
>`
SELECT * FROM opt_analytics_dataset_version
WHERE dataset_id = ${datasetId}
@@ -237,11 +260,29 @@ export class AnalyticsDomainRepository {
async createMetric(
scope: TenantScope,
input: Omit<MetricDefinition, "tenant_id" | "project_id" | "created_at" | "updated_at" | "current_version">,
input: Omit<
MetricDefinition,
'tenant_id' | 'project_id' | 'created_at' | 'updated_at' | 'current_version'
>,
): Promise<MetricDefinition> {
assertScope(scope);
const rows = await this.sql<
{ metric_id: string; tenant_id: string; project_id: string; name: string; dataset_id: string; aggregation: string; measure_field: string; denominator_field: string | null; allowed_dimension_ids: string[]; current_version: number; owner_id: string; description: string | null; created_at: string | Date; updated_at: string | Date | null }[]
{
metric_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_id: string;
aggregation: string;
measure_field: string;
denominator_field: string | null;
allowed_dimension_ids: string[];
current_version: number;
owner_id: string;
description: string | null;
created_at: string | Date;
updated_at: string | Date | null;
}[]
>`
INSERT INTO opt_analytics_metric_definition
(metric_id, tenant_id, project_id, name, dataset_id, aggregation, measure_field,
@@ -258,7 +299,7 @@ export class AnalyticsDomainRepository {
project_id: r.project_id,
name: r.name,
dataset_id: r.dataset_id,
aggregation: r.aggregation as MetricDefinition["aggregation"],
aggregation: r.aggregation as MetricDefinition['aggregation'],
measure_field: r.measure_field,
...(r.denominator_field ? { denominator_field: r.denominator_field } : {}),
allowed_dimension_ids: r.allowed_dimension_ids ?? [],
@@ -276,10 +317,21 @@ export class AnalyticsDomainRepository {
input: { metric_id: string; definition_json: string; change_reason?: string; created_by?: string },
): Promise<MetricVersion> {
assertScope(scope);
const hash = crypto.createHash("sha256").update(input.definition_json).digest("hex");
const id = `mv_${crypto.randomUUID().replace(/-/g, "")}`;
const hash = crypto.createHash('sha256').update(input.definition_json).digest('hex');
const id = `mv_${crypto.randomUUID().replace(/-/g, '')}`;
const rows = await this.sql<
{ metric_version_id: string; metric_id: string; tenant_id: string; project_id: string; version: number; definition_json: string; definition_hash: string; change_reason: string | null; created_at: string | Date; created_by: string | null }[]
{
metric_version_id: string;
metric_id: string;
tenant_id: string;
project_id: string;
version: number;
definition_json: string;
definition_hash: string;
change_reason: string | null;
created_at: string | Date;
created_by: string | null;
}[]
>`
INSERT INTO opt_analytics_metric_version
(metric_version_id, metric_id, tenant_id, project_id, version, definition_json,
@@ -309,11 +361,22 @@ export class AnalyticsDomainRepository {
async createDimension(
scope: TenantScope,
input: Omit<DimensionDefinition, "tenant_id" | "project_id" | "created_at">,
input: Omit<DimensionDefinition, 'tenant_id' | 'project_id' | 'created_at'>,
): Promise<DimensionDefinition> {
assertScope(scope);
const rows = await this.sql<
{ dimension_id: string; tenant_id: string; project_id: string; name: string; dataset_id: string; field_name: string; field_type: string; classification: string; description: string | null; created_at: string | Date }[]
{
dimension_id: string;
tenant_id: string;
project_id: string;
name: string;
dataset_id: string;
field_name: string;
field_type: string;
classification: string;
description: string | null;
created_at: string | Date;
}[]
>`
INSERT INTO opt_analytics_dimension_definition
(dimension_id, tenant_id, project_id, name, dataset_id, field_name, field_type, classification, description)
@@ -329,7 +392,7 @@ export class AnalyticsDomainRepository {
name: r.name,
dataset_id: r.dataset_id,
field_name: r.field_name,
field_type: r.field_type as DimensionDefinition["field_type"],
field_type: r.field_type as DimensionDefinition['field_type'],
classification: r.classification as PiiClassification,
...(r.description ? { description: r.description } : {}),
created_at: iso(r.created_at)!,
+376
View File
@@ -0,0 +1,376 @@
/**
* src/analytics/sql/analyst-sql-session.ts
* =========================================
* BI-P017 — ANALYST SQL CONTRACT.
*
* "For privileged analyst role only. Implement separate AnalyticsSQLSession
* using Trino/read-only endpoints. Security: role-gated; query timeout;
* row/byte limits; read only; tenant/project catalogs; audit; statement
* history."
*
* SEPARATE is the operative word, and it is why this is its own class rather
* than a method on `SiaxAnalyticsEngine`. `executeMetric` has no raw-SQL
* surface at all; if analyst SQL lived on the same object, the closed DSL
* would be one refactor away from growing one. `ClickHouseAnalyticsEngine
* .executeQuery` stays a documented refusal.
*
* The four layers are described in statement-guard.ts. This class owns layers
* 1 (role) and the enforcement of every named limit; the guard is layer 2;
* tenant-catalog.ts renders layers 3 and 4.
*
* AUDIT AND STATEMENT HISTORY — the deliberate split, because BI-P017 requires
* statement history and BI-P018 requires NOT storing sensitive raw SQL:
*
* * the BI-P018 execution record stores a HASH of the compiled statement
* and nothing else;
* * the analyst statement history stores the NORMALIZED statement (every
* literal replaced by `?`) always — that is the searchable, non-PII form;
* * the RAW statement is retained only when `retainRawStatements` is on, and
* the entry is classified so a retention job can find it. It is on by
* default for analyst sessions, because a privileged human executing
* unreviewed SQL against tenant data is exactly the case where "who ran
* what" must survive, and a masked statement cannot answer it.
*
* A caller who needs the non-PII form gets `normalized`; nothing forces raw
* SQL into a downstream sink.
*/
import crypto from 'node:crypto';
import { SiaxError } from '../../platform/errors';
import type { AnalyticsIdentity } from '../engine/siax-analytics-engine';
import type { ResourceBudget } from '../engine/resource-governance';
import { applyQuota, BUDGET_TIERS, DEFAULT_BUDGETS } from '../engine/resource-governance';
import { guardAnalystStatement, type GuardedStatement } from './statement-guard';
/** The CL0UD role BI-P017 gates on. Verified upstream; never self-asserted. */
export const ANALYST_SQL_ROLE = 'analytics.sql.analyst';
/**
* An identity carrying CL0UD-verified roles. Roles are absent by default and
* absence is a denial — a session must never open because a field was missing.
*/
export interface AnalystIdentity extends AnalyticsIdentity {
roles?: readonly string[];
}
export interface AnalystStatementRecord {
statement_id: string;
tenant_id: string;
project_id?: string;
principal_id: string;
/** Literals masked. Always present. */
normalized: string;
/** Present only when the session retains raw statements. */
raw?: string;
statement_hash: string;
referenced_objects: string[];
submitted_at: string;
finished_at?: string;
duration_ms?: number;
rows_returned?: number;
bytes_read?: number;
rows_read?: number;
outcome: 'admitted' | 'refused' | 'succeeded' | 'failed' | 'cancelled';
/** SiaxErrorCode on refusal/failure. Never an engine body. */
error_code?: string;
/** Short operator-facing reason. Never echoes the statement. */
refusal_reason?: string;
correlation_id?: string;
}
/** Where the history goes. AUD0 is the system of record; this is the port. */
export interface AnalystAuditSink {
record(entry: AnalystStatementRecord): Promise<void> | void;
}
/** The read-only endpoint the session executes against. */
export interface ReadOnlySqlEndpoint {
/** "clickhouse" | "trino" — recorded on every execution. */
readonly engine: string;
/**
* Execute an ALREADY-GUARDED statement as the tenant's restricted user.
* The implementation must not add privileges, and must apply `settings`.
*/
execute(args: {
sql: string;
queryId: string;
settings: Record<string, string>;
signal: AbortSignal;
}): Promise<SqlEndpointResult>;
/** Stop a running statement server-side. Returns true when it is gone. */
cancel(queryId: string): Promise<boolean>;
}
export interface SqlEndpointResult {
columns: string[];
rows: unknown[][];
rows_read?: number;
bytes_read?: number;
}
export interface AnalystSqlSessionOptions {
identity: AnalystIdentity;
endpoint: ReadOnlySqlEndpoint;
/** The tenant's own catalog of pre-filtered views (BI-P017 layer 4). */
catalog: string;
/** Objects inside it the analyst may read. */
objects: readonly string[];
audit: AnalystAuditSink;
/**
* Budget tier. ANALYTICAL is the default for a human analyst; the tier is
* still only ever TIGHTENED by a CL0UD quota, never loosened (BI-P012).
*/
tier?: (typeof BUDGET_TIERS)[number];
retainRawStatements?: boolean;
/** Injected for deterministic tests. */
now?: () => number;
}
export interface AnalystQueryOutcome {
statement_id: string;
query_id: string;
columns: string[];
rows: unknown[][];
duration_ms: number;
rows_read?: number;
bytes_read?: number;
/** Objects the statement was permitted to read, as resolved by the guard. */
referenced_objects: string[];
truncated: boolean;
}
export class AnalyticsSQLSession {
private readonly identity: AnalystIdentity;
private readonly endpoint: ReadOnlySqlEndpoint;
private readonly catalog: string;
private readonly objects: readonly string[];
private readonly audit: AnalystAuditSink;
private readonly budget: ResourceBudget;
private readonly retainRaw: boolean;
private readonly now: () => number;
private readonly running = new Map<string, AbortController>();
private closed = false;
/**
* Opening a session is itself the role gate. A caller without the analyst
* role never obtains an object that can run SQL — as opposed to obtaining
* one whose methods happen to check a flag.
*/
constructor(opts: AnalystSqlSessionOptions) {
const id = opts.identity;
if (!id?.tenant_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics.sql',
'analyst SQL requires a verified tenant identity',
);
}
if (!id.principal_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics.sql',
'analyst SQL requires a verified principal',
);
}
const roles = id.roles ?? [];
if (!roles.includes(ANALYST_SQL_ROLE)) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.sql',
`analyst SQL requires the ${ANALYST_SQL_ROLE} role`,
);
}
if (opts.objects.length === 0) {
throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics.sql', 'session exposes no readable objects');
}
this.identity = id;
this.endpoint = opts.endpoint;
this.catalog = opts.catalog;
this.objects = opts.objects;
this.audit = opts.audit;
this.budget = applyQuota(DEFAULT_BUDGETS[opts.tier ?? 'ANALYTICAL'], id.quota);
this.retainRaw = opts.retainRawStatements ?? true;
this.now = opts.now ?? Date.now;
}
get resourceBudget(): ResourceBudget {
return { ...this.budget };
}
/**
* Guard a statement WITHOUT running it. Exposed so a UI can validate as the
* analyst types, and so the adversarial test corpus has a pure entry point.
*/
guard(sql: string): GuardedStatement {
return guardAnalystStatement(sql, { allowedCatalog: this.catalog, allowedObjects: this.objects });
}
async query(sql: string): Promise<AnalystQueryOutcome> {
if (this.closed) {
throw new SiaxError('CONFLICT', '0pt.analytics.sql', 'session is closed');
}
const statementId = crypto.randomUUID();
const submittedAt = new Date(this.now()).toISOString();
const base = {
statement_id: statementId,
tenant_id: this.identity.tenant_id,
project_id: this.identity.project_id,
principal_id: this.identity.principal_id,
correlation_id: this.identity.correlation_id,
submitted_at: submittedAt,
};
let guarded: GuardedStatement;
try {
guarded = this.guard(sql);
} catch (e) {
const err = e as SiaxError;
// A REFUSAL is audited as loudly as an execution. A guard whose
// rejections are invisible cannot be reviewed, and an analyst probing
// the boundary is exactly what an operator needs to see.
await this.audit.record({
...base,
normalized: safeNormalize(sql),
statement_hash: hashStatement(sql),
referenced_objects: [],
outcome: 'refused',
error_code: err.code ?? 'PERMANENT_FAILURE',
// `message` is already the sanitised "[CODE] source: detail" form; it
// never contains the caller's statement, only the guard's reason.
refusal_reason: err.message ?? 'refused',
});
throw e;
}
const queryId = this.newQueryId();
const controller = new AbortController();
this.running.set(queryId, controller);
const startedMs = this.now();
const record: AnalystStatementRecord = {
...base,
normalized: guarded.normalized,
...(this.retainRaw ? { raw: guarded.raw } : {}),
statement_hash: hashStatement(guarded.raw),
referenced_objects: guarded.referencedObjects,
outcome: 'admitted',
};
try {
const result = await this.endpoint.execute({
// The statement is passed THROUGH unchanged. This class does not
// rewrite SQL: a rewriter must be a correct parser of the dialect to
// be safe, and layers 3+4 do not need it to be one.
sql: guarded.raw,
queryId,
settings: this.executionSettings(),
signal: controller.signal,
});
const duration = this.now() - startedMs;
const truncated = result.rows.length >= this.budget.maxResultRows;
await this.audit.record({
...record,
outcome: 'succeeded',
finished_at: new Date(this.now()).toISOString(),
duration_ms: duration,
rows_returned: result.rows.length,
rows_read: result.rows_read,
bytes_read: result.bytes_read,
});
return {
statement_id: statementId,
query_id: queryId,
columns: result.columns,
rows: result.rows,
duration_ms: duration,
rows_read: result.rows_read,
bytes_read: result.bytes_read,
referenced_objects: guarded.referencedObjects,
truncated,
};
} catch (e) {
const err = e as SiaxError;
await this.audit.record({
...record,
outcome: controller.signal.aborted ? 'cancelled' : 'failed',
finished_at: new Date(this.now()).toISOString(),
duration_ms: this.now() - startedMs,
error_code: err.code ?? 'PERMANENT_FAILURE',
});
throw e;
} finally {
this.running.delete(queryId);
}
}
/** Cancel a statement this session started. Never another session's. */
async cancel(queryId: string): Promise<boolean> {
if (!queryId.startsWith(this.queryIdPrefix())) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.sql',
'statement does not belong to this session',
);
}
this.running.get(queryId)?.abort();
return this.endpoint.cancel(queryId);
}
/** Abort everything in flight. Idempotent. */
async close(): Promise<void> {
this.closed = true;
const ids = [...this.running.keys()];
for (const id of ids) {
this.running.get(id)?.abort();
try {
await this.endpoint.cancel(id);
} catch {
/* best effort; the abort already stopped us waiting */
}
this.running.delete(id);
}
}
/**
* Every limit BI-P017 names, as engine settings. `readonly` is `1`, not `2`:
* `readonly = 2` permits SETTINGS changes, which would let a statement raise
* its own ceilings.
*/
private executionSettings(): Record<string, string> {
return {
readonly: '1',
max_execution_time: String(this.budget.maxExecutionTimeSec),
timeout_overflow_mode: 'throw',
max_result_rows: String(this.budget.maxResultRows),
result_overflow_mode: 'throw',
max_rows_to_read: String(this.budget.maxRowsToRead),
max_bytes_to_read: String(this.budget.maxBytesToRead),
read_overflow_mode: 'throw',
max_memory_usage: String(this.budget.maxMemoryUsageBytes),
};
}
private queryIdPrefix(): string {
return `sql_${crypto.createHash('sha256').update(this.identity.tenant_id).digest('hex').slice(0, 12)}_`;
}
private newQueryId(): string {
return `${this.queryIdPrefix()}${crypto.randomUUID().replace(/-/g, '')}`;
}
}
export function hashStatement(sql: string): string {
return crypto.createHash('sha256').update(sql.trim()).digest('hex');
}
/**
* Mask literals in a statement that FAILED the guard, so a refusal can be
* audited without copying whatever the caller pasted. Best-effort by design:
* the statement did not parse cleanly, so neither will this.
*/
function safeNormalize(sql: string): string {
return sql
.replace(/'(?:[^'\\]|\\.|'')*'/g, '?')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 2000);
}
+499
View File
@@ -0,0 +1,499 @@
/**
* src/analytics/sql/statement-guard.ts
* =====================================
* BI-P017 — ANALYST SQL CONTRACT, layer 2 (statement admission).
*
* READ THIS BEFORE TRUSTING IT.
*
* This module is a GUARD, not a proof. It is the second of four layers, and
* it is the WEAKEST of the four, because it reasons about SQL text without
* being ClickHouse's parser. A guard that reads a dialect it does not
* implement can always be wrong about some string. The layers below it are
* the ones that hold when it is:
*
* 1. ROLE — only a CL0UD-verified analyst role reaches a session
* at all (analyst-sql-session.ts).
* 2. THIS GUARD — statement admission: one read-only statement, no
* banned construct, every table reference resolved
* into the tenant's own catalog.
* 3. GRANTS — the session authenticates as a per-tenant ClickHouse
* user with `readonly = 1` and SELECT granted ONLY on
* that tenant's catalog. A statement this guard wrongly
* admits still cannot read a table the user cannot see.
* 4. VIEW PREDICATE — the tenant catalog contains VIEWS, never base tables,
* and each view bakes `WHERE tenant_id = '<tenant>'`
* into its own definition. A row policy on the base
* tables repeats it server-side.
*
* tests/integration/analyst-sql-clickhouse.integration.test.ts runs the
* adversarial corpus against a live ClickHouse with layer 2 REMOVED, and
* requires layers 3 and 4 to refuse it anyway. A defence-in-depth claim that
* has never been tested with a layer removed is not evidence — this estate
* has shipped several.
*
* DESIGN NOTES that are load-bearing:
*
* * Identifiers must resolve to an ALLOW-LIST. The deny-lists below are a
* second opinion and a better error message, never the mechanism. Every
* table reference is checked positively against the tenant's catalog.
* * Outside string literals the statement must be ASCII. Homoglyph and
* zero-width tricks against keyword matching stop being expressible.
* * Comments and string literals are removed BEFORE any keyword scan, using
* ClickHouse's own lexical rules (`--` and `#` to end of line, `/* *\/`
* non-nesting, `'` with backslash and doubled-quote escapes, `"` and
* backtick as identifier quotes).
*/
import { SiaxError } from '../../platform/errors';
export interface StatementGuardOptions {
/**
* The ONLY database name a table reference may carry. This is the tenant's
* own catalog of pre-filtered views, not the shared analytics database.
*/
allowedCatalog: string;
/** Object names inside that catalog the analyst may read. */
allowedObjects: readonly string[];
/** Hard ceiling on statement length; a megabyte of SQL is an attack, not a query. */
maxLength?: number;
}
export interface GuardedStatement {
/** The statement as submitted, unchanged. */
raw: string;
/** Comments and literals removed — what the keyword scan actually saw. */
stripped: string;
/** Literals replaced by `?`, for statement history that is not a PII dump. */
normalized: string;
/** Fully-qualified objects the statement reads, resolved against the catalog. */
referencedObjects: string[];
/** Common-table-expression names defined by the statement itself. */
cteNames: string[];
}
const DEFAULT_MAX_LENGTH = 20_000;
/**
* Statement-level constructs that make a statement not-a-read. Matched as
* whole words against the stripped text.
*
* `SETTINGS` is here because a trailing `SETTINGS max_rows_to_read = …` is the
* obvious way to try to lift the governance ceiling from inside the query.
* `FORMAT` is here because the session appends its own; a caller-supplied one
* is either a duplicate or an attempt at `FORMAT ...` side effects.
*/
const BANNED_KEYWORDS = [
'insert',
'update',
'delete',
'drop',
'alter',
'create',
'truncate',
'rename',
'attach',
'detach',
'replace',
'optimize',
'grant',
'revoke',
'kill',
'system',
'use',
'set',
'settings',
'exchange',
'move',
'undrop',
'backup',
'restore',
'outfile',
'infile',
'format',
'watch',
'check',
'explain',
'show',
'exists',
'call',
'execute',
'declare',
'begin',
'commit',
'rollback',
] as const;
/**
* Functions that read something other than a table the grants control:
* the filesystem, the network, another server, a dictionary, an executable.
* ClickHouse table functions are the whole reason an analyst SQL surface is
* dangerous — `SELECT * FROM url('http://…')` needs no table privilege at all.
*/
const BANNED_FUNCTIONS = [
'file',
'url',
'urlcluster',
's3',
's3cluster',
'gcs',
'azureblobstorage',
'remote',
'remotesecure',
'cluster',
'clusterallreplicas',
'hdfs',
'hdfscluster',
'mysql',
'postgresql',
'mongodb',
'jdbc',
'odbc',
'sqlite',
'redis',
'deltalake',
'hudi',
'iceberg',
'executable',
'input',
'generaterandom',
'numbers_mt',
'merge',
'view',
'viewifpermitted',
'loop',
'fuzzjson',
'fuzzquery',
'dictget',
'dictgetordefault',
'dictgetornull',
'dictgetstring',
'dictgetuint64',
'dictgethierarchy',
'dictisin',
'dicthas',
'dictgetchildren',
'dictgetdescendants',
'filesystemavailable',
'filesystemfree',
'filesystemcapacity',
'currentdatabase',
'currentuser',
'hostname',
'fqdn',
'uptime',
'version',
'getsetting',
'getmacro',
'shardnum',
'shardcount',
'buildid',
'servertimezone',
'readwkt',
'structurefromjson',
's3queue',
'timeseries',
'mergetreeindex',
] as const;
/**
* Constructs that a whole-word keyword ban gets WRONG, so they get a pattern.
*
* `DESC` is the case that proves the point: banning the word breaks every
* `ORDER BY x DESC` an analyst will ever write, and the test corpus caught it
* immediately. What is actually dangerous is `DESCRIBE`/`DESC` used as a
* STATEMENT — including inside a subquery, where ClickHouse accepts
* `SELECT * FROM (DESCRIBE TABLE x)` and the FROM-scan sees only a `(`.
*/
const BANNED_PATTERNS: Array<{ re: RegExp; reason: string }> = [
{ re: /\bdesc(ribe)?\s+(table|\()/i, reason: 'DESCRIBE is not permitted in a read-only analyst session' },
{ re: /\bcurrent_user\b/i, reason: 'CURRENT_USER is not permitted in an analyst session' },
{ re: /\binto\s+outfile\b/i, reason: 'INTO OUTFILE is not permitted in an analyst session' },
];
/** Names that are catalogs an analyst may never reach, whatever the grants say. */
const BANNED_CATALOGS = [
'system',
'information_schema',
'INFORMATION_SCHEMA',
'default',
'opt_analytics',
'opt_scraped',
];
const IDENT = '[A-Za-z_][A-Za-z0-9_]*';
const QUALIFIED_RE = new RegExp(`^${IDENT}\\.${IDENT}$`);
function deny(detail: string): never {
throw new SiaxError('AUTHORIZATION_DENIED', '0pt.analytics.sql', detail);
}
function invalid(detail: string): never {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.sql', detail);
}
interface StripResult {
stripped: string;
normalized: string;
/** Identifier tokens that were quoted, kept so they can still be resolved. */
hadQuotedIdentifier: boolean;
}
/**
* Remove comments and string literals using ClickHouse's lexical rules.
*
* Two outputs, deliberately: `stripped` keeps the literal DELIMITERS so the
* token stream still parses (`'x'` becomes `''`), and `normalized` replaces
* each literal with `?` so a statement history is searchable without being a
* copy of the tenant's data.
*
* An unterminated literal or comment is a REJECTION. Silently treating the
* rest of the statement as a string is exactly how a guard and an engine come
* to disagree about where the query ends.
*/
export function stripSqlText(sql: string): StripResult {
let stripped = '';
let normalized = '';
let hadQuotedIdentifier = false;
let i = 0;
const n = sql.length;
while (i < n) {
const c = sql[i];
const next = sql[i + 1];
// -- line comment
if (c === '-' && next === '-') {
while (i < n && sql[i] !== '\n') i += 1;
stripped += ' ';
normalized += ' ';
continue;
}
// # line comment (ClickHouse accepts `#` and `#!`)
if (c === '#') {
while (i < n && sql[i] !== '\n') i += 1;
stripped += ' ';
normalized += ' ';
continue;
}
// /* block comment */ — ClickHouse does NOT nest these
if (c === '/' && next === '*') {
const end = sql.indexOf('*/', i + 2);
if (end === -1) invalid('unterminated block comment');
i = end + 2;
stripped += ' ';
normalized += ' ';
continue;
}
// 'string literal'
if (c === "'") {
i += 1;
while (i < n) {
if (sql[i] === '\\') {
i += 2;
continue;
}
if (sql[i] === "'") {
if (sql[i + 1] === "'") {
i += 2;
continue;
}
break;
}
i += 1;
}
if (i >= n) invalid('unterminated string literal');
i += 1; // closing quote
stripped += "''";
normalized += '?';
continue;
}
// "quoted identifier" / `quoted identifier`
if (c === '"' || c === '`') {
const quote = c;
let ident = '';
i += 1;
while (i < n) {
if (sql[i] === '\\') {
ident += sql[i + 1] ?? '';
i += 2;
continue;
}
if (sql[i] === quote) {
if (sql[i + 1] === quote) {
ident += quote;
i += 2;
continue;
}
break;
}
ident += sql[i];
i += 1;
}
if (i >= n) invalid('unterminated quoted identifier');
i += 1;
hadQuotedIdentifier = true;
// The identifier is put back UNQUOTED so the table-reference scan sees
// it exactly as it would see a bare one. A quoted identifier that does
// not survive that scan is refused like any other.
if (!new RegExp(`^${IDENT}$`).test(ident)) {
deny(`quoted identifier "${ident.slice(0, 32)}" is not a plain name`);
}
stripped += ident;
normalized += ident;
continue;
}
stripped += c;
normalized += c;
i += 1;
}
return { stripped, normalized, hadQuotedIdentifier };
}
/**
* Admit a statement, or refuse it.
*
* Returns the parsed view of what was admitted; the caller (the session) is
* responsible for actually running it under the restricted user.
*/
export function guardAnalystStatement(sql: string, opts: StatementGuardOptions): GuardedStatement {
const maxLength = opts.maxLength ?? DEFAULT_MAX_LENGTH;
if (typeof sql !== 'string') invalid('statement must be a string');
const raw = sql.trim();
if (!raw) invalid('statement is empty');
if (raw.length > maxLength) invalid(`statement exceeds ${maxLength} characters`);
if (!opts.allowedCatalog || !new RegExp(`^${IDENT}$`).test(opts.allowedCatalog)) {
// A misconfigured session must not degrade to "any catalog".
deny('session has no valid tenant catalog');
}
if (BANNED_CATALOGS.includes(opts.allowedCatalog)) {
deny(`session catalog "${opts.allowedCatalog}" is a reserved catalog`);
}
if (opts.allowedObjects.length === 0) {
deny('session exposes no readable objects');
}
const { stripped, normalized } = stripSqlText(raw);
// ── ASCII-only outside literals ────────────────────────────────────────
// Homoglyphs, zero-width joiners and RTL overrides stop being expressible
// against the keyword scan. Values are unaffected: they live in literals,
// which have already been removed at this point.
const nonAscii = /[^\x09\x0a\x0d\x20-\x7e]/.exec(stripped);
if (nonAscii) {
deny(
`statement contains a non-ASCII character (U+${nonAscii[0].codePointAt(0)?.toString(16).padStart(4, '0')}) outside a string literal`,
);
}
if (stripped.includes('\0')) deny('statement contains a NUL byte');
// ── exactly one statement ──────────────────────────────────────────────
const withoutTrailingSemi = stripped.replace(/;\s*$/, '');
if (withoutTrailingSemi.includes(';')) {
deny('multiple statements are not allowed in an analyst SQL session');
}
const lower = ` ${withoutTrailingSemi.toLowerCase().replace(/\s+/g, ' ').trim()} `;
// ── must be a read ─────────────────────────────────────────────────────
if (!/^\s*(select|with)\b/i.test(withoutTrailingSemi.trim())) {
deny('analyst SQL sessions accept SELECT and WITH statements only');
}
for (const kw of BANNED_KEYWORDS) {
if (new RegExp(`(^|[^A-Za-z0-9_])${kw}([^A-Za-z0-9_]|$)`).test(lower)) {
deny(`"${kw.toUpperCase()}" is not permitted in a read-only analyst session`);
}
}
for (const { re, reason } of BANNED_PATTERNS) {
if (re.test(lower)) deny(reason);
}
// ── banned functions, matched as `name(` ───────────────────────────────
const calls = [...lower.matchAll(new RegExp(`([a-z_][a-z0-9_]*)\\s*\\(`, 'g'))].map((m) => m[1]);
for (const call of calls) {
if ((BANNED_FUNCTIONS as readonly string[]).includes(call)) {
deny(`function "${call}" is not permitted in an analyst session`);
}
}
// ── table references: positively resolved against the catalog ──────────
const cteNames = collectCteNames(withoutTrailingSemi);
const referencedObjects = collectTableReferences(withoutTrailingSemi, cteNames, opts);
if (referencedObjects.length === 0) {
// A SELECT with no FROM (`SELECT 1`) is harmless, but so is refusing it,
// and "no table reference" is also what a successful parser evasion looks
// like. Refuse: an analyst session exists to read tables.
deny('statement references no readable object in the tenant catalog');
}
return { raw, stripped, normalized, referencedObjects, cteNames };
}
/** `WITH x AS (…), y AS (…)` — names the statement defines for itself. */
function collectCteNames(stripped: string): string[] {
const names: string[] = [];
const re = new RegExp(`(?:^|[,\\s(])(${IDENT})\\s+as\\s*\\(`, 'gi');
for (const m of stripped.matchAll(re)) names.push(m[1].toLowerCase());
return names;
}
/**
* Every `FROM` / `JOIN` target, resolved.
*
* Rules, all fail-closed:
* * `(` after FROM/JOIN is a subquery — fine, its own FROM is scanned too.
* * `name(` after FROM/JOIN is a TABLE FUNCTION — refused outright, even if
* the name is not on the deny-list, because an unknown table function is
* precisely the case the deny-list cannot cover.
* * a bare `name` must be a CTE this statement defined.
* * a `db.name` must have `db === allowedCatalog` and `name` in the
* allow-list. Three-part `a.b.c` names are refused.
*/
function collectTableReferences(stripped: string, cteNames: string[], opts: StatementGuardOptions): string[] {
const allowed = new Set(opts.allowedObjects.map((o) => o.toLowerCase()));
const ctes = new Set(cteNames);
const found = new Set<string>();
const re = /(^|[^A-Za-z0-9_])(from|join)([^A-Za-z0-9_]|$)/gi;
let m: RegExpExecArray | null;
while ((m = re.exec(stripped)) !== null) {
const after = stripped.slice(m.index + m[0].length - 1);
const target = /^\s*([A-Za-z_][A-Za-z0-9_.]*|\()/.exec(after);
if (!target) deny('could not resolve a FROM/JOIN target');
const token = target[1];
if (token === '(') continue; // subquery; its own FROM is scanned by this loop
const rest = after.slice(target[0].length);
if (/^\s*\(/.test(rest)) {
deny(`table function "${token}" is not permitted in an analyst session`);
}
const parts = token.split('.');
if (parts.length === 1) {
if (!ctes.has(parts[0].toLowerCase())) {
deny(
`unqualified table "${parts[0]}" — an analyst statement must name ` +
`${opts.allowedCatalog}.<object>, or a CTE it defined itself`,
);
}
continue;
}
if (parts.length !== 2 || !QUALIFIED_RE.test(token)) {
deny(`"${token}" is not a valid <catalog>.<object> reference`);
}
const [catalog, object] = parts;
if (catalog.toLowerCase() !== opts.allowedCatalog.toLowerCase()) {
deny(`catalog "${catalog}" is not readable by this session`);
}
if (!allowed.has(object.toLowerCase())) {
deny(`object "${catalog}.${object}" is not readable by this session`);
}
found.add(`${catalog}.${object}`);
}
return [...found];
}
/** Exported for the test corpus and for operator documentation. */
export const GUARD_BANNED_KEYWORDS = BANNED_KEYWORDS;
export const GUARD_BANNED_FUNCTIONS = BANNED_FUNCTIONS;
+238
View File
@@ -0,0 +1,238 @@
/**
* src/analytics/sql/tenant-catalog.ts
* ====================================
* BI-P017 — ANALYST SQL CONTRACT, layers 3 and 4.
*
* The analyst never touches a base table. Each tenant gets its OWN ClickHouse
* database containing nothing but VIEWS, and every view has the BI-P011 forced
* predicate baked into its own definition:
*
* CREATE VIEW t_alpha_sql.opt_analytics_event AS
* SELECT … FROM opt_analytics.opt_analytics_event
* WHERE tenant_id = 't_alpha'
*
* That is the difference between "the guard rewrites your SQL to add a WHERE"
* (fragile — it depends on the guard being a correct SQL parser) and "there is
* no unfiltered object in reach" (structural — it depends only on the grants).
*
* The session's ClickHouse user is created with `readonly = 1` and is granted
* SELECT on that database ALONE. `GRANT SELECT ON opt_analytics.*` is never
* issued, so a statement the guard wrongly admits still cannot read the base
* table: ClickHouse answers "Not enough privileges", not rows.
*
* The `tenant_id` column is deliberately DROPPED from the view projection.
* An analyst cannot filter on, group by, or select a column that does not
* exist in the object they can see — which removes the whole class of
* "predicate on tenant_id looks legitimate" confusion from the audit trail.
*/
import { SiaxError } from '../../platform/errors';
import { assertSafeIdentifier } from '../engine/query-compiler';
import type { ResourceBudget } from '../engine/resource-governance';
export interface TenantSqlCatalogSpec {
/** Shared analytics database holding the base tables. */
sourceDatabase: string;
/** Verified tenant id. Embedded as a literal — validated strictly first. */
tenantId: string;
/** The tenant's own catalog name, e.g. `t_alpha_sql`. */
catalog: string;
/** Base tables to expose, with the columns each view projects. */
objects: ReadonlyArray<{ table: string; columns: readonly string[] }>;
}
export interface TenantSqlUserSpec extends TenantSqlCatalogSpec {
userName: string;
/** From a secret ref. Never a literal in code, never logged. */
password: string;
/**
* BI-P012 ceilings. MEASURED CONSTRAINT, not a style choice: a ClickHouse
* user whose profile carries `readonly = 1` cannot have ANY setting changed
* from the request — the server answers
*
* Code: 164. Cannot modify 'max_rows_to_read' setting in readonly mode.
*
* (measured on 24.8.14.39; see evidence/bi-p017/). So the ceilings cannot be
* client-supplied per request the way `clickhouseSettings()` supplies them
* for the non-readonly engine user. They must be baked into the user's
* SETTINGS PROFILE at provisioning time.
*
* That is strictly BETTER: the ceiling no longer depends on the client
* remembering to send it, and the same `readonly = 1` that forbids raising
* it also forbids lowering it or turning it off.
*/
budget?: ResourceBudget;
/** Explicit profile name; defaults to `<userName>_profile`. */
settingsProfile?: string;
}
const TENANT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
function assertTenantId(tenantId: string): string {
if (!TENANT_ID_RE.test(tenantId)) {
// ClickHouse view definitions take no bound parameters, so validation is
// the only protection available here and it is applied strictly.
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.sql', 'tenant id is not catalog-safe');
}
return tenantId;
}
/**
* DDL creating the tenant's read-only catalog of pre-filtered views.
* Idempotent; safe to re-run on every deploy.
*/
export function tenantSqlCatalogDdl(spec: TenantSqlCatalogSpec): string[] {
assertSafeIdentifier(spec.sourceDatabase, 'database');
assertSafeIdentifier(spec.catalog, 'catalog');
assertTenantId(spec.tenantId);
if (spec.catalog === spec.sourceDatabase) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.sql',
'tenant catalog must not be the source database',
);
}
const stmts: string[] = [`CREATE DATABASE IF NOT EXISTS ${spec.catalog}`];
for (const obj of spec.objects) {
assertSafeIdentifier(obj.table, 'table');
if (obj.columns.length === 0) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.sql', `view ${obj.table} projects no columns`);
}
for (const col of obj.columns) {
assertSafeIdentifier(col, 'column');
if (col === 'tenant_id') {
// Not an oversight to guard against — a deliberate refusal. Exposing
// tenant_id inside a single-tenant view invites a reader to believe
// filtering on it means something.
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.sql',
'tenant_id must not be projected into a tenant SQL view',
);
}
}
stmts.push(
`CREATE OR REPLACE VIEW ${spec.catalog}.${obj.table} AS ` +
`SELECT ${obj.columns.join(', ')} FROM ${spec.sourceDatabase}.${obj.table} ` +
`WHERE tenant_id = '${spec.tenantId}'`,
);
}
return stmts;
}
/**
* DDL for the session's ClickHouse user.
*
* Every line here is a layer-3 control:
* * `readonly = 1` — no writes AND no settings changes from inside a query,
* which is what stops `SETTINGS max_rows_to_read = …` lifting the ceiling.
* * `allow_ddl = 0` — belt to readonly's braces.
* * SELECT granted on the tenant catalog ONLY. The base database is never
* granted, so a guard bypass hits a privilege error.
* * A row policy on the BASE tables as well, so even a mistaken grant, or a
* view accidentally created without its predicate, still filters.
*/
export function tenantSqlUserDdl(spec: TenantSqlUserSpec): string[] {
assertSafeIdentifier(spec.userName, 'user');
assertSafeIdentifier(spec.catalog, 'catalog');
assertSafeIdentifier(spec.sourceDatabase, 'database');
assertTenantId(spec.tenantId);
if (spec.password.includes("'") || spec.password.includes('\\')) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.sql',
'password contains characters that cannot be embedded',
);
}
if (spec.settingsProfile) assertSafeIdentifier(spec.settingsProfile, 'settings profile');
const profileName = spec.settingsProfile ?? `${spec.userName}_profile`;
assertSafeIdentifier(profileName, 'settings profile');
const stmts: string[] = [];
if (spec.budget) {
// Every BI-P012 ceiling, plus the overflow modes. `throw` is explicit
// because ClickHouse's default for some of these is `break`, which returns
// a PARTIAL result that looks complete — the analytics equivalent of a
// false green.
// `OR REPLACE`, for the same measured reason as the row policy below:
// `CREATE SETTINGS PROFILE IF NOT EXISTS` is a silent no-op when the
// profile already exists, so a CHANGED budget never lands. Found the hard
// way — a re-provisioning run kept a stale 60-row ceiling and starved
// every legitimate analyst statement in the integration suite, while the
// provisioning DDL reported success on every statement.
stmts.push(
`CREATE SETTINGS PROFILE OR REPLACE ${profileName} SETTINGS ` +
`max_execution_time = ${spec.budget.maxExecutionTimeSec}, ` +
`timeout_overflow_mode = 'throw', ` +
`max_result_rows = ${spec.budget.maxResultRows}, ` +
`result_overflow_mode = 'throw', ` +
`max_rows_to_read = ${spec.budget.maxRowsToRead}, ` +
`max_bytes_to_read = ${spec.budget.maxBytesToRead}, ` +
`read_overflow_mode = 'throw', ` +
`max_memory_usage = ${spec.budget.maxMemoryUsageBytes}, ` +
`readonly = 1`,
);
}
const settings = spec.budget ? `SETTINGS PROFILE ${profileName}` : `SETTINGS readonly = 1, allow_ddl = 0`;
stmts.push(
`CREATE USER IF NOT EXISTS ${spec.userName} IDENTIFIED WITH sha256_password BY '${spec.password}' ${settings}`,
);
// Re-applied on every provisioning run so a rotated budget actually lands on
// an already-existing user; CREATE USER IF NOT EXISTS would silently skip it.
stmts.push(`ALTER USER ${spec.userName} ${settings}`);
stmts.push(`GRANT SELECT ON ${spec.catalog}.* TO ${spec.userName}`);
for (const obj of spec.objects) {
assertSafeIdentifier(obj.table, 'table');
// A view reads its source with the DEFINER's rights in ClickHouse only for
// parameterised/materialised cases; for a plain view the reader still needs
// SELECT on the source. Grant it on the SOURCE TABLE and pin a row policy
// to it, so the grant can never be wider than the tenant.
stmts.push(`GRANT SELECT ON ${spec.sourceDatabase}.${obj.table} TO ${spec.userName}`);
// `OR REPLACE`, never `IF NOT EXISTS`. MEASURED FAILURE, found by a test
// that attempted the bypass:
//
// Dropping and re-creating the user empties the policy's apply-to list
// (ClickHouse removes the dropped user from it). On the next
// provisioning run `CREATE ROW POLICY IF NOT EXISTS` sees the policy
// already exists and does NOTHING — so the policy survives with
// `apply_to_list = []`, applying to nobody, while `system.row_policies`
// still shows the right `select_filter`. An operator reading that table
// sees a policy protecting `opt_analytics.sales` and is wrong: the
// restricted user read 100 rows of 100, both tenants.
//
// This is the "green check that does not gate" shape. `OR REPLACE` makes
// provisioning idempotent in the way that was intended, and
// `rowPolicyVerificationSql` below turns "the policy is applied" from an
// assumption into a query.
stmts.push(
`CREATE ROW POLICY OR REPLACE ${spec.userName}_${obj.table}_rp ON ${spec.sourceDatabase}.${obj.table} ` +
`AS restrictive FOR SELECT USING tenant_id = '${spec.tenantId}' TO ${spec.userName}`,
);
}
return stmts;
}
/**
* The query that PROVES the row policies landed, rather than assuming it.
*
* Returns one row per (table, policy) with `applied_to_user` — which must be
* 1 for every object. Run it after provisioning and fail the deploy if any
* row reads 0; a policy with an empty apply-to list is indistinguishable from
* a working one in `SHOW ROW POLICIES`.
*/
export function rowPolicyVerificationSql(spec: TenantSqlUserSpec): string {
assertSafeIdentifier(spec.userName, 'user');
assertSafeIdentifier(spec.sourceDatabase, 'database');
assertTenantId(spec.tenantId);
return (
`SELECT table, short_name, has(apply_to_list, '${spec.userName}') AS applied_to_user, select_filter ` +
`FROM system.row_policies WHERE database = '${spec.sourceDatabase}' ` +
`AND short_name LIKE '${spec.userName}%' FORMAT JSON`
);
}
/** Object names the guard's allow-list is built from. */
export function catalogObjectNames(spec: TenantSqlCatalogSpec): string[] {
return spec.objects.map((o) => o.table);
}