feat(analytics): BI-P014 — DuckDB provider, and the measured finding that its sandbox does not work the way it looks
CI (SIAX Cloud) / integration (push) Failing after 42s
CI (SIAX Cloud) / security (push) Successful in 24s
CI (SIAX Cloud) / quality (push) Successful in 1m6s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Failing after 43s
CI (SIAX Cloud) / quality (pull_request) Successful in 57s
CI (SIAX Cloud) / integration (push) Failing after 42s
CI (SIAX Cloud) / security (push) Successful in 24s
CI (SIAX Cloud) / quality (push) Successful in 1m6s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Failing after 43s
CI (SIAX Cloud) / quality (pull_request) Successful in 57s
BI-P014's security requirement is the whole prompt: DuckDB is a local engine
with `read_csv('/etc/passwd')` built in. Two layers.
LAYER 1, the mount registry: a caller names ARTIFACT IDS, never paths. The
registry resolves an id, 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. A symlink to /etc/passwd, a traversing relative path, an
absolute path, and a sibling directory sharing the root's prefix
(/mnt/artifacts-evil for root /mnt/artifacts) are each refused. A cross-tenant
read is AUTHORIZATION_DENIED, deliberately not NOT_FOUND — an operator reading
the audit trail needs to see an attempted cross-tenant read as one.
LAYER 2, THE FINDING:
`SET allowed_directories=[...]` ALONE IS A NO-OP.
Measured on DuckDB 1.5.5. With allowed_directories set to a single 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. That is `trivy --exit-code 0` in a different costume. The
bootstrap is therefore emitted as ONE unit, `assertSessionSandboxed` refuses a
session missing any part of it, and the measurement itself is PINNED by a test
that never skips: if someone simplifies the bootstrap, the pinned evidence
(`read_etc_passwd_succeeded: true` for the naive spelling) keeps the finding
attached to the build rather than to a comment that would rot.
Twelve bypass attempts run against a real DuckDB with LAYER 1 REMOVED — sent
straight to the engine, registry not in the picture. Zero succeeded. The
counterfactual runs in the same session and is asserted: the mounted file IS
readable, so "nothing succeeded" is not a sandbox that blocks everything, which
would be an outage rather than a control. A locked session is then shown unable
to re-open its own sandbox, all three ways.
DoD, against real fixtures: Parquet aggregates correctly (SE 394.5, NO 105.5),
CSV round-trips a value containing a quote, and an ICEBERG SNAPSHOT reads via
iceberg_scan on an exact metadata JSON — which is not a workaround: DuckDB
refuses to glob for the latest version because globbing can read uncommitted
data, and an exact metadata file is what "snapshot" means. Arrow is reported
UNPROVEN by `readiness()` with the reason: DuckDB's arrow extension is a
network install the offline environment could not download.
THREE DEFECTS IN MY OWN TESTS, found and fixed rather than tidied away:
* a bypass-corpus entry was `SELECT 1 FROM (SELECT 1) t` — not an attack at
all. It succeeded and was reported as a leak. A corpus entry that cannot
fail is as useless as a check that cannot. Replaced with real ATTACH and
COPY attempts.
* the harness ran the session bootstrap outside its try block, so a statement
that correctly REFUSED to re-open a locked sandbox killed the subprocess
and surfaced as an unreadable "Command failed" instead of as the meaningful
refusal it was.
* the Iceberg fallback was `expect(evidence.iceberg ?? "unbuilt").toBeDefined()`
— a check that can never fail. It let a run without the fixture ERASE the
recorded Iceberg result from the evidence file while both suites stayed
green. It now rebuilds the fixture when pyiceberg is available and, when it
is not, asserts against the previously recorded result and marks it as
carried forward.
The Iceberg fixture is deliberately NOT committed: pyiceberg writes absolute
paths into its metadata and Avro manifests, so a committed table resolves only
on the machine that built it, and a fixture that silently fails everywhere else
is worse than none. tests/fixtures/duckdb/README.md says so and gives the
rebuild command; the recorded result is the artefact instead.
Heavy artifacts are refused with CAPABILITY_UNAVAILABLE and pointed at N0D,
per BI-P014 — silently running a 40 GB scan in the API process is how a preview
engine takes down a control plane.
35 unit tests, 12 live tests. Evidence: evidence/bi-p014/duckdb-sandbox.json.
Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* 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/integration/duckdb-provider.integration.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, "''");
|
||||
}
|
||||
Reference in New Issue
Block a user