Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions packages/void/src/cli/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -818,16 +818,18 @@ async function runSeed(

/**
* Fail-closed check for read-only SQL (SELECT or plain EXPLAIN), which skips the remote
* confirmation prompt. Comments are stripped first so they cannot hide `ANALYZE`.
* Multiple statements and `WITH` (a CTE can write) are rejected, and so is `EXPLAIN ANALYZE`
* in either form, because PostgreSQL executes the analyzed statement.
* confirmation prompt. A semicolon anywhere but the end means a script, and it is read from the
* raw text: a semicolon inside a literal must stay visible, or `SELECT '--' ; DROP TABLE users`
* reads as one comment-only SELECT and skips the prompt. Comments are stripped for the read-only
* test so they cannot hide `ANALYZE`. `WITH` (a CTE can write) is rejected, and so is
* `EXPLAIN ANALYZE` in either form, because PostgreSQL executes the analyzed statement.
*/
function isSafeStatement(sql: string): boolean {
const decommented = sql.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/--[^\n]*/g, ' ');
const stripped = decommented.replace(/;\s*$/, '');
if (stripped.includes(';')) {
if (sql.replace(/;\s*$/, '').includes(';')) {
return false;
}
const decommented = sql.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/--[^\n]*/g, ' ');
const stripped = decommented.replace(/;\s*$/, '');
if (/^\s*SELECT\b/i.test(stripped)) {
return true;
}
Expand Down
5 changes: 5 additions & 0 deletions packages/void/test/unit/db-execute-remote.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,11 @@ describe('void db execute --remote (D1)', () => {
['EXPLAIN SELECT * FROM users', false],
['EXPLAIN (VERBOSE) SELECT 1', false],
['-- header\nSELECT 1', false],
['SELECT 1;', false],
["SELECT '--'", false],
["SELECT '--' ; DROP TABLE users", true],
["SELECT '/*' ; DROP TABLE users", true],
['-- a; comment\nSELECT 1', true],
['EXPLAIN ANALYZE DELETE FROM users', true],
['EXPLAIN (ANALYZE) DELETE FROM users', true],
['EXPLAIN (ANALYZE TRUE) UPDATE users SET name = $1', true],
Expand Down
Loading