From 73f3bffa5d1c4366678d326df5add3731ee01f71 Mon Sep 17 00:00:00 2001 From: John Simons Date: Fri, 27 Nov 2026 08:31:51 +1000 Subject: [PATCH] Match audit logging rules on exact category names, not prefixes The audit rule used a prefix pattern (`AuthorizationAuditLog.AuditCategory*`), which also matched the audit instance's own loggers under the `ServiceControl.Audit` namespace (e.g. `AuditPersister`). Those loggers were being routed to the audit target instead of the operational log. Switch to exact-name matching per audit category and split the authorization and message-action audit categories into separate rules, so only genuine audit events are final-routed to the audit target while audit instance diagnostics keep flowing to the operational log with the full layout. --- .../LoggingConfiguratorTests.cs | 74 +++++++++++++++---- .../LoggingConfigurator.cs | 29 +++++--- 2 files changed, 77 insertions(+), 26 deletions(-) diff --git a/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs b/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs index 3e32ba8d39..d0c86f9b01 100644 --- a/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs +++ b/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs @@ -1,6 +1,8 @@ #nullable enable namespace ServiceControl.Infrastructure.Tests; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; @@ -17,31 +19,31 @@ namespace ServiceControl.Infrastructure.Tests; [TestFixture] public class LoggingConfiguratorTests { - static readonly string AuditPattern = $"{AuthorizationAuditLog.AuditCategory}*"; - static LoggingConfiguration BuildConfig() => LoggingConfigurator.BuildConfiguration("logfile.txt", Path.GetTempPath(), LogLevel.Info); + static List AuditRules(LoggingConfiguration config) => + [.. config.LoggingRules.Where(r => r.Targets.Any(t => t.Name == "audit-console"))]; + + static NLog.Layouts.Layout LayoutOf(LoggingConfiguration config, string targetName) => + config.AllTargets.OfType().Single(t => t.Name == targetName).Layout; + [Test] public void Audit_target_emits_the_prerendered_event_verbatim() { - var auditTarget = BuildConfig().LoggingRules - .Single(r => r.LoggerNamePattern == AuditPattern) - .Targets.OfType() - .Single(t => t.Name == "audit-console"); - - var rendered = auditTarget.Layout.Render(new LogEventInfo(LogLevel.Info, AuthorizationAuditLog.AuditCategory, "ECS-PAYLOAD")); + var rendered = LayoutOf(BuildConfig(), "audit-console").Render(new LogEventInfo(LogLevel.Info, AuthorizationAuditLog.AuditCategory, "ECS-PAYLOAD")); Assert.That(rendered, Is.EqualTo("ECS-PAYLOAD"), "the audit target must pass the pre-rendered ECS JSON through unwrapped, not double-encode it"); } - [Test] - public void Audit_events_do_not_fall_through_to_the_operational_log() + [TestCase(AuthorizationAuditLog.AuditCategory)] + [TestCase(MessageActionAuditLog.MessageCategory)] + public void Audit_events_do_not_fall_through_to_the_operational_log(string category) { var config = BuildConfig(); - var auditRule = config.LoggingRules.Single(r => r.LoggerNamePattern == AuditPattern); + var auditRule = AuditRules(config).Single(r => r.NameMatches(category)); var operationalConsoleRule = config.LoggingRules.Single(r => r.LoggerNamePattern == "*" && r.Targets.Any(t => t.Name == "console")); Assert.That(auditRule.Final, Is.True, "the audit rule must be final so audit JSON is not duplicated into the plain-text operational log"); @@ -63,7 +65,7 @@ public void Audit_decisions_render_as_valid_structured_json() // ...and capture what it renders, driven through the real audit logger over an isolated NLog factory. var captured = new MemoryTarget("audit-capture") { Layout = auditLayout }; var captureConfig = new LoggingConfiguration(); - captureConfig.AddRule(LogLevel.Info, LogLevel.Fatal, captured, AuditPattern); + captureConfig.AddRule(LogLevel.Info, LogLevel.Fatal, captured, AuthorizationAuditLog.AuditCategory); var logFactory = new LogFactory { Configuration = captureConfig }; using (var loggerFactory = LoggerFactory.Create(b => b.AddNLog(_ => logFactory))) @@ -108,11 +110,53 @@ public void Audit_decisions_render_as_valid_structured_json() [Test] public void Message_action_subcategory_is_captured_by_the_audit_rule() + { + var auditRules = AuditRules(BuildConfig()); + + Assert.That(auditRules.Any(r => r.NameMatches(MessageActionAuditLog.MessageCategory)), Is.True); + Assert.That(auditRules.Any(r => r.NameMatches(MessageActionAuditLog.OperationCategory)), Is.True); + } + + [Test] + public void Audit_instance_loggers_write_to_the_operational_log_with_the_full_layout() { var config = BuildConfig(); - var auditRule = config.LoggingRules.Single(r => r.LoggerNamePattern == AuditPattern); + var operational = new MemoryTarget("operational-capture") { Layout = LayoutOf(config, "console") }; + var audit = new MemoryTarget("audit-capture") { Layout = LayoutOf(config, "audit-console") }; + using var logFactory = new LogFactory { Configuration = RouteToMemory(config, operational, audit) }; + + logFactory.GetLogger("ServiceControl.Audit.Auditing.AuditPersister").Error(new InvalidOperationException("boom"), "Processing of message failed"); + logFactory.Flush(); + + Assert.Multiple(() => + { + Assert.That(operational.Logs, Has.One.EndsWith("|Error|ServiceControl.Audit.Auditing.AuditPersister|Processing of message failed|System.InvalidOperationException: boom"), + "an audit instance logger must keep the level, logger name and exception of the operational layout"); + Assert.That(audit.Logs, Is.Empty, "only the authorization and message action categories belong in the audit trail"); + }); + } + + static LoggingConfiguration RouteToMemory(LoggingConfiguration config, Target operational, Target audit) + { + var routed = new LoggingConfiguration(); + + foreach (var rule in config.LoggingRules) + { + var targets = rule.Targets + .Select(t => t.Name switch + { + "console" => operational, + "audit-console" => audit, + _ => null + }) + .OfType() + .ToList(); + + rule.Targets.Clear(); + targets.ForEach(rule.Targets.Add); + routed.LoggingRules.Add(rule); + } - Assert.That(auditRule.NameMatches(ServiceControl.Infrastructure.Auth.MessageActionAuditLog.MessageCategory), Is.True); - Assert.That(auditRule.NameMatches(ServiceControl.Infrastructure.Auth.MessageActionAuditLog.OperationCategory), Is.True); + return routed; } } diff --git a/src/ServiceControl.Infrastructure/LoggingConfigurator.cs b/src/ServiceControl.Infrastructure/LoggingConfigurator.cs index 5e232163a0..efc766c84b 100644 --- a/src/ServiceControl.Infrastructure/LoggingConfigurator.cs +++ b/src/ServiceControl.Infrastructure/LoggingConfigurator.cs @@ -108,18 +108,24 @@ public static LoggingConfiguration BuildConfiguration(string logFileName, string // Audit events are captured from Info upward (allow = Information, deny = Warning) regardless of the // operational LogLevel — lowering the operational verbosity must never drop entries from the audit trail. - // Final stops audit events from also reaching the catch-all operational rules below, so this rule must + // Final stops audit events from also reaching the catch-all operational rules below, so these rules must // be registered before them. - var auditRule = new LoggingRule + LoggingRule AuditRule(string category) { - LoggerNamePattern = $"{AuthorizationAuditLog.AuditCategory}*", - Final = true - }; - auditRule.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal); - auditRule.Targets.Add(auditConsoleTarget); - if (!AppEnvironment.RunningInContainer) - { - auditRule.Targets.Add(auditFileTarget); + var rule = new LoggingRule + { + // An exact name, not a prefix: the audit instance's own loggers are in the ServiceControl.Audit namespace. + LoggerNamePattern = category, + Final = true + }; + rule.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal); + rule.Targets.Add(auditConsoleTarget); + if (!AppEnvironment.RunningInContainer) + { + rule.Targets.Add(auditFileTarget); + } + + return rule; } nlogConfig.AddTarget(consoleTarget); @@ -128,7 +134,8 @@ public static LoggingConfiguration BuildConfiguration(string logFileName, string nlogConfig.LoggingRules.Add(aspNetCoreRule); nlogConfig.LoggingRules.Add(httpClientRule); nlogConfig.LoggingRules.Add(efCoreRule); - nlogConfig.LoggingRules.Add(auditRule); + nlogConfig.LoggingRules.Add(AuditRule(AuthorizationAuditLog.AuditCategory)); + nlogConfig.LoggingRules.Add(AuditRule(MessageActionAuditLog.MessageCategory)); nlogConfig.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget));