From 9756ab843e50e3280cdc296736cb509c719bd767 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:46:43 -0500 Subject: [PATCH] perf(audit): indexed, chunked retention sweep that runs off the startup path (SEC-014, #256) --- docs/DesignDecisions.md | 2 +- docs/GatewayConfiguration.md | 2 +- .../Security/Audit/AuditDrainService.cs | 5 +- .../Audit/SqliteCanonicalAuditStore.cs | 64 ++++++++++++++--- .../Security/Audit/ChannelAuditWriterTests.cs | 71 ++++++++++++++++++- 5 files changed, 128 insertions(+), 16 deletions(-) diff --git a/docs/DesignDecisions.md b/docs/DesignDecisions.md index 3a82cbb6..4094f1d2 100644 --- a/docs/DesignDecisions.md +++ b/docs/DesignDecisions.md @@ -403,7 +403,7 @@ it is about to do; a deployment that needs crash-durable admin audit should ship rather than rely on this table. `MxGateway:Security:AuditRetentionDays` (default 90, minimum 1) bounds the table: the drain sweeps -at startup and hourly, deleting older rows. Retention cannot be configured off. The sweep compares +hourly, deleting older rows in 5,000-row chunks (the first sweep runs from the background loop right after host startup, not inside it; an expression index on `datetime(occurred_at_utc)`, created by the first sweep, keeps the delete from scanning the table). Retention cannot be configured off. The sweep compares through SQLite's `datetime()` rather than on the stored ISO-8601 text. Text comparison is correct only while every row is UTC-normalized — which the canonical model guarantees for rows written through the store, but not for rows that entered the table any other way — and on a mixed-format diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 076705f4..5af21923 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -462,7 +462,7 @@ model requires otherwise. | `MxGateway:Security:ApiKeyFailureWindowSeconds` | `60` | Sliding-window length, in seconds, over which API-key verification failures are counted, for both the per-partition and the per-key-id aggregate layer. Must be greater than zero. | | `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(peer, key id)` partition. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. | | `MxGateway:Security:ApiKeyFailureProbeIntervalSeconds` | `5` | Minimum interval, in seconds, between probe admissions for an over-limit partition or key-id aggregate. An over-limit state is a valve rather than a wall: one request per interval reaches the real verifier — exactly one, even when a burst arrives together at the interval boundary — so the holder of the correct secret always gets through and clears the state, while everything else is still refused before the store read. `0` blocks absolutely instead — **not recommended**, because an unauthenticated peer can then deny the key to its holder for the whole window. Must be zero or greater. | -| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps once at startup and hourly thereafter, deleting rows older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. | +| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps hourly (the first sweep runs from the background loop right after startup, without delaying host startup), deleting rows in bounded chunks older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. | | `MxGateway:Security:ApiKeyFailureTrackedPeers` | `4096` | Maximum distinct partitions tracked by the failure counter (a bounded LRU) so a spray of unique tokens cannot grow memory without limit. It cannot be used to flush an active block either: only a validly shaped `mxgw__` token mints a key-id partition (everything else lands on the sender's transport-peer partition), each address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition, and eviction prefers fully expired windows, never removing an over-limit partition until the map exceeds twice this cap. Must be greater than zero. | ## Metrics Options diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs index 5bba3037..13378178 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs @@ -45,7 +45,6 @@ public sealed class AuditDrainService( try { await sink.EnsureInitializedAsync(cancellationToken).ConfigureAwait(false); - await SweepRetentionAsync(cancellationToken).ConfigureAwait(false); } catch (Exception exception) { @@ -250,6 +249,10 @@ public sealed class AuditDrainService( { try { + // The first sweep runs here rather than in StartAsync: on a large audit table it can + // take a while (and builds the retention index once), and host startup must not wait on it. + await SweepRetentionAsync(stoppingToken).ConfigureAwait(false); + using PeriodicTimer timer = new(RetentionSweepInterval, timeProvider); while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs index 11170abc..b638478e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs @@ -66,6 +66,19 @@ public sealed class SqliteCanonicalAuditStore( $category, $target, $source_node, $correlation_id, $details_json); """; + // Index on the same expression the sweep compares, so the DELETE seeks instead of scanning the + // whole table. It is the instant (datetime()), not the raw text, that is indexed: the sweep + // compares instants so rows in a non-UTC or mixed format are still judged correctly. + private const string CreateRetentionIndexSql = + "CREATE INDEX IF NOT EXISTS ix_audit_event_occurred_instant ON audit_event (datetime(occurred_at_utc));"; + + // Rows removed per statement. Each chunk is its own implicit transaction, so the single SQLite + // write lock (shared with the API-key store's last_used writes) is released between chunks. + private const int SweepChunkSize = 5000; + + /// 0 until the retention index has been created at least once by this instance. + private int _retentionIndexEnsured; + /// 0 until the audit_event table has been created at least once by this instance. private int _tableEnsured; @@ -162,17 +175,32 @@ public sealed class SqliteCanonicalAuditStore( await EnsureTableAsync(connection, cancellationToken).ConfigureAwait(false); - await using SqliteCommand command = connection.CreateCommand(); - command.CommandText = - """ - DELETE FROM audit_event - WHERE datetime(occurred_at_utc) < datetime($cutoff); - """; - command.Parameters.AddWithValue( - "$cutoff", - cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)); + await EnsureRetentionIndexAsync(connection, cancellationToken).ConfigureAwait(false); - return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + string cutoff = cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture); + int total = 0; + int deleted; + + do + { + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = + """ + DELETE FROM audit_event + WHERE rowid IN ( + SELECT rowid FROM audit_event + WHERE datetime(occurred_at_utc) < datetime($cutoff) + LIMIT $chunk); + """; + command.Parameters.AddWithValue("$cutoff", cutoff); + command.Parameters.AddWithValue("$chunk", SweepChunkSize); + + deleted = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + total += deleted; + } + while (deleted >= SweepChunkSize); + + return total; } /// Returns the most recent canonical audit events, newest first. @@ -226,6 +254,22 @@ public sealed class SqliteCanonicalAuditStore( return events; } + // Created lazily by the sweep rather than with the table: building it over a large existing + // table is a one-time cost, and it belongs on the background retention loop, not on startup. + private async Task EnsureRetentionIndexAsync(SqliteConnection connection, CancellationToken cancellationToken) + { + if (Volatile.Read(ref _retentionIndexEnsured) == 1) + { + return; + } + + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = CreateRetentionIndexSql; + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + + Volatile.Write(ref _retentionIndexEnsured, 1); + } + // Latched bootstrap: after the first success this is a single volatile read, so the DDL // round-trip is paid once per process rather than once per audit write. private async Task EnsureTableAsync(SqliteConnection connection, CancellationToken cancellationToken) diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs index 9f40f2ab..95ed6f13 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs @@ -6,6 +6,7 @@ using ZB.MOM.WW.Auth.ApiKeys.Sqlite; using ZB.MOM.WW.MxGateway.Server.Configuration; using ZB.MOM.WW.MxGateway.Server.Security.Audit; using ZB.MOM.WW.MxGateway.Tests.Security.Authentication; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; namespace ZB.MOM.WW.MxGateway.Tests.Security.Audit; @@ -160,7 +161,8 @@ public sealed class ChannelAuditWriterTests : IDisposable /// /// The retention sweep deletes rows older than AuditRetentionDays, measured from the - /// injected clock, and runs once at startup after the one-time table bootstrap. + /// injected clock. The table bootstrap completes in StartAsync; the first sweep runs from + /// the background loop so a large audit table cannot delay host startup (SEC-014). /// /// A task that represents the asynchronous operation. [Fact] @@ -174,12 +176,67 @@ public sealed class ChannelAuditWriterTests : IDisposable clock); await drain.StartAsync(CancellationToken.None); + await Eventually.WaitUntilAsync(() => sink.DeleteCutoffs.Count >= 1, TimeSpan.FromSeconds(10)); await drain.StopAsync(CancellationToken.None); Assert.Equal(1, sink.EnsureInitializedCalls); Assert.Equal(new DateTimeOffset(2026, 7, 16, 12, 0, 0, TimeSpan.Zero), Assert.Single(sink.DeleteCutoffs)); } + /// SEC-014: a sweep that blocks (a big table) must not hold up StartAsync. + /// A task that represents the asynchronous operation. + [Fact] + public async Task StartAsync_WhenTheSweepBlocks_StillCompletes() + { + CountingAuditSink sink = new() { BlockDelete = new TaskCompletionSource() }; + (_, AuditDrainService drain) = CreateWriterAndDrain(sink); + + await drain.StartAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)); + + sink.BlockDelete.SetResult(); + await drain.StopAsync(CancellationToken.None); + } + + /// + /// SEC-014: the sweep seeks an index on the instant it compares rather than scanning the table, + /// and removes a backlog larger than one chunk. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SqliteStore_DeleteOlderThan_UsesTheRetentionIndexAndSweepsMoreThanOneChunk() + { + (SqliteCanonicalAuditStore store, AuthSqliteConnectionFactory factory) = CreateStore(); + DateTimeOffset old = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + List backlog = []; + for (int index = 0; index < 5200; index++) + { + backlog.Add(MakeEvent("old", old)); + } + + await store.InsertBatchAsync(backlog, CancellationToken.None); + await store.InsertAsync(MakeEvent("fresh", new DateTimeOffset(2026, 6, 1, 0, 0, 0, TimeSpan.Zero)), CancellationToken.None); + + int deleted = await store.DeleteOlderThanAsync(new DateTimeOffset(2026, 3, 1, 0, 0, 0, TimeSpan.Zero), CancellationToken.None); + + Assert.Equal(5200, deleted); + Assert.Equal(["fresh"], await ListActionsAsync(factory)); + + await using SqliteConnection connection = await factory.OpenConnectionAsync(CancellationToken.None); + await using SqliteCommand plan = connection.CreateCommand(); + plan.CommandText = + "EXPLAIN QUERY PLAN SELECT rowid FROM audit_event WHERE datetime(occurred_at_utc) < datetime('2026-03-01T00:00:00.0000000+00:00') LIMIT 5000;"; + List details = []; + await using (SqliteDataReader reader = await plan.ExecuteReaderAsync(CancellationToken.None)) + { + while (await reader.ReadAsync(CancellationToken.None)) + { + details.Add(reader.GetString(3)); + } + } + + Assert.Contains(details, detail => detail.Contains("ix_audit_event_occurred_instant", StringComparison.Ordinal)); + } + /// /// The sweep compares instants, not stored text, and never deletes a row it cannot date. /// @@ -357,6 +414,9 @@ public sealed class ChannelAuditWriterTests : IDisposable /// Gets the number of accepted calls. public int InsertBatchCalls => BatchSizes.Count; + /// Gets or sets a gate the sweep waits on, to model a long-running delete. + public TaskCompletionSource? BlockDelete { get; set; } + /// Gets the number of calls. public int EnsureInitializedCalls { get; private set; } @@ -395,14 +455,19 @@ public sealed class ChannelAuditWriterTests : IDisposable } /// - public Task DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken) + public async Task DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken) { lock (_gate) { DeleteCutoffs.Add(cutoffUtc); } - return Task.FromResult(0); + if (BlockDelete is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + + return 0; } } }