Skip to main content
This guide explains how to use TrueFoundry’s built-in SQL Sanitizer guardrail to detect and handle potentially dangerous SQL patterns in LLM interactions.

What is SQL Sanitizer?

SQL Sanitizer is a built-in TrueFoundry guardrail that identifies and handles risky SQL patterns in text content. It can detect destructive SQL statements, unsafe query patterns, and potential SQL injection vectors. The guardrail runs directly within the AI Gateway without requiring external API calls.

Key Features

  1. Destructive Statement Detection: Identifies dangerous SQL operations including:
    • DROP statements that can delete tables or databases
    • TRUNCATE statements that remove all data from tables
    • ALTER statements that modify table structures
    • GRANT and REVOKE statements that change permissions
  2. Unsafe Pattern Detection: Identifies risky query patterns:
    • DELETE statements without WHERE clauses
    • UPDATE statements without WHERE clauses
    • String interpolation patterns that may indicate SQL injection vulnerabilities
  3. Flexible Operation Modes:
    • Validate: Detect risky patterns and block requests/responses
    • Mutate: Detect patterns, optionally strip comments, and continue with sanitized output

Adding SQL Sanitizer Guardrail

To add SQL Sanitizer to your TrueFoundry setup, follow these steps:
1

Navigate to Guardrails

Go to the AI Gateway dashboard and navigate to the Guardrails section.
2

Create or Select a Guardrails Group

Create a new guardrails group or select an existing one where you want to add the SQL Sanitizer guardrail.
3

Add SQL Sanitizer Integration

Click on Add Guardrail and select SQL Sanitizer from the TrueFoundry Guardrails section.
TrueFoundry guardrail selection interface showing SQL Sanitizer option
4

Configure the Guardrail

Fill in the configuration form with your desired settings (see Configuration Options below).
5

Save the Configuration

Click Save to add the guardrail to your group.

Configuration Options

ParameterDefaultDescription
Operationvalidatevalidate (block) or mutate (sanitize + continue)
Priority1Execution order for mutate guardrails (lower runs first)
Enforcing Strategyenforceenforce, enforce_but_ignore_on_error, or audit
Block DROP/TRUNCATE/ALTER/GRANT/REVOKEtrueBlock destructive statements
Strip SQL CommentstrueRemove -- and /* */ comments
Block DELETE/UPDATE without WHEREtrueBlock bulk operations
Require ParameterizationfalseFlag string interpolation patterns
See Guardrails Overview for Operation Modes and Enforcing Strategy details.

Validate vs Mutate

BehaviorValidateMutate
Blocked statements (DROP, etc.)Block requestLog but continue
DELETE/UPDATE without WHEREBlock requestLog but continue
SQL commentsPreservedStripped
Interpolation patternsBlock requestLog but continue

Detected SQL Patterns

Destructive Statements

StatementRisk LevelDescription
DROP TABLECriticalPermanently deletes tables
DROP DATABASECriticalPermanently deletes entire databases
TRUNCATE TABLECriticalRemoves all rows from a table
ALTER TABLEHighModifies table structure
GRANTHighAdds permissions
REVOKEHighRemoves permissions

Unsafe Query Patterns

PatternRisk LevelDescription
DELETE FROM table (no WHERE)HighDeletes all rows in table
UPDATE table SET (no WHERE)HighUpdates all rows in table

SQL Injection Detection (Require Parameterization)

When Require Parameterization is enabled, the guardrail detects potential SQL injection vectors by looking for string interpolation patterns:
Pattern TypeDetectionExample
String Concatenation+ operator"SELECT * FROM " + table_name
Python % Formatting%. pattern"SELECT * FROM %s" % table
Template Literals / F-strings{...} bracesf"SELECT * FROM {table}"
Interpolation detection is heuristic-based and may have false positives (e.g., JSON data with braces). Enable this option only when you specifically need to enforce parameterized queries.

SQL Comment Patterns

The guardrail detects and can strip SQL comments:
Comment TypePatternExample
Line Comment-- ...SELECT * FROM users; -- admin bypass
Block Comment/* ... */SELECT * /* hidden */ FROM users
Comments can be used to hide malicious SQL. Enable Strip SQL Comments to remove them, especially when processing user-provided or LLM-generated SQL.

How It Works

  1. Recursively scans all string content (including nested objects/arrays)
  2. Strips comments (if enabled) before checking patterns
  3. Checks for blocked statements and missing WHERE clauses
  4. Returns verdict and optionally sanitized content (up to 10 issues per request)
{
  "error": null,
  "verdict": false,
  "data": {
    "issues": [
      { "type": "blocked_statement", "message": "Blocked SQL statement detected: DROP", "field": "messages[0].content" },
      { "type": "delete_without_where", "message": "DELETE without WHERE clause detected", "field": "messages[0].content" }
    ],
    "sanitized": false,
    "explanation": "Detected 2 SQL issue(s): blocked_statement, delete_without_where"
  },
  "transformedData": {
    "request": { "json": null },
    "response": { "json": null }
  },
  "transformed": false
}

Validate Mode

When configured in validate mode, the guardrail blocks requests containing risky patterns.
DROP TABLE users;
Result: Blocked - blocked_statement: Blocked SQL statement detected: DROP
DELETE FROM orders;
Result: Blocked - delete_without_where: DELETE without WHERE clause detected
SELECT * FROM users WHERE id = 1;
Result: Allowed - No SQL issues detected
DELETE FROM orders WHERE created_at < '2024-01-01';
Result: Allowed - DELETE has WHERE clause

Mutate Mode

When configured in mutate mode, the guardrail:
  • Strips SQL comments from the output (line comments -- and block comments /* */)
  • Logs all detected issues but allows the request to continue
  • Returns sanitized content with comments removed
Input:
SELECT * FROM users; -- bypass authentication
Output:
SELECT * FROM users;
Issues logged: Comment stripped (no blocking issue)
Input:
SELECT * /* admin */ FROM users WHERE role = 'user'
Output:
SELECT *  FROM users WHERE role = 'user'
Input:
DROP TABLE temp_data;
Output: Same as input (not modified)
Issues logged: blocked_statement: Blocked SQL statement detected: DROP
Verdict: Allowed (mutate mode doesn’t block)
Use mutate mode carefully: In mutate mode, even dangerous statements like DROP are logged but not blocked. Use this mode only when you have additional safeguards in place or need to sanitize comments while monitoring for issues.

Use Cases

Text-to-SQL Applications

When building applications that convert natural language to SQL, apply SQL Sanitizer on MCP Pre Tool to validate queries before they’re executed by the database tool:
name: guardrails-control
type: gateway-guardrails-config
rules:
  - id: text-to-sql-safety
    when:
      target:
        operator: or
        conditions:
          mcpServers:
            values:
              - database-tools
            condition: in
          mcpTools:
            values:
              - execute_query
            condition: in
      subjects:
        operator: and
        conditions:
          in:
            - team:data-engineering
          not_in:
            - user:db-admin@example.com
    llm_input_guardrails: []
    llm_output_guardrails: []
    mcp_tool_pre_invoke_guardrails:
      - my-guardrail-group/sql-sanitizer
    mcp_tool_post_invoke_guardrails: []
This ensures dangerous SQL (DROP, TRUNCATE, DELETE without WHERE) is blocked before reaching the database.

Input Validation

Apply SQL Sanitizer to user inputs to detect potential SQL injection attempts:
curl -X POST "https://{controlPlaneURL}/api/llm/chat/completions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H 'X-TFY-GUARDRAILS: {"llm_input_guardrails":["my-guardrail-group/sql-sanitizer"],"llm_output_guardrails":[]}' \
  -d '{
    "model": "openai-main/gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "Search for user: Robert'); DROP TABLE users;--"}
    ]
  }'

Best Practices

SQL Sanitizer provides defense-in-depth but doesn’t replace database permissions. Always configure database users with minimum required privileges.
Pattern-based detection: Case-insensitive regex matching. May have false positives in prose text. Complex obfuscation may bypass detection.
HookUse Case
LLM OutputValidate SQL in LLM responses (text-to-SQL apps)
MCP Pre ToolValidate SQL before execution by database tools
MCP Post ToolSanitize SQL in tool outputs
name: guardrails-control
type: gateway-guardrails-config
rules:
  - id: database-tool-safety
    when:
      target:
        operator: or
        conditions:
          mcpServers:
            values:
              - database-tools
            condition: in
      subjects:
        operator: and
        conditions:
          in:
            - team:engineering
          not_in:
            - user:db-admin@example.com
    llm_input_guardrails: []
    llm_output_guardrails: []
    mcp_tool_pre_invoke_guardrails:
      - my-guardrail-group/sql-sanitizer
    mcp_tool_post_invoke_guardrails: []
Always apply SQL Sanitizer to MCP Pre Tool for database tools to prevent dangerous SQL execution.

Customizing Rules

Read-only apps: Enable all blocking options. Write-enabled apps: Keep DROP/TRUNCATE/ALTER blocking, optionally disable DELETE/UPDATE without WHERE checks.