From 78ca99352860c051973e50f9d71c69a5559d9f11 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 08:14:18 +1100 Subject: [PATCH] feat(collector): add atomic policy hot reload with SIGHUP, HTTP endpoint, file watch, and reload ledger (#96) --- docs/operations/fleet-and-queue-integrity.md | 28 ++ src/Bower.Abstractions/PolicyRuntime.cs | 23 ++ src/Bower.Collector/CollectorApplication.cs | 180 ++++++--- src/Bower.Collector/CollectorJson.cs | 5 + src/Bower.Collector/CollectorSettings.cs | 22 +- src/Bower.Collector/ConfigHotReloadService.cs | 269 +++++++++++++ .../Jobs/ManagedPrivacyProfileJob.cs | 8 +- .../Jobs/ManagementHeartbeatJob.cs | 11 +- src/Bower.Collector/ManagementEnrolment.cs | 5 +- src/Bower.Collector/PackEndpoints.cs | 3 +- src/Bower.Collector/PackRecordIntake.cs | 15 +- src/Bower.Collector/PolicyBundleHolder.cs | 184 +++++++++ src/Bower.Collector/SyslogIntake.cs | 16 +- src/Bower.Core/SecurityEventProcessor.cs | 23 +- src/Bower.Persistence/SqliteEventQueue.cs | 2 +- .../SqliteEventStore.ConfigReloads.cs | 283 ++++++++++++++ tests/Bower.UnitTests/ConfigHotReloadTests.cs | 362 ++++++++++++++++++ 17 files changed, 1359 insertions(+), 80 deletions(-) create mode 100644 src/Bower.Abstractions/PolicyRuntime.cs create mode 100644 src/Bower.Collector/ConfigHotReloadService.cs create mode 100644 src/Bower.Collector/PolicyBundleHolder.cs create mode 100644 src/Bower.Persistence/SqliteEventStore.ConfigReloads.cs create mode 100644 tests/Bower.UnitTests/ConfigHotReloadTests.cs diff --git a/docs/operations/fleet-and-queue-integrity.md b/docs/operations/fleet-and-queue-integrity.md index a972bfeb..605370fc 100644 --- a/docs/operations/fleet-and-queue-integrity.md +++ b/docs/operations/fleet-and-queue-integrity.md @@ -34,6 +34,34 @@ POST /api/collectors/{id}/desired-policy The console shows each collector as *In sync*, *Drift* or *Unassigned*; drifted collectors appear in fleet exceptions. The action is audited. +## Hot reload without restart + +Policies (`BOWER_POLICY_DIRECTORY`), signed packs (`BOWER_PACKS` and +`BOWER_PACK_TRUSTED_KEYS`), pack parsers/detections and local privacy profiles +(`BOWER_PRIVACY_PROFILE`) can be reloaded in place without stopping the collector, +closing listener sockets, or interrupting queue delivery: + +- **Unix `SIGHUP`:** triggers a serialized atomic reload. +- **`POST /v1/reload`:** authenticated operator endpoint (requires the shared + `BOWER_INGEST_TOKEN` or a producer listed in `BOWER_TAP_PRODUCERS`, or loopback when + ingest authentication is off). Returns metadata only (`outcome`, `trigger`, `policyHash`, + `previousPolicyHash`, `ledgerSequence`, or `errorType` on HTTP 422). +- **Optional file watcher:** set `BOWER_POLICY_WATCH=true` (off by default) to watch + the configured policy directory, privacy profile and pack files and coalesce rapid saves + using `BOWER_POLICY_WATCH_DEBOUNCE_MS` (default `500`, range `100`–`30000`). + +Before swapping the active snapshot, the collector validates every policy, pack signature, +privacy profile, source route (syslog, Windows Event Log, file tail) and health-record +policy. If any check fails, the reload is rejected with a metadata-only error (`EventId 1702`) +and the previous bundle stays active untouched. Each applied reload records a hash-chained +entry in `queue_config_reloads` bound to the queue ledger head before swapping atomically; +each in-flight event captures one immutable `(redactor, policyEvaluator)` pair so no event +is ever split across two bundles. `/v1/status` exposes `reload` and the updated `policy.hash`, +and the next heartbeat reports the new hashes to management. + +Listener addresses, output adapters, TLS server sockets and environment variables still +require a supervised restart (`reload` management command, exit code 75). + ## Fleet overview: exceptions and source coverage `GET /api/overview` is computed at query time from the 15-minute heartbeat diff --git a/src/Bower.Abstractions/PolicyRuntime.cs b/src/Bower.Abstractions/PolicyRuntime.cs new file mode 100644 index 00000000..e83b73be --- /dev/null +++ b/src/Bower.Abstractions/PolicyRuntime.cs @@ -0,0 +1,23 @@ +namespace Bower.Abstractions; + +/// +/// Immutable redactor and policy evaluator pair captured once per event so an atomic hot +/// reload never causes one event to be redacted under one bundle and evaluated under another. +/// +public sealed record ActivePolicyRuntime( + IEventRedactor Redactor, + ITelemetryPolicyEvaluator PolicyEvaluator); + +/// +/// Supplies the active redactor and policy evaluator pair for hot-reloading hosts. +/// +public interface IPolicyRuntimeProvider +{ + ActivePolicyRuntime Current { get; } +} + +/// Fixed runtime provider used when a host or test overrides DI services directly. +public sealed class StaticPolicyRuntimeProvider(ActivePolicyRuntime current) : IPolicyRuntimeProvider +{ + public ActivePolicyRuntime Current { get; } = current; +} diff --git a/src/Bower.Collector/CollectorApplication.cs b/src/Bower.Collector/CollectorApplication.cs index 36303351..447a21fd 100644 --- a/src/Bower.Collector/CollectorApplication.cs +++ b/src/Bower.Collector/CollectorApplication.cs @@ -88,9 +88,6 @@ public static WebApplication Build( builder.Services.AddSingleton(settings.UsesManagedPrivacyProfile ? new ManagedPrivacyProfileState(cachedManagedProfile, settings.ManagedPrivacyAllowDefault) : ManagedPrivacyProfileState.Local); - builder.Services.AddSingleton(new PackDetectionRedactor( - new JsonEventRedactor(bundle.Privacy), new DeterministicPolicyEvaluator(bundle.Policies), - bundle.LoadedPacks.SelectMany(pack => pack.Detections).ToArray())); // Free-space watermarks for the queue volume. Tests may supply an IDiskSpaceProbe. builder.Services.AddSingleton(services => new StorageGuard( settings.QueuePath, @@ -126,7 +123,25 @@ public static WebApplication Build( settings.MaximumQueueBytes, services.GetRequiredService(), services.GetRequiredService())); - builder.Services.AddSingleton(new DeterministicPolicyEvaluator(bundle.Policies)); + builder.Services.AddSingleton(services => new PolicyBundleHolder( + bundle, + settings, + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService>())); + builder.Services.AddSingleton(services => services.GetRequiredService().Current.Redactor); + builder.Services.AddSingleton(services => services.GetRequiredService().Current.PolicyEvaluator); + builder.Services.AddSingleton(services => + { + PolicyBundleHolder holder = services.GetRequiredService(); + IEventRedactor redactor = services.GetRequiredService(); + ITelemetryPolicyEvaluator evaluator = services.GetRequiredService(); + ActivePolicyRuntime initial = holder.Current; + return ReferenceEquals(redactor, initial.Redactor) && ReferenceEquals(evaluator, initial.PolicyEvaluator) + ? holder + : new StaticPolicyRuntimeProvider(new ActivePolicyRuntime(redactor, evaluator)); + }); + builder.Services.AddHostedService(); builder.Services.AddSingleton(); // Live post-redaction tap (bower tap). In memory only; never persisted. builder.Services.AddSingleton(services => @@ -161,41 +176,49 @@ public static WebApplication Build( builder.Services.AddHostedService(); if (sources.Syslog is { } syslog) { - builder.Services.AddSingleton(services => new SyslogSource( - syslog, - new CollectorSyslogSink( - bundle, - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService()), - services.GetRequiredService())); + builder.Services.AddSingleton(services => + { + PolicyBundleHolder bundleHolder = services.GetRequiredService(); + return new SyslogSource( + syslog, + new CollectorSyslogSink( + () => bundleHolder.CurrentBundle, + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService()), + services.GetRequiredService()); + }); builder.Services.AddHostedService(); } if (sources.WindowsEventLog is { } windowsEventLog) { // Bookmarks live with the queue, so a restart resumes where the queue left off. builder.Services.AddSingleton(new WindowsEventLogBookmarks(settings.QueuePath)); - builder.Services.AddSingleton(services => new WindowsEventLogSource( - windowsEventLog, - new CollectorWindowsEventSink(new PackRecordIntake( - bundle, - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService()), - services.GetRequiredService() as SqliteEventStore), - services.GetRequiredService().Store, - // Tests supply an in-memory channel; otherwise the Windows reader (Windows only). - services.GetService() ?? WindowsEventLogRoutes.PlatformChannels(), - services.GetRequiredService()) + builder.Services.AddSingleton(services => { - // A busy queue database (for example during a retention batch) is backpressure. - IsTransientStorageFailure = QueueStorageErrors.IsBusy + PolicyBundleHolder bundleHolder = services.GetRequiredService(); + return new WindowsEventLogSource( + windowsEventLog, + new CollectorWindowsEventSink(new PackRecordIntake( + () => bundleHolder.CurrentBundle, + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService()), + services.GetRequiredService() as SqliteEventStore), + services.GetRequiredService().Store, + // Tests supply an in-memory channel; otherwise the Windows reader (Windows only). + services.GetService() ?? WindowsEventLogRoutes.PlatformChannels(), + services.GetRequiredService()) + { + // A busy queue database (for example during a retention batch) is backpressure. + IsTransientStorageFailure = QueueStorageErrors.IsBusy + }; }); builder.Services.AddHostedService(); string[] wecSubscriptions = sources.WindowsEventLog.Subscriptions @@ -217,32 +240,36 @@ public static WebApplication Build( { // Cursors live with the queue, so a restart resumes where the queue left off. builder.Services.AddSingleton(new FileTailCursors(settings.QueuePath)); - builder.Services.AddSingleton(services => new FileTailSource( - fileTail, - new CollectorFileTailSink(new PackRecordIntake( - bundle, - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService(), - services.GetRequiredService())), - services.GetRequiredService().Store, - services.GetRequiredService(), - input => PackRecordIntake.Parser(bundle, input.Route.Pack, input.Route.Parser)?.Multiline is { } rule - ? new FileTailMultilineOptions( - rule.Mode == MultilineMode.Start, - rule.Pattern, - rule.MaxLines, - rule.MaxBytes, - rule.FlushTimeoutMilliseconds, - rule.JoinSeparator) - : null) + builder.Services.AddSingleton(services => { - // A busy queue database (for example during a retention batch) is backpressure. - IsTransientStorageFailure = QueueStorageErrors.IsBusy, - // Metadata only: the input id and a reason code, never a path. - InputRefused = FileTailIntakeService.Refused(services.GetRequiredService>()) + PolicyBundleHolder bundleHolder = services.GetRequiredService(); + return new FileTailSource( + fileTail, + new CollectorFileTailSink(new PackRecordIntake( + () => bundleHolder.CurrentBundle, + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService(), + services.GetRequiredService())), + services.GetRequiredService().Store, + services.GetRequiredService(), + input => PackRecordIntake.Parser(bundleHolder.CurrentBundle, input.Route.Pack, input.Route.Parser)?.Multiline is { } rule + ? new FileTailMultilineOptions( + rule.Mode == MultilineMode.Start, + rule.Pattern, + rule.MaxLines, + rule.MaxBytes, + rule.FlushTimeoutMilliseconds, + rule.JoinSeparator) + : null) + { + // A busy queue database (for example during a retention batch) is backpressure. + IsTransientStorageFailure = QueueStorageErrors.IsBusy, + // Metadata only: the input id and a reason code, never a path. + InputRefused = FileTailIntakeService.Refused(services.GetRequiredService>()) + }; }); builder.Services.AddHostedService(); } @@ -610,7 +637,7 @@ result.PolicyDecision is null IDurableEventStore eventQueue, BackgroundJobCatalog jobs, EventIdentityConflicts conflicts, - PolicyBundle bundle, + PolicyBundleHolder bundleHolder, ManagedPrivacyProfileState managedPrivacy, CollectorSettings settings, PipelineTelemetry telemetry, @@ -622,6 +649,7 @@ result.PolicyDecision is null HttpContext context, CancellationToken cancellationToken) => { + PolicyBundle bundle = bundleHolder.CurrentBundle; QueueSnapshot snapshot = await eventQueue.GetSnapshotAsync(cancellationToken); LedgerHead ledger = await eventQueue.GetLedgerHeadAsync(cancellationToken); IReadOnlyList sources = sourceHealth.Evaluate(); @@ -682,11 +710,45 @@ [.. pack.Parsers.Select(parser => parser.Runtime is null ? "inactive-preview-onl Storage = await QueueStorageStatus.TryCaptureAsync( eventQueue, snapshot, pressure, telemetry, clock.GetUtcNow(), pages, cancellationToken), Recovery = context.RequestServices.GetRequiredService().Last, - Volumes = volumes.HasVolumes ? volumes.Evaluate() : null + Volumes = volumes.HasVolumes ? volumes.Evaluate() : null, + Reload = bundleHolder.LastReload }; return Results.Json(status, CollectorJsonContext.Default.StatusResponse); }) .AddEndpointFilter(); + + // Operator-triggered zero-downtime hot reload of policies, signed packs and local + // privacy profile. Restricted to the shared token ("default") or configured operator + // tap producers; invalid configuration is rejected and keeps the active bundle. + app.MapPost( + "/v1/reload", + async ( + PolicyBundleHolder bundleHolder, + CollectorSettings settings, + IngestAuthentication authentication, + HttpContext context, + CancellationToken cancellationToken) => + { + string producer = context.Items[IngestAuthenticationFilter.ProducerItem] as string ?? "anonymous"; + bool allowed = authentication.Required + ? string.Equals(producer, "default", StringComparison.Ordinal) + || settings.TapProducers.Contains(producer, StringComparer.Ordinal) + : settings.IsLoopbackListener; + if (!allowed) + { + return Results.Json( + new ErrorResponse("Producer is not authorized to reload collector policy."), + CollectorJsonContext.Default.ErrorResponse, + statusCode: StatusCodes.Status403Forbidden); + } + + ConfigReloadStatus result = await bundleHolder.ReloadAsync("http", cancellationToken); + int statusCode = string.Equals(result.Outcome, "rejected", StringComparison.Ordinal) + ? StatusCodes.Status422UnprocessableEntity + : StatusCodes.Status200OK; + return Results.Json(result, CollectorJsonContext.Default.ConfigReloadStatus, statusCode: statusCode); + }) + .AddEndpointFilter(); } /// diff --git a/src/Bower.Collector/CollectorJson.cs b/src/Bower.Collector/CollectorJson.cs index be99f721..b49ae106 100644 --- a/src/Bower.Collector/CollectorJson.cs +++ b/src/Bower.Collector/CollectorJson.cs @@ -108,6 +108,10 @@ internal sealed record StatusResponse( /// Free-space health for configured spool and archive volumes. Metadata only. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList? Volumes { get; init; } + + /// Most recent in-process configuration hot reload outcome. Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public ConfigReloadStatus? Reload { get; init; } } /// First server-sent event of a tap session: its effective filters and caps. @@ -282,4 +286,5 @@ internal sealed record OutputReport( [JsonSerializable(typeof(CollectorEnrolmentRequest))] [JsonSerializable(typeof(CollectorCredentialRotationRequest))] [JsonSerializable(typeof(IssuedCollectorCredential))] +[JsonSerializable(typeof(ConfigReloadStatus))] internal sealed partial class CollectorJsonContext : JsonSerializerContext; diff --git a/src/Bower.Collector/CollectorSettings.cs b/src/Bower.Collector/CollectorSettings.cs index 753882bd..854ccf6f 100644 --- a/src/Bower.Collector/CollectorSettings.cs +++ b/src/Bower.Collector/CollectorSettings.cs @@ -180,6 +180,18 @@ public sealed record CollectorSettings /// JSON file of security-selected local files and their pack routes (BOWER_FILE_CONFIG). public string? FileTailConfigPath { get; init; } + /// + /// BOWER_POLICY_WATCH (default false): watch the policy directory, local privacy profile + /// and configured signed pack files and hot-reload atomically on change. + /// + public bool PolicyWatchEnabled { get; init; } + + /// + /// BOWER_POLICY_WATCH_DEBOUNCE_MS (default 500, range 100-30000): coalescing delay after + /// a watched policy/pack file changes before validating and hot-reloading. + /// + public TimeSpan PolicyWatchDebounce { get; init; } = TimeSpan.FromMilliseconds(500); + public string? ManagementScope { get; init; } /// @@ -442,7 +454,9 @@ public static CollectorSettings FromEnvironment(Func? read = nu TapProducers = SplitList(read("BOWER_TAP_PRODUCERS")), OriginProducers = SplitList(read("BOWER_ORIGIN_PRODUCERS")), WindowsEventLogConfigPath = Blank(read("BOWER_WINDOWS_EVENTLOG_CONFIG")), - FileTailConfigPath = Blank(read("BOWER_FILE_CONFIG")) + FileTailConfigPath = Blank(read("BOWER_FILE_CONFIG")), + PolicyWatchEnabled = ReadBoolean(read, "BOWER_POLICY_WATCH"), + PolicyWatchDebounce = TimeSpan.FromMilliseconds(ReadInt32(read, "BOWER_POLICY_WATCH_DEBOUNCE_MS", 500)) }; settings.Validate(); return settings; @@ -539,6 +553,12 @@ public void Validate() "BOWER_HEALTH_RECORD_INTERVAL_SECONDS must be 0 (off) or between 60 and 3600."); } + if (PolicyWatchDebounce < TimeSpan.FromMilliseconds(100) || PolicyWatchDebounce > TimeSpan.FromSeconds(30)) + { + throw new InvalidOperationException( + "BOWER_POLICY_WATCH_DEBOUNCE_MS must be between 100 and 30000."); + } + if (OutputType is not ("none" or "ama-spool" or "azure-logs-ingestion" or "relay" or "s3" or "http" or "ama-syslog")) { throw new InvalidOperationException($"Unsupported BOWER_OUTPUT value: {OutputType}"); diff --git a/src/Bower.Collector/ConfigHotReloadService.cs b/src/Bower.Collector/ConfigHotReloadService.cs new file mode 100644 index 00000000..6623c39d --- /dev/null +++ b/src/Bower.Collector/ConfigHotReloadService.cs @@ -0,0 +1,269 @@ +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Channels; + +namespace Bower.Collector; + +/// +/// Coordinates zero-downtime hot reload triggers for : +/// SIGHUP on Unix hosts and optional debounced file watching (BOWER_POLICY_WATCH=true). +/// Rapid bursts coalesce into a single serialized reload without closing the queue, +/// dropping active connections or interrupting delivery workers. +/// +public sealed partial class ConfigHotReloadService( + PolicyBundleHolder holder, + CollectorSettings settings, + ILogger logger) : BackgroundService +{ + private readonly Channel triggers = Channel.CreateBounded(new BoundedChannelOptions(1) + { + SingleReader = true, + FullMode = BoundedChannelFullMode.DropOldest + }); + private readonly List watchers = []; + private PosixSignalRegistration? sighup; + private string? lastWatchedFingerprint; + + public override Task StartAsync(CancellationToken cancellationToken) + { + sighup = RegisterSighup(); + if (settings.PolicyWatchEnabled) + { + lastWatchedFingerprint = CaptureWatchedFingerprint(); + StartWatchers(watchers); + } + + return base.StartAsync(cancellationToken); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + Task? pollTask = settings.PolicyWatchEnabled ? PollWatchedMetadataAsync(linked.Token) : null; + try + { + await foreach (string trigger in triggers.Reader.ReadAllAsync(stoppingToken)) + { + if (string.Equals(trigger, "watch", StringComparison.Ordinal)) + { + // Debounce bursts from atomic saves / multi-file deployments. + await Task.Delay(settings.PolicyWatchDebounce, stoppingToken); + while (triggers.Reader.TryRead(out _)) + { + } + + lastWatchedFingerprint = CaptureWatchedFingerprint(); + } + + try + { + await holder.ReloadAsync(trigger, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception exception) + { + LogTriggerFailure(logger, trigger, exception.GetType().Name); + } + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + // Normal host shutdown. + } + finally + { + await linked.CancelAsync(); + if (pollTask is not null) + { + try + { + await pollTask; + } + catch (OperationCanceledException) + { + } + } + + DisposeResources(); + } + } + + public override void Dispose() + { + DisposeResources(); + base.Dispose(); + } + + private void DisposeResources() + { + sighup?.Dispose(); + sighup = null; + foreach (FileSystemWatcher watcher in watchers) + { + watcher.EnableRaisingEvents = false; + watcher.Dispose(); + } + + watchers.Clear(); + } + + private async Task PollWatchedMetadataAsync(CancellationToken stoppingToken) + { + TimeSpan interval = settings.PolicyWatchDebounce > TimeSpan.FromMilliseconds(250) + ? settings.PolicyWatchDebounce + : TimeSpan.FromMilliseconds(250); + using PeriodicTimer timer = new(interval); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + string current = CaptureWatchedFingerprint(); + if (!string.Equals(current, lastWatchedFingerprint, StringComparison.Ordinal)) + { + lastWatchedFingerprint = current; + triggers.Writer.TryWrite("watch"); + } + } + } + + private string CaptureWatchedFingerprint() + { + StringBuilder sb = new(); + if (Directory.Exists(settings.PolicyDirectory)) + { + try + { + foreach (string file in Directory.GetFiles(settings.PolicyDirectory).Order(StringComparer.Ordinal)) + { + AppendFileStat(sb, file); + } + } + catch (IOException) + { + } + } + + if (!string.IsNullOrWhiteSpace(settings.PrivacyProfilePath)) + { + AppendFileStat(sb, Path.GetFullPath(settings.PrivacyProfilePath)); + } + + foreach (string packPath in settings.Packs.Order(StringComparer.Ordinal)) + { + AppendFileStat(sb, Path.GetFullPath(packPath)); + } + + return sb.ToString(); + } + + private static void AppendFileStat(StringBuilder sb, string path) + { + try + { + FileInfo info = new(path); + if (!info.Exists) + { + sb.Append(path).Append("|missing\n"); + return; + } + + sb.Append(path).Append('|').Append(info.Length).Append('|').Append(info.LastWriteTimeUtc.Ticks).Append('\n'); + } + catch (IOException) + { + sb.Append(path).Append("|io-error\n"); + } + } + + private PosixSignalRegistration? RegisterSighup() + { + if (OperatingSystem.IsWindows()) + { + return null; + } + + try + { + return PosixSignalRegistration.Create(PosixSignal.SIGHUP, context => + { + context.Cancel = true; + triggers.Writer.TryWrite("sighup"); + }); + } + catch (PlatformNotSupportedException) + { + return null; + } + } + + private void StartWatchers(List targetWatchers) + { + HashSet watchedKeys = new(StringComparer.Ordinal); + if (Directory.Exists(settings.PolicyDirectory)) + { + AddWatcher(targetWatchers, watchedKeys, Path.GetFullPath(settings.PolicyDirectory), "*"); + } + + if (!string.IsNullOrWhiteSpace(settings.PrivacyProfilePath)) + { + string full = Path.GetFullPath(settings.PrivacyProfilePath); + if (Path.GetDirectoryName(full) is { } dir && Directory.Exists(dir)) + { + AddWatcher(targetWatchers, watchedKeys, dir, Path.GetFileName(full)); + } + } + + foreach (string packPath in settings.Packs) + { + string full = Path.GetFullPath(packPath); + if (Path.GetDirectoryName(full) is { } dir && Directory.Exists(dir)) + { + AddWatcher(targetWatchers, watchedKeys, dir, Path.GetFileName(full)); + } + } + + LogWatchStarted(logger, targetWatchers.Count, (int)settings.PolicyWatchDebounce.TotalMilliseconds); + } + + private void AddWatcher( + List targetWatchers, + HashSet watchedKeys, + string directory, + string filter) + { + string key = $"{directory}\u001f{filter}"; + if (!watchedKeys.Add(key)) + { + return; + } + + FileSystemWatcher watcher = new(directory, filter) + { + NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.Size, + IncludeSubdirectories = false + }; + FileSystemEventHandler onChanged = (_, _) => triggers.Writer.TryWrite("watch"); + RenamedEventHandler onRenamed = (_, _) => triggers.Writer.TryWrite("watch"); + ErrorEventHandler onError = (_, _) => triggers.Writer.TryWrite("watch"); + watcher.Changed += onChanged; + watcher.Created += onChanged; + watcher.Deleted += onChanged; + watcher.Renamed += onRenamed; + watcher.Error += onError; + watcher.EnableRaisingEvents = true; + targetWatchers.Add(watcher); + } + + [LoggerMessage( + EventId = 1704, + Level = LogLevel.Information, + Message = "Policy file watch enabled on {WatcherCount} target(s) with {DebounceMilliseconds} ms debounce.")] + private static partial void LogWatchStarted(ILogger logger, int watcherCount, int debounceMilliseconds); + + [LoggerMessage( + EventId = 1705, + Level = LogLevel.Warning, + Message = "Hot reload trigger ({Trigger}) failed with {ExceptionType}; the previous policy bundle stays active.")] + private static partial void LogTriggerFailure(ILogger logger, string trigger, string exceptionType); +} diff --git a/src/Bower.Collector/Jobs/ManagedPrivacyProfileJob.cs b/src/Bower.Collector/Jobs/ManagedPrivacyProfileJob.cs index 91fa439b..a3ad38c7 100644 --- a/src/Bower.Collector/Jobs/ManagedPrivacyProfileJob.cs +++ b/src/Bower.Collector/Jobs/ManagedPrivacyProfileJob.cs @@ -28,7 +28,8 @@ public sealed partial class ManagedPrivacyProfileJob( PolicyBundle bundle, ManagedPrivacyProfileState state, IHostApplicationLifetime lifetime, - ILogger logger) + ILogger logger, + PolicyBundleHolder? bundleHolder = null) { public const string Id = "managed-privacy-profile"; @@ -124,9 +125,10 @@ private void Apply(byte[] document) // Only verified bytes reach the disk, and only through an atomic replace. The new // envelope becomes the high-water mark even when it needs no restart. ManagedPrivacyProfileCache.WriteAtomically(ManagedPrivacyProfileCache.CachePath(settings), document); + PolicyBundle activeBundle = bundleHolder?.CurrentBundle ?? bundle; bool changesProtection = verified.IsCleared - ? bundle.PrivacyProfileHash is not null - : !string.Equals(verified.ContentHash, bundle.PrivacyProfileHash, StringComparison.Ordinal); + ? activeBundle.PrivacyProfileHash is not null + : !string.Equals(verified.ContentHash, activeBundle.PrivacyProfileHash, StringComparison.Ordinal); if (!changesProtection) { state.MarkResolved(verified); diff --git a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs index f90ae2ec..5d771c67 100644 --- a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs +++ b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs @@ -31,8 +31,10 @@ public sealed partial class ManagementHeartbeatJob( QueueStoragePressure? storagePressure = null, WindowsEventLogSource? windowsEventLog = null, WecRuntimeStatusTracker? wecRuntime = null, - CrashRecoveryState? crashRecovery = null) + CrashRecoveryState? crashRecovery = null, + PolicyBundleHolder? bundleHolder = null) { + private PolicyBundle ActiveBundle => bundleHolder?.CurrentBundle ?? bundle; public const string Id = "management-heartbeat"; public const string HttpClientName = "bower-management"; @@ -140,6 +142,7 @@ private async Task ReportAsync(CancellationToken cancellationToken) // witness: a later head with a lower sequence or a different hash is tampering. LedgerHead ledger = await eventStore.GetLedgerHeadAsync(cancellationToken); + PolicyBundle activeBundle = ActiveBundle; using HttpRequestMessage registration = CreateRequest( "api/collectors/register", accessToken.Token, @@ -150,7 +153,7 @@ private async Task ReportAsync(CancellationToken cancellationToken) settings.Environment, settings.Version, settings.ConfigurationHash(), - bundle.Hash, + activeBundle.Hash, sources, outputs), CollectorJsonContext.Default.CollectorRegistration)); @@ -168,7 +171,7 @@ private async Task ReportAsync(CancellationToken cancellationToken) new CollectorHeartbeat( settings.Version, settings.ConfigurationHash(), - bundle.Hash, + activeBundle.Hash, snapshot.Queued + snapshot.Retrying + snapshot.Uploading, deliveryStatus, sources, @@ -176,7 +179,7 @@ private async Task ReportAsync(CancellationToken cancellationToken) jobReports, snapshot.DeadLettered, new LedgerResponse(ledger.Sequence, ledger.Hash), - bundle.PrivacyProfileHash ?? "default") + activeBundle.PrivacyProfileHash ?? "default") { HeartbeatIntervalSeconds = IntervalSeconds, OldestUndeliveredAgeSeconds = snapshot.OldestUndelivered is { } oldest diff --git a/src/Bower.Collector/ManagementEnrolment.cs b/src/Bower.Collector/ManagementEnrolment.cs index 26145996..fa0c1740 100644 --- a/src/Bower.Collector/ManagementEnrolment.cs +++ b/src/Bower.Collector/ManagementEnrolment.cs @@ -163,7 +163,8 @@ public sealed partial class ManagementEnrolment( CollectorSettings settings, PolicyBundle bundle, TimeProvider clock, - ILogger logger) : IDisposable + ILogger logger, + PolicyBundleHolder? bundleHolder = null) : IDisposable { /// Scheduled rotation: when 10 of the credential's 30 days remain. public static readonly TimeSpan RotateBefore = TimeSpan.FromDays(10); @@ -259,7 +260,7 @@ public async Task EnsureEnrolledAsync(CancellationToken cancellationToken) settings.Environment, settings.Version, settings.ConfigurationHash(), - bundle.Hash, + (bundleHolder?.CurrentBundle ?? bundle).Hash, publicKey), CollectorJsonContext.Default.CollectorEnrolmentRequest) }; diff --git a/src/Bower.Collector/PackEndpoints.cs b/src/Bower.Collector/PackEndpoints.cs index 112e88a8..9baccc68 100644 --- a/src/Bower.Collector/PackEndpoints.cs +++ b/src/Bower.Collector/PackEndpoints.cs @@ -14,11 +14,12 @@ private static void MapPackEndpoints(WebApplication app) { app.MapPost("/v1/packs/{packId}/parsers/{parserIndex:int}/events", async (string packId, int parserIndex, HttpContext context, - PolicyBundle bundle, SecurityEventProcessor processor, ProducerAuthorization authorization, + PolicyBundleHolder bundleHolder, SecurityEventProcessor processor, ProducerAuthorization authorization, CollectorIdentity identity, EventIdentityConflicts conflicts, IngestAuthentication authentication, PipelineTelemetry telemetry, EventTap tap, TimeProvider clock, CancellationToken cancellationToken) => { cancellationToken.ThrowIfCancellationRequested(); + PolicyBundle bundle = bundleHolder.CurrentBundle; LoadedPack? pack = bundle.LoadedPacks.SingleOrDefault(pack => pack.Manifest.Id == packId); if (pack is null || parserIndex < 0 || parserIndex >= pack.Parsers.Count || pack.Parsers[parserIndex].Runtime is null) { diff --git a/src/Bower.Collector/PackRecordIntake.cs b/src/Bower.Collector/PackRecordIntake.cs index f36e5102..24438b0b 100644 --- a/src/Bower.Collector/PackRecordIntake.cs +++ b/src/Bower.Collector/PackRecordIntake.cs @@ -33,7 +33,7 @@ internal enum PackRecordOutcome /// its cursor past it; counters and tap frames for it are recorded only after the commit. /// internal sealed class PackRecordIntake( - PolicyBundle bundle, + Func bundleProvider, SecurityEventProcessor processor, CollectorIdentity identity, ManagedPrivacyProfileState managedPrivacy, @@ -41,6 +41,17 @@ internal sealed class PackRecordIntake( TimeProvider timeProvider, EventTap? tap = null) { + public PackRecordIntake( + PolicyBundle bundle, + SecurityEventProcessor processor, + CollectorIdentity identity, + ManagedPrivacyProfileState managedPrivacy, + PipelineTelemetry telemetry, + TimeProvider timeProvider, + EventTap? tap = null) + : this(() => bundle, processor, identity, managedPrivacy, telemetry, timeProvider, tap) + { + } /// The active parser of a loaded signed pack, or null. public static CustomLogParserConfiguration? Parser(PolicyBundle bundle, string pack, int parser) { @@ -62,7 +73,7 @@ public async ValueTask SubmitAsync( return PackRecordOutcome.Unavailable; } - CustomLogParserConfiguration parser = Parser(bundle, pack, parserIndex)!; + CustomLogParserConfiguration parser = Parser(bundleProvider(), pack, parserIndex)!; SecurityEventEnvelope? envelope; try { diff --git a/src/Bower.Collector/PolicyBundleHolder.cs b/src/Bower.Collector/PolicyBundleHolder.cs new file mode 100644 index 00000000..2e70c7cb --- /dev/null +++ b/src/Bower.Collector/PolicyBundleHolder.cs @@ -0,0 +1,184 @@ +using System.Text.Json.Serialization; +using Bower.Abstractions; +using Bower.Packs; +using Bower.Persistence; +using Bower.PolicyEngine; +using Bower.Redaction; + +namespace Bower.Collector; + +/// +/// Metadata-only outcome of the most recent in-process configuration hot reload. Never +/// contains file paths, YAML content, secrets or credentials. +/// +public sealed record ConfigReloadStatus( + string Outcome, + string Trigger, + DateTimeOffset At, + string PolicyHash, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + string? PreviousPolicyHash = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + string? ErrorType = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + long? LedgerSequence = null); + +/// +/// Atomic holder for the collector's active , redactor and policy +/// evaluator. Readers observe an immutable snapshot lock-free; reloads validate every file +/// (policies, signed packs, trusted keys, privacy profile, source routes and health-record +/// policy) and record a hash-chained ledger entry before swapping the active reference. +/// Invalid reloads leave the running snapshot untouched. +/// +public sealed partial class PolicyBundleHolder : IPolicyRuntimeProvider, IDisposable +{ + private sealed record Snapshot(PolicyBundle Bundle, ActivePolicyRuntime Runtime); + + private readonly CollectorSettings settings; + private readonly IDurableEventStore? eventStore; + private readonly TimeProvider clock; + private readonly ILogger logger; + private readonly SemaphoreSlim reloadGate = new(1, 1); + + private Snapshot current; + private ConfigReloadStatus? lastReload; + + public PolicyBundleHolder( + PolicyBundle initialBundle, + CollectorSettings settings, + IDurableEventStore? eventStore = null, + TimeProvider? clock = null, + ILogger? logger = null) + { + ArgumentNullException.ThrowIfNull(initialBundle); + ArgumentNullException.ThrowIfNull(settings); + this.settings = settings; + this.eventStore = eventStore; + this.clock = clock ?? TimeProvider.System; + this.logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + current = CreateSnapshot(initialBundle); + } + + public PolicyBundle CurrentBundle => Volatile.Read(ref current).Bundle; + + public ActivePolicyRuntime Current => Volatile.Read(ref current).Runtime; + + public ConfigReloadStatus? LastReload => Volatile.Read(ref lastReload); + + /// + /// Reloads policies, signed packs and privacy profile from disk without stopping the + /// collector or interrupting queued delivery. Serialized so concurrent SIGHUP, watcher + /// and HTTP triggers cannot interleave. + /// + public async Task ReloadAsync(string trigger, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(trigger); + await reloadGate.WaitAsync(cancellationToken); + try + { + Snapshot active = Volatile.Read(ref current); + DateTimeOffset now = clock.GetUtcNow(); + PolicyBundle candidate; + try + { + candidate = PolicyBundle.Load(settings.PolicySources()); + _ = CollectorStartupSources.Load(settings, candidate); + if (settings.HealthRecordInterval is not null) + { + CollectorApplication.RequireHealthRecordPolicy(settings, candidate); + } + } + catch (Exception exception) when (exception is not OutOfMemoryException and not OperationCanceledException) + { + string errorType = exception.GetType().Name; + LogReloadRejected(logger, trigger, errorType); + ConfigReloadStatus rejected = new( + "rejected", + trigger, + now, + active.Bundle.Hash, + ErrorType: errorType); + Volatile.Write(ref lastReload, rejected); + return rejected; + } + + if (string.Equals(candidate.Hash, active.Bundle.Hash, StringComparison.Ordinal) + && string.Equals(candidate.PrivacyProfileHash, active.Bundle.PrivacyProfileHash, StringComparison.Ordinal)) + { + ConfigReloadStatus unchanged = new( + "unchanged", + trigger, + now, + active.Bundle.Hash); + Volatile.Write(ref lastReload, unchanged); + LogReloadUnchanged(logger, trigger, active.Bundle.Hash); + return unchanged; + } + + Snapshot next = CreateSnapshot(candidate); + long? ledgerSequence = null; + if (eventStore is SqliteEventStore sqlite) + { + ConfigReloadLedgerEntry entry = await sqlite.RecordConfigReloadAsync( + trigger, + active.Bundle.Hash, + candidate.Hash, + active.Bundle.PrivacyProfileHash ?? "default", + candidate.PrivacyProfileHash ?? "default", + cancellationToken); + ledgerSequence = entry.Sequence; + } + + Interlocked.Exchange(ref current, next); + ConfigReloadStatus reloaded = new( + "reloaded", + trigger, + now, + candidate.Hash, + PreviousPolicyHash: active.Bundle.Hash, + LedgerSequence: ledgerSequence); + Volatile.Write(ref lastReload, reloaded); + LogReloadSucceeded(logger, trigger, active.Bundle.Hash, candidate.Hash, ledgerSequence ?? 0); + return reloaded; + } + finally + { + reloadGate.Release(); + } + } + + public void Dispose() => reloadGate.Dispose(); + + private static Snapshot CreateSnapshot(PolicyBundle bundle) + { + DeterministicPolicyEvaluator evaluator = new(bundle.Policies); + PackDetectionRedactor redactor = new( + new JsonEventRedactor(bundle.Privacy), + evaluator, + bundle.LoadedPacks.SelectMany(pack => pack.Detections).ToArray()); + return new Snapshot(bundle, new ActivePolicyRuntime(redactor, evaluator)); + } + + [LoggerMessage( + EventId = 1701, + Level = LogLevel.Information, + Message = "Hot reload ({Trigger}) applied: policy bundle changed from {PreviousHash} to {NewHash} (reload ledger sequence {LedgerSequence}).")] + private static partial void LogReloadSucceeded( + ILogger logger, + string trigger, + string previousHash, + string newHash, + long ledgerSequence); + + [LoggerMessage( + EventId = 1702, + Level = LogLevel.Error, + Message = "Hot reload ({Trigger}) rejected ({ErrorType}); the previous policy bundle stays active.")] + private static partial void LogReloadRejected(ILogger logger, string trigger, string errorType); + + [LoggerMessage( + EventId = 1703, + Level = LogLevel.Information, + Message = "Hot reload ({Trigger}) verified with no policy bundle change ({PolicyHash}).")] + private static partial void LogReloadUnchanged(ILogger logger, string trigger, string policyHash); +} diff --git a/src/Bower.Collector/SyslogIntake.cs b/src/Bower.Collector/SyslogIntake.cs index 3e39ff74..d003691b 100644 --- a/src/Bower.Collector/SyslogIntake.cs +++ b/src/Bower.Collector/SyslogIntake.cs @@ -12,7 +12,7 @@ namespace Bower.Collector; /// to the sender; bytes buffered before admission can be lost on a process crash. /// internal sealed class CollectorSyslogSink( - PolicyBundle bundle, + Func bundleProvider, SecurityEventProcessor processor, CollectorIdentity identity, ManagedPrivacyProfileState managedPrivacy, @@ -20,7 +20,19 @@ internal sealed class CollectorSyslogSink( TimeProvider timeProvider, EventTap? tap = null) : ISyslogSink { - private readonly PackRecordIntake intake = new(bundle, processor, identity, managedPrivacy, telemetry, timeProvider, tap); + public CollectorSyslogSink( + PolicyBundle bundle, + SecurityEventProcessor processor, + CollectorIdentity identity, + ManagedPrivacyProfileState managedPrivacy, + PipelineTelemetry telemetry, + TimeProvider timeProvider, + EventTap? tap = null) + : this(() => bundle, processor, identity, managedPrivacy, telemetry, timeProvider, tap) + { + } + + private readonly PackRecordIntake intake = new(bundleProvider, processor, identity, managedPrivacy, telemetry, timeProvider, tap); public async ValueTask SubmitAsync( SyslogListenerOptions listener, diff --git a/src/Bower.Core/SecurityEventProcessor.cs b/src/Bower.Core/SecurityEventProcessor.cs index d030c685..2c63629b 100644 --- a/src/Bower.Core/SecurityEventProcessor.cs +++ b/src/Bower.Core/SecurityEventProcessor.cs @@ -14,8 +14,13 @@ public sealed class SecurityEventProcessor( IDurableEventStore queue, TimeProvider clock, PipelineTelemetry? telemetry = null, - EventTap? tap = null) + EventTap? tap = null, + IPolicyRuntimeProvider? policyRuntime = null) { + private (IEventRedactor Redactor, ITelemetryPolicyEvaluator PolicyEvaluator) ActivePolicy() => + policyRuntime is { } provider + ? (provider.Current.Redactor, provider.Current.PolicyEvaluator) + : (redactor, policyEvaluator); public Task ProcessAsync( string candidateJson, CollectorIdentity collector, @@ -142,12 +147,13 @@ public Task CloseSuppressionWindowsAsync( { ArgumentNullException.ThrowIfNull(collector); DateTimeOffset now = clock.GetUtcNow(); + (_, ITelemetryPolicyEvaluator activeEvaluator) = ActivePolicy(); return queue.CloseExpiredSuppressionWindowsAsync( now, window => { SecurityEventEnvelope summary = Suppression.CreateSummary(window, collector, now); - PolicyDecision decision = policyEvaluator.Evaluate(summary); + PolicyDecision decision = activeEvaluator.Evaluate(summary); if (decision.Action is not (DecisionAction.Accept or DecisionAction.RedactAndAccept)) { throw new SuppressionSummaryRejectedException(decision.PolicyId, decision.Action); @@ -228,12 +234,15 @@ private async Task ProcessCoreAsync( bool internalHealth, CancellationToken cancellationToken) { + // Capture one immutable (redactor, evaluator) pair per event so hot reload never + // evaluates an event with mixed privacy and policy versions. + (IEventRedactor activeRedactor, ITelemetryPolicyEvaluator activeEvaluator) = ActivePolicy(); // Captured before redaction, never persisted; see IsArchiveReplayFromAnotherCollector. string? replayOrigin = ArchiveReplayOrigin(candidateJson); RedactionResult redaction; try { - redaction = redactor.Redact(candidateJson, context); + redaction = activeRedactor.Redact(candidateJson, context); } catch (Exception exception) when (exception is not OperationCanceledException) { @@ -329,12 +338,13 @@ private async Task ProcessCoreAsync( redaction, collector, bytesIn, + activeEvaluator, cancellationToken); return quarantined with { PrivacyAlertEventId = alertId }; } - PolicyDecision decision = policyEvaluator.Evaluate(candidate); + PolicyDecision decision = activeEvaluator.Evaluate(candidate); if (decision.Action is not (DecisionAction.Accept or DecisionAction.RedactAndAccept)) { ProcessingResult rejected = Decided( @@ -352,6 +362,7 @@ private async Task ProcessCoreAsync( redaction, collector, bytesIn, + activeEvaluator, cancellationToken); return rejected with { PrivacyAlertEventId = rejectedAlertId }; @@ -444,6 +455,7 @@ private async Task ProcessCoreAsync( redaction, collector, bytesIn, + activeEvaluator, cancellationToken); List reasons = [.. decision.Reasons, .. decision.Warnings]; @@ -504,6 +516,7 @@ private ProcessingResult RedactionFailure(string original, long bytesIn, bool id RedactionResult redaction, CollectorIdentity collector, long bytesIn, + ITelemetryPolicyEvaluator activeEvaluator, CancellationToken cancellationToken) { IReadOnlyList detected = redaction.PrivacyDetected ?? []; @@ -610,7 +623,7 @@ private ProcessingResult RedactionFailure(string original, long bytesIn, bool id } }; - PolicyDecision alertDecision = policyEvaluator.Evaluate(alert); + PolicyDecision alertDecision = activeEvaluator.Evaluate(alert); if (alertDecision.Action is not (DecisionAction.Accept or DecisionAction.RedactAndAccept)) { return null; diff --git a/src/Bower.Persistence/SqliteEventQueue.cs b/src/Bower.Persistence/SqliteEventQueue.cs index 716b42ae..1a9d9488 100644 --- a/src/Bower.Persistence/SqliteEventQueue.cs +++ b/src/Bower.Persistence/SqliteEventQueue.cs @@ -141,7 +141,7 @@ public async Task InitializeAsync(CancellationToken cancellationToken = default) CREATE INDEX IF NOT EXISTS ix_queue_events_state_bytes ON queue_events_v5(state, payload_bytes, received_at); INSERT OR IGNORE INTO schema_history(version, applied_at, hash) VALUES (4, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), 'bower-queue-v4-capacity-index'); - """ + AuxiliarySchema + DeadLetterPurgeSchema; + """ + AuxiliarySchema + DeadLetterPurgeSchema + "\n" + ConfigReloadSchema; await check.ExecuteNonQueryAsync(cancellationToken); await repair.CommitAsync(cancellationToken); ApplyRestrictivePermissions(); diff --git a/src/Bower.Persistence/SqliteEventStore.ConfigReloads.cs b/src/Bower.Persistence/SqliteEventStore.ConfigReloads.cs new file mode 100644 index 00000000..024b5873 --- /dev/null +++ b/src/Bower.Persistence/SqliteEventStore.ConfigReloads.cs @@ -0,0 +1,283 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Bower.Abstractions; +using Microsoft.Data.Sqlite; + +namespace Bower.Persistence; + +/// +/// Tamper-evident record of an in-process configuration hot reload, hash-chained to the +/// previous reload record and bound to the queue event ledger head at the reload boundary. +/// Metadata only: never stores raw policy YAML, secrets or file paths. +/// +public sealed record ConfigReloadLedgerEntry( + long Sequence, + DateTimeOffset ReloadedAt, + string Trigger, + string PreviousPolicyHash, + string NewPolicyHash, + string PreviousPrivacyHash, + string NewPrivacyHash, + long QueueLedgerSequence, + string QueueLedgerHash, + string ChainHash); + +public sealed partial class SqliteEventStore +{ + private const string ConfigReloadGenesis = "bower-config-reload-ledger-v1"; + + private const string ConfigReloadSchema = + """ + CREATE TABLE IF NOT EXISTS queue_config_reloads ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + reloaded_at TEXT NOT NULL, + trigger TEXT NOT NULL, + previous_policy_hash TEXT NOT NULL, + new_policy_hash TEXT NOT NULL, + previous_privacy_hash TEXT NOT NULL, + new_privacy_hash TEXT NOT NULL, + queue_ledger_sequence INTEGER NOT NULL, + queue_ledger_hash TEXT NOT NULL, + chain_hash TEXT NOT NULL + ); + """; + + public async Task RecordConfigReloadAsync( + string trigger, + string previousPolicyHash, + string newPolicyHash, + string previousPrivacyHash, + string newPrivacyHash, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(trigger); + ArgumentException.ThrowIfNullOrWhiteSpace(previousPolicyHash); + ArgumentException.ThrowIfNullOrWhiteSpace(newPolicyHash); + ArgumentException.ThrowIfNullOrWhiteSpace(previousPrivacyHash); + ArgumentException.ThrowIfNullOrWhiteSpace(newPrivacyHash); + + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = await BeginWriteAsync(connection, true, cancellationToken); + + await EnsureConfigReloadTableAsync(connection, transaction, cancellationToken); + + (long ledgerSeq, string ledgerHash) = await QueueLedger.HeadAsync(connection, transaction, cancellationToken); + + string previousChainHash = ConfigReloadGenesisHash(); + long nextSequence = 1; + await using (SqliteCommand prevCmd = connection.CreateCommand()) + { + prevCmd.Transaction = transaction; + prevCmd.CommandText = "SELECT sequence, chain_hash FROM queue_config_reloads ORDER BY sequence DESC LIMIT 1;"; + await using SqliteDataReader reader = await prevCmd.ExecuteReaderAsync(cancellationToken); + if (await reader.ReadAsync(cancellationToken)) + { + nextSequence = reader.GetInt64(0) + 1; + previousChainHash = reader.GetString(1); + } + } + + DateTimeOffset now = clock.GetUtcNow(); + string reloadedAt = now.ToString("O", CultureInfo.InvariantCulture); + string chainHash = ComputeConfigReloadChainHash( + previousChainHash, + nextSequence, + reloadedAt, + trigger, + previousPolicyHash, + newPolicyHash, + previousPrivacyHash, + newPrivacyHash, + ledgerSeq, + ledgerHash); + + await using (SqliteCommand insertCmd = connection.CreateCommand()) + { + insertCmd.Transaction = transaction; + insertCmd.CommandText = + """ + INSERT INTO queue_config_reloads ( + sequence, reloaded_at, trigger, + previous_policy_hash, new_policy_hash, + previous_privacy_hash, new_privacy_hash, + queue_ledger_sequence, queue_ledger_hash, chain_hash) + VALUES ( + $sequence, $reloaded_at, $trigger, + $previous_policy_hash, $new_policy_hash, + $previous_privacy_hash, $new_privacy_hash, + $queue_ledger_sequence, $queue_ledger_hash, $chain_hash); + """; + insertCmd.Parameters.AddWithValue("$sequence", nextSequence); + insertCmd.Parameters.AddWithValue("$reloaded_at", reloadedAt); + insertCmd.Parameters.AddWithValue("$trigger", trigger); + insertCmd.Parameters.AddWithValue("$previous_policy_hash", previousPolicyHash); + insertCmd.Parameters.AddWithValue("$new_policy_hash", newPolicyHash); + insertCmd.Parameters.AddWithValue("$previous_privacy_hash", previousPrivacyHash); + insertCmd.Parameters.AddWithValue("$new_privacy_hash", newPrivacyHash); + insertCmd.Parameters.AddWithValue("$queue_ledger_sequence", ledgerSeq); + insertCmd.Parameters.AddWithValue("$queue_ledger_hash", ledgerHash); + insertCmd.Parameters.AddWithValue("$chain_hash", chainHash); + await insertCmd.ExecuteNonQueryAsync(cancellationToken); + } + + await transaction.CommitAsync(cancellationToken); + return new ConfigReloadLedgerEntry( + nextSequence, + now, + trigger, + previousPolicyHash, + newPolicyHash, + previousPrivacyHash, + newPrivacyHash, + ledgerSeq, + ledgerHash, + chainHash); + } + + public async Task> ListConfigReloadsAsync( + int limit = 50, + CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(limit, 1); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + if (!await TableExistsAsync(connection, "queue_config_reloads", cancellationToken)) + { + return []; + } + + List entries = []; + await using SqliteCommand cmd = connection.CreateCommand(); + cmd.CommandText = + """ + SELECT sequence, reloaded_at, trigger, + previous_policy_hash, new_policy_hash, + previous_privacy_hash, new_privacy_hash, + queue_ledger_sequence, queue_ledger_hash, chain_hash + FROM queue_config_reloads + ORDER BY sequence DESC + LIMIT $limit; + """; + cmd.Parameters.AddWithValue("$limit", limit); + await using SqliteDataReader reader = await cmd.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + entries.Add(new ConfigReloadLedgerEntry( + reader.GetInt64(0), + DateTimeOffset.Parse(reader.GetString(1), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), + reader.GetString(2), + reader.GetString(3), + reader.GetString(4), + reader.GetString(5), + reader.GetString(6), + reader.GetInt64(7), + reader.GetString(8), + reader.GetString(9))); + } + + return entries; + } + + public async Task VerifyConfigReloadLedgerAsync(CancellationToken cancellationToken = default) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + if (!await TableExistsAsync(connection, "queue_config_reloads", cancellationToken)) + { + return true; + } + + string previousHash = ConfigReloadGenesisHash(); + long expectedSequence = 1; + await using SqliteCommand cmd = connection.CreateCommand(); + cmd.CommandText = + """ + SELECT sequence, reloaded_at, trigger, + previous_policy_hash, new_policy_hash, + previous_privacy_hash, new_privacy_hash, + queue_ledger_sequence, queue_ledger_hash, chain_hash + FROM queue_config_reloads + ORDER BY sequence ASC; + """; + await using SqliteDataReader reader = await cmd.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + long sequence = reader.GetInt64(0); + if (sequence != expectedSequence) + { + return false; + } + + string expectedHash = ComputeConfigReloadChainHash( + previousHash, + sequence, + reader.GetString(1), + reader.GetString(2), + reader.GetString(3), + reader.GetString(4), + reader.GetString(5), + reader.GetString(6), + reader.GetInt64(7), + reader.GetString(8)); + + string actualHash = reader.GetString(9); + if (!string.Equals(expectedHash, actualHash, StringComparison.Ordinal)) + { + return false; + } + + previousHash = actualHash; + expectedSequence++; + } + + return true; + } + + private static async Task EnsureConfigReloadTableAsync( + SqliteConnection connection, + SqliteTransaction transaction, + CancellationToken cancellationToken) + { + await using SqliteCommand cmd = connection.CreateCommand(); + cmd.Transaction = transaction; + cmd.CommandText = ConfigReloadSchema; + await cmd.ExecuteNonQueryAsync(cancellationToken); + } + + private static async Task TableExistsAsync( + SqliteConnection connection, + string tableName, + CancellationToken cancellationToken) + { + await using SqliteCommand cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = $name;"; + cmd.Parameters.AddWithValue("$name", tableName); + return Convert.ToInt64(await cmd.ExecuteScalarAsync(cancellationToken), CultureInfo.InvariantCulture) > 0; + } + + private static string ConfigReloadGenesisHash() => + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(ConfigReloadGenesis))); + + private static string ComputeConfigReloadChainHash( + string previousHash, + long sequence, + string reloadedAt, + string trigger, + string previousPolicyHash, + string newPolicyHash, + string previousPrivacyHash, + string newPrivacyHash, + long queueLedgerSequence, + string queueLedgerHash) => + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join( + '\u001f', + previousHash, + sequence.ToString(CultureInfo.InvariantCulture), + reloadedAt, + trigger, + previousPolicyHash, + newPolicyHash, + previousPrivacyHash, + newPrivacyHash, + queueLedgerSequence.ToString(CultureInfo.InvariantCulture), + queueLedgerHash)))); +} diff --git a/tests/Bower.UnitTests/ConfigHotReloadTests.cs b/tests/Bower.UnitTests/ConfigHotReloadTests.cs new file mode 100644 index 00000000..4d181743 --- /dev/null +++ b/tests/Bower.UnitTests/ConfigHotReloadTests.cs @@ -0,0 +1,362 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Collector; +using Bower.Contracts; +using Bower.Persistence; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; + +namespace Bower.UnitTests; + +/// +/// Config hot reload without dropping or duplicating queued events (#96): atomic policy +/// swap, pre-validation fail-safe, hash-chained reload ledger, concurrent ingest soak, +/// operator authorization on POST /v1/reload, and optional debounced file watcher. +/// +public sealed class ConfigHotReloadTests +{ + private const string SharedToken = "hot-reload-test-token-0123456789abcdef"; + + [Fact] + public async Task HotReload_ValidAndInvalidPolicyChanges_UpdatesStatusLedgerAndKeepsPreviousOnError() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + string policyDir = Path.Combine(directory.Path, "policies"); + Directory.CreateDirectory(policyDir); + string policyFile = Path.Combine(policyDir, "auth.yaml"); + await File.WriteAllTextAsync(policyFile, PolicyYaml("1.0.0", "accept"), cancellation); + + CollectorSettings settings = CreateSettings(directory.Path, policyDir); + await using WebApplication app = BuildCollector(settings); + await CollectorApplication.InitializeAsync(app, cancellation); + await app.StartAsync(cancellation); + + try + { + using HttpClient client = app.GetTestClient(); + string initialHash = await GetPolicyHashAsync(client, cancellation); + + // Event accepted under policy v1.0.0. + using HttpResponseMessage first = await PostEventAsync(client, "evt-reload-1", cancellation); + Assert.Equal(HttpStatusCode.Accepted, first.StatusCode); + + // Update policy to v2.0.0 rejecting authentication_failure, then POST /v1/reload. + await File.WriteAllTextAsync(policyFile, PolicyYaml("2.0.0", "reject"), cancellation); + using HttpResponseMessage reloadResponse = await PostReloadAsync(client, SharedToken, cancellation); + Assert.Equal(HttpStatusCode.OK, reloadResponse.StatusCode); + using JsonDocument reloadJson = JsonDocument.Parse(await reloadResponse.Content.ReadAsStringAsync(cancellation)); + Assert.Equal("reloaded", reloadJson.RootElement.GetProperty("outcome").GetString()); + Assert.Equal("http", reloadJson.RootElement.GetProperty("trigger").GetString()); + string updatedHash = reloadJson.RootElement.GetProperty("policyHash").GetString()!; + Assert.NotEqual(initialHash, updatedHash); + Assert.Equal(initialHash, reloadJson.RootElement.GetProperty("previousPolicyHash").GetString()); + Assert.Equal(1, reloadJson.RootElement.GetProperty("ledgerSequence").GetInt64()); + + // /v1/status reflects the new policy hash and reload metadata. + Assert.Equal(updatedHash, await GetPolicyHashAsync(client, cancellation)); + + // New event now rejected under v2.0.0. + using HttpResponseMessage second = await PostEventAsync(client, "evt-reload-2", cancellation); + Assert.Equal(HttpStatusCode.UnprocessableEntity, second.StatusCode); + + // Corrupt the YAML on disk; reload must fail with 422 and keep v2.0.0 active. + await File.WriteAllTextAsync(policyFile, "not: [valid: yaml: :::", cancellation); + using HttpResponseMessage badReload = await PostReloadAsync(client, SharedToken, cancellation); + Assert.Equal(HttpStatusCode.UnprocessableEntity, badReload.StatusCode); + using JsonDocument badJson = JsonDocument.Parse(await badReload.Content.ReadAsStringAsync(cancellation)); + Assert.Equal("rejected", badJson.RootElement.GetProperty("outcome").GetString()); + Assert.Equal(updatedHash, badJson.RootElement.GetProperty("policyHash").GetString()); + Assert.False(string.IsNullOrWhiteSpace(badJson.RootElement.GetProperty("errorType").GetString())); + // Metadata only: error never leaks file path or raw YAML. + string badBody = badJson.RootElement.GetRawText(); + Assert.DoesNotContain(policyFile, badBody, StringComparison.Ordinal); + + // Previous v2.0.0 policy still active (still rejects). + using HttpResponseMessage third = await PostEventAsync(client, "evt-reload-3", cancellation); + Assert.Equal(HttpStatusCode.UnprocessableEntity, third.StatusCode); + + // Reload ledger and queue ledger both remain intact. + SqliteEventStore store = (SqliteEventStore)app.Services.GetRequiredService(); + IReadOnlyList reloads = await store.ListConfigReloadsAsync(cancellationToken: cancellation); + ConfigReloadLedgerEntry entry = Assert.Single(reloads); + Assert.Equal(initialHash, entry.PreviousPolicyHash); + Assert.Equal(updatedHash, entry.NewPolicyHash); + Assert.True(await store.VerifyConfigReloadLedgerAsync(cancellation)); + Assert.True((await store.VerifyLedgerAsync(cancellation)).Intact); + } + finally + { + await app.StopAsync(cancellation); + } + } + + [Fact] + public async Task HotReload_ConcurrentIngestAndMultipleReloads_NeverDropsOrDuplicatesEvents() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + string policyDir = Path.Combine(directory.Path, "policies"); + Directory.CreateDirectory(policyDir); + string policyFile = Path.Combine(policyDir, "auth.yaml"); + await File.WriteAllTextAsync(policyFile, PolicyYaml("1.0.0", "accept"), cancellation); + + RecordingOutputAdapter output = new(); + CollectorSettings settings = CreateSettings(directory.Path, policyDir); + await using WebApplication app = BuildCollector(settings, output); + await CollectorApplication.InitializeAsync(app, cancellation); + await app.StartAsync(cancellation); + + try + { + using HttpClient client = app.GetTestClient(); + PolicyBundleHolder holder = app.Services.GetRequiredService(); + + const int totalEvents = 60; + ConcurrentBag acceptedIds = []; + Task producers = Task.WhenAll(Enumerable.Range(0, totalEvents).Select(async i => + { + string id = $"soak-evt-{i:D4}"; + using HttpResponseMessage response = await PostEventAsync(client, id, cancellation); + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + acceptedIds.Add(id); + })); + + Task reloader = Task.Run(async () => + { + for (int version = 2; version <= 6; version++) + { + await File.WriteAllTextAsync(policyFile, PolicyYaml($"{version}.0.0", "accept"), cancellation); + ConfigReloadStatus status = await holder.ReloadAsync("sighup", cancellation); + Assert.Equal("reloaded", status.Outcome); + await Task.Delay(5, cancellation); + } + }, cancellation); + + await Task.WhenAll(producers, reloader); + Assert.Equal(totalEvents, acceptedIds.Count); + + // Wait for delivery worker to acknowledge every queued event (no drops, no duplicates). + DateTimeOffset deadline = DateTimeOffset.UtcNow.AddSeconds(10); + while (output.DeliveredIds.Count < totalEvents && DateTimeOffset.UtcNow < deadline) + { + await Task.Delay(25, cancellation); + } + + Assert.Equal(totalEvents, output.DeliveredIds.Count); + Assert.Equal(totalEvents, output.DeliveredIds.Distinct(StringComparer.Ordinal).Count()); + + SqliteEventStore store = (SqliteEventStore)app.Services.GetRequiredService(); + Assert.True(await store.VerifyConfigReloadLedgerAsync(cancellation)); + Assert.True((await store.VerifyLedgerAsync(cancellation)).Intact); + Assert.Equal(5, (await store.ListConfigReloadsAsync(cancellationToken: cancellation)).Count); + } + finally + { + await app.StopAsync(cancellation); + } + } + + [Fact] + public async Task HotReload_PolicyWatchEnabled_AutomaticallyReloadsOnFileEdit() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + string policyDir = Path.Combine(directory.Path, "policies"); + Directory.CreateDirectory(policyDir); + string policyFile = Path.Combine(policyDir, "auth.yaml"); + await File.WriteAllTextAsync(policyFile, PolicyYaml("1.0.0", "accept"), cancellation); + + CollectorSettings settings = CreateSettings(directory.Path, policyDir) with + { + PolicyWatchEnabled = true, + PolicyWatchDebounce = TimeSpan.FromMilliseconds(100) + }; + await using WebApplication app = BuildCollector(settings); + await CollectorApplication.InitializeAsync(app, cancellation); + await app.StartAsync(cancellation); + + try + { + PolicyBundleHolder holder = app.Services.GetRequiredService(); + string initialHash = holder.CurrentBundle.Hash; + + await File.WriteAllTextAsync(policyFile, PolicyYaml("1.1.0", "accept"), cancellation); + + DateTimeOffset deadline = DateTimeOffset.UtcNow.AddSeconds(5); + while (string.Equals(holder.CurrentBundle.Hash, initialHash, StringComparison.Ordinal) + && DateTimeOffset.UtcNow < deadline) + { + await Task.Delay(50, cancellation); + } + + Assert.NotEqual(initialHash, holder.CurrentBundle.Hash); + Assert.Equal("watch", holder.LastReload?.Trigger); + Assert.Equal("reloaded", holder.LastReload?.Outcome); + } + finally + { + await app.StopAsync(cancellation); + } + } + + [Fact] + public async Task HotReload_HttpEndpoint_RejectsNonOperatorProducerToken() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + string policyDir = Path.Combine(directory.Path, "policies"); + Directory.CreateDirectory(policyDir); + await File.WriteAllTextAsync(Path.Combine(policyDir, "auth.yaml"), PolicyYaml("1.0.0", "accept"), cancellation); + + const string producerSecret = "ordinary-producer-token-0123456789abcdef"; + string hash = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(producerSecret))); + string tokensFile = Path.Combine(directory.Path, "tokens.txt"); + await File.WriteAllTextAsync(tokensFile, $"app-01 sha256:{hash}\n", cancellation); + + CollectorSettings settings = CreateSettings(directory.Path, policyDir) with + { + IngestToken = null, + IngestTokensFile = tokensFile + }; + await using WebApplication app = BuildCollector(settings); + await CollectorApplication.InitializeAsync(app, cancellation); + await app.StartAsync(cancellation); + + try + { + using HttpClient client = app.GetTestClient(); + using HttpResponseMessage forbidden = await PostReloadAsync(client, producerSecret, cancellation); + Assert.Equal(HttpStatusCode.Forbidden, forbidden.StatusCode); + } + finally + { + await app.StopAsync(cancellation); + } + } + + private static CollectorSettings CreateSettings(string directory, string policyDir) => new() + { + CollectorId = "hot-reload-01", + Environment = "test", + ListenUrl = "http://127.0.0.1:4319", + PolicyDirectory = policyDir, + QueuePath = Path.Combine(directory, "queue.db"), + OutputType = "none", + IngestToken = SharedToken, + SingleTrustDomain = true + }; + + private static WebApplication BuildCollector(CollectorSettings settings, IOutputAdapter? output = null) => + CollectorApplication.Build( + settings, + output: output, + configure: builder => builder.WebHost.UseTestServer()); + + private static async Task GetPolicyHashAsync(HttpClient client, CancellationToken cancellation) + { + using HttpRequestMessage request = new(HttpMethod.Get, "/v1/status"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", SharedToken); + using HttpResponseMessage response = await client.SendAsync(request, cancellation); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellation)); + return doc.RootElement.GetProperty("policy").GetProperty("hash").GetString()!; + } + + private static async Task PostReloadAsync(HttpClient client, string token, CancellationToken cancellation) + { + using HttpRequestMessage request = new(HttpMethod.Post, "/v1/reload"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + return await client.SendAsync(request, cancellation); + } + + private static async Task PostEventAsync(HttpClient client, string eventId, CancellationToken cancellation) + { + string body = $$""" + { + "schemaVersion": "1.0.0", + "eventId": "{{eventId}}", + "timeGenerated": "{{DateTimeOffset.UtcNow:O}}", + "eventCategory": "authentication", + "eventType": "authentication_failure", + "eventAction": "login.failed", + "eventResult": "failure", + "eventSeverity": "medium", + "eventOutcomeReason": "invalid_credentials", + "application": { "name": "portal", "environment": "test" }, + "actor": { "username": "alice", "type": "human" }, + "source": { "ipAddress": "198.51.100.10" }, + "request": { "correlationId": "corr-{{eventId}}" } + } + """; + using HttpRequestMessage request = new(HttpMethod.Post, "/v1/events") + { + Content = new StringContent(body, Encoding.UTF8, "application/json") + }; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", SharedToken); + return await client.SendAsync(request, cancellation); + } + + private static string PolicyYaml(string version, string action) => $$""" + apiVersion: bower.security/v1 + kind: TelemetryPolicy + + metadata: + id: BWR-POL-AUTH-FAILURE + name: Authentication failures + version: {{version}} + owner: Security Operations + reviewDate: 2027-01-01 + + match: + eventCategories: + - authentication + eventTypes: + - authentication_failure + + requirements: + requiredFields: + - timeGenerated + - eventType + - eventResult + - application.name + atLeastOne: + - actor.userId + - actor.username + + decision: + action: {{action}} + minimumValueScore: 70 + neverSample: true + + routing: + profile: authentication + destination: security-events + """; + + private sealed class RecordingOutputAdapter : IOutputAdapter + { + public string Id => "recording"; + public ConcurrentBag DeliveredIds { get; } = []; + + public Task DeliverAsync(IReadOnlyList batch, CancellationToken cancellationToken) + { + List acked = []; + foreach (QueuedEvent item in batch) + { + DeliveredIds.Add(item.EventId); + acked.Add(item.EventId); + } + + return Task.FromResult(new DeliveryResult( + acked, + [], + $"ack-{Guid.NewGuid():N}")); + } + } +}