diff --git a/apps/product-analytics/src/insights/sandbox-parser.ts b/apps/product-analytics/src/insights/sandbox-parser.ts index 88e7563c..857f1a71 100644 --- a/apps/product-analytics/src/insights/sandbox-parser.ts +++ b/apps/product-analytics/src/insights/sandbox-parser.ts @@ -66,6 +66,10 @@ const DENIED_FUNCTIONS = new Set([ "inet_server_addr", "inet_server_port", "inet_client_addr", + // Build one value of up to 1 GB inside the database from a short query. + "repeat", + "lpad", + "rpad", ]); type Node = Record; diff --git a/apps/product-analytics/src/insights/sandbox.ts b/apps/product-analytics/src/insights/sandbox.ts index ee2c4f31..0a6e8ff7 100644 --- a/apps/product-analytics/src/insights/sandbox.ts +++ b/apps/product-analytics/src/insights/sandbox.ts @@ -16,6 +16,10 @@ import { checkSql, SqlRejected } from "./sandbox-parser.ts"; export const SQL_TIMEOUT_MS = 10_000; export const SQL_MAX_ROWS = 10_000; +/** Largest answer (sum of the rows' text size) read into the service; the service runs under a 192 MiB cap. */ +export const SQL_MAX_BYTES = 8 * 1024 * 1024; +/** Marker of the database-side refusal of an answer over SQL_MAX_BYTES. */ +const TOO_LARGE = "pa_answer_too_large"; export const SANDBOX_ROLE = "pa_sql_login"; export interface SqlResult { @@ -27,6 +31,7 @@ export interface SqlResult { export interface SandboxOptions { timeoutMs?: number; maxRows?: number; + maxBytes?: number; } export class SqlUnavailable extends Error { @@ -42,8 +47,11 @@ function jsonSafe(v: unknown): unknown { } /** Postgres errors a person can act on, in plain words; anything else is generic. */ -function plain(err: unknown, timeoutMs: number): Error { +function plain(err: unknown, timeoutMs: number, maxBytes: number): Error { const e = err as { code?: string; message?: string }; + if (e.code === "22P02" && (e.message ?? "").includes(TOO_LARGE)) { + return new SqlRejected(`The answer is larger than ${Math.round(maxBytes / 1024 / 1024)} MB. Select fewer columns, add a limit or aggregate, or use an export.`); + } if (e.code === "57014") return new SqlRejected(`The query took longer than ${Math.round(timeoutMs / 1000)} seconds and was stopped. Narrow the time range or add a limit.`); if (e.code === "42501") return new SqlRejected(`Not allowed: ${e.message ?? "permission denied"}.`); if (e.code === "25006") return new SqlRejected("Only reading is allowed here: cannot write in a read-only transaction."); @@ -60,7 +68,7 @@ export class SqlSandbox { constructor(owner: Db, opts: SandboxOptions = {}) { this.owner = owner; - this.opts = { timeoutMs: opts.timeoutMs ?? SQL_TIMEOUT_MS, maxRows: opts.maxRows ?? SQL_MAX_ROWS }; + this.opts = { timeoutMs: opts.timeoutMs ?? SQL_TIMEOUT_MS, maxRows: opts.maxRows ?? SQL_MAX_ROWS, maxBytes: opts.maxBytes ?? SQL_MAX_BYTES }; } /** Gives the sandbox login a fresh random password (as the owner) and opens its pool. */ @@ -112,8 +120,15 @@ export class SqlSandbox { await client.query("begin transaction read only"); await client.query(`set local statement_timeout = ${Math.max(100, Math.floor(this.opts.timeoutMs))}`); // A bound parameter forces the extended protocol: one statement only. + // The running text size of the rows is checked in the database; past + // the cap the query fails there (a cast that cannot succeed, not folded + // at plan time because it depends on the row), so a huge answer never + // reaches the service's memory. + const text = + `select (w.q).* from (select q, sum(octet_length(q::text)) over (rows between unbounded preceding and current row) as pa_bytes from (${sql}\n) as q) as w` + + ` where case when w.pa_bytes > $2 then (w.pa_bytes::text || '${TOO_LARGE}')::int = 0 else true end limit $1`; const res = await withDeadline( - client.query({ text: `select * from (${sql}\n) as q limit $1`, values: [this.opts.maxRows + 1], rowMode: "array" }), + client.query({ text, values: [this.opts.maxRows + 1, this.opts.maxBytes], rowMode: "array" }), this.opts.timeoutMs + 2000, () => { broken = true; @@ -126,7 +141,7 @@ export class SqlSandbox { await client.query("rollback").catch(() => { broken = true; }); - throw plain(err, this.opts.timeoutMs); + throw plain(err, this.opts.timeoutMs, this.opts.maxBytes); } finally { client.release(broken); if (pid) await this.owner.query("delete from pa.sql_sandbox_sessions where pid = $1", [pid]).catch(() => undefined); diff --git a/apps/product-analytics/test/a2/sandbox.test.ts b/apps/product-analytics/test/a2/sandbox.test.ts index 3c4191e6..3b10f2df 100644 --- a/apps/product-analytics/test/a2/sandbox.test.ts +++ b/apps/product-analytics/test/a2/sandbox.test.ts @@ -81,7 +81,7 @@ test("with the parser skipped, the database still refuses everything outside one ["select set_config('role', 'postgres', true)", /permission denied|must be/], ["select 1; delete from pa.events", /multiple commands|cannot insert|syntax error/], // Closing the wrapper by hand still meets the one-statement protocol. - ["select 1) as q; delete from pa.events; select * from (select 1", /multiple commands|cannot insert/], + ["select 1) as q; delete from pa.events; select * from (select 1", /multiple commands|cannot insert|syntax error/], ["with d as (delete from pa_view.events returning 1) select count(*) from d", /read-only|cannot|permission|top level/], ["select pa_view.project(), set_config('transaction_read_only', 'off', true)", /read-write|cannot set/], ]; @@ -113,6 +113,30 @@ test("long queries stop at the timeout; large answers stop at 10 000 rows", { sk assert.equal(small.truncated, false); }); +test("an answer larger than the byte cap is refused in the database, before it reaches the service", { skip: skipNoPg }, async () => { + // One 40 MB value, or many rows adding up past the cap, would otherwise be + // read whole into the service (192 MiB cap) and stop it for every tenant. + const before = process.memoryUsage().rss; + await assert.rejects(box.runUnchecked(f.projectId, "select repeat(md5(n::text), 1250000) as a from generate_series(1, 1) n"), /larger than/); + await assert.rejects(box.runUnchecked(f.projectId, "select repeat(md5(n::text), 32) as a from generate_series(1, 10000) n"), /larger than/); + assert.ok(process.memoryUsage().rss - before < 64 * 1024 * 1024, "the service did not read the large answer"); + // Answers under the cap keep their columns, order and duplicate names. + const ok = await box.run(f.projectId, "select n as a, n * 2 as a from generate_series(1, 5) n order by n desc"); + assert.deepEqual(ok.columns, ["a", "a"]); + assert.deepEqual(ok.rows.map((r) => r.map(Number)), [[5, 10], [4, 8], [3, 6], [2, 4], [1, 2]]); + const events = await box.run(f.projectId, "select * from pa_view.events order by timestamp limit 3"); + assert.equal(events.rows.length, 3); + assert.ok(events.columns.includes("properties")); + // A user's own cast error is still reported as theirs. + await assert.rejects(box.run(f.projectId, "select 'abc'::int"), (e: unknown) => e instanceof SqlRejected && /invalid input syntax/.test((e as Error).message) && !/larger than/.test((e as Error).message)); +}); + +test("the parser refuses functions that build very large values in the database", () => { + for (const sql of ["select repeat('x', 1000000000)", "select lpad('', 1000000000, 'x')", "select rpad('', 1000000000, 'x') from pa_view.events"]) { + assert.throws(() => checkSql(sql), (e: unknown) => e instanceof SqlRejected && /not allowed/.test((e as Error).message), sql); + } +}); + test("CSV download escapes quotes, commas, new lines and formula starts", () => { const csv = toCsv({ columns: ["a", "b"], rows: [["x,y", 'say "hi"'], ["=1+1", null], [3, { k: 1 }]], truncated: false }); assert.equal(csv, 'a,b\r\n"x,y","say ""hi"""\r\n\'=1+1,\r\n3,"{""k"":1}"\r\n');