DBW.

Intermediate

Preventing Secret Leakage in Query Logs and Error Messages

Article diagram
November 25, 2026·11 min read

Database systems must normalize query literals and sanitize error messages at the logging boundary to prevent secrets from leaking into broadly accessible diagnostic infrastructure.

Database systems routinely produce diagnostic output: slow query logs, error messages returned to clients, explain plans, audit trails, and crash dumps.
Each of these channels can inadvertently expose sensitive data that was embedded in SQL statements, query parameters, or internal state.
Secrets such as passwords, API keys, personally identifiable information (PII), and encryption keys regularly appear in plaintext within these artifacts.
The problem is structural, not incidental.
It arises from the way query processing pipelines handle literal values, and fixing it requires deliberate intervention at multiple layers of the system.

How Secrets Enter Queries

diagram-1
Paths by which secrets embedded in SQL reach diagnostic artifacts

Sensitive values reach the query processor through several paths.
The most common is direct embedding of literals in SQL text:

INSERT INTO users (email, ssn, api_key)
VALUES ('alice@example.com', '123-45-6789', 'sk_live_abc123def456');

When this statement is logged (whether by the slow query log, the general query log, or a statement-level replication log), every literal appears in full.
The same applies to WHERE clauses that filter on secret values, UPDATE statements that set new passwords, and dynamic SQL constructed through string concatenation.

Parameterized queries (prepared statements) partially mitigate this problem.
The query text contains placeholders, and bound parameter values travel separately.
However, many logging implementations reconstitute the full query by interpolating parameters back into the template before writing the log entry.
MySQL's general query log records the Execute command and may include parameter values depending on the client library and protocol path; MySQL's binary log in statement-based replication mode logs the fully interpolated SQL text, making it a particularly significant exposure surface.
PostgreSQL's log_min_duration_statement can log queries with parameter values appended, and whether those values appear inline or separately is controlled by settings such as log_parameter_max_length — the behavior is configurable rather than fixed, but default configurations in many deployments do expose bound values.

Error messages present a second exposure surface.
When a query fails due to a constraint violation, type mismatch, or syntax error, the database engine often includes the offending value in the error text.
A unique constraint violation on an email column may return the duplicate email address to the client.
A failed CAST operation may echo the original string.
These messages propagate to application logs, error tracking services, and sometimes directly to end users.

Threat Model

The adversary in this context is anyone with access to log files, error tracking dashboards, monitoring systems, or backup archives that contain diagnostic output.
This includes:

  • Operations engineers with access to log aggregation platforms (Elasticsearch, Splunk, Datadog).
  • Developers reviewing error reports in tools like Sentry or Bugsnag.
  • Attackers who compromise a logging pipeline or storage backend.
  • Third-party vendors who receive log data for analysis.

The key insight is that log storage often has weaker access controls than the database itself.
Organizations invest heavily in database-level encryption, access control, and audit logging, and then route the plaintext content of queries into systems with broad read access.
This creates an asymmetry: the database is locked down, but its secrets leak sideways through operational tooling.

Mitigation Strategies

1. Query Normalization in the Logging Layer

Query normalization replaces all literal values in a SQL statement with placeholder tokens before the statement is written to any log.
The normalized form of the query above would be:

INSERT INTO users (email, ssn, api_key) VALUES (?, ?, ?);

This transformation preserves the structural information needed for performance analysis (identifying slow query patterns, grouping similar queries) while eliminating literal values entirely.

PostgreSQL supports this through the pg_stat_statements extension, which normalizes queries by replacing constants with positional parameters.
In PostgreSQL 14 and later, these appear as $1, $2, etc.; in earlier versions, they appear as ?.
MySQL's Performance Schema normalizes digest text similarly; however, these mechanisms apply only to their specific subsystems.
The general query log, slow query log, and binary log in MySQL still contain raw literals unless additional measures are taken.

For PostgreSQL, setting log_parameter_max_length = -1 disables logging of bound parameter values in server logs entirely; setting it to a positive integer truncates values to that many bytes.
Setting log_parameter_max_length_on_error = -1 similarly suppresses parameter values from error-context log lines. (Note: 0 does not suppress parameter logging — it removes the length cap and logs parameters in full.
Use -1 to disable parameter value logging.)

A robust implementation normalizes queries at the boundary where text exits the query processor, before it reaches any logging sink.
This requires parsing the SQL to identify literal positions, which is nontrivial for complex dialects.

2. Sensitive Column Tagging and Redaction

diagram-3
Redaction decision flow using sensitive-column catalog

Some systems allow columns to be tagged with sensitivity metadata.
When a query references a tagged column, any literal value associated with that column in log output is redacted or masked.
Oracle Data Redaction and SQL Server Dynamic Data Masking operate on query results returned to clients — they do not extend to query log content — but the same tagging principle can be implemented in a custom logging layer.

A practical implementation maintains a catalog of sensitive columns:

users.ssn         -> FULL_REDACT
users.api_key     -> FULL_REDACT
users.email       -> PARTIAL_REDACT (preserve domain)

The logging interceptor cross-references query AST nodes against this catalog and applies the appropriate redaction policy to literals in WHERE, SET, and VALUES clauses that bind to tagged columns.

3. Error Message Sanitization

Error messages must be sanitized before they leave the database server.
This involves two distinct concerns: messages returned to the client and messages written to server-side logs.

For client-facing messages, the principle is minimal disclosure.
A constraint violation should report the constraint name and the column involved, not the value that caused the violation.
Instead of:

ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(alice@example.com) already exists.

The client should receive:

ERROR: duplicate key value violates unique constraint "users_email_key"

The DETAIL line, which contains the actual value, should be suppressed or redacted in client responses while optionally being retained (in redacted form) in server logs for debugging.

In PostgreSQL, the log_error_verbosity GUC controls the verbosity of messages written to the server log only — setting it to TERSE omits DETAIL and HINT lines from server log output, but has no effect on what is transmitted to the client.
The client_min_messages GUC controls the minimum severity of messages sent to the client but does not filter DETAIL fields within a message at a given severity level.
The most reliable approach for stripping DETAIL from client responses is interception at the application driver level — catching the structured error object and re-raising it without the detail field — or through a connection pooler or proxy that filters error responses.
Applications can also configure error tracking integrations (e.g., Sentry's before-send hooks) to strip detail fields before they are transmitted.

4. Transport-Layer Controls

Even when logging is properly sanitized, secrets can leak through network-level captures, replication streams, and backup files.
Binary log events in MySQL contain the full SQL text (for statement-based replication) or row images (for row-based replication).
Both can contain sensitive data.
MySQL 8.0 and later support binary log encryption via the binlog_encryption system variable, which protects at-rest binary log files from unauthorized readers, though it does not remove sensitive values from the stream — authorized readers can still observe plaintext content.

Encrypting replication streams (TLS for in-transit, encryption-at-rest for log files) prevents passive observation but does not prevent authorized readers from seeing secrets.
The only complete mitigation is to ensure secrets are removed or masked before they enter any persistent artifact.

Walkthrough

diagram-2
Logging interceptor pipeline for normalization and redaction

The following walkthrough describes a query logging interceptor that performs normalization and sensitive-column redaction before writing log entries.

Step 1: Intercept the query at the logging boundary. After the query executor completes (or fails), the logging subsystem receives the original SQL text, the execution plan, timing information, and any error state.

Step 2: Parse the SQL text into an AST. Use the database's internal parser or a standalone SQL parser to produce an abstract syntax tree.
Identify all literal nodes (string literals, numeric literals, and typed constants).

Step 3: Classify literals by context. For each literal node, determine its syntactic context.
If it appears in a VALUES clause, identify the target column.
If it appears in a WHERE clause with a column comparison (e.g., WHERE ssn = '123-45-6789'), identify the referenced column.
For expressions involving functions or subqueries, classify the literal as "unknown context."

Step 4: Apply redaction policy. Consult the sensitive column catalog.
If the literal binds to a column tagged FULL_REDACT, replace it with [REDACTED].
If tagged PARTIAL_REDACT, apply the column-specific masking function.
For literals in unknown context or bound to untagged columns, apply the default policy (which may be full normalization to ? for maximum safety, or passthrough for maximum debuggability).

Step 5: Reconstruct the SQL text from the modified AST. Serialize the AST back to SQL text with redacted/normalized literals in place.

Step 6: Sanitize error messages. If the query produced an error, apply structured scanning to the error message to identify and redact substrings that match known sensitive patterns (SSN formats, API key prefixes, email addresses) or that correspond to values from redacted literals.
Note that pattern-based scanning is inherently incomplete — novel or non-standard secret formats will not be matched — so it should be treated as a supplementary control rather than a primary defense.
Wherever possible, prefer suppressing the DETAIL field entirely rather than attempting to scan and redact it.

Step 7: Write the sanitized entry to the log sink. The final log entry contains the normalized/redacted SQL, execution metadata, and sanitized error text; no plaintext secret reaches the log file.

Example applying the catalog defined above (users.email → PARTIAL_REDACT preserving domain; users.ssn → FULL_REDACT):

Input:  INSERT INTO users (email, ssn) VALUES ('alice@example.com', '123-45-6789')
Output: INSERT INTO users (email, ssn) VALUES ('[REDACTED]@example.com', '[REDACTED]')

Operational Considerations

Normalization and redaction have a cost.
Parsing SQL at logging time adds latency to every query.
For high-throughput systems, this overhead may be unacceptable.
Practical mitigations include caching normalized templates keyed by query digest, performing normalization asynchronously in a log processing pipeline (accepting a brief window of plaintext exposure), or applying normalization only to queries that touch tables with tagged sensitive columns.

There is also a tension between security and debuggability.
Fully normalized logs make it harder to reproduce bugs that depend on specific input values.
Organizations typically address this by maintaining a separate, tightly access-controlled debug log that retains full literals, with strict retention policies and audit logging on access.

Finally, any redaction system is only as complete as its catalog of sensitive columns.
Schema changes that add new sensitive columns must trigger updates to the redaction catalog.
Integrating the catalog with schema migration tooling (so that adding a column requires declaring its sensitivity classification) helps prevent gaps.

Key Points

  • Query logs, error messages, replication streams, and crash dumps are all channels through which secrets embedded in SQL literals can leak.
  • Log storage systems typically have broader access than the database itself, creating an asymmetry that amplifies the impact of leaked values.
  • Query normalization (replacing all literals with placeholders) is the most effective blanket mitigation for log-based leakage.
  • Sensitive column tagging enables context-aware redaction that preserves debuggability for non-sensitive values while protecting classified data.
  • Error messages returned to clients should follow minimal disclosure principles, omitting literal values that triggered failures; suppressing DETAIL fields at the driver or proxy layer is more reliable than pattern-based scanning.
  • Parameterized queries reduce but do not eliminate leakage, because many logging implementations interpolate bound parameters back into the query text. In PostgreSQL, set log_parameter_max_length = -1 (not 0) to suppress parameter value logging.
  • Replication stream encryption (e.g., MySQL binlog_encryption) limits unauthorized access to binary logs but does not remove sensitive values; masking before ingestion into any persistent artifact remains the only complete control.
  • Redaction catalogs must be maintained in sync with schema changes to prevent coverage gaps.

References

OWASP Foundation. "Logging Cheat Sheet." OWASP Cheat Sheet Series, 2023. https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html

PostgreSQL Global Development Group. "pg_stat_statements: Track Execution Statistics of SQL Statements." PostgreSQL Documentation, 2024.

PostgreSQL Global Development Group. "Error Reporting and Logging." PostgreSQL Documentation, Chapter 20.8, 2024. https://www.postgresql.org/docs/current/runtime-config-logging.html

Saltzer, J.H. and Schroeder, M.D. "The Protection of Information in Computer Systems." Proceedings of the IEEE, 63(9), 1975, pp. 1278-1308.

NIST. "Guide to Computer Security Log Management." Special Publication 800-92, 2006. https://csrc.nist.gov/publications/detail/sp/800-92/final

Newsletter

Signal
over noise.

Database deep-dives, delivered once a week. Storage engines, query optimization, and the data layer.

You will receive Databases Weekly.