Files
0pt/tests/analytics/analyst-sql-evidence.test.ts
Claude Opus 5 d9c8f7190b
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
feat(analytics): BI-P017 — analyst SQL contract, proven against live ClickHouse with the guard removed
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>
2026-09-07 02:17:07 +02:00

109 lines
4.8 KiB
TypeScript

/**
* tests/analytics/analyst-sql-evidence.test.ts
* =============================================
* BI-P017 — the test that does NOT skip.
*
* The live suite (tests/integration/analyst-sql-clickhouse.integration.test.ts)
* only runs when `CLICKHOUSE_URL` is set. On a runner without ClickHouse it
* contributes nothing, and a suite that contributes nothing while reporting
* green is how l0re's 28 Postgres tests stayed silently skipped for months.
*
* So the live run WRITES its result to
* `evidence/bi-p017/analyst-sql-live-bypass.json`, that file is committed, and
* this test — which always runs — checks it against the corpus:
*
* * every attempt in the corpus must appear in the evidence, so adding an
* attack without re-running the live suite BREAKS THE BUILD rather than
* quietly going untested;
* * zero attempts may have leaked;
* * the legitimate statements must all have succeeded, so the evidence
* cannot be a recording of a database that refuses everything;
* * the counterfactual numbers must be present, so the evidence cannot be a
* recording of an EMPTY database, where "no foreign row came back" is
* true and meaningless.
*/
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { BYPASS_CORPUS, GUARD_ADMITS_ENGINE_REFUSES, LEGITIMATE_CORPUS } from './analyst-sql-bypass-corpus';
const EVIDENCE_PATH = path.join(process.cwd(), 'evidence/bi-p017/analyst-sql-live-bypass.json');
interface Evidence {
clickhouse_version: string;
recorded_at: string;
base_table_rows_both_tenants: number;
tenant_view_rows_alpha: number;
attempts_total: number;
attempts_that_leaked: number;
legitimate_statements_that_succeeded: number;
legitimate_statements_total: number;
attempts: Array<{
id: string;
engine_http_status: number;
engine_succeeded: boolean;
leaked_foreign_tenant_row: boolean;
leaked_ungranted_table_row: boolean;
leaked_server_metadata: boolean;
guard_verdict_for_reference: string;
}>;
legitimate: Array<{ id: string; ok: boolean; contains_beta_canary: boolean }>;
}
describe('BI-P017 — the committed live evidence covers the current corpus', () => {
it('the evidence file exists', () => {
expect(
fs.existsSync(EVIDENCE_PATH),
'evidence/bi-p017/analyst-sql-live-bypass.json is missing — run the live suite with CLICKHOUSE_URL set',
).toBe(true);
});
const evidence: Evidence = fs.existsSync(EVIDENCE_PATH)
? (JSON.parse(fs.readFileSync(EVIDENCE_PATH, 'utf8')) as Evidence)
: ({ attempts: [], legitimate: [] } as unknown as Evidence);
it('was recorded against a real ClickHouse, named by version', () => {
expect(evidence.clickhouse_version).toMatch(/^\d+\.\d+/);
expect(Date.parse(evidence.recorded_at)).toBeGreaterThan(0);
});
it("records the counterfactual, so 'nothing leaked' is not a statement about an empty database", () => {
expect(evidence.base_table_rows_both_tenants).toBe(100);
expect(evidence.tenant_view_rows_alpha).toBe(50);
});
it('covers EVERY attempt in the corpus — a new attack without a re-run fails here', () => {
const recorded = new Set(evidence.attempts.map((a) => a.id));
const missing = [...BYPASS_CORPUS, ...GUARD_ADMITS_ENGINE_REFUSES]
.map((a) => a.id)
.filter((id) => !recorded.has(id));
expect(missing, `attempts never run against a live engine: ${missing.join(', ')}`).toEqual([]);
expect(evidence.attempts_total).toBe(BYPASS_CORPUS.length + GUARD_ADMITS_ENGINE_REFUSES.length);
});
it('no attempt leaked a foreign-tenant row, an ungranted row, or a foreign object name', () => {
const leaked = evidence.attempts.filter(
(a) => a.leaked_foreign_tenant_row || a.leaked_ungranted_table_row || a.leaked_server_metadata,
);
expect(leaked.map((a) => a.id)).toEqual([]);
expect(evidence.attempts_that_leaked).toBe(0);
});
it('records which attempts the ENGINE alone stopped, with the guard removed', () => {
// The interesting number: attempts that the guard would have admitted and
// the engine refused anyway. If it were zero, the layered claim would rest
// entirely on the guard.
const engineOnly = evidence.attempts.filter((a) => a.guard_verdict_for_reference === 'admitted');
expect(engineOnly.length).toBeGreaterThan(0);
for (const a of engineOnly) {
expect(a.engine_succeeded, `${a.id} was admitted by the guard AND succeeded at the engine`).toBe(false);
}
});
it('legitimate analyst work succeeded — the evidence is not a recording of a database that refuses everything', () => {
expect(evidence.legitimate_statements_total).toBe(LEGITIMATE_CORPUS.length);
expect(evidence.legitimate_statements_that_succeeded).toBe(LEGITIMATE_CORPUS.length);
expect(evidence.legitimate.every((l) => l.contains_beta_canary === false)).toBe(true);
});
});