Skip to content

feat: DataCollection now sanitizes SQL statements on SqlClient, EF Core and EF6 spans and breadcrumbs - #5966

Merged
ric-oliv merged 11 commits into
mainfrom
ai/dc-5964-sql-sanitize-5d7980
Nov 24, 2026
Merged

ric-oliv merged 11 commits into
mainfrom
ai/dc-5964-sql-sanitize-5d7980

Conversation

@jamescrosswell

@jamescrosswell jamescrosswell commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

When an app calls the experimental ConfigureDataCollection(...), the SDK now replaces string and numeric literals in SQL statements with ? and removes comments before attaching them to:

  • SqlClient db.query span descriptions
  • EF Core command span descriptions
  • EF6 command span descriptions and breadcrumb messages

EF Core query-compile spans get the database system (sqlite, mssql, ...) as their description instead of the LINQ expression.

SELECT * FROM [Users] WHERE [Email] = N'[email protected]' AND [Id] > 42 -- from checkout
SELECT * FROM [Users] WHERE [Email] = ? AND [Id] > ?

Apps that don't call ConfigureDataCollection send exactly what they send today. None of these call sites puts the statement anywhere else (no db.query.text span data, no breadcrumb data), so the description and the breadcrumb message are the only places it changes.

The sanitizer is a small internal tokenizer (Sentry.Internal.DataCollection.SqlSanitizer), modelled on sentry-go's sql integration. It adds no package dependency.

Part of #5420.

Decisions for review

The issue is labelled Needs Discussion. These are the defaults this draft takes.

  1. Rollout: only for apps that opt in. DataCollectionResolver.SanitizeDbStatements is true once SentryOptions.DataCollection is set. There is no new public option, and SendDefaultPii plays no part. Technically there's no reason for this 'fix' to be restricted to people who opt into the new Data Collection configuration settings - however it's a change in behaviour so enabling it only for those people makes it easier/smoother to introduce. If we wanted to, we could simply add this filtering everywhere (including for people who have not opted into the data collection settings).
  2. Lexer: our own. It handles '...' with '' escapes, N'...', X'...', B'...', PostgreSQL E'...' and $$...$$ / $tag$...$tag$, decimal, exponent and hex/binary/octal numbers, and --, /* */ (nested) and MySQL # comments. It leaves "...", [...] and backtick identifiers, digits inside identifiers (t1, col2) and placeholders (@p0, :name, $1, ?) alone. OpenTelemetry's contrib repo has a fuller one, src/Shared/SqlProcessor.cs (Apache-2.0), that also builds db.query.summary. Vendoring it is an alternative if we want the summary later.
  3. Dialects: one tokenizer, three rule sets. The dialects conflict in five places: "..." (a string in MySQL, an identifier elsewhere), backslash escapes (MySQL, and PostgreSQL's E'...'), [...] (an identifier in SQL Server and SQLite, an array subscript in PostgreSQL), # (a comment in MySQL, a temp table in SQL Server) and $12.50 (money in SQL Server, against PostgreSQL's $1 parameter). SqlSanitizer.Sanitize takes the db.system value and picks the rules in one switch: mssql, mssqlcompact and sqlite → SQL Server rules, mysql and spanner → MySQL rules, anything else (PostgreSQL included) → generic rules. SQLite shares SQL Server's rules: the two only differ on $ before a digit, so a SQLite $1 parameter becomes ?. EF Core's SQLite provider writes @p0. Each call site passes what it already knows:
    • SqlClient passes mssql.
    • EF Core passes the db.system it already sets.
    • EF6 has no db.system, so it maps the ADO.NET command's namespace to one. System.Data.SqlClient and Microsoft.Data.SqlClient → mssql; System.Data.SqlServerCe → mssqlcompact; MySql.Data.MySqlClient, MySqlConnector and Devart.Data.MySql → mysql; System.Data.SQLite, Microsoft.Data.Sqlite and Devart.Data.SQLite → sqlite; anything else, including a wrapped command such as MiniProfiler's, → none, so generic rules. For breadcrumbs, SentryCommandInterceptor passes it to the SDK's own SentryQueryLogger; a custom IQueryLogger still receives the text through the public Log(string), as before. EF6 spans could now set db.system too, which they don't today; that's left for a separate change.
    • Generic rules treat [ as punctuation. That never leaks: at worst a digit inside a bracketed identifier becomes ?. They also treat @ or # before a digit as PostgreSQL's abs and XOR operators, so @5 becomes @?. SQL Server rules keep #1 and @1 as names.
    • SQLite keeps "..." as an identifier. sentry-go treats it as a value, but EF Core's SQLite provider quotes every identifier that way, so its statements would become SELECT ?.? FROM ? AS ?.
  4. Failure: sanitize what we can, then ? for the rest. An unterminated literal or quoted identifier replaces everything after it with one ?, and an unterminated block comment is dropped. go-sqllexer and OpenTelemetry's SqlProcessor do the same. A fixed description would lose the operation and table for every malformed statement. This keeps the part that could be read and never emits the part that couldn't. The tokenizer can't fail outright: every character is either copied as structure or consumed by a literal or comment.
  5. Formatting is kept, not normalised. Whitespace stays as it was, a removed comment leaves the whitespace around it (SELECT /* x */ 1 → SELECT ?), and the result is trimmed. OpenTelemetry's processor does the same. Oracle's positional :1 becomes :?.
  6. EF Core query-compile spans don't get the expression. Their description is the LINQ expression, and EF Core's printer doesn't produce anything a SQL tokenizer can read safely. Captured on EF Core 10 with SQLite:
    'DbSet<Item>()
        .Where(i => i.Name == "it's "quoted" \ back")'
    'DbSet<Item>()
        .Where(i => i.Name.StartsWith("abc") && i.Name.Contains(x))'
    'DbSet<Item>().FromSql(SELECT * FROM Items WHERE Name = 'raw', @p)
    '
    
    The whole expression is wrapped in '...', string constants are printed in "..." without escaping, a char constant is printed with no quotes (Contains(x) for 'x'), and FromSql text is inlined unquoted. Captured variables already print as @captured. The Queries spec says that when the SDK doesn't replace the literals, the description MUST NOT contain the query, and lists what to use instead. A compile event has no summary, operation or target, so the description is the last item on that list, db.system. Keeping the expression would need its own sanitizing, such as replacing ConstantExpression nodes in QueryExpressionEventData.Expression before printing.
  7. Query summary is out of scope. db.query.summary and the operation name are tracked by sentry-java in Generate low-cardinality SQL summaries for database spans sentry-java#5981.
  8. Every comment is removed, including EF Core's tags. EF Core writes TagWith() and TagWithCallSite() as -- lines before the statement, and those go too. A tag can carry free text, such as TagWith($"user {email}") or the source file path from TagWithCallSite(), and people turn this on to send less. This matches every other Sentry SDK that sanitizes SQL: sentry-go (via go-sqllexer) and sentry-javascript (sanitizeSqlQuery) both drop every comment, as do OpenTelemetry's SqlProcessor and Relay, which strips comments before grouping spans for the Queries view. SDKs that don't sanitize (Python, Java, Ruby) send the driver's statement as written, tags included.

Notes

  • EF Core command spans read the command's text. They used to take it from EF Core's log message, after its first line. With EnableSensitiveDataLogging(), a parameter value containing a newline cut that message in the middle of the parameter list, so the description started with other parameter values. They now read the event's LogCommandText (EF Core 10+), then Command.CommandText (EF Core 8 and 9), then the log message. LogCommandText comes first because EF Core 10 replaces values it inlines as sensitive with ? there, and only there, unless sensitive data logging is on; earlier versions don't redact, so their CommandText is what they log. This applies whether or not ConfigureDataCollection is called, and descriptions are otherwise the same as before.

  • OpenTelemetry already sanitizes. Its SqlClient instrumentation always sanitizes db.query.text, with no opt-out (since 1.11.0-beta.1; first stable 1.15.0). Its EF Core instrumentation does the same for SQL-like providers, in prerelease builds only (since 1.13.0-beta.1). This PR doesn't touch Sentry.OpenTelemetry.

  • EF Core's own log messages aren't covered. Sentry.Extensions.Logging turns EF Core's Information-level Executed DbCommand log into a breadcrumb that carries the raw SQL. That is a log message rather than a statement the SDK attaches, so it is left for a separate decision.

Closes #5964

🤖 Generated with Claude Code

…re and EF6 spans and breadcrumbs

When an app calls ConfigureDataCollection, string and numeric literals in
SQL statements are replaced with ? and comments are removed before the
statement becomes a span description or EF6 breadcrumb message. Apps that
don't opt in are unchanged.

The sanitizer is an internal tokenizer modelled on sentry-go's sql
integration, with per-dialect rules where SQL Server, MySQL, SQLite and
PostgreSQL quoting conflict. Unterminated literals replace the rest of the
statement with ?.

Refs #5964

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to approve, with optional comments

The PR fixes the cause: the three SQL call sites now run the statement through an internal tokenizer before it goes into a span description or breadcrumb, and only for apps that call ConfigureDataCollection. The tokenizer always moves forward and cannot throw, there is no public API change, and the tests cover each call site with the option on and off, plus the EF Core dialect mapping.

  • Optional: Closes #5964 will close the issue when this merges, but #5964 lists EF Core query-compile spans (EFQueryCompilerDiagnosticSourceHelper.GetDescription, line 11) as one of the places statements are attached, and this PR leaves them raw on purpose (decision 6). Use Part of #5964 or open a follow-up so that path stays tracked.
  • Optional: EF6 uses generic rules, so on MySQL a backslash-escaped quote also leaks part of a literal, not only "..." strings: 'O\'Brien' becomes ?Brien?. Both EF6 call sites have the DbCommand (SentryQueryPerformanceListener.CreateSpan, and SentryCommandInterceptor.Log at lines 61/65 before it calls IQueryLogger.Log(string)), so the dialect could come from the command or connection type, the way EF Core uses db.system. If you keep generic rules, a test that records this would make the limitation visible.

This is an automated preliminary review.

EF6 has no db.system, so the span and breadcrumb paths used generic rules
and a MySQL statement like 'O\'Brien' leaked part of its literal. Map the
command's namespace to SQL Server, MySQL or SQLite rules instead, and pass
the dialect from SentryCommandInterceptor to SentryQueryLogger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.14%. Comparing base (93c7c4c) to head (203384d).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5966      +/-   ##
==========================================
+ Coverage   77.74%   78.14%   +0.40%     
==========================================
  Files         535      537       +2     
  Lines       19747    20018     +271     
  Branches     3938     4020      +82     
==========================================
+ Hits        15353    15644     +291     
+ Misses       3543     3532      -11     
+ Partials      851      842       -9     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

jamescrosswell and others added 2 commits November 19, 2026 10:41
PostgreSQL uses @ and # as the abs and XOR operators, so @5 and x#5 kept
the digit as part of a name and sent it unsanitized. The generic rules now
replace the number, and no longer let @ or # continue a word. SQL Server,
MySQL and SQLite rules are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Mutation testing breaks the lines a PR changes on purpose, one mutation at a time, and checks that a test fails each time. A changed line no test runs fails the check, and a mutant that survives the tests only warns. Full report

Stryker didn't finish, so not every changed line was checked. The job log has the details.

jamescrosswell and others added 2 commits November 19, 2026 12:24
CI's mutation run timed out, so it was run locally. The surviving mutants
pointed at untested cases (the digit 9, lowercase hex, one-digit exponents,
a leading .5, block comments at either end or touching a token, and most of
the EF6 namespace map) and at two redundant branches, which are removed:
the N'/X'/B' case re-scanned a string the quote case already handles, and
SQL Server's $.5 money branch added nothing ($.5 still becomes $.?).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EF Core writes TagWith() and TagWithCallSite() as '-- ' lines before the
statement. Those tags are how people identify a query, so the sanitizer now
copies that leading block and still removes every other comment.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@jamescrosswell
jamescrosswell marked this pull request as ready for review November 22, 2026 22:57
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

PR risk: medium

For commit 203384d.

Main concerns: data sent to Sentry, host performance, reach.

This label is a hint for reviewers, not an approval.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a big one... but it looks good!
I even tried to find some alternatives, packages, or a less hand-crafted way of doing this, but I couldn't 😄

- SqlSanitizer.Sanitize takes the db.system value and maps it to rules in
  one place. EF6 maps the command namespace to a db.system instead of a
  dialect.
- SQLite shares SQL Server's rules; they only differed on $ before a digit.
- E'...' escape strings only apply under the generic (PostgreSQL) rules.
- EF Core command spans read Command.CommandText, falling back to the log
  message, so a parameter value with a newline no longer cuts the SQL.
- When sanitizing, EF Core query-compile spans use db.system as their
  description instead of the LINQ expression, per the Queries spec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 23, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 11d826e. Configure here.

EF Core 10 replaces values inlined with sensitive: true by ? in
LogCommandText, unless sensitive data logging is on, and leaves them in
Command.CommandText. Reading CommandText first sent those values for apps
that haven't opted into DataCollection. Older EF Core versions don't
redact, so CommandText is still the fallback there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 23, 2026
Every Sentry SDK that sanitizes SQL (sentry-go, sentry-javascript) drops
every comment, as do OpenTelemetry's SqlProcessor and Relay's span
grouping. Keeping EF Core's TagWith() lines was the one place sanitizing
sent free text, such as TagWith($"user {email}") or the source paths from
TagWithCallSite().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot removed the risk: medium PR risk score: medium label Nov 23, 2026
@github-actions github-actions Bot added risk: medium PR risk score: medium and removed risk: medium PR risk score: medium labels Nov 23, 2026
@ric-oliv
ric-oliv merged commit eedb23b into main Nov 24, 2026
63 checks passed
@ric-oliv
ric-oliv deleted the ai/dc-5964-sql-sanitize-5d7980 branch November 24, 2026 08:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sanitize SQL statements before attaching them to database spans and breadcrumbs

2 participants