using FluentAssertions; using Microsoft.Extensions.Logging; using Sentry; using SlpModularCms.Core.Hosting.Observability; using SlpModularCms.Core.Observability; using Xunit; namespace SlpModularCms.Core.Tests.Hosting.Observability; /// /// Guards the property that makes alert rules possible at all. /// /// /// Sentry groups log-derived events by their message. If a failed-login entry interpolated the /// email address, every distinct address would become its own Sentry issue and an alert rule of /// the form "more than 20 failed logins in five minutes" could never fire, because no single /// issue would ever reach 20. Everything would look like it worked: events arrive, they are /// visible, they are tagged. Only the alerting would silently be impossible. /// /// These tests assert that the rendered message is identical across different argument values. /// public class SecurityEventsTests { private sealed class CapturingLogger : ILogger { public List<(LogLevel Level, EventId EventId, string Message)> Entries { get; } = []; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log( LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { Entries.Add((logLevel, eventId, formatter(state, exception))); } } [Fact] public void FailedLogin_ShouldRenderTheSameMessage_ForDifferentAccounts() { var logger = new CapturingLogger(); SecurityEvents.FailedLogin(logger, "/api/v1/Auth/login", accountExists: true); SecurityEvents.FailedLogin(logger, "/api/v1/Auth/login", accountExists: true); logger.Entries.Should().HaveCount(2); logger.Entries[0].Message.Should().Be(logger.Entries[1].Message); } [Fact] public void FailedLogin_ShouldCarryTheEventNameAndNoCredentials() { var logger = new CapturingLogger(); SecurityEvents.FailedLogin(logger, "/api/v1/Auth/login", accountExists: false); var entry = logger.Entries.Single(); entry.Message.Should().Contain(SecurityEventNames.FailedLogin); entry.EventId.Id.Should().Be(SecurityEvents.FailedLoginEventId); entry.Level.Should().Be(LogLevel.Warning); } /// /// All six must cross the Sentry event threshold by construction rather than by a /// coincidence of configuration. /// [Fact] public void AllEvents_ShouldBeWarningOrAbove() { var logger = new CapturingLogger(); SecurityEvents.FailedLogin(logger, "/e", accountExists: true); SecurityEvents.AuthorizationDenied(logger, "/e", "OwnerOnly"); SecurityEvents.MasterApiKeyRejected(logger, "/e", "10.0.0.1"); SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.InvalidSignature); SecurityEvents.RateLimitTriggered(logger, "login", "/e"); SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 5); SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); logger.Entries.Should().HaveCount(7); logger.Entries.Should().OnlyContain(e => e.Level >= LogLevel.Warning); } [Fact] public void AllEvents_ShouldUseDistinctEventIds() { var logger = new CapturingLogger(); SecurityEvents.FailedLogin(logger, "/e", accountExists: true); SecurityEvents.AuthorizationDenied(logger, "/e", "OwnerOnly"); SecurityEvents.MasterApiKeyRejected(logger, "/e", "10.0.0.1"); SecurityEvents.AdminBypassRejected(logger, "/e", BypassRejectionReason.Expired); SecurityEvents.RateLimitTriggered(logger, "login", "/e"); SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 1); SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); logger.Entries.Select(e => e.EventId.Id).Should().OnlyHaveUniqueItems(); } [Fact] public void SetupTokenRejected_ShouldCarryTheEventNameAndId() { var logger = new CapturingLogger(); SecurityEvents.SetupTokenRejected(logger, "/Setup/owner"); var entry = logger.Entries.Single(); entry.Message.Should().Contain(SecurityEventNames.SetupTokenRejected); entry.EventId.Id.Should().Be(5007); } [Fact] public void MigrationFailure_ShouldBeCritical() { var logger = new CapturingLogger(); SecurityEvents.MigrationFailure(logger, new InvalidOperationException("boom"), attempts: 5); logger.Entries.Single().Level.Should().Be(LogLevel.Critical); } /// /// The reason class distinguishes forgery from a stale tab. The token itself must never /// appear anywhere in the entry. /// [Fact] public void AdminBypassRejected_ShouldCarryTheReasonClass() { var logger = new CapturingLogger(); SecurityEvents.AdminBypassRejected(logger, "/admin", BypassRejectionReason.InvalidSignature); logger.Entries.Single().Message.Should().Contain(nameof(BypassRejectionReason.InvalidSignature)); } } public class SecurityEventProcessorTests { private readonly SecurityEventProcessor _processor = new(); [Fact] public void Process_ShouldTagKnownSecurityEvents() { var sentryEvent = new SentryEvent(); sentryEvent.SetExtra("SecurityEvent", SecurityEventNames.FailedLogin); var processed = _processor.Process(sentryEvent); processed!.Tags[SecurityEventProcessor.TagName].Should().Be(SecurityEventNames.FailedLogin); } /// /// Alert rules filter on the tag rather than on message text, because a rule that matches /// nothing looks exactly like a rule with nothing to match. /// [Fact] public void Process_ShouldNotTagUnknownValues() { var sentryEvent = new SentryEvent(); sentryEvent.SetExtra("SecurityEvent", "something_else"); var processed = _processor.Process(sentryEvent); processed!.Tags.Should().NotContainKey(SecurityEventProcessor.TagName); } [Fact] public void Process_ShouldLeaveOrdinaryEventsUntouched() { var processed = _processor.Process(new SentryEvent()); processed!.Tags.Should().NotContainKey(SecurityEventProcessor.TagName); } }