/** * 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 `_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); }