From c7dae284e0cc78df7127bccfe538659c9187bef1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 1 Oct 2026 22:40:41 +0200 Subject: [PATCH] Retention had a privacy answer and no test that ever ran it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RetentionWorker is the reason this project can say a source key sits in the database for a bounded time: observations older than ObservationRetention, engine bans expired before BanRetention, and alerts older than BanRetention get deleted on a timer. Both windows default to 7 days. Nothing had ever called PruneAsync. Not a unit test, not scripts/smoke.sh, not scripts/compose-smoke.sh, not the CI workflow — the worker is registered as a hosted service with a 30-minute first tick, so no gate in the repo reaches it. The claim "the aggregates age out" was a number in a record and an unexecuted code path. Three integration tests now execute it (dotnet/OpenWaf.Tests.Integration/ RetentionPruneTests.cs): - observations: 3 sources written and flushed, 2 backdated 8 days -> prune leaves 1. This also pins the DateTimeOffset-vs-SQLite-text comparison: a wrong offset ordering would delete all three or none. - blocks: an engine ban expired 8 days ago goes, one expired yesterday stays (an automatic ban has to stay explainable after it stops being live), and an operator row is never touched — neither the one with a past expiry nor the one with none. - alerts: 9 days old goes, 6 days and 2 hours old stay. Teeth, counted rather than assumed: making PruneAsync return before its first delete fails exactly these 3 tests and leaves 34 passing. Gates on this tree: build 0 warnings / 0 errors, unit 59/59, integration 37/37. What this did NOT find: the worker is not broken. Prune works on SQLite, keeps operator rows, and respects both windows. What it did find is that BanRetention and ObservationRetention are read from nowhere — no configuration key, no admin surface — so an operator who needs a shorter window than 7 days has no lever, unlike the snapshot TTL (OPEN-13). That asymmetry is recorded as an open question rather than fixed here, because the window is a privacy and forensics tradeoff, not a knob to hand out by default. --- .../RetentionPruneTests.cs | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 dotnet/OpenWaf.Tests.Integration/RetentionPruneTests.cs diff --git a/dotnet/OpenWaf.Tests.Integration/RetentionPruneTests.cs b/dotnet/OpenWaf.Tests.Integration/RetentionPruneTests.cs new file mode 100644 index 0000000..d370bcc --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/RetentionPruneTests.cs @@ -0,0 +1,120 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Retention is the privacy answer this project gives: it stores aggregates, +/// not a request log, and the aggregates age out. Until now nothing ran +/// RetentionWorker.PruneAsync — not a unit test, not the smoke script, not the +/// compose gate — so "how long does a source key sit in the database" was a +/// number in a record nobody had ever executed. These tests execute it. +/// +/// The fixture's policy keeps the defaults: BanRetention and +/// ObservationRetention are both 7 days, and neither is read from +/// configuration. Rows are backdated past that window rather than the window +/// being shrunk, because shrinking it would test a setting that does not exist. +/// +public sealed class RetentionPruneTests +{ + private static async Task ObservationCount(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().Observations.CountAsync(); + } + + private static async Task BackdateObservations(EdgeFixture f, int howMany, int days) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var o in await db.Observations.OrderBy(o => o.SourceKey).Take(howMany).ToListAsync()) + { + o.LastSeenAt = DateTimeOffset.UtcNow.AddDays(-days); + } + await db.SaveChangesAsync(); + } + + [Fact] + public async Task Retention_ages_out_idle_observations_and_keeps_the_recent_one() + { + await using var f = new EdgeFixture(); + var client = f.Client; + + foreach (var ip in new[] { "203.0.113.11", "203.0.113.12", "203.0.113.13" }) + { + await f.SendAsync(client, "/", ip); + } + await f.FlushObservationsAsync(); + Assert.Equal(3, await ObservationCount(f)); + + await BackdateObservations(f, 2, days: 8); + await f.Service().PruneAsync(CancellationToken.None); + + // The comparison is DateTimeOffset against a column SQLite stores as + // text; if the offsets sorted differently the prune would take all + // three or none. + Assert.Equal(1, await ObservationCount(f)); + } + + [Fact] + public async Task Retention_deletes_expired_engine_bans_but_never_an_operator_row() + { + await using var f = new EdgeFixture(); + var now = DateTimeOffset.UtcNow; + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Blocks.AddRange( + new BlockEntry { SourceKey = "203.0.113.21", Source = BlockSource.Engine, ExpiresAt = now.AddDays(-8), Reason = "engine, long expired" }, + new BlockEntry { SourceKey = "203.0.113.22", Source = BlockSource.Engine, ExpiresAt = now.AddDays(-1), Reason = "engine, expired inside the window" }, + new BlockEntry { SourceKey = "203.0.113.23", Source = BlockSource.Operator, ExpiresAt = now.AddDays(-30), Reason = "operator row with a past expiry" }, + new BlockEntry { SourceKey = "203.0.113.24", Source = BlockSource.Operator, ExpiresAt = null, Reason = "operator row that never expires" }); + await db.SaveChangesAsync(); + } + + await f.Service().PruneAsync(CancellationToken.None); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var left = await db.Blocks.OrderBy(b => b.SourceKey).Select(b => new { b.SourceKey, b.Source }).ToListAsync(); + + // Only the engine ban older than the retention window goes. The + // one that expired yesterday stays: an automatic ban has to stay + // explainable after it stops being live. + Assert.Equal( + new[] { "203.0.113.22", "203.0.113.23", "203.0.113.24" }, + left.Select(b => b.SourceKey).ToArray()); + Assert.DoesNotContain(left, b => b.SourceKey == "203.0.113.21"); + } + } + + [Fact] + public async Task Retention_ages_out_alerts_older_than_the_ban_window() + { + await using var f = new EdgeFixture(); + var now = DateTimeOffset.UtcNow; + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Alerts.AddRange( + new EdgeAlert { SourceKey = "203.0.113.31", Kind = "server_error_streak", Count = 12, CreatedAt = now.AddDays(-9), Detail = "old outage" }, + new EdgeAlert { SourceKey = "203.0.113.32", Kind = "server_error_streak", Count = 4, CreatedAt = now.AddDays(-6), Detail = "inside the window" }, + new EdgeAlert { SourceKey = "203.0.113.33", Kind = "candidate_ban", Count = 3, CreatedAt = now.AddHours(-2), Detail = "fresh" }); + await db.SaveChangesAsync(); + } + + await f.Service().PruneAsync(CancellationToken.None); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var keys = await db.Alerts.OrderBy(a => a.SourceKey).Select(a => a.SourceKey).ToListAsync(); + Assert.Equal(new[] { "203.0.113.32", "203.0.113.33" }, keys); + } + } +}