Skip to content

fix(prepare-db): add SQL injection protection to explain_generic#18

Closed
NikolayS wants to merge 2 commits into
mainfrom
claude/fix-explain-generic-sql-injection-boJKG
Closed

fix(prepare-db): add SQL injection protection to explain_generic#18
NikolayS wants to merge 2 commits into
mainfrom
claude/fix-explain-generic-sql-injection-boJKG

Conversation

@NikolayS
Copy link
Copy Markdown
Contributor

Summary

  • Add input validation to postgres_ai.explain_generic() function to prevent SQL injection
  • Reject empty/null queries
  • Detect and reject multiple statements (semicolon outside trailing position)
  • Strip trailing semicolons for convenience
  • Add comprehensive integration tests for the validation logic

Fixes #70

Changes

SQL injection protection (cli/sql/05.helpers.sql)

-- Input validation: reject empty queries
if query is null or trim(query) = '' then
  raise exception 'query cannot be empty';
end if;

-- Input validation: strip semicolons and anything after them
v_clean_query := trim(query);
if v_clean_query like '%;%' then
  v_clean_query := regexp_replace(v_clean_query, ';\s*$', '');
  if v_clean_query like '%;%' then
    raise exception 'query contains multiple statements (semicolon detected)';
  end if;
end if;

Add defense-in-depth measures to prevent SQL injection in the
explain_generic function:

- Validate that query is not empty
- Strip trailing semicolons
- Reject queries containing multiple statements (semicolons mid-query)
- Add security documentation explaining why EXPLAIN is inherently safe
  (read-only, single statement only)

The function remains safe because:
1. EXPLAIN without ANALYZE only plans, never executes
2. PostgreSQL's EXPLAIN only accepts a single statement
3. PL/pgSQL EXECUTE only runs one statement

Closes: https://gitlab.com/postgres-ai/postgres_ai/-/issues/70
…tion protection

Add comprehensive tests for the SQL injection validation in explain_generic:
- Empty query rejection
- Null query rejection
- Multiple statements (semicolon) rejection
- Trailing semicolon handling
- Valid query execution
- JSON format output

Related to: https://gitlab.com/postgres-ai/postgres_ai/-/issues/70
@NikolayS NikolayS closed this Dec 30, 2025
@NikolayS NikolayS deleted the claude/fix-explain-generic-sql-injection-boJKG branch December 30, 2025 04:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants