Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(hooks): close raw-SQL detection gaps in custom-checks (#3543)

LearningCircuit165c9d08d5e9
diff --git a/.pre-commit-hooks/custom-checks.py b/.pre-commit-hooks/custom-checks.py
index d1a446aaf5..144a75a998 100755
--- a/.pre-commit-hooks/custom-checks.py
+++ b/.pre-commit-hooks/custom-checks.py
@@ -13,6 +13,7 @@ import ast
import sys
import re
import os
+from pathlib import Path
from typing import List, Tuple
# Set environment variable for pre-commit hooks to allow unencrypted databases
@@ -296,13 +297,44 @@ class CustomCodeChecker(ast.NodeVisitor):
self.generic_visit(node)
+# Database utility files where direct SQL is required for bootstrap / low-level access.
+# Single source of truth — used by both execute-call and SQL-string checks.
+DB_UTIL_FILES = {
+ "sqlcipher_utils.py",
+ "socket_service.py",
+ "thread_local_session.py",
+ "encrypted_db.py",
+ "initialize.py",
+ "auth_db.py",
+ "backup_service.py",
+}
+
+
+def _is_raw_sql_exempt(filename: str) -> bool:
+ """Return True if this file is exempt from raw-SQL checks."""
+ fn = filename.replace("\\", "/")
+ lower = fn.lower()
+ if "migration" in lower or "migrate" in lower or "alembic" in lower:
+ return True
+ base = Path(fn).name
+ # Test files: /tests/ directory or test_* prefix (strict, avoids "attest"/"contest" matches)
+ if "/tests/" in fn or base.startswith("test_") or base.endswith("_test.py"):
+ return True
+ if base in DB_UTIL_FILES:
+ return True
+ return False
+
+
def check_raw_sql(content: str, filename: str) -> List[Tuple[int, str]]:
"""Check for raw SQL usage patterns."""
errors = []
lines = content.split("\n")
# Skip checking this file itself (contains regex patterns that look like SQL)
- if "custom-checks.py" in filename:
+ if Path(filename).name == "custom-checks.py":
+ return errors
+
+ if _is_raw_sql_exempt(filename):
return errors
# More specific patterns for database execute calls to avoid false positives
@@ -312,20 +344,25 @@ def check_raw_sql(content: str, filename: str) -> List[Tuple[int, str]]:
r"conn\.execute\s*\(", # connection.execute()
r"connection\.execute\s*\(", # connection.execute()
r"session\.execute\s*\(\s*[\"']", # session.execute() with raw SQL string
+ r"session\.execute\s*\(\s*[fr]{1,2}[\"']", # session.execute(f"...") / fr"..." / rf"..." — prefixed SQL literal
]
- # SQL statement patterns (only check if they appear to be raw SQL strings)
+ # SQL statement patterns (only check if they appear to be raw SQL strings).
+ # The [fr]{0,2} prefix (with IGNORECASE) covers f"", F"", r"", fr"", rf"",
+ # and their case variants — the highest-risk form being the f-string (injection).
sql_statement_patterns = [
- r"[\"']\s*SELECT\s+.*FROM\s+", # Raw SELECT in strings
- r"[\"']\s*INSERT\s+INTO\s+", # Raw INSERT in strings
- r"[\"']\s*UPDATE\s+.*SET\s+", # Raw UPDATE in strings
- r"[\"']\s*DELETE\s+FROM\s+", # Raw DELETE in strings
- r"[\"']\s*CREATE\s+TABLE\s+", # Raw CREATE TABLE in strings
- r"[\"']\s*DROP\s+TABLE\s+", # Raw DROP TABLE in strings
- r"[\"']\s*ALTER\s+TABLE\s+", # Raw ALTER TABLE in strings
+ r"[fr]{0,2}[\"']\s*SELECT\s+.*FROM\s+",
+ r"[fr]{0,2}[\"']\s*INSERT\s+INTO\s+",
+ r"[fr]{0,2}[\"']\s*UPDATE\s+.*SET\s+",
+ r"[fr]{0,2}[\"']\s*DELETE\s+FROM\s+",
+ r"[fr]{0,2}[\"']\s*CREATE\s+TABLE\s+",
+ r"[fr]{0,2}[\"']\s*DROP\s+TABLE\s+",
+ r"[fr]{0,2}[\"']\s*ALTER\s+TABLE\s+",
]
- # Allowed patterns (ORM usage and legitimate cases)
+ # Allowed patterns (ORM usage only). Intentionally does NOT include:
+ # - f-strings (previously whitelisted the entire line — masked f-string SQL injection)
+ # - "# ... SQL" comments (trivially bypassed the check with a trailing comment)
allowed_patterns = [
r"session\.query\(",
r"\.filter\(",
@@ -339,11 +376,7 @@ def check_raw_sql(content: str, filename: str) -> List[Tuple[int, str]]:
r"relationship\(",
r"Column\(",
r"Table\(",
- r"text\(", # SQLAlchemy text() function for raw SQL
- r"#.*SQL", # Comments mentioning SQL
- r"\"\"\".*SQL", # Docstrings mentioning SQL
- r"'''.*SQL", # Docstrings mentioning SQL
- r"f[\"'].*{", # f-strings (often used for dynamic ORM queries)
+ r"text\(", # SQLAlchemy text() function — the sanctioned way to do raw SQL
]
for line_num, line in enumerate(lines, 1):
@@ -367,68 +400,25 @@ def check_raw_sql(content: str, filename: str) -> List[Tuple[int, str]]:
if has_allowed_pattern:
continue
- # Check for database execute patterns
for pattern in db_execute_patterns:
if re.search(pattern, line, re.IGNORECASE):
- # Check if this might be acceptable (in migrations or tests)
- is_migration = (
- "migration" in filename.lower()
- or "migrate" in filename.lower()
- or "alembic" in filename.lower()
- or "/migrations/" in filename
- )
- is_test = "test" in filename.lower()
-
- # Allow raw SQL in database utility files that need direct access
- is_db_util = (
- "sqlcipher_utils.py" in filename
- or "socket_service.py" in filename
- or "thread_local_session.py" in filename
- or "encrypted_db.py" in filename
- or "initialize.py" in filename
- or "auth_db.py" in filename
- or "backup_service.py" in filename
- )
-
- # Allow raw SQL in migrations, db utils, and all test files
- if not (is_migration or is_db_util or is_test):
- errors.append(
- (
- line_num,
- f"Raw SQL execute detected: '{line_stripped[:50]}...'. Use ORM methods instead.",
- )
+ errors.append(
+ (
+ line_num,
+ f"Raw SQL execute detected: '{line_stripped[:50]}...'. Use ORM methods instead.",
)
+ )
+ break
- # Check for SQL statement patterns
for pattern in sql_statement_patterns:
if re.search(pattern, line, re.IGNORECASE):
- # Check if this might be acceptable (in migrations or tests)
- is_migration = (
- "migration" in filename.lower()
- or "migrate" in filename.lower()
- or "alembic" in filename.lower()
- or "/migrations/" in filename
- )
- is_test = "test" in filename.lower()
-
- # Allow raw SQL in database utility files that need direct access
- is_db_util = (
- "sqlcipher_utils.py" in filename
- or "socket_service.py" in filename
- or "thread_local_session.py" in filename
- or "encrypted_db.py" in filename
- or "initialize.py" in filename
- or "backup_service.py" in filename
- )
-
- # Allow raw SQL in migrations, db utils, and all test files
- if not (is_migration or is_db_util or is_test):
- errors.append(
- (
- line_num,
- f"Raw SQL statement detected: '{line_stripped[:50]}...'. Use ORM methods instead.",
- )
+ errors.append(
+ (
+ line_num,
+ f"Raw SQL statement detected: '{line_stripped[:50]}...'. Use ORM methods instead.",
)
+ )
+ break
return errors
diff --git a/tests/hooks/test_custom_checks_raw_sql.py b/tests/hooks/test_custom_checks_raw_sql.py
new file mode 100644
index 0000000000..89b0b3b11e
--- /dev/null
+++ b/tests/hooks/test_custom_checks_raw_sql.py
@@ -0,0 +1,157 @@
+"""
+Tests for the raw-SQL check inside the custom-checks pre-commit hook.
+
+Covers regressions for previously-missed patterns:
+- f-string SQL (e.g. f"SELECT ... FROM ...") — highest-risk form (injection)
+- trailing `# SQL` comments that previously bypassed the check
+- auth_db.py allowlist inconsistency between execute and statement patterns
+- loose "test" substring filename matching (e.g. attestation_service.py)
+"""
+
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+HOOK_SCRIPT = (
+ Path(__file__).parent.parent.parent
+ / ".pre-commit-hooks"
+ / "custom-checks.py"
+)
+
+
+def _run_hook(content: str, filename: str) -> subprocess.CompletedProcess:
+ """Write content to a temp file with a specific basename and run the hook."""
+ with tempfile.TemporaryDirectory() as d:
+ path = Path(d) / filename
+ path.write_text(content)
+ return subprocess.run(
+ [sys.executable, str(HOOK_SCRIPT), str(path)],
+ capture_output=True,
+ text=True,
+ )
+
+
+class TestFlagsRawSql:
+ """Patterns that must be flagged by the hook."""
+
+ def test_plain_cursor_execute(self):
+ result = _run_hook(
+ 'cursor.execute("SELECT * FROM users")\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+ assert "Raw SQL" in result.stdout
+
+ def test_fstring_cursor_execute(self):
+ """f-string SQL is an injection risk — must not be silently allowed."""
+ result = _run_hook(
+ 'cursor.execute(f"DELETE FROM users WHERE id = {user_id}")\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+ assert "Raw SQL" in result.stdout
+
+ def test_fstring_conn_execute(self):
+ result = _run_hook(
+ 'conn.execute(f"INSERT INTO logs VALUES ({val})")\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+
+ def test_fstring_session_execute(self):
+ result = _run_hook(
+ "session.execute(f\"UPDATE users SET name = '{n}'\")\n",
+ "service.py",
+ )
+ assert result.returncode == 1
+
+ def test_trailing_sql_comment_does_not_bypass(self):
+ """Previously, `# SQL` anywhere on the line disabled the whole check."""
+ result = _run_hook(
+ 'cursor.execute("DELETE FROM users") # SQL cleanup\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+
+ def test_attestation_filename_not_exempted(self):
+ """'attestation' contains the substring 'test' but is not a test file."""
+ result = _run_hook(
+ 'cursor.execute("SELECT * FROM certificates")\n',
+ "attestation_service.py",
+ )
+ assert result.returncode == 1
+
+ def test_uppercase_f_prefix(self):
+ """Uppercase F-string prefix must also be caught (re.IGNORECASE)."""
+ result = _run_hook(
+ 'query = F"SELECT * FROM users WHERE id = {uid}"\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+ assert "Raw SQL" in result.stdout
+
+ def test_rf_prefix(self):
+ """rf"..." raw-f-string prefix variant must be caught."""
+ result = _run_hook(
+ 'query = rf"DELETE FROM users WHERE id = {uid}"\n',
+ "service.py",
+ )
+ assert result.returncode == 1
+
+ def test_fr_prefix(self):
+ """fr"..." f-raw-string prefix variant must be caught."""
+ result = _run_hook(
+ "query = fr\"UPDATE users SET name = '{n}'\"\n",
+ "service.py",
+ )
+ assert result.returncode == 1
+
+
+class TestAllowsLegitimateUsage:
+ """Patterns that must continue to pass."""
+
+ def test_orm_query(self):
+ result = _run_hook(
+ "session.query(User).filter(User.id == 1).all()\n",
+ "service.py",
+ )
+ assert result.returncode == 0
+
+ def test_text_escape_hatch(self):
+ """SQLAlchemy text() is the sanctioned way to run raw SQL."""
+ result = _run_hook(
+ 'session.execute(text("SELECT 1"))\n',
+ "service.py",
+ )
+ assert result.returncode == 0
+
+ def test_test_file_exempted(self):
+ result = _run_hook(
+ 'cursor.execute("DELETE FROM users")\n',
+ "test_example.py",
+ )
+ assert result.returncode == 0
+
+ def test_migration_file_exempted(self):
+ result = _run_hook(
+ 'cursor.execute("CREATE TABLE foo (id INT)")\n',
+ "migration_001.py",
+ )
+ assert result.returncode == 0
+
+ def test_auth_db_exempted_for_statement_pattern(self):
+ """Regression: auth_db.py was missing from one of the two allowlists."""
+ result = _run_hook(
+ 'cursor.execute("SELECT * FROM users")\n',
+ "auth_db.py",
+ )
+ assert result.returncode == 0
+
+ def test_auth_db_exempted_for_fstring_pattern(self):
+ result = _run_hook(
+ 'conn.execute(f"INSERT INTO logs VALUES ({val})")\n',
+ "auth_db.py",
+ )
+ assert result.returncode == 0