M17: Dialect-Aware SqlSecurityGuard (--dialect CLI & verity_database_guard Support)¶
- Task ID:
M17 - Priority:
P2(Master Rank#6, Track A — Product & Customer Value) - Status:
Done - Dependencies:
M3,M5 - Target Repository:
/Users/ivan/Project/3t.tools.intellij/verityredteam-free(verity-redteam-core) - GitHub Project #5: Verity RedTeam Free Task Board
1. Context & Problem Statement¶
SqlSecurityGuard.validate_single_select_statement() (src/verity/mcp_library/sql_guard.py) hardcodes read="postgres" for every sqlglot.tokenize / sqlglot.parse call (lines 90, 119, 133, 136). Non-Postgres SQL is therefore mis-tokenized/mis-parsed: MySQL backticks, T-SQL square-bracket identifiers, LIMIT/TOP/QUALIFY variants, and Snowflake/DuckDB/BigQuery specific constructs cause either false positives (valid read queries blocked) or false negatives (dialect-only keywords slipped past the prohibited-token scan). The verity test --sql subcommand and the verity_database_guard MCP handler also lack any way to select the dialect, so callers facing a MySQL/SQLite/Snowflake warehouse cannot obtain accurate validation.
2. Requirements & Target Files¶
src/verity/mcp_library/sql_guard.py- Add
dialect: str = "postgres"keyword parameter toSqlSecurityGuard.validate_single_select_statement(query, dialect="postgres"). - Replace every
read="postgres"withread=dialectin thesqlglot.tokenize(...)calls on lines 90, 119 (decommented variants use same dialect) and the twosqlglot.parse(...)calls (lines 133, 136). - Keep the default
"postgres"so existing callers are 100% backward compatible. - Validate the supplied dialect against the allowlist (
postgres,mysql,sqlite,duckdb,tsql,bigquery,snowflake); raiseSqlSecurityErrorfor unknown dialects. -
Preserve all existing checks (semicolon/stacked detection, keyword token scan, prohibited AST nodes, catalog access, etc.) but evaluate them under the active dialect.
-
src/verity/cli.py - Add
--dialectargument to thetestsubparser (_cmd_test),choices=("postgres","mysql","sqlite","duckdb","tsql","bigquery","snowflake"),default="postgres". - Pass the value through to
SqlSecurityGuard.validate_single_select_statement(args.sql, dialect=args.dialect); include#dialect=<name>in the PASS/FAIL resultdetailsfor observability. -
Also thread a compatible
dialectoption into any scan path that surfaces the SQL validator (no behavior change when omitted). -
src/verity/mcp_server/handlers/database_guard.py - In the
validate_sql_queryaction of_execute_database_guard, readoptions.get("dialect", "postgres"). - Pass
dialect=intoSqlSecurityGuard.validate_single_select_statement(...). -
Return the resolved
"dialect"field in bothALLOWEDandBLOCKEDresponses so MCP clients see what was actually applied. -
src/verity/scanner/static_rules.py(optional, only if SQL strings are evaluated there) — no new dialect behavior required; leave unchanged unless a clear call-site is found.
3. Automated Tests to Verify (tests/unit/test_sql_guard_dialects.py)¶
- Backward compatibility:
validate_single_select_statement("SELECT 1")with nodialectbehaves exactly as before (still accepts, still blocksDROP/stacked queries). - MySQL: a query with backtick-quoted identifiers (
SELECT `id`, `email` FROM `users` WHERE `tenant` = ?) passes withdialect="mysql"and does not crash under the default"postgres"dialect. - SQLite:
SELECT * FROM users LIMIT 10 OFFSET 5passes underdialect="sqlite"; a stackedSELECT 1; DROP TABLE usersstill raisesSqlSecurityErrorunder every dialect. - T-SQL:
SELECT TOP 5 [id] FROM [dbo].[users]passes underdialect="tsql". - Snowflake/BigQuery/DuckDB: representative
QUALIFY(Snowflake/DuckDB) andSELECT * EXCEPT(col)(BigQuery) queries pass under their respective dialects and remain subject to the prohibited-keyword/AST scans. - Unknown dialect:
validate_single_select_statement("SELECT 1", dialect="oracle")raisesSqlSecurityErrormentioning the unknown dialect. - Universal prohibitions: parametrized
SELECT 1; DROP TABLE x,DELETE FROM,GRANT,pg_catalog/information_schemaaccess must raiseSqlSecurityErroracross all seven dialects. - Handler parity:
_execute_database_guard({"action": "validate_sql_query", "options": {"sql_query": ..., "dialect": "mysql"}})returnsok=Truewith"dialect": "mysql"for a valid backtick query. - CLI parity: invoking
_cmd_test(Namespace(sql=..., dialect="mysql"))yields aPASSresult whosedetailsincludemysql.
4. Acceptance Scenario in Clean Container with Real MCP Server/Database Flow¶
Extend tests/e2e_containers/verify_all_scenarios.sh with a new Scenario (Dialect-aware SQL guard):
- SQLite path — start a real SQLite-backed database flow (
/tmp/verity_demo.db) and populate auserstable with one row. - Run a valid query through
verity test --sql 'SELECTid,nameFROMusersLIMIT 1' --dialect mysql→ expect exit0,PASS,detailscontainingmysql. - Validate and execute a real SQLite query (
SELECT id, name FROM users LIMIT 1 OFFSET 0) underdialect="sqlite"againstsqlite3.connect('/tmp/verity_demo.db')→ expectPASS. - MCP handler flow — call the
verity_database_guardtool via an MCP client (verity serve) with:Assert{"action": "validate_sql_query", "options": {"sql_query": "SELECT TOP 5 [id] FROM [dbo].[users]", "dialect": "tsql"}}ok=true,verdict="ALLOWED", and"dialect": "tsql"in the response. - Regression — confirm a stacked
SELECT 1; DROP TABLE usersis blocked in every dialect used above.
Assertions: exit codes as described; all SQL/MCP command variants produce the expected PASS/FAIL; scan_for_leaks finds no unexpected data; full INSTALL_SOURCE=wheel ./tests/e2e_containers/run_e2e.sh passes.
5. Verification Commands¶
cd /Users/ivan/Project/3t.tools.intellij/verityredteam-free
uv run ruff check src tests
uv run pytest tests/unit/test_sql_guard_dialects.py -v
uv run pytest tests/
uv run verity test --sql 'SELECT `id` FROM `users` LIMIT 1' --dialect mysql --format json
INSTALL_SOURCE=wheel ./tests/e2e_containers/run_e2e.sh
6. Acceptance Criteria¶
- [ ]
SqlSecurityGuard.validate_single_select_statement()acceptsdialect(default"postgres") and forwards it to everysqlglot.tokenize/sqlglot.parsecall; existing callers remain unaffected. - [ ] All seven dialects (
postgres,mysql,sqlite,duckdb,tsql,bigquery,snowflake) are supported end-to-end viaverity test --sql --dialectand viaverity_database_guard'soptions.dialect. - [ ] Unknown dialects raise a clear
SqlSecurityError; unsafe/stacked/destructive queries remain blocked under every dialect. - [ ] MCP handler responses echo the applied
"dialect"in bothALLOWEDandBLOCKEDoutputs. - [ ]
tests/unit/test_sql_guard_dialects.py, the fullpytest tests/,ruff check src tests, and the container E2E scenario pass cleanly.