fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
+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);
}
+516
View File
@@ -0,0 +1,516 @@
/**
* 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.
* * The FROM/JOIN scan is CONSERVATIVE where it is unsure, and that costs
* something worth naming: ClickHouse's `ARRAY JOIN arr` is a legitimate
* construct whose target is a COLUMN, not a table, and this guard refuses
* it because the token after JOIN is neither a CTE nor a qualified object.
* A false refusal an analyst can see and report is the right side of that
* trade; a false ADMISSION is not. Supporting it means teaching the scan
* which JOIN flavours take a non-table target, which is the direction that
* grows holes, so it stays refused until someone needs it and can add it
* WITH a corpus entry proving the narrowing did not open anything else.
* * 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.
// Written as a code-point scan rather than a character class: a regex of
// control characters is unreadable, trips `no-control-regex`, and is the
// kind of expression a reviewer nods at without checking. Permitted: tab,
// LF, CR and printable ASCII. Everything else, NUL included, is refused.
for (let i = 0; i < stripped.length; i += 1) {
const code = stripped.charCodeAt(i);
const printable = code >= 0x20 && code <= 0x7e;
const allowedWhitespace = code === 0x09 || code === 0x0a || code === 0x0d;
if (!printable && !allowedWhitespace) {
deny(
`statement contains a disallowed character (U+${code.toString(16).toUpperCase().padStart(4, '0')}) ` +
`outside a string literal`,
);
}
}
// ── 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);
}