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 <[email protected]>
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
+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);
}