Skip to content

fix(db): reject nested and trailing writes in read-only SQL check - #1544

Open
pcbeingused33 wants to merge 1 commit into
dataease:mainfrom
pcbeingused33:fix/check-sql-read-nested-writes
Open

pcbeingused33 wants to merge 1 commit into
dataease:mainfrom
pcbeingused33:fix/check-sql-read-nested-writes

Conversation

@pcbeingused33

Copy link
Copy Markdown
Contributor

Fixes #1542

check_sql_read() decided whether SQL writes by looking only at the type of each top-level statement and at the first keyword of the whole string. That missed:

  • writes nested inside a CTE (WITH d AS (DELETE ... RETURNING id) SELECT * FROM d), which parse as a top-level Select;
  • PostgreSQL SELECT ... INTO new_table, also a Select;
  • a write placed after a harmless first statement when its node type was not in the list (SELECT 1; TRUNCATE TABLE t, SET, GRANT, REVOKE), or when sqlglot falls back to a generic Command (SELECT 1; CALL proc()).

Fix

  • Search each statement recursively (stmt.find(*write_types)) instead of checking only its root type.
  • Add TruncateTable, Set, Grant, Revoke and Into to the write node types.
  • For statements sqlglot parses as Command, check that statement's own keyword against the allowed read commands, so CALL is rejected while SHOW/EXPLAIN still follow SQLBOT_ALLOW_METADATA_QUERIES.

Multi-statement reads (SELECT ...; SELECT ...) are still accepted; the dangerous-function denylist (points 4-5 of the issue) is unchanged.

Tests

New backend/tests/test_check_sql_read_writes.py covers the bypasses from the issue (CTE DELETE/UPDATE/INSERT, SELECT ... INTO, trailing TRUNCATE/SET/GRANT/REVOKE/CALL), ordinary reads with CTEs and subqueries, and metadata commands with the setting enabled. Before the fix 10 cases fail; after it all pass, together with tests/test_postgres_denylist.py:

cd backend && pytest tests/test_check_sql_read_writes.py tests/test_postgres_denylist.py

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant