Repository navigation
feat: DataCollection now sanitizes SQL statements on SqlClient, EF Core and EF6 spans and breadcrumbs - #5966
jamescrosswell wants to merge 10 commits into
Conversation
…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 <noreply@anthropic.com>
There was a problem hiding this comment.
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 #5964will 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). UsePart of #5964or 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 theDbCommand(SentryQueryPerformanceListener.CreateSpan, andSentryCommandInterceptor.Logat lines 61/65 before it callsIQueryLogger.Log(string)), so the dialect could come from the command or connection type, the way EF Core usesdb.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 <noreply@anthropic.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #5966 +/- ##
==========================================
+ Coverage 77.74% 78.12% +0.38%
==========================================
Files 535 537 +2
Lines 19747 20022 +275
Branches 3938 4022 +84
==========================================
+ Hits 15353 15643 +290
+ Misses 3543 3535 -8
+ Partials 851 844 -7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
|
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. |
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…o ai/dc-5964-sql-sanitize-5d7980 # Conflicts: # test/Sentry.Tests/Internals/DataCollectionResolverTests.cs
PR risk: mediumFor commit Main concerns: data sent to Sentry, host performance, reach. This label is a hint for reviewers, not an approval. |
| private char Peek(int offset = 1) => _position + offset < sql.Length ? sql[_position + offset] : '\0'; | ||
|
|
||
| // EF Core writes TagWith() and TagWithCallSite() as "-- " lines ahead of the statement | ||
| private void CopyLeadingLineComments() |
There was a problem hiding this comment.
Keeping the leading -- lines is the one place where we send free text on purpose. TagWithCallSite() puts a source file path there, and TagWith($"user {email}") would send the email as written. sentry-go and OpenTelemetry's sanitizer drop every comment. Decision 8 explains why tags are useful in Sentry. I'm just not sure keeping them should be the default for an option people turn on to send less. What do you think?
There was a problem hiding this comment.
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 <noreply@anthropic.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ 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 <noreply@anthropic.com>

When an app calls the experimental
ConfigureDataCollection(...), the SDK now replaces string and numeric literals in SQL statements with?and removes comments, apart from--lines ahead of the statement, before attaching them to:db.queryspan descriptionsEF Core query-compile spans get the database system (
sqlite,mssql, ...) as their description instead of the LINQ expression.Apps that don't call
ConfigureDataCollectionsend exactly what they send today. None of these call sites puts the statement anywhere else (nodb.query.textspan 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'ssqlintegration. It adds no package dependency.Part of #5420.
Decisions for review
The issue is labelled Needs Discussion. These are the defaults this draft takes.
DataCollectionResolver.SanitizeDbStatementsis true onceSentryOptions.DataCollectionis set. There is no new public option, andSendDefaultPiiplays 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).'...'with''escapes,N'...',X'...',B'...', PostgreSQLE'...'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 buildsdb.query.summary. Vendoring it is an alternative if we want the summary later."..."(a string in MySQL, an identifier elsewhere), backslash escapes (MySQL, and PostgreSQL'sE'...'),[...](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$1parameter).SqlSanitizer.Sanitizetakes thedb.systemvalue and picks the rules in one switch:mssql,mssqlcompactandsqlite→ SQL Server rules,mysqlandspanner→ 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$1parameter becomes?. EF Core's SQLite provider writes@p0. Each call site passes what it already knows:mssql.db.systemit already sets.db.system, so it maps the ADO.NET command's namespace to one.System.Data.SqlClientandMicrosoft.Data.SqlClient→mssql;System.Data.SqlServerCe→mssqlcompact;MySql.Data.MySqlClient,MySqlConnectorandDevart.Data.MySql→mysql;System.Data.SQLite,Microsoft.Data.SqliteandDevart.Data.SQLite→sqlite; anything else, including a wrapped command such as MiniProfiler's, → none, so generic rules. For breadcrumbs,SentryCommandInterceptorpasses it to the SDK's ownSentryQueryLogger; a customIQueryLoggerstill receives the text through the publicLog(string), as before. EF6 spans could now setdb.systemtoo, which they don't today; that's left for a separate change.[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@5becomes@?. SQL Server rules keep#1and@1as names."..."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 becomeSELECT ?.? FROM ? AS ?.?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'sSqlProcessordo 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.SELECT /* x */ 1→SELECT ?), and the result is trimmed. OpenTelemetry's processor does the same. Oracle's positional:1becomes:?.'...', string constants are printed in"..."without escaping, acharconstant is printed with no quotes (Contains(x)for'x'), andFromSqltext 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 replacingConstantExpressionnodes inQueryExpressionEventData.Expressionbefore printing.db.query.summaryand the operation name are tracked by sentry-java in Generate low-cardinality SQL summaries for database spans sentry-java#5981.TagWith()andTagWithCallSite()as--lines before the statement, and people add those tags to find a query in tools like Sentry. Removing them would be the one change from sanitizing that users notice. So the sanitizer copies--lines up to the first token of the statement and removes every other comment:#comments ahead of the statement go too, since EF Core doesn't write tags that way. A tag built from a runtime value, such asTagWith($"user {email}"), is sent as written, as it is today.TagWithCallSite()puts a source file path in the tag.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'sLogCommandText(EF Core 10+), thenCommand.CommandText(EF Core 8 and 9), then the log message.LogCommandTextcomes 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 theirCommandTextis what they log. This applies whether or notConfigureDataCollectionis 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 touchSentry.OpenTelemetry.EF Core's own log messages aren't covered.
Sentry.Extensions.Loggingturns EF Core's Information-levelExecuted DbCommandlog 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