Files
0pt/tests/analytics/query-compiler-injection.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

227 lines
7.3 KiB
TypeScript

/**
* BI-P011's adversarial list, at the compiler layer:
*
* tenant A query B dataset · tenant A forged dataset ID · raw SQL attempt
* SQL injection · dimension identifier injection · filter injection
*
* These are the cases that never reach the network. The cases that DO reach a
* real server — and the with-fix/without-fix proof BI-P011 actually demands —
* are tests/integration/analytics-tenant-isolation.integration.test.ts.
*/
import { describe, it, expect } from 'vitest';
import {
assertSafeIdentifier,
compileMetricQuery,
compileProjectionQuery,
dimensionCatalogFrom,
restrictedTenantUserDdl,
} from '@/src/analytics/engine/query-compiler';
const catalog = dimensionCatalogFrom({ severity: 'severity', make: 'vehicle_make' });
const HOSTILE = [
"x'; DROP TABLE opt_analytics_event; --",
'1 OR 1=1',
'tenant_id',
'*/ OR 1=1 /*',
'severity UNION ALL SELECT tenant_id FROM opt_analytics_event',
'dim_values[1]',
'__proto__',
'constructor',
'sever ity',
'sévérité',
'a'.repeat(200),
'',
];
describe('BI-P011 injection surfaces at the compiler', () => {
it('dimension identifier injection: hostile group_by names are refused, not escaped', () => {
for (const bad of HOSTILE) {
expect(
() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', group_by: [bad] },
'opt_analytics',
catalog,
1000,
),
`group_by "${bad}" was not refused`,
).toThrowError(/unknown group_by dimension/);
}
});
it('filter injection: hostile filter KEYS are refused by catalog resolution', () => {
for (const bad of HOSTILE) {
expect(
() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', filters: { [bad]: 'v' } },
'opt_analytics',
catalog,
1000,
),
`filter key "${bad}" was not refused`,
).toThrowError(/unknown filter dimension/);
}
});
it('prototype-chain keys resolve to undefined rather than to Object.prototype members', () => {
// A naive `catalog[name]` lookup would resolve "constructor" to a
// function and "toString" to a method; the Map-based catalog must not.
for (const key of ['constructor', 'toString', 'hasOwnProperty', '__proto__', 'valueOf']) {
expect(catalog.resolve(key)).toBeUndefined();
}
});
it('filter VALUES are never spliced, however hostile', () => {
const compiled = compileMetricQuery(
{
tenant_id: 't_alpha',
metric: 'm',
aggregate: 'sum',
filters: { make: "volvo'; DROP TABLE opt_analytics_event; --" },
},
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toContain('DROP TABLE');
expect(compiled.sql).not.toContain('volvo');
expect(compiled.params.param_f0v).toBe("volvo'; DROP TABLE opt_analytics_event; --");
// The physical column name came from the catalog, not the caller.
expect(compiled.params.param_f0n).toBe('vehicle_make');
});
it('metric and dataset VALUES are never spliced either', () => {
const compiled = compileMetricQuery(
{
tenant_id: 't_alpha',
metric: "m'; SELECT 1; --",
dataset_id: "ds'; SELECT 1; --",
aggregate: 'sum',
},
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toContain('SELECT 1');
expect(compiled.sql.match(/SELECT/g)).toHaveLength(1);
});
it('raw SQL attempt: there is no request shape that reaches a second table', () => {
const compiled = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum' },
'opt_analytics',
catalog,
1000,
);
expect(compiled.sql).not.toMatch(/\bUNION\b/i);
expect(compiled.sql).not.toMatch(/\bJOIN\b/i);
expect((compiled.sql.match(/\bFROM\b/gi) ?? []).length).toBe(1);
expect(compiled.table).toBe('opt_analytics_event');
});
it('a forged table name is refused rather than reaching the FROM clause', () => {
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', table: 'system.tables' as never },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/invalid table identifier/);
});
it('an unsupported aggregate is refused rather than being interpolated', () => {
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum(1),tenant_id' as never },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/unsupported aggregate/);
});
it('group-by cardinality is capped so a caller cannot explode the GROUP BY', () => {
const many = Array.from({ length: 9 }, () => 'severity');
expect(() =>
compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', group_by: many },
'opt_analytics',
catalog,
1000,
),
).toThrowError(/at most 8 group-by/);
});
it('LIMIT is clamped to the governance ceiling, and never below 1', () => {
const big = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', limit: 10_000_000 },
'opt_analytics',
catalog,
500,
);
expect(big.sql).toContain('LIMIT 500');
const zero = compileMetricQuery(
{ tenant_id: 't_alpha', metric: 'm', aggregate: 'sum', limit: 0 },
'opt_analytics',
catalog,
500,
);
expect(zero.sql).toContain('LIMIT 1');
});
it('the projection compiler forces the tenant and parameterizes entity keys', () => {
const compiled = compileProjectionQuery(
{ tenant_id: 't_alpha', dataset_id: 'ds_x', entity_keys: ["a'; DROP", 'b'] },
'opt_analytics',
100,
);
expect(compiled.sql).toMatch(/WHERE tenant_id = \{tenant:String\}/);
expect(compiled.sql).not.toContain('DROP');
expect(compiled.params.param_entityKeys).toBe(JSON.stringify(["a'; DROP", 'b']));
});
it('assertSafeIdentifier accepts real identifiers and rejects everything else', () => {
for (const good of ['severity', 'vehicle_make', '_x', 'a1_b2']) {
expect(assertSafeIdentifier(good, 'test')).toBe(good);
}
for (const bad of ['1abc', 'a-b', 'a b', 'a;b', '', 'a'.repeat(64)]) {
expect(() => assertSafeIdentifier(bad, 'test')).toThrowError(/invalid test identifier/);
}
});
it('restrictedTenantUserDdl refuses a tenant id or password it cannot safely embed', () => {
expect(() =>
restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: "t_alpha' OR '1'='1",
userName: 'opt_t_alpha',
password: 'pw',
tables: ['opt_analytics_event'],
}),
).toThrowError(/not policy-safe/);
expect(() =>
restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: 't_alpha',
userName: 'opt_t_alpha',
password: "pw' OR '1'='1",
tables: ['opt_analytics_event'],
}),
).toThrowError(/cannot be embedded/);
const stmts = restrictedTenantUserDdl({
db: 'opt_analytics',
tenantId: 't_alpha',
userName: 'opt_t_alpha',
password: 'safe_pw_123',
tables: ['opt_analytics_event'],
});
expect(stmts.join(' ')).toContain('CREATE ROW POLICY IF NOT EXISTS');
expect(stmts.join(' ')).toContain("USING tenant_id = 't_alpha'");
});
});