diff --git a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFCommandDiagnosticSourceHelper.cs b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFCommandDiagnosticSourceHelper.cs index 930c4a0d4a..ed51fc51a3 100644 --- a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFCommandDiagnosticSourceHelper.cs +++ b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFCommandDiagnosticSourceHelper.cs @@ -1,4 +1,5 @@ using Sentry.Extensibility; +using Sentry.Internal.DataCollection; using Sentry.Internal.Extensions; namespace Sentry.Internal.DiagnosticSource; @@ -11,7 +12,16 @@ internal EFCommandDiagnosticSourceHelper(IHub hub, SentryOptions options) : base protected override string Operation => "db.query"; - protected override string GetDescription(object? diagnosticSourceValue) => FilterNewLineValue(diagnosticSourceValue) ?? string.Empty; + protected override string GetDescription(object? diagnosticSourceValue) + { + // EF Core 10 redacts sensitive inlined values in LogCommandText only; older versions don't redact + var commandText = (diagnosticSourceValue?.GetStringProperty("LogCommandText", Options.DiagnosticLogger) + ?? diagnosticSourceValue?.GetStringProperty("Command.CommandText", Options.DiagnosticLogger))?.TrimEnd() + ?? FilterNewLineValue(diagnosticSourceValue) ?? string.Empty; + return Options.DataCollectionResolver.SanitizeDbStatements + ? SqlSanitizer.Sanitize(commandText, GetDatabaseSystem(diagnosticSourceValue)) + : commandText; + } private Guid? GetCommandId(object? diagnosticSourceValue) => diagnosticSourceValue?.GetGuidProperty("CommandId", Options.DiagnosticLogger); diff --git a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFQueryCompilerDiagnosticSourceHelper.cs b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFQueryCompilerDiagnosticSourceHelper.cs index 2d64db6e13..57d0a57b6b 100644 --- a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFQueryCompilerDiagnosticSourceHelper.cs +++ b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/EFQueryCompilerDiagnosticSourceHelper.cs @@ -8,7 +8,10 @@ internal EFQueryCompilerDiagnosticSourceHelper(IHub hub, SentryOptions options) protected override string Operation => "db.query.compile"; - protected override string GetDescription(object? diagnosticSourceValue) => FilterNewLineValue(diagnosticSourceValue) ?? string.Empty; + protected override string? GetDescription(object? diagnosticSourceValue) => + Options.DataCollectionResolver.SanitizeDbStatements + ? GetDatabaseSystem(diagnosticSourceValue) + : FilterNewLineValue(diagnosticSourceValue) ?? string.Empty; /// /// We don't have a correlation id for compiled query events. We just return the first unfinished query compile span. diff --git a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/SentrySqlListener.cs b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/SentrySqlListener.cs index d141095386..c53b4183ea 100644 --- a/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/SentrySqlListener.cs +++ b/src/Sentry.DiagnosticSource/Internal/DiagnosticSource/SentrySqlListener.cs @@ -3,6 +3,7 @@ #if !NETFRAMEWORK using Sentry.Extensibility; +using Sentry.Internal.DataCollection; using Sentry.Internal.Extensions; namespace Sentry.Internal.DiagnosticSource; @@ -210,7 +211,10 @@ private void FinishCommandSpan(object? value, SpanStatus spanStatus) } } - commandSpan.Description = value.GetStringProperty("Command.CommandText", _options.DiagnosticLogger); + var commandText = value.GetStringProperty("Command.CommandText", _options.DiagnosticLogger); + commandSpan.Description = _options.DataCollectionResolver.SanitizeDbStatements + ? SqlSanitizer.Sanitize(commandText, "mssql") + : commandText; commandSpan.Finish(spanStatus); } diff --git a/src/Sentry.EntityFramework/DbCommandExtensions.cs b/src/Sentry.EntityFramework/DbCommandExtensions.cs new file mode 100644 index 0000000000..b2be2b61a2 --- /dev/null +++ b/src/Sentry.EntityFramework/DbCommandExtensions.cs @@ -0,0 +1,15 @@ +namespace Sentry.EntityFramework; + +internal static class DbCommandExtensions +{ + internal static string? GetDbSystem(this DbCommand command) => DbSystemForNamespace(command.GetType().Namespace); + + internal static string? DbSystemForNamespace(string? commandNamespace) => commandNamespace switch + { + "System.Data.SqlClient" or "Microsoft.Data.SqlClient" => "mssql", + "System.Data.SqlServerCe" => "mssqlcompact", + "MySql.Data.MySqlClient" or "MySqlConnector" or "Devart.Data.MySql" => "mysql", + "System.Data.SQLite" or "Microsoft.Data.Sqlite" or "Devart.Data.SQLite" => "sqlite", + _ => null + }; +} diff --git a/src/Sentry.EntityFramework/SentryCommandInterceptor.cs b/src/Sentry.EntityFramework/SentryCommandInterceptor.cs index d0662c6226..db52fbba33 100644 --- a/src/Sentry.EntityFramework/SentryCommandInterceptor.cs +++ b/src/Sentry.EntityFramework/SentryCommandInterceptor.cs @@ -56,13 +56,14 @@ public virtual void Log(DbCommand command, DbCommandInterceptionContext in return; } - if (interceptionContext.Exception == null) + var level = interceptionContext.Exception == null ? BreadcrumbLevel.Debug : BreadcrumbLevel.Error; + if (_queryLogger is SentryQueryLogger sentryQueryLogger) { - _queryLogger.Log(command.CommandText); + sentryQueryLogger.Log(command.CommandText, command.GetDbSystem(), level); } else { - _queryLogger.Log(command.CommandText, BreadcrumbLevel.Error); + _queryLogger.Log(command.CommandText, level); } } } diff --git a/src/Sentry.EntityFramework/SentryQueryLogger.cs b/src/Sentry.EntityFramework/SentryQueryLogger.cs index d87df0341d..4bdc4ba862 100644 --- a/src/Sentry.EntityFramework/SentryQueryLogger.cs +++ b/src/Sentry.EntityFramework/SentryQueryLogger.cs @@ -1,3 +1,5 @@ +using Sentry.Internal.DataCollection; + namespace Sentry.EntityFramework; internal class SentryQueryLogger : IQueryLogger @@ -7,8 +9,13 @@ internal class SentryQueryLogger : IQueryLogger public SentryQueryLogger(IHub? hub = null) => _hub = hub ?? HubAdapter.Instance; public void Log(string text, BreadcrumbLevel level = BreadcrumbLevel.Debug) + => Log(text, null, level); + + internal void Log(string text, string? dbSystem, BreadcrumbLevel level) => _hub.AddBreadcrumb( - message: text, + message: _hub.GetSentryOptions()?.DataCollectionResolver.SanitizeDbStatements == true + ? SqlSanitizer.Sanitize(text, dbSystem) + : text, category: "Entity Framework", type: null, data: null, diff --git a/src/Sentry.EntityFramework/SentryQueryPerformanceListener.cs b/src/Sentry.EntityFramework/SentryQueryPerformanceListener.cs index 2d4fea7d8f..ef9c746d24 100644 --- a/src/Sentry.EntityFramework/SentryQueryPerformanceListener.cs +++ b/src/Sentry.EntityFramework/SentryQueryPerformanceListener.cs @@ -1,4 +1,5 @@ using Sentry.Internal; +using Sentry.Internal.DataCollection; namespace Sentry.EntityFramework; @@ -21,31 +22,37 @@ internal SentryQueryPerformanceListener(IHub hub, SentryOptions options) } public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) - => CreateSpan(DbReaderKey, command.CommandText, interceptionContext); + => CreateSpan(DbReaderKey, command, interceptionContext); public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) => Finish(DbReaderKey, interceptionContext); public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) - => CreateSpan(DbNonQueryKey, command.CommandText, interceptionContext); + => CreateSpan(DbNonQueryKey, command, interceptionContext); public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) => Finish(DbNonQueryKey, interceptionContext); public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext) - => CreateSpan(DbScalarKey, command.CommandText, interceptionContext); + => CreateSpan(DbScalarKey, command, interceptionContext); public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext) => Finish(DbScalarKey, interceptionContext); - private void CreateSpan(string key, string? command, + private void CreateSpan(string key, DbCommand command, DbCommandInterceptionContext interceptionContext) { - if (_hub.GetSpan()?.StartChild(key, command) is { } span) + if (_hub.GetSpan() is not { } parent) { - span.SetOrigin(EntityFrameworkOrigin); - interceptionContext.AttachSpan(span); + return; } + + var description = _options.DataCollectionResolver.SanitizeDbStatements + ? SqlSanitizer.Sanitize(command.CommandText, command.GetDbSystem()) + : command.CommandText; + var span = parent.StartChild(key, description); + span.SetOrigin(EntityFrameworkOrigin); + interceptionContext.AttachSpan(span); } /// diff --git a/src/Sentry/Internal/DataCollection/SqlSanitizer.cs b/src/Sentry/Internal/DataCollection/SqlSanitizer.cs new file mode 100644 index 0000000000..861e2276cb --- /dev/null +++ b/src/Sentry/Internal/DataCollection/SqlSanitizer.cs @@ -0,0 +1,297 @@ +namespace Sentry.Internal.DataCollection; + +internal static class SqlSanitizer +{ + [return: NotNullIfNotNull(nameof(sql))] + internal static string? Sanitize(string? sql, string? dbSystem = null) => + sql is null ? null : new Scanner(sql, DialectFor(dbSystem)).Run(); + + private static SqlDialect DialectFor(string? dbSystem) => dbSystem switch + { + "mssql" or "mssqlcompact" or "sqlite" => SqlDialect.SqlServer, + "mysql" or "spanner" => SqlDialect.MySql, + _ => SqlDialect.Generic + }; + + private enum SqlDialect + { + Generic, // Postgres compatible + SqlServer, + MySql + } + + private sealed class Scanner(string sql, SqlDialect dialect) + { + private const char Placeholder = '?'; + + private readonly StringBuilder _output = new(sql.Length); + private int _position; + + internal string Run() + { + while (_position < sql.Length) + { + ScanToken(); + } + + return _output.ToString().Trim(); + } + + private char Current => sql[_position]; + + private char Peek(int offset = 1) => _position + offset < sql.Length ? sql[_position + offset] : '\0'; + + private void ScanToken() + { + var current = Current; + var next = Peek(); + switch (current) + { + case '-' when next == '-': + case '#' when dialect == SqlDialect.MySql: + SkipLineComment(); + return; + case '/' when next == '*': + SkipBlockComment(); + return; + case '\'': + SkipString('\'', backslashEscapes: dialect == SqlDialect.MySql); + return; + case 'N' or 'n' or 'X' or 'x' or 'B' or 'b' when next == '\'': + _position++; + return; + case 'E' or 'e' when next == '\'' && dialect == SqlDialect.Generic: + _position++; + SkipString('\'', backslashEscapes: true); + return; + case '"' when dialect == SqlDialect.MySql: + SkipString('"', backslashEscapes: true); + return; + case '"': + case '`': + CopyQuotedIdentifier(current); + return; + case '[' when dialect == SqlDialect.SqlServer: + CopyQuotedIdentifier(']'); + return; + case '$': + ScanDollar(); + return; + case '.' when IsDigit(next) && !FollowsWord(): + SkipNumber(); + return; + case '@' or '#' when dialect == SqlDialect.Generic && IsDigit(next): + _output.Append(current); + _position++; + return; + } + + if (IsDigit(current)) + { + SkipNumber(); + } + else if (IsWordStart(current)) + { + CopyWord(); + } + else + { + _output.Append(current); + _position++; + } + } + + private void SkipLineComment() + { + while (_position < sql.Length && Current is not ('\n' or '\r')) + { + _position++; + } + } + + private void SkipBlockComment() + { + _position += 2; + var depth = 1; + while (_position < sql.Length && depth > 0) + { + if (Current == '/' && Peek() == '*') + { + depth++; + _position += 2; + } + else if (Current == '*' && Peek() == '/') + { + depth--; + _position += 2; + } + else + { + _position++; + } + } + + if (_output.Length > 0 && !char.IsWhiteSpace(_output[_output.Length - 1]) && + _position < sql.Length && !char.IsWhiteSpace(Current)) + { + _output.Append(' '); + } + } + + private void SkipString(char quote, bool backslashEscapes) + { + _position++; + while (_position < sql.Length) + { + var current = Current; + if (backslashEscapes && current == '\\') + { + _position = Math.Min(_position + 2, sql.Length); + continue; + } + + _position++; + if (current == quote) + { + if (_position < sql.Length && Current == quote) + { + _position++; + continue; + } + + break; + } + } + + _output.Append(Placeholder); + } + + private void CopyQuotedIdentifier(char closingQuote) + { + var start = _position; + _position++; + while (_position < sql.Length) + { + var current = Current; + _position++; + if (current == closingQuote) + { + if (_position < sql.Length && Current == closingQuote) + { + _position++; + continue; + } + + _output.Append(sql, start, _position - start); + return; + } + } + + _output.Append(Placeholder); + } + + private void ScanDollar() + { + if (IsDigit(Peek())) + { + if (dialect == SqlDialect.SqlServer) + { + _position++; + SkipNumber(); + } + else + { + CopyWord(); + } + + return; + } + + var tagEnd = _position + 1; + while (tagEnd < sql.Length && (char.IsLetterOrDigit(sql[tagEnd]) || sql[tagEnd] == '_')) + { + tagEnd++; + } + + if (tagEnd < sql.Length && sql[tagEnd] == '$') + { + var delimiter = sql.Substring(_position, tagEnd + 1 - _position); + var closingDelimiter = sql.IndexOf(delimiter, tagEnd + 1, StringComparison.Ordinal); + _position = closingDelimiter < 0 ? sql.Length : closingDelimiter + delimiter.Length; + _output.Append(Placeholder); + return; + } + + CopyWord(); + } + + private void SkipNumber() + { + if (Current == '0' && Peek() is 'x' or 'X' or 'b' or 'B' or 'o' or 'O' && IsHexDigit(Peek(2))) + { + _position += 2; + while (_position < sql.Length && (IsHexDigit(Current) || Current == '_')) + { + _position++; + } + } + else + { + SkipDigits(); + if (_position < sql.Length && Current == '.' && IsDigit(Peek())) + { + _position++; + SkipDigits(); + } + + if (_position < sql.Length && Current is 'e' or 'E') + { + var exponentStart = Peek() is '+' or '-' ? 2 : 1; + if (IsDigit(Peek(exponentStart))) + { + _position += exponentStart; + SkipDigits(); + } + } + } + + _output.Append(Placeholder); + } + + private void SkipDigits() + { + while (_position < sql.Length && (IsDigit(Current) || Current == '_')) + { + _position++; + } + } + + private void CopyWord() + { + var start = _position; + _position++; + while (_position < sql.Length && IsWordPart(Current)) + { + _position++; + } + + _output.Append(sql, start, _position - start); + } + + private bool FollowsWord() => _position > 0 && IsWordPart(sql[_position - 1]); + + private static bool IsWordStart(char c) => char.IsLetter(c) || c is '_' or '@' or '#'; + + private bool IsWordPart(char c) => c switch + { + '_' or '$' => true, + '@' => dialect != SqlDialect.Generic, + '#' => dialect == SqlDialect.SqlServer, + _ => char.IsLetterOrDigit(c) + }; + + private static bool IsDigit(char c) => c is >= '0' and <= '9'; + + private static bool IsHexDigit(char c) => IsDigit(c) || c is >= 'a' and <= 'f' or >= 'A' and <= 'F'; + } +} diff --git a/src/Sentry/Internal/DataCollectionResolver.cs b/src/Sentry/Internal/DataCollectionResolver.cs index c5e442077d..c281070e07 100644 --- a/src/Sentry/Internal/DataCollectionResolver.cs +++ b/src/Sentry/Internal/DataCollectionResolver.cs @@ -29,6 +29,8 @@ internal sealed class DataCollectionResolver(SentryOptions options) public bool GenAIOutputs => Configured?.GenAI.Outputs ?? true; + public bool SanitizeDbStatements => Configured is not null; + public KeyValueCollectionBehavior Cookies => Configured?.Cookies ?? (SendDefaultPii ? DenyList : Off); diff --git a/test/Sentry.DiagnosticSource.Tests/SentryEFCoreListenerTests.cs b/test/Sentry.DiagnosticSource.Tests/SentryEFCoreListenerTests.cs index 7659ac1cb8..7df1ba940b 100644 --- a/test/Sentry.DiagnosticSource.Tests/SentryEFCoreListenerTests.cs +++ b/test/Sentry.DiagnosticSource.Tests/SentryEFCoreListenerTests.cs @@ -203,7 +203,7 @@ public class ContextInfo { public class DatabaseInfo { - public string ProviderName { get; } = "Microsoft.EntityFrameworkCore.SqlServer"; + public string ProviderName { get; set; } = "Microsoft.EntityFrameworkCore.SqlServer"; } public DatabaseInfo Database { get; } = new(); } @@ -225,6 +225,13 @@ public FakeDiagnosticCommandEventData(FakeDiagnosticConnectionEventData connecti public Guid ConnectionId { get; set; } public Guid CommandId { get; set; } = Guid.NewGuid(); + + public class CommandInfo + { + public string CommandText { get; set; } + } + public CommandInfo Command { get; set; } + public string LogCommandText { get; set; } } [Fact] @@ -299,6 +306,112 @@ public void OnNext_HappyPath_IsValid() ((SpanTracer)commandSpan).Origin.Should().Be(SentryEFCoreListener.EFCoreListenerOrigin); } + [Fact] + public void OnNext_CommandExecuting_DataCollectionNotConfigured_DescriptionUnchanged() + { + // Arrange + const string sql = "SELECT [i].[Name] FROM [Items] AS [i] WHERE [i].[Name] = N'jane@example.com'"; + var fixture = new Fixture(); + var listener = new SentryEFCoreListener(fixture.Hub, fixture.Options); + var connection = new FakeDiagnosticConnectionEventData("connection"); + var command = new FakeDiagnosticCommandEventData(connection, $"Executing DbCommand\r\n{sql}"); + + // Act + listener.OnNext(new(EFCommandExecuting, command)); + + // Assert + fixture.Spans.Single(s => s.Operation == "db.query").Description.Should().Be(sql); + } + + [Theory] + [InlineData("Microsoft.EntityFrameworkCore.SqlServer", + "SELECT [Order 1].[Name] FROM [Order 1] WHERE [Name] = N'jane'", + "SELECT [Order 1].[Name] FROM [Order 1] WHERE [Name] = ?")] + [InlineData("Microsoft.EntityFrameworkCore.Sqlite", + "SELECT \"i\".\"Name\" FROM [Order 1] AS \"i\" WHERE \"i\".\"Name\" = 'jane' LIMIT 10", + "SELECT \"i\".\"Name\" FROM [Order 1] AS \"i\" WHERE \"i\".\"Name\" = ? LIMIT ?")] + [InlineData("Pomelo.EntityFrameworkCore.MySql", + "SELECT `i`.`Name` FROM `Items` AS `i` WHERE `i`.`Name` = \"jane\" OR `i`.`Name` = 'it\\'s'", + "SELECT `i`.`Name` FROM `Items` AS `i` WHERE `i`.`Name` = ? OR `i`.`Name` = ?")] + [InlineData("Npgsql.EntityFrameworkCore.PostgreSQL", + "SELECT \"i\".\"Name\" FROM \"Items\" AS \"i\" WHERE \"i\".\"Tags\" @> ARRAY['jane'] AND \"i\".\"Id\" = $1", + "SELECT \"i\".\"Name\" FROM \"Items\" AS \"i\" WHERE \"i\".\"Tags\" @> ARRAY[?] AND \"i\".\"Id\" = $1")] + public void OnNext_CommandExecuting_DataCollectionConfigured_SanitizesForProvider(string providerName, string sql, string expected) + { + // Arrange + var fixture = new Fixture(); + fixture.Options.ConfigureDataCollection(_ => { }); + var listener = new SentryEFCoreListener(fixture.Hub, fixture.Options); + var connection = new FakeDiagnosticConnectionEventData("connection"); + var command = new FakeDiagnosticCommandEventData(connection, $"Executing DbCommand\r\n{sql}"); + command.Context.Database.ProviderName = providerName; + + // Act + listener.OnNext(new(EFCommandExecuting, command)); + + // Assert + fixture.Spans.Single(s => s.Operation == "db.query").Description.Should().Be(expected); + } + + [Fact] + public void OnNext_CommandExecuting_CommandAvailable_DescriptionIsItsText() + { + // Arrange + const string sql = "SELECT [i].[Name] FROM [Items] AS [i] WHERE [i].[Name] = @p0"; + var fixture = new Fixture(); + var listener = new SentryEFCoreListener(fixture.Hub, fixture.Options); + var connection = new FakeDiagnosticConnectionEventData("connection"); + var command = new FakeDiagnosticCommandEventData(connection, + $"Executing DbCommand [Parameters=[@p0='line one\nline two' (Size = 17)], CommandType='Text']\n{sql}") + { + Command = new() { CommandText = sql + "\r\n" } + }; + + // Act + listener.OnNext(new(EFCommandExecuting, command)); + + // Assert + fixture.Spans.Single(s => s.Operation == "db.query").Description.Should().Be(sql); + } + + [Fact] + public void OnNext_CommandExecuting_LogCommandTextAvailable_PreferredOverCommandText() + { + // Arrange + const string redacted = "SELECT [i].[Name] FROM [Items] AS [i] WHERE [i].[Email] IN (?)"; + var fixture = new Fixture(); + var listener = new SentryEFCoreListener(fixture.Hub, fixture.Options); + var connection = new FakeDiagnosticConnectionEventData("connection"); + var command = new FakeDiagnosticCommandEventData(connection, $"Executing DbCommand\n{redacted}") + { + Command = new() { CommandText = "SELECT [i].[Name] FROM [Items] AS [i] WHERE [i].[Email] IN (N'jane@example.com')" }, + LogCommandText = redacted + "\r\n" + }; + + // Act + listener.OnNext(new(EFCommandExecuting, command)); + + // Assert + fixture.Spans.Single(s => s.Operation == "db.query").Description.Should().Be(redacted); + } + + [Fact] + public void OnNext_QueryCompiling_DataCollectionConfigured_DescriptionIsDbSystem() + { + // Arrange + var fixture = new Fixture(); + fixture.Options.ConfigureDataCollection(_ => { }); + var listener = new SentryEFCoreListener(fixture.Hub, fixture.Options); + var query = new FakeDiagnosticEventData( + "Compiling query expression: \n'DbSet().FromSql(SELECT * FROM Items WHERE Email = 'jane@example.com', @p)'"); + + // Act + listener.OnNext(new(EFQueryCompiling, query)); + + // Assert + fixture.Spans.Single(s => s.Operation == "db.query.compile").Description.Should().Be("mssql"); + } + [Fact] public void OnNext_HappyPathInsideChildSpan_IsValid() { diff --git a/test/Sentry.DiagnosticSource.Tests/SentrySqlListenerTests.cs b/test/Sentry.DiagnosticSource.Tests/SentrySqlListenerTests.cs index 5db1124f16..78d2b9373f 100644 --- a/test/Sentry.DiagnosticSource.Tests/SentrySqlListenerTests.cs +++ b/test/Sentry.DiagnosticSource.Tests/SentrySqlListenerTests.cs @@ -587,6 +587,40 @@ void SimulateDbRequest(List connectionOperationIds, List queryOperat fixture.Logger.Entries.Should().BeEmpty(); } + [Theory] + [InlineData(false, "SELECT * FROM [Order Details 2] WHERE [Email] = N'jane@example.com' AND [Id] > 42")] + [InlineData(true, "SELECT * FROM [Order Details 2] WHERE [Email] = ? AND [Id] > ?")] + public void OnNext_DataCollection_SanitizesCommandTextOnlyWhenConfigured(bool configureDataCollection, string expectedDescription) + { + // Arrange + var fixture = new Fixture(); + var options = new SentryOptions(); + if (configureDataCollection) + { + options.ConfigureDataCollection(_ => { }); + } + var listener = new SentrySqlListener(fixture.Hub, options); + var operationId = Guid.NewGuid(); + var connectionId = Guid.NewGuid(); + + // Act + listener.OnNext(new(SqlMicrosoftBeforeExecuteCommand, new { OperationId = operationId, ConnectionId = connectionId })); + listener.OnNext( + new(SqlMicrosoftAfterExecuteCommand, + new + { + OperationId = operationId, + ConnectionId = connectionId, + Command = new + { + CommandText = "SELECT * FROM [Order Details 2] WHERE [Email] = N'jane@example.com' AND [Id] > 42" + } + })); + + // Assert + fixture.Spans.Single().Description.Should().Be(expectedDescription); + } + [Fact] public void OnNext_HappyPathWithError_TransactionWithErroredCommand() { diff --git a/test/Sentry.EntityFramework.Tests/DbCommandExtensionsTests.cs b/test/Sentry.EntityFramework.Tests/DbCommandExtensionsTests.cs new file mode 100644 index 0000000000..999ffa17c6 --- /dev/null +++ b/test/Sentry.EntityFramework.Tests/DbCommandExtensionsTests.cs @@ -0,0 +1,30 @@ +namespace Sentry.EntityFramework.Tests; + +public class DbCommandExtensionsTests +{ + [Theory] + [InlineData("System.Data.SqlClient", "mssql")] + [InlineData("Microsoft.Data.SqlClient", "mssql")] + [InlineData("System.Data.SqlServerCe", "mssqlcompact")] + [InlineData("MySql.Data.MySqlClient", "mysql")] + [InlineData("MySqlConnector", "mysql")] + [InlineData("Devart.Data.MySql", "mysql")] + [InlineData("System.Data.SQLite", "sqlite")] + [InlineData("Microsoft.Data.Sqlite", "sqlite")] + [InlineData("Devart.Data.SQLite", "sqlite")] + [InlineData("Npgsql", null)] + [InlineData("Effort.Provider", null)] + [InlineData(null, null)] + public void DbSystemForNamespace_ProviderNamespace_MapsToDbSystem(string commandNamespace, string expectedDbSystem) => + DbCommandExtensions.DbSystemForNamespace(commandNamespace).Should().Be(expectedDbSystem); + + [Fact] + public void GetDbSystem_Command_UsesItsTypeNamespace() + { + using (new AssertionScope()) + { + new MySql.Data.MySqlClient.FakeMySqlCommand().GetDbSystem().Should().Be("mysql"); + new EffortCommand().GetDbSystem().Should().BeNull(); + } + } +} diff --git a/test/Sentry.EntityFramework.Tests/FakeProviderCommands.cs b/test/Sentry.EntityFramework.Tests/FakeProviderCommands.cs new file mode 100644 index 0000000000..0d5bced007 --- /dev/null +++ b/test/Sentry.EntityFramework.Tests/FakeProviderCommands.cs @@ -0,0 +1,28 @@ +using System.Data; + +namespace Sentry.EntityFramework.Tests +{ + internal abstract class FakeDbCommand : DbCommand + { + public override string CommandText { get; set; } + public override int CommandTimeout { get; set; } + public override CommandType CommandType { get; set; } + public override bool DesignTimeVisible { get; set; } + public override UpdateRowSource UpdatedRowSource { get; set; } + protected override DbConnection DbConnection { get; set; } + protected override DbParameterCollection DbParameterCollection => throw new NotSupportedException(); + protected override DbTransaction DbTransaction { get; set; } + + public override void Cancel() { } + public override int ExecuteNonQuery() => throw new NotSupportedException(); + public override object ExecuteScalar() => throw new NotSupportedException(); + public override void Prepare() { } + protected override DbParameter CreateDbParameter() => throw new NotSupportedException(); + protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) => throw new NotSupportedException(); + } +} + +namespace MySql.Data.MySqlClient +{ + internal class FakeMySqlCommand : Sentry.EntityFramework.Tests.FakeDbCommand; +} diff --git a/test/Sentry.EntityFramework.Tests/SentryQueryLoggerTests.cs b/test/Sentry.EntityFramework.Tests/SentryQueryLoggerTests.cs index c961a309eb..a6d30a51f5 100644 --- a/test/Sentry.EntityFramework.Tests/SentryQueryLoggerTests.cs +++ b/test/Sentry.EntityFramework.Tests/SentryQueryLoggerTests.cs @@ -1,7 +1,9 @@ namespace Sentry.EntityFramework.Tests; -public class SentryQueryLoggerTests +public class SentryQueryLoggerTests : IDisposable { + public void Dispose() => SentryClientExtensions.SentryOptionsForTestingOnly = null; + [Fact] public void Log_QueryLogger_CaptureEvent() { @@ -26,4 +28,45 @@ public void Log_QueryLogger_CaptureEvent() Assert.Equal(expected.Category, b.Category); Assert.Equal(expected.Level, b.Level); } + + [Theory] + [InlineData(false, "SELECT * FROM Users WHERE Email = 'jane@example.com'")] + [InlineData(true, "SELECT * FROM Users WHERE Email = ?")] + public void Log_DataCollection_SanitizesOnlyWhenConfigured(bool configureDataCollection, string expectedMessage) + { + var options = new SentryOptions(); + if (configureDataCollection) + { + options.ConfigureDataCollection(_ => { }); + } + SentryClientExtensions.SentryOptionsForTestingOnly = options; + + var scope = new Scope(options); + var hub = Substitute.For(); + hub.IsEnabled.Returns(true); + hub.SubstituteConfigureScope(scope); + + new SentryQueryLogger(hub).Log("SELECT * FROM Users WHERE Email = 'jane@example.com'"); + + scope.Breadcrumbs.Single().Message.Should().Be(expectedMessage); + } + + [Fact] + public void Log_MySqlCommandThroughInterceptor_UsesMySqlQuoting() + { + var options = new SentryOptions(); + options.ConfigureDataCollection(_ => { }); + SentryClientExtensions.SentryOptionsForTestingOnly = options; + + var scope = new Scope(options); + var hub = Substitute.For(); + hub.IsEnabled.Returns(true); + hub.SubstituteConfigureScope(scope); + var interceptor = new SentryCommandInterceptor(new SentryQueryLogger(hub)); + var command = new MySql.Data.MySqlClient.FakeMySqlCommand { CommandText = "SELECT * FROM Users WHERE Name = 'O\\'Brien'" }; + + interceptor.ReaderExecuting(command, new DbCommandInterceptionContext()); + + scope.Breadcrumbs.Single().Message.Should().Be("SELECT * FROM Users WHERE Name = ?"); + } } diff --git a/test/Sentry.EntityFramework.Tests/SentryQueryPerformanceListenerTests.cs b/test/Sentry.EntityFramework.Tests/SentryQueryPerformanceListenerTests.cs index 83bef2cc44..6090170478 100644 --- a/test/Sentry.EntityFramework.Tests/SentryQueryPerformanceListenerTests.cs +++ b/test/Sentry.EntityFramework.Tests/SentryQueryPerformanceListenerTests.cs @@ -196,6 +196,37 @@ public void InterceptorInvokeExecuted_WithoutException_CloseSpanWithOk(string ex span.Received(1).Finish(Arg.Is(status => status == SpanStatus.Ok)); } + [Theory] + [InlineData(false, "SELECT * FROM Users WHERE Email = 'jane@example.com'")] + [InlineData(true, "SELECT * FROM Users WHERE Email = ?")] + public void ReaderExecuting_DataCollection_SanitizesOnlyWhenConfigured(bool configureDataCollection, string expectedDescription) + { + var options = new SentryOptions(); + if (configureDataCollection) + { + options.ConfigureDataCollection(_ => { }); + } + var listener = new SentryQueryPerformanceListener(_fixture.Hub, options); + var command = new EffortCommand { CommandText = "SELECT * FROM Users WHERE Email = 'jane@example.com'" }; + + listener.ReaderExecuting(command, new DbCommandInterceptionContext()); + + _fixture.Spans.Single().Description.Should().Be(expectedDescription); + } + + [Fact] + public void ReaderExecuting_MySqlCommand_UsesMySqlQuoting() + { + var options = new SentryOptions(); + options.ConfigureDataCollection(_ => { }); + var listener = new SentryQueryPerformanceListener(_fixture.Hub, options); + var command = new MySql.Data.MySqlClient.FakeMySqlCommand { CommandText = "SELECT * FROM Users WHERE Name = 'O\\'Brien'" }; + + listener.ReaderExecuting(command, new DbCommandInterceptionContext()); + + _fixture.Spans.Single().Description.Should().Be("SELECT * FROM Users WHERE Name = ?"); + } + [Fact] public void FirstOrDefault_FromDatabase_CapturesQuery() { @@ -242,4 +273,16 @@ public void Finish_NoActiveTransaction_LoggerNotCalled() // Assert _logger.DidNotReceiveWithAnyArgs().Log(default, default!); } + + [Fact] + public void ReaderExecuting_NoActiveSpan_StartsNoSpan() + { + _fixture.Hub.GetSpan().ReturnsNull(); + var context = new DbCommandInterceptionContext(); + + _fixture.GetListener().ReaderExecuting(new EffortCommand { CommandText = "SELECT 1" }, context); + + _fixture.Spans.Should().BeEmpty(); + context.GetSpanFromContext().Should().BeNull(); + } } diff --git a/test/Sentry.Tests/Internals/DataCollection/SqlSanitizerTests.cs b/test/Sentry.Tests/Internals/DataCollection/SqlSanitizerTests.cs new file mode 100644 index 0000000000..e9c6572da6 --- /dev/null +++ b/test/Sentry.Tests/Internals/DataCollection/SqlSanitizerTests.cs @@ -0,0 +1,210 @@ +using Sentry.Internal.DataCollection; + +namespace Sentry.Tests.Internals.DataCollection; + +public class SqlSanitizerTests +{ + [Theory] + [InlineData("SELECT * FROM users WHERE email = 'jane@example.com'", "SELECT * FROM users WHERE email = ?")] + [InlineData("SELECT * FROM users WHERE name = 'O''Brien' AND id = 1", "SELECT * FROM users WHERE name = ? AND id = ?")] + [InlineData("SELECT '' FROM t", "SELECT ? FROM t")] + [InlineData("SELECT 'a', 'b' FROM t", "SELECT ?, ? FROM t")] + [InlineData("SELECT 'C:\\' FROM t WHERE x = 'y'", "SELECT ? FROM t WHERE x = ?")] + [InlineData("SELECT 'multi\nline' FROM t", "SELECT ? FROM t")] + [InlineData("SELECT N'jane' FROM t", "SELECT ? FROM t")] + [InlineData("SELECT n'jane' FROM t", "SELECT ? FROM t")] + [InlineData("SELECT X'DEADBEEF', B'0101' FROM t", "SELECT ?, ? FROM t")] + [InlineData("SELECT E'it\\'s' FROM t WHERE x = 1", "SELECT ? FROM t WHERE x = ?")] + [InlineData("SELECT $$it's$$ FROM t", "SELECT ? FROM t")] + [InlineData("SELECT $tag$a $$ b$tag$ FROM t", "SELECT ? FROM t")] + public void Sanitize_StringLiterals_AreReplaced(string sql, string expected) => + SqlSanitizer.Sanitize(sql).Should().Be(expected); + + [Theory] + [InlineData("SELECT 42", "SELECT ?")] + [InlineData("SELECT -42", "SELECT -?")] + [InlineData("SELECT 3.14, .5, 1e10, 1e5, 1.5E-3, 2e+8", "SELECT ?, ?, ?, ?, ?, ?")] + [InlineData("SELECT 9, 1999, 0.99", "SELECT ?, ?, ?")] + [InlineData(".5", "?")] + [InlineData("SELECT x.5", "SELECT x.?")] + [InlineData("SELECT 1_000_000", "SELECT ?")] + [InlineData("SELECT 0xDEADBEEF, 0X1f, 0xabcdef, 0b1010, 0o17", "SELECT ?, ?, ?, ?, ?")] + [InlineData("SELECT * FROM t LIMIT 10 OFFSET 20", "SELECT * FROM t LIMIT ? OFFSET ?")] + [InlineData("SELECT * FROM t WHERE id IN (1, 2, 3)", "SELECT * FROM t WHERE id IN (?, ?, ?)")] + [InlineData("SELECT CHAR(13)", "SELECT CHAR(?)")] + public void Sanitize_NumericLiterals_AreReplaced(string sql, string expected) => + SqlSanitizer.Sanitize(sql).Should().Be(expected); + + [Theory] + [InlineData("SELECT 1 -- jane@example.com\nFROM t", "SELECT ? \nFROM t")] + [InlineData("SELECT 1 -- trailing", "SELECT ?")] + [InlineData("-- TagWith: jane\n\nSELECT 1", "SELECT ?")] + [InlineData("\r\n-- GetOrders\r\n-- File: Orders.cs:42\r\n\r\nSELECT 1", "SELECT ?")] + [InlineData("/* jane */\nSELECT 1", "SELECT ?")] + [InlineData("SELECT /* jane */ 1", "SELECT ?")] + [InlineData("SELECT/* jane */1", "SELECT ?")] + [InlineData("SELECT /* jane */1", "SELECT ?")] + [InlineData("SELECT/* jane */ 1", "SELECT ?")] + [InlineData("/* app */SELECT 1", "SELECT ?")] + [InlineData("SELECT 1/* jane */", "SELECT ?")] + [InlineData("SELECT /*+ INDEX(t idx) */ * FROM t", "SELECT * FROM t")] + [InlineData("SELECT /* outer /* inner */ still a comment */ 1", "SELECT ?")] + [InlineData("SELECT 1 /* unterminated 'jane'", "SELECT ?")] + [InlineData("SELECT '--not a comment', '/*nor this*/' FROM t", "SELECT ?, ? FROM t")] + public void Sanitize_Comments_AreRemoved(string sql, string expected) => + SqlSanitizer.Sanitize(sql).Should().Be(expected); + + [Fact] + public void Sanitize_MySqlHashCommentBeforeTheStatement_IsRemoved() => + SqlSanitizer.Sanitize("# jane\nSELECT 1", "mysql").Should().Be("SELECT ?"); + + [Theory] + [InlineData("SELECT \"u\".\"Id\", \"u\".\"Name\" FROM \"Users\" AS \"u\"")] + [InlineData("SELECT \"col \"\"1\"\"\" FROM t")] + [InlineData("SELECT `u`.`Id` FROM `Users` AS `u`")] + [InlineData("SELECT t1.col2, x9 FROM table3 AS t1")] + [InlineData("SELECT * FROM #temp JOIN ##global ON #temp.id = ##global.id")] + [InlineData("SELECT * FROM t WHERE a = @p0 AND b = @__name_1 AND c = @@ROWCOUNT")] + [InlineData("SELECT * FROM t WHERE a = :name AND b = ?")] + [InlineData("SELECT * FROM t WHERE a = $1 AND b = $2::int")] + [InlineData("OUTPUT $action, inserted.$IDENTITY")] + [InlineData("SELECT data->>'key' FROM t")] + public void Sanitize_IdentifiersAndPlaceholders_AreLeftAlone(string sql) + { + var expected = sql.Replace("'key'", "?"); + + SqlSanitizer.Sanitize(sql).Should().Be(expected); + } + + [Theory] + [InlineData("mssql", "SELECT \"x\", [y 2] FROM t")] + [InlineData("mssqlcompact", "SELECT \"x\", [y 2] FROM t")] + [InlineData("sqlite", "SELECT \"x\", [y 2] FROM t")] + [InlineData("mysql", "SELECT ?, [y ?] FROM t")] + [InlineData("spanner", "SELECT ?, [y ?] FROM t")] + [InlineData("postgresql", "SELECT \"x\", [y ?] FROM t")] + [InlineData("oracle", "SELECT \"x\", [y ?] FROM t")] + [InlineData(null, "SELECT \"x\", [y ?] FROM t")] + public void Sanitize_DbSystem_PicksItsRules(string dbSystem, string expected) => + SqlSanitizer.Sanitize("SELECT \"x\", [y 2] FROM t", dbSystem).Should().Be(expected); + + [Theory] + [InlineData("mssql")] + [InlineData("sqlite")] + public void Sanitize_SqlServerAndSqliteBrackets_AreIdentifiers(string dbSystem) + { + const string sql = "SELECT [Order Details 2].[Unit's Price] FROM [dbo].[t]]1]"; + + SqlSanitizer.Sanitize(sql, dbSystem).Should().Be(sql); + } + + [Theory] + [InlineData(null)] + [InlineData("mysql")] + public void Sanitize_OtherDialectBrackets_AreNotIdentifiers(string dbSystem) => + SqlSanitizer.Sanitize("SELECT ARRAY['jane'], tags[1] FROM t", dbSystem) + .Should().Be("SELECT ARRAY[?], tags[?] FROM t"); + + [Theory] + [InlineData("SELECT @5, @ -5 FROM t", "SELECT @?, @ -? FROM t")] + [InlineData("SELECT 5 #3, 5#3, x#5 FROM t", "SELECT ? #?, ?#?, x#? FROM t")] + [InlineData("SELECT * FROM t WHERE a@1 = b", "SELECT * FROM t WHERE a@? = b")] + public void Sanitize_PostgreSqlOperatorsBeforeDigits_ReplaceTheNumber(string sql, string expected) => + SqlSanitizer.Sanitize(sql).Should().Be(expected); + + [Fact] + public void Sanitize_SqlServerAtAndHashBeforeDigits_AreIdentifiers() => + SqlSanitizer.Sanitize("SELECT * FROM #1 JOIN t#2 ON @1 = 1", "mssql") + .Should().Be("SELECT * FROM #1 JOIN t#2 ON @1 = ?"); + + [Fact] + public void Sanitize_SqlServerMoneyLiteral_IsReplaced() => + SqlSanitizer.Sanitize("SELECT $12.50, $.5 FROM t", "mssql") + .Should().Be("SELECT ?, $.? FROM t"); + + [Fact] + public void Sanitize_SqlServerEscapeStringPrefix_IsAWord() => + SqlSanitizer.Sanitize("a = 'zq' AND b = 1E'zq\\' OR c = 'zq2'", "mssql") + .Should().Be("a = ? AND b = ?E? OR c = ?"); + + [Theory] + [InlineData("SELECT * FROM t WHERE name = \"jane\"", "SELECT * FROM t WHERE name = ?")] + [InlineData("SELECT * FROM t WHERE name = 'it\\'s' AND x = 1", "SELECT * FROM t WHERE name = ? AND x = ?")] + [InlineData("SELECT * FROM t WHERE name = N'it\\'s' AND x = 1", "SELECT * FROM t WHERE name = ? AND x = ?")] + [InlineData("SELECT * FROM t WHERE name = \"say \\\"hi\\\"\" AND x = 1", "SELECT * FROM t WHERE name = ? AND x = ?")] + [InlineData("SELECT 1 # jane@example.com\nFROM t", "SELECT ? \nFROM t")] + [InlineData("SELECT a# jane\nFROM t", "SELECT a\nFROM t")] + [InlineData("SELECT `Id` FROM `Users`", "SELECT `Id` FROM `Users`")] + public void Sanitize_MySql_UsesMySqlQuoting(string sql, string expected) => + SqlSanitizer.Sanitize(sql, "mysql").Should().Be(expected); + + [Theory] + [InlineData(null)] + [InlineData("mssql")] + [InlineData("sqlite")] + public void Sanitize_DoubleQuotesOutsideMySql_AreIdentifiers(string dbSystem) => + SqlSanitizer.Sanitize("SELECT \"Name\" FROM \"Users\" WHERE \"Id\" = 1", dbSystem) + .Should().Be("SELECT \"Name\" FROM \"Users\" WHERE \"Id\" = ?"); + + [Theory] + [InlineData("SELECT * FROM t WHERE name = 'jane", "SELECT * FROM t WHERE name = ?")] + [InlineData("SELECT * FROM t WHERE name = 'jane'' AND id = 1", "SELECT * FROM t WHERE name = ?")] + [InlineData("SELECT * FROM t WHERE name = $$jane", "SELECT * FROM t WHERE name = ?")] + [InlineData("SELECT * FROM t WHERE name = $tag$jane$other$", "SELECT * FROM t WHERE name = ?")] + [InlineData("SELECT * FROM \"t WHERE name = 'jane'", "SELECT * FROM ?")] + [InlineData("SELECT * FROM `t WHERE name = 'jane'", "SELECT * FROM ?")] + [InlineData("SELECT * FROM t WHERE name = E'jane\\'", "SELECT * FROM t WHERE name = ?")] + public void Sanitize_UnterminatedLiteral_ReplacesTheRest(string sql, string expected) => + SqlSanitizer.Sanitize(sql).Should().Be(expected); + + [Fact] + public void Sanitize_UnterminatedDialectLiteral_ReplacesTheRest() + { + using (new AssertionScope()) + { + SqlSanitizer.Sanitize("SELECT * FROM [t WHERE name = 'jane'", "mssql") + .Should().Be("SELECT * FROM ?"); + SqlSanitizer.Sanitize("SELECT * FROM t WHERE name = \"jane\\\"", "mysql") + .Should().Be("SELECT * FROM t WHERE name = ?"); + } + } + + [Fact] + public void Sanitize_EfCoreSqliteCommand_KeepsStructure() + { + const string sql = """ + SELECT "i"."Id", "i"."Name" + FROM "Items" AS "i" + WHERE "i"."Name" = 'jane@example.com' AND "i"."Id" > 42 AND "i"."Name" = @captured + LIMIT @p0 OFFSET @p + """; + + SqlSanitizer.Sanitize(sql, "sqlite").Should().Be(""" + SELECT "i"."Id", "i"."Name" + FROM "Items" AS "i" + WHERE "i"."Name" = ? AND "i"."Id" > ? AND "i"."Name" = @captured + LIMIT @p0 OFFSET @p + """); + } + + [Fact] + public void Sanitize_Null_ReturnsNull() => + SqlSanitizer.Sanitize(null).Should().BeNull(); + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\r\n\t")] + [InlineData("/* only a comment */")] + [InlineData("-- only a comment")] + public void Sanitize_EmptyOrWhitespace_ReturnsEmpty(string sql) => + SqlSanitizer.Sanitize(sql).Should().BeEmpty(); + + [Fact] + public void Sanitize_StatementWithoutLiterals_IsUnchanged() + { + const string sql = "UPDATE [Users] SET [Name] = @p0 WHERE [Id] = @p1;\nSELECT @@ROWCOUNT;"; + + SqlSanitizer.Sanitize(sql, "mssql").Should().Be(sql); + } +} diff --git a/test/Sentry.Tests/Internals/DataCollectionResolverTests.cs b/test/Sentry.Tests/Internals/DataCollectionResolverTests.cs index 99b33b5974..5038e75240 100644 --- a/test/Sentry.Tests/Internals/DataCollectionResolverTests.cs +++ b/test/Sentry.Tests/Internals/DataCollectionResolverTests.cs @@ -91,6 +91,25 @@ public void GenAI_WithoutDataCollection_IsCollectedRegardlessOfSendDefaultPii(bo } } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SanitizeDbStatements_WithoutDataCollection_IsFalseRegardlessOfSendDefaultPii(bool sendDefaultPii) + { + var options = new SentryOptions { SendDefaultPii = sendDefaultPii }; + + Resolver(options).SanitizeDbStatements.Should().BeFalse(); + } + + [Fact] + public void SanitizeDbStatements_WithDataCollection_IsTrue() + { + var options = new SentryOptions(); + options.ConfigureDataCollection(_ => { }); + + Resolver(options).SanitizeDbStatements.Should().BeTrue(); + } + [Fact] public void ConfiguredDataCollection_WithoutSendDefaultPii_UsesSpecDefaults() {