diff --git a/README.md b/README.md index 93870cf..0200e2f 100644 --- a/README.md +++ b/README.md @@ -174,12 +174,17 @@ warning naming the key and the value, and `DecisionEngine` refuses to put a status the wire cannot carry (outside 100–999) on a response at all, answering 403 instead. The ranges live in one file, `OpenWaf.Domain/Policy/PolicyBounds.cs`. -One key is not policy and cannot be changed at runtime, because it decides how -long this process may keep enforcing a list that is already out of date: +Three keys are not policy and cannot be changed at runtime. One decides how long +this process may keep enforcing a list that is already out of date; the other two +decide how long the data behind the privacy promise sits in storage, and are +startup-time because widening a retention window is a deployment decision, not +something a request should be able to do: | key | default | meaning | |-----|---------|---------| | `OpenWaf:State:RefreshTtlSeconds` | `30` | how stale the in-memory block list may get. On a single edge this is invisible; behind a load balancer it **is** the propagation delay — 23.7 s measured at ~36 req/s in `research/2026-10-01-multi-instance/`. Anything outside 1–300 aborts startup: the process exits non-zero and the log names the key. In Docker the container stays `Up` with nothing listening until the image `HEALTHCHECK` marks it unhealthy — that is what any startup failure in this image looks like, not a special case. `/healthz` reports the value an operator actually got, as `snapshotTtlSeconds`. | +| `OpenWaf:Policy:ObservationRetentionDays` | `7` | how long a `source_observations` row survives past its last request. 1–365 whole days; anything else aborts startup naming the key, exactly as `RefreshTtlSeconds` does rather than falling back to 7 — a silently widened window keeps rows longer than the deployment asked for and nothing would say so. Surfaced as `observationRetentionDays` on `/admin-api/state` and `/admin-api/policy`, and as `rows are pruned after Nd` on the console. | +| `OpenWaf:Policy:BanRetentionDays` | `7` | how long an expired engine ban and an alert stay readable after they stopped being live. Same 1–365 bound, same startup refusal, surfaced as `banRetentionDays` and `alerts are pruned after Nd`. Two keys rather than one because the two windows answer different questions, and their sharing 7 days was coincidence. Operator-written rows are never pruned by either window. | Database: `Database:Provider` = `sqlite` (default) or `postgres`, `ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. @@ -795,17 +800,24 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged -into one green line. macOS host, this tree: build 0 warnings / 0 errors, unit -**132/132**, integration **173/173**, smoke **passed 28, failed 0**, compose **209 -passed, 0 failed**, console **75 assertions, 0 failed**, image 261 MB, 0 -containers left behind, enforcement lag 33 ms (`/tmp/c26_build.log`, -`/tmp/c26_unit.log`, `/tmp/c26_int4.log`, `/tmp/c26_smoke.log`, -`/tmp/c26_compose5.log`, `/tmp/c26_console4.log`). The integration count says -how it was scheduled, because that changed the answer: the suite as xUnit runs -it — parallel test collections — answered **157 passed, 16 failed**, every one -of them `Timed out waiting for the entry point to build the IHost after -00:05:00` (`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` -the same tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Earlier in the +into one green line. macOS host, this tree, re-measured 2026-10-04 with the +retention window as configuration: build 0 warnings / 0 errors, unit **132/132**, +integration **181/181 in 20 s**, console **76 assertions, 0 failed**, smoke +**passed 28, failed 0**. Carried from the 2026-10-02 run and not re-measured +since: compose **209 passed, 0 failed**, image 261 MB, 0 containers left behind, +enforcement lag 33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`, +`/tmp/c26_int4.log`, `/tmp/c26_smoke.log`, `/tmp/c26_compose5.log`, +`/tmp/c26_console4.log`). The integration count says how it was scheduled, +because that changed the answer once: the suite as xUnit runs it — parallel test +collections — answered **157 passed, 16 failed**, every one of them `Timed out +waiting for the entry point to build the IHost after 00:05:00` +(`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` the same +tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Re-measured 2026-10-04, +the default parallel scheduling answered **181/181 in 20 s**, and the same tree +run inside a filesystem-and-network sandbox failed **every** fixture with exactly +that timeout — a test host that cannot bind a loopback socket hangs in this +shape. Scheduling is one variable in that symptom; whether the test host can +open a socket at all is another, and it is the one that decided the run today. Earlier in the same cycle two overlapping runs of the suite produced the older OPEN-47 symptom on `PillarFailureVisibilityTests.The_snapshot_age_is_measured_against_the_ttl_it_is_supposed_to_respect` — a real `Assert.False`, not a timeout — while that test passed on its own. The @@ -954,8 +966,9 @@ Stated, because a defence that hides its failure modes is not a defence. list is already shared through the database; the streak map is not. Numbers, method and caveats: `research/2026-10-01-multi-instance/RESULTS.md`. * **Aggregates, not a request log.** `source_observations` keeps counters and - the last-seen evidence per source, and ages out after `ObservationRetention`. - Raw IPs are not logged. + the last-seen evidence per source, and ages out after + `OpenWaf:Policy:ObservationRetentionDays` (default 7, 1–365). Raw IPs are not + logged. ## Shape diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 08a061f..c0069a6 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -279,6 +279,12 @@ async function load() { : obsRes.truncated ? 'newest ' + obs.length + ' of ' + obsRes.total + ' recorded sources — the rest are older and this table is not the whole window' : obsRes.total + ' ' + plural(Number(obsRes.total), 'source') + ' the edge has recorded'; + // The window these rows age out at, printed on the table it applies to. + // Without the number, "3 sources recorded" reads the same whether the edge + // keeps them a week or a year — and the window is the answer to "how far + // back can this incident still be explained" (OPEN-19). + if (state.observationRetentionDays != null) + el('obsnote').textContent += ' · rows are pruned after ' + state.observationRetentionDays + 'd'; const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed])); // A failed write is not a stale read: the row never existed, and the // listing kept answering 200 with the count it already had. Measured on the @@ -422,6 +428,8 @@ async function load() { ? 'server_error_streak = your upstream is failing, and the edge will not ban the visitor who saw it; candidate_ban = the rule would have banned, mode is Observe. ' + (alertsRes.truncated ? 'Newest ' + alerts.length + ' of ' + alertsRes.total + ' alerts.' : 'All ' + alertsRes.total + ' alerts are listed.') : 'no alerts. server_error_streak means the upstream is failing; candidate_ban means a dry run would have banned.'; + if (state.banRetentionDays != null) + el('alertnote').textContent += ' · alerts are pruned after ' + state.banRetentionDays + 'd'; el('countries').tBodies[0].innerHTML = seen.map((c) => row([ { v: c.code }, { v: c.sources, n: true }, { v: c.refusals, n: true }, diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index c4dd96a..0ef8f50 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -57,7 +57,9 @@ internal sealed record PolicyDto( int Ipv6KeyPrefixLength, int EngineBlockStatus, int OperatorBlockStatus, - IReadOnlyList DefaultRedirectTargets); + IReadOnlyList DefaultRedirectTargets, + int ObservationRetentionDays, + int BanRetentionDays); /// Every field is optional and null means "leave it alone" — a /// partial update is the only sane shape for a live policy knob. diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 6b779a0..e96ac1b 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -537,6 +537,11 @@ internal static class AdminEndpoints retentionPruneFailures = durability.Get(DurabilityHealth.Retention).Failures, retentionLastError = durability.Get(DurabilityHealth.Retention).LastError, retentionLastPruneAt = durability.Get(DurabilityHealth.Retention).LastSuccessAt, + // The window itself, next to the counter that says whether it is + // running. "Nothing was pruned" and "nothing is due for 300 days" + // look identical without the number the promise is measured against. + observationRetentionDays = (int)state.Current.Policy.ObservationRetention.TotalDays, + banRetentionDays = (int)state.Current.Policy.BanRetention.TotalDays, mode = state.Current.Policy.Mode.ToString() }); }); @@ -715,7 +720,8 @@ internal static class AdminEndpoints p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes, p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders, p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus, - p.OperatorBlockStatus, p.DefaultRedirectTargets); + p.OperatorBlockStatus, p.DefaultRedirectTargets, + (int)p.ObservationRetention.TotalDays, (int)p.BanRetention.TotalDays); /// /// The provenance filter, parsed honestly. The old shape mapped any unrecognised diff --git a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs index fbf1aa2..fa275be 100644 --- a/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs +++ b/dotnet/OpenWaf.Edge/Configuration/EdgePolicyOptions.cs @@ -30,6 +30,24 @@ internal sealed class EdgePolicyOptions // leave a duplicate target in every deployment. public string[] DefaultRedirectTargets { get; set; } = []; + // Retention is the privacy promise this project makes: aggregates about a + // source outlive the traffic that produced them by exactly this long + // (OPEN-19). It used to be a constant on the domain record, so the operator + // who wanted either end of that promise — a shorter window, or an incident + // from nine days ago that is still explainable — had no lever at all. + // Two keys, not one: an observation ages out a fact about a source, while a + // ban's evidence row stays readable after the ban itself stopped being + // live. They shared 7 days by coincidence, not by design. + // Out-of-range refuses startup rather than falling back to 7. A silently + // widened window keeps rows a month longer than the deployment asked for, + // and nothing on any surface would say so — the same class of lie this + // project keeps chasing elsewhere. + public int ObservationRetentionDays { get; set; } = 7; + public int BanRetentionDays { get; set; } = 7; + + public const int RetentionDaysFloor = 1; + public const int RetentionDaysCeiling = 365; + public EdgePolicy ToPolicy() => new() { Mode = Enum.TryParse(Mode, true, out var m) ? m : EnforcementMode.Observe, @@ -47,9 +65,22 @@ internal sealed class EdgePolicyOptions OperatorBlockStatus = OperatorBlockStatus, DefaultRedirectTargets = DefaultRedirectTargets.Length == 0 ? new[] { "https://www.iana.org/help/example-domains" } - : DefaultRedirectTargets + : DefaultRedirectTargets, + ObservationRetention = RetentionDays(ObservationRetentionDays, "OpenWaf:Policy:ObservationRetentionDays"), + BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays") }; + /// Whole days, 1..365. Anything else is a deployment mistake and + /// is named as one at startup. + private static TimeSpan RetentionDays(int days, string configKey) + { + if (days < RetentionDaysFloor || days > RetentionDaysCeiling) + throw new InvalidOperationException( + $"{configKey} must be a whole number of days between {RetentionDaysFloor} and " + + $"{RetentionDaysCeiling}; got {days}"); + return TimeSpan.FromDays(days); + } + /// Accepts both 00:05:00 and a bare number of minutes. private static TimeSpan ParseWindow(string value, TimeSpan fallback) { diff --git a/dotnet/OpenWaf.Edge/appsettings.json b/dotnet/OpenWaf.Edge/appsettings.json index 18ad77d..825eee0 100644 --- a/dotnet/OpenWaf.Edge/appsettings.json +++ b/dotnet/OpenWaf.Edge/appsettings.json @@ -37,6 +37,8 @@ "Ipv6KeyPrefixLength": 64, "EngineBlockStatus": 403, "OperatorBlockStatus": 301, + "ObservationRetentionDays": 7, + "BanRetentionDays": 7, "DefaultRedirectTargets": [ "https://www.iana.org/help/example-domains" ] } }, diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs index c0db512..bbe82f0 100644 --- a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs +++ b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs @@ -27,6 +27,8 @@ internal sealed class EdgeFixture : IAsyncDisposable string banDuration = "01:00:00", string geo = "Off", int? refreshTtlSeconds = null, + int? observationRetentionDays = null, + int? banRetentionDays = null, string? adminToken = AdminToken) { Factory = new WebApplicationFactory().WithWebHostBuilder(builder => @@ -47,6 +49,12 @@ internal sealed class EdgeFixture : IAsyncDisposable builder.UseSetting("OpenWaf:Policy:TrustProxyHeaders", "true"); if (refreshTtlSeconds is { } ttl) builder.UseSetting("OpenWaf:State:RefreshTtlSeconds", ttl.ToString()); + // The retention window is configuration as of OPEN-19, so a test can + // ask for a short window instead of backdating rows past a constant. + if (observationRetentionDays is { } ord) + builder.UseSetting("OpenWaf:Policy:ObservationRetentionDays", ord.ToString()); + if (banRetentionDays is { } brd) + builder.UseSetting("OpenWaf:Policy:BanRetentionDays", brd.ToString()); builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address); }); } diff --git a/dotnet/OpenWaf.Tests.Integration/RetentionConfigTests.cs b/dotnet/OpenWaf.Tests.Integration/RetentionConfigTests.cs new file mode 100644 index 0000000..27c550a --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/RetentionConfigTests.cs @@ -0,0 +1,110 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Edge.Configuration; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Retention used to be a constant on the policy record: the operator could +/// neither shorten the privacy window nor lengthen the period an incident stays +/// explainable, and no surface said what the window was (OPEN-19). These tests +/// are the two halves of having a lever — a bad value is refused by name at +/// startup, and a good value is what the prune actually honours. +/// +public sealed class RetentionConfigTests +{ + [Theory] + [InlineData(0)] + [InlineData(-5)] + [InlineData(400)] + public void A_retention_window_outside_the_bound_is_refused_by_name(int days) + { + var ex = Assert.Throws(() => new EdgePolicyOptions + { ObservationRetentionDays = days }.ToPolicy()); + Assert.Contains("OpenWaf:Policy:ObservationRetentionDays", ex.Message); + Assert.Contains(days.ToString(), ex.Message); + } + + [Theory] + [InlineData(1)] + [InlineData(365)] + public void The_bound_is_inclusive_on_both_ends(int days) + { + var policy = new EdgePolicyOptions + { + ObservationRetentionDays = days, + BanRetentionDays = days + }.ToPolicy(); + Assert.Equal(TimeSpan.FromDays(days), policy.ObservationRetention); + Assert.Equal(TimeSpan.FromDays(days), policy.BanRetention); + } + + [Fact] + public async Task The_two_windows_are_separate_knobs_and_the_default_reports_itself_on_both_surfaces() + { + await using var f = new EdgeFixture(observationRetentionDays: 30, banRetentionDays: 2); + var state = await (await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync(); + Assert.Contains("\"observationRetentionDays\":30", state); + Assert.Contains("\"banRetentionDays\":2", state); + + var policy = await (await f.Client.GetAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync(); + Assert.Contains("\"observationRetentionDays\":30", policy); + Assert.Contains("\"banRetentionDays\":2", policy); + } + + [Fact] + public async Task A_shortened_window_prunes_what_the_default_window_would_have_kept() + { + // The tooth: with the default 7-day window these rows survive, so a + // prune that ignored the configured value would still pass a test that + // only backdated rows by eight days. + await using var f = new EdgeFixture(observationRetentionDays: 1); + foreach (var ip in new[] { "203.0.113.41", "203.0.113.42", "203.0.113.43" }) + await f.SendAsync(f.Client, "/", ip); + await f.FlushObservationsAsync(); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var o in await db.Observations.OrderBy(o => o.SourceKey).Take(2).ToListAsync()) + o.LastSeenAt = DateTimeOffset.UtcNow.AddDays(-3); + await db.SaveChangesAsync(); + } + + await f.Service().PruneAsync(CancellationToken.None); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await db.Observations.CountAsync()); + } + } + + [Fact] + public async Task A_lengthened_ban_window_keeps_the_evidence_row_the_default_would_have_pruned() + { + await using var f = new EdgeFixture(banRetentionDays: 30); + var now = DateTimeOffset.UtcNow; + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Blocks.Add(new OpenWaf.Domain.Security.BlockEntry + { + SourceKey = "203.0.113.44", + Source = OpenWaf.Domain.Security.BlockSource.Engine, + ExpiresAt = now.AddDays(-10), + Reason = "engine ban, ten days past expiry" + }); + await db.SaveChangesAsync(); + } + + await f.Service().PruneAsync(CancellationToken.None); + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await db.Blocks.CountAsync(b => b.SourceKey == "203.0.113.44")); + } + } +} diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 632403d..4e44254 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -117,7 +117,7 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); // 1000 rows back, no total and no flag. const obsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim(); check('the observation table states how many sources were recorded, not only the rows it shows', - /^\d+ sources? the edge has recorded$/.test(obsNote) || /^newest \d+ of \d+ recorded sources/.test(obsNote), + /^\d+ sources? the edge has recorded( \u00b7 rows are pruned after \d+d)?$/.test(obsNote) || /^newest \d+ of \d+ recorded sources/.test(obsNote), obsNote); const streakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim(); const standing = streakNote.match(/(\d+) of (\d+) standing streaks listed/); @@ -162,6 +162,13 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); const alertnote = (await page.textContent('#alertnote')).replace(/\s+/g, ' ').trim(); check('the page says a server error is never a reason to ban', /will not ban/.test(alertnote), alertnote); + // The window the rows age out at, printed on the tables it governs + // (OPEN-19). "3 sources recorded" reads the same whether this edge keeps them + // a week or a year, and the window is the answer to "how far back can this + // incident still be explained" — so it is asserted, not just printed. + check('both tables state the retention window they age out at', + /rows are pruned after \d+d/.test(obsNote) && /alerts are pruned after \d+d/.test(alertnote), + JSON.stringify([obsNote, alertnote])); const warnCells = await page.$$eval('#alerts tbody tr .warn', (els) => els.map((e) => e.textContent)); check('the kind an operator has to act on is marked, not only printed', warnCells.includes('server_error_streak'), JSON.stringify(warnCells)); @@ -757,7 +764,7 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); const emptyObsRow = await srcCells(); const emptyStreakNote = await noteOf('#streaknote'); check('a source with nothing recorded is named in words, with a total of zero', - emptyObsNote === 'no recorded observations for ' + NO_MATCH + emptyObsNote === 'no recorded observations for ' + NO_MATCH + ' · rows are pruned after 7d' && emptyObsRow.length === 1 && emptyObsRow[0] === 'nothing recorded for ' + NO_MATCH, `${JSON.stringify(emptyObsNote)} row=${JSON.stringify(emptyObsRow)}`); check('and the streak line says nothing is standing for that source', @@ -779,7 +786,7 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); const markupTitle = await page.title(); check('a filter value containing markup is printed as text and creates no element', markupInjected === 0 && markupTitle.indexOf('XSS3') === -1 - && markupNote === 'no recorded observations for ' + MARKUP_KEY, + && markupNote === 'no recorded observations for ' + MARKUP_KEY + ' · rows are pruned after 7d', `${markupInjected} injected elements, title ${JSON.stringify(markupTitle)}, note ${JSON.stringify(markupNote)}`); // And back out. Clearing has to restore the unfiltered totals, not leave a