Files
0pt/src/analytics/providers/duckdb-provider.ts
T
Claude Opus 5 3ee023017b
CI (SIAX Cloud) / security (push) Successful in 28s
CI (SIAX Cloud) / integration (push) Successful in 42s
Security Scan (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / quality (push) Successful in 1m2s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Successful in 40s
CI (SIAX Cloud) / quality (pull_request) Successful in 58s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 20s
fix(analytics): move the DuckDB live suite out of tests/integration, and add the BI docs
CI's integration job failed, and it failed CORRECTLY. That job provides a live
OpenSearch and a live ClickHouse and then asserts that nothing in
tests/integration/ skipped, on the stated principle that "a skipped suite must
never masquerade as a green integration gate". The DuckDB suite needs a Python
interpreter that job does not provide, so it skipped, and the guard fired — the
first suite in that directory ever to skip there.

Moving the file to tests/duckdb/ respects the guard rather than weakening it.
Loosening it to tolerate skips would have traded a real gate for one green job,
which is the trade this estate keeps regretting. The suite still runs, still
fails rather than skipping when DUCKDB_PYTHON is set and DuckDB is broken, and
is still pinned by the committed evidence.

Also fixed: "does NOT ship the Iceberg table" asserted against the FILESYSTEM
when the claim is about what is COMMITTED. The live suite rebuilds that table
locally, so the assertion failed whenever both suites ran in one pass — it was
testing the wrong thing rather than catching a real problem. It now asserts
against `git ls-files`, and also asserts the parquet/csv fixtures ARE tracked,
so a version that stopped shipping any fixture would fail too.

docs/analytics/BI_QUERY_METRIC_QUALITY.md is organised around what is PROVEN
and what is NOT, because the second list is the one that gets dropped. It
records the five findings and the six open items, including that BI-P029's
MetricFlow was never executed and that BI-P021's budget is a bound rather than
a hard cap (measured 130x overshoot at a 100ms poll).

It also reports, without changing it, a latent flaw in .gitea/workflows/ci.yml
(a protected file this branch does not touch): the integration guard's second
pattern `Tests  [0-9]+ passed` never matches, because vitest writes that
summary with ANSI colour codes between the words. The guard is therefore
STRICTER than it reads — "any skip fails" rather than "skipped and nothing
passed" — so nothing is currently unguarded, but the escape hatch does not
work and someone will eventually be puzzled by it.

957 tests pass with ClickHouse, Postgres and DuckDB all live.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 03:08:11 +02:00

435 lines
16 KiB
TypeScript

/**
* src/analytics/providers/duckdb-provider.ts
* ==========================================
* BI-P014 — DUCKDB PROVIDER.
*
* Use cases BI-P014 names: Parquet, Iceberg preview, local query, test, CSV,
* ad-hoc files, report build, notebook. Heavy jobs go through N0D.
*
* ── THE SECURITY REQUIREMENT, AND THE MEASURED SURPRISE ───────────────────
* "No uncontrolled filesystem access. Explicit ST0RE-mounted/input artifacts
* only."
*
* DuckDB is a local engine with `read_csv('/etc/passwd')` built in, so this is
* the whole prompt. Two layers, and the second is not what it looks like:
*
* LAYER 1 — MOUNT REGISTRY. A caller names ARTIFACT IDS, never paths. The
* registry resolves an id to a path, checks the artifact belongs to
* the caller's tenant, and `realpath`s the result to confirm it is
* still inside the mount root once symlinks are followed. The query
* builder is the only thing that ever writes a path into SQL.
*
* LAYER 2 — DUCKDB'S OWN SANDBOX. And here is the finding:
*
* `SET allowed_directories=[...]` ALONE IS A NO-OP.
*
* Measured on DuckDB 1.5.5: with `allowed_directories` set to one
* mount directory and nothing else, `read_csv('/etc/passwd')`
* RETURNED THE FILE, and an https:// URL was fetched over the
* network. Only when `enable_external_access = false` is ALSO set
* does the allow-list bind — the same reads then fail with
* "Permission Error: Cannot access file". `lock_configuration=true`
* afterwards stops a query re-opening either.
*
* So the obvious spelling of this control — set the allow-list and
* move on — yields a setting that appears in `duckdb_settings()`,
* looks like a sandbox, and permits everything. Same shape as
* `trivy --exit-code 0`. Hence `duckDbSessionBootstrap()` emits the
* three statements as one unit, and `assertSessionSandboxed()`
* refuses a session missing any of them.
*
* Evidence: evidence/bi-p014/duckdb-sandbox.json, written by
* tests/duckdb/duckdb-provider.live.test.ts, which runs the bypass
* corpus with LAYER 1 REMOVED and requires layer 2 to refuse it anyway.
*/
import path from 'node:path';
import fs from 'node:fs';
import { SiaxError } from '../../platform/errors';
import type { AnalyticsIdentity } from '../engine/siax-analytics-engine';
export const ARTIFACT_FORMATS = ['parquet', 'csv', 'json', 'iceberg', 'arrow_ipc'] as const;
export type ArtifactFormat = (typeof ARTIFACT_FORMATS)[number];
/**
* A file the provider is allowed to read. Registered by the ST0RE mount
* process, never by a query.
*/
export interface ArtifactMount {
artifact_id: string;
tenant_id: string;
project_id?: string;
/** Canonical ST0RE reference, for lineage. */
st0re_ref: string;
/** Path RELATIVE to the mount root. Never absolute, never traversing. */
relative_path: string;
format: ArtifactFormat;
/** Bytes, from ST0RE metadata. Drives the N0D hand-off policy. */
size_bytes: number;
}
const ARTIFACT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
/**
* Resolves artifact ids to real paths, and refuses everything else.
*
* `realpathSync` is the load-bearing call: a relative path that passes a string
* check can still be a symlink into `/etc`. The check is on the RESOLVED path,
* after the filesystem has had its say.
*/
export class ArtifactMountRegistry {
private readonly mounts = new Map<string, ArtifactMount>();
private readonly rootReal: string;
constructor(
/** The single directory every mounted artifact lives under. */
readonly root: string,
private readonly statPath: (p: string) => string = (p) => fs.realpathSync(p),
) {
if (!path.isAbsolute(root)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
'the mount root must be an absolute path',
);
}
this.rootReal = this.statPath(root);
}
register(mount: ArtifactMount): void {
if (!ARTIFACT_ID_RE.test(mount.artifact_id)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.duckdb', 'artifact id is not registry-safe');
}
if (!mount.tenant_id?.trim()) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.duckdb', 'a mount must name its owning tenant');
}
if (path.isAbsolute(mount.relative_path)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
'a mount path must be relative to the mount root',
);
}
// Resolve BEFORE storing, so a bad mount is refused at registration rather
// than at query time when the caller is a tenant.
this.resolveWithin(mount.relative_path);
this.mounts.set(mount.artifact_id, mount);
}
/**
* Resolve an artifact for a VERIFIED identity.
*
* Two refusals that are easy to conflate but must stay distinct:
* * an unknown artifact is NOT_FOUND;
* * an artifact owned by another tenant is AUTHORIZATION_DENIED, and
* deliberately NOT reported as NOT_FOUND — an operator reading the audit
* trail needs to see an attempted cross-tenant read as one.
*/
resolve(identity: AnalyticsIdentity, artifactId: string): { mount: ArtifactMount; absolutePath: string } {
if (!identity?.tenant_id?.trim()) {
throw new SiaxError(
'UNAUTHENTICATED',
'0pt.analytics.duckdb',
'artifact access requires a verified tenant',
);
}
if (!ARTIFACT_ID_RE.test(artifactId)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.duckdb', 'artifact id is not registry-safe');
}
const mount = this.mounts.get(artifactId);
if (!mount) {
throw new SiaxError('NOT_FOUND', '0pt.analytics.duckdb', `artifact "${artifactId}" is not mounted`);
}
if (mount.tenant_id !== identity.tenant_id) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.duckdb',
`artifact "${artifactId}" belongs to another tenant`,
);
}
if (mount.project_id && identity.project_id && mount.project_id !== identity.project_id) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.duckdb',
`artifact "${artifactId}" belongs to another project`,
);
}
return { mount, absolutePath: this.resolveWithin(mount.relative_path) };
}
/** Join, resolve symlinks, and confirm the result is still under the root. */
private resolveWithin(relative: string): string {
const joined = path.resolve(this.rootReal, relative);
let real: string;
try {
real = this.statPath(joined);
} catch {
throw new SiaxError('NOT_FOUND', '0pt.analytics.duckdb', 'mounted artifact is not present on disk');
}
// `startsWith(root)` alone would accept `/mnt-evil` for root `/mnt`.
if (real !== this.rootReal && !real.startsWith(`${this.rootReal}${path.sep}`)) {
throw new SiaxError(
'AUTHORIZATION_DENIED',
'0pt.analytics.duckdb',
'artifact resolves outside the mount root (traversal or symlink)',
);
}
return real;
}
/** Every directory DuckDB is told about. One entry: the root itself. */
allowedDirectories(): string[] {
return [this.rootReal];
}
list(tenantId: string): ArtifactMount[] {
return [...this.mounts.values()].filter((m) => m.tenant_id === tenantId);
}
}
// ── layer 2: the DuckDB session sandbox ────────────────────────────────────
/**
* The three statements, as ONE unit.
*
* Order matters and is not cosmetic: `allowed_directories` must be set while
* the configuration is still open, `enable_external_access = false` is what
* makes the list bind at all, and `lock_configuration = true` must come last
* or a query could undo the other two.
*/
export function duckDbSessionBootstrap(allowedDirectories: readonly string[]): string[] {
if (allowedDirectories.length === 0) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
'refusing to open a DuckDB session with no allowed directory — an empty list is not a sandbox',
);
}
for (const dir of allowedDirectories) {
if (!path.isAbsolute(dir)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.duckdb', 'an allowed directory must be absolute');
}
if (dir.includes("'")) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
'an allowed directory must not contain a quote',
);
}
}
return [
`SET allowed_directories=[${allowedDirectories.map((d) => `'${d}'`).join(', ')}]`,
// MEASURED: without this, the line above permits everything, including
// /etc/passwd and outbound HTTP. See this file's header.
'SET enable_external_access=false',
'SET lock_configuration=true',
];
}
/** The settings that must all be present for a session to be sandboxed. */
export const REQUIRED_SANDBOX_SETTINGS = [
'allowed_directories',
'enable_external_access',
'lock_configuration',
] as const;
export function assertSessionSandboxed(statements: readonly string[]): void {
const joined = statements.join('\n').toLowerCase();
for (const setting of REQUIRED_SANDBOX_SETTINGS) {
if (!joined.includes(setting)) {
throw new SiaxError(
'PERMANENT_FAILURE',
'0pt.analytics.duckdb',
`DuckDB session is missing "${setting}" — allowed_directories WITHOUT ` +
`enable_external_access=false is a no-op, measured on 1.5.5`,
);
}
}
if (!/enable_external_access\s*=\s*false/i.test(joined)) {
throw new SiaxError(
'PERMANENT_FAILURE',
'0pt.analytics.duckdb',
'DuckDB session leaves external access ENABLED; the directory allow-list is then not enforced',
);
}
}
// ── the provider ───────────────────────────────────────────────────────────
export interface DuckDbRunner {
readonly engine: string;
/** Open a session with the bootstrap applied, run `sql`, return rows. */
run(args: { bootstrap: readonly string[]; sql: string }): Promise<Array<Record<string, unknown>>>;
}
export const DUCKDB_AGGREGATES = ['sum', 'avg', 'min', 'max', 'count', 'count_distinct'] as const;
export type DuckDbAggregate = (typeof DUCKDB_AGGREGATES)[number];
/**
* A closed request. There is NO caller SQL on this provider, for the same
* reason `executeMetric` has none: an analyst SQL surface is a separate,
* role-gated thing (BI-P017), and letting the ad-hoc FILE engine grow one would
* put raw SQL next to a filesystem.
*/
export interface DuckDbArtifactQuery {
artifact_id: string;
/** Column names to select. Validated as identifiers. */
select?: string[];
aggregate?: { fn: DuckDbAggregate; column: string; alias?: string };
group_by?: string[];
/** Equality filters. Names validated, values escaped. */
filters?: Record<string, string>;
limit?: number;
}
const COLUMN_RE = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
function column(name: string): string {
if (!COLUMN_RE.test(name)) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
`"${name.slice(0, 32)}" is not a column name`,
);
}
return name;
}
const READER: Record<ArtifactFormat, (p: string) => string> = {
parquet: (p) => `read_parquet('${p}')`,
csv: (p) => `read_csv('${p}', header=true, auto_detect=true)`,
json: (p) => `read_json_auto('${p}')`,
// The iceberg extension reads a table DIRECTORY, not a single file.
iceberg: (p) => `iceberg_scan('${p}')`,
arrow_ipc: (p) => `read_arrow('${p}')`,
};
export interface N0dHandoffPolicy {
/** Above this, the query is refused here and must go to N0D. */
maxLocalBytes: number;
}
export const DEFAULT_N0D_HANDOFF: N0dHandoffPolicy = { maxLocalBytes: 2 * 1024 * 1024 * 1024 };
export class DuckDbAnalyticsProvider {
readonly provider = 'duckdb';
constructor(
private readonly registry: ArtifactMountRegistry,
private readonly runner: DuckDbRunner,
private readonly handoff: N0dHandoffPolicy = DEFAULT_N0D_HANDOFF,
) {}
/** Formats this build can read. See `readiness()` for what has been PROVEN. */
supports(format: ArtifactFormat): boolean {
return ['parquet', 'csv', 'json', 'iceberg'].includes(format);
}
/**
* What has been demonstrated against a real DuckDB, and what has not.
* Same posture as BI-P029's `providerReadiness`: a capability list nobody
* can check is a capability list that overstates.
*/
readiness(): { proven: ArtifactFormat[]; unproven: Array<{ format: ArtifactFormat; reason: string }> } {
return {
proven: ['parquet', 'csv', 'iceberg'],
unproven: [
{
format: 'arrow_ipc',
reason:
"DuckDB's `arrow` extension is a network install and the offline verification " +
'environment could not download it, so read_arrow() has NOT been exercised',
},
{ format: 'json', reason: 'no fixture was built for it in the verification run' },
],
};
}
async query(
identity: AnalyticsIdentity,
request: DuckDbArtifactQuery,
): Promise<Array<Record<string, unknown>>> {
const { mount, absolutePath } = this.registry.resolve(identity, request.artifact_id);
if (!this.supports(mount.format)) {
throw new SiaxError(
'CAPABILITY_UNAVAILABLE',
'0pt.analytics.duckdb',
`format "${mount.format}" is not readable by this provider build`,
);
}
if (mount.size_bytes > this.handoff.maxLocalBytes) {
// BI-P014: "Run heavy jobs through N0D." Refusing is the honest form —
// silently running a 40 GB scan in the API process is how a preview
// engine takes down a control plane.
throw new SiaxError(
'CAPABILITY_UNAVAILABLE',
'0pt.analytics.duckdb',
`artifact is ${mount.size_bytes} bytes, above the ${this.handoff.maxLocalBytes}-byte local ceiling — ` +
`submit it as an N0D job`,
);
}
const source = READER[mount.format](absolutePath);
const selectParts: string[] = [];
const groupParts: string[] = [];
for (const g of request.group_by ?? []) {
selectParts.push(column(g));
groupParts.push(column(g));
}
if (request.aggregate) {
const col = column(request.aggregate.column);
const alias = column(request.aggregate.alias ?? 'value');
const fn = request.aggregate.fn;
if (!DUCKDB_AGGREGATES.includes(fn)) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics.duckdb', `unsupported aggregate "${fn}"`);
}
const expr =
fn === 'count' ? 'count(*)' : fn === 'count_distinct' ? `count(DISTINCT ${col})` : `${fn}(${col})`;
selectParts.push(`${expr} AS ${alias}`);
} else {
for (const s of request.select ?? []) selectParts.push(column(s));
}
if (selectParts.length === 0) selectParts.push('*');
const conditions: string[] = [];
for (const [name, value] of Object.entries(request.filters ?? {})) {
// Not every DuckDB binding exposes a bound-parameter transport, so values
// are ESCAPED here — and the escaping is asserted against a hostile
// corpus in the test rather than assumed.
conditions.push(`${column(name)} = '${escapeLiteral(value)}'`);
}
const limit = Math.max(1, Math.min(Math.floor(request.limit ?? 1000), 1_000_000));
const sql =
`SELECT ${selectParts.join(', ')} FROM ${source}` +
(conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '') +
(groupParts.length ? ` GROUP BY ${groupParts.join(', ')}` : '') +
` LIMIT ${limit}`;
const bootstrap = duckDbSessionBootstrap(this.registry.allowedDirectories());
assertSessionSandboxed(bootstrap);
return this.runner.run({ bootstrap, sql });
}
}
/**
* Escape a value for a DuckDB string literal.
*
* Doubling `'` is the whole grammar — DuckDB does NOT treat backslash as an
* escape inside a standard single-quoted string, so `\'` does not close one.
* A NUL is REFUSED rather than escaped: a truncating byte inside a literal is
* a parser disagreement waiting to happen, and there is no legitimate filter
* value that contains one.
*/
export function escapeLiteral(value: string): string {
if (value.includes('\u0000')) {
throw new SiaxError(
'INVALID_REQUEST',
'0pt.analytics.duckdb',
'a filter value must not contain a NUL byte',
);
}
return value.replace(/'/g, "''");
}