diff --git a/README.md b/README.md index 21bb99d..c14dce8 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,14 @@ the edge generated itself must never feed the streak that produced the ban. The ban takes effect on the request *after* the one that matured the streak, because the edge decides from the response it has already served. +The reset is done by the observer, not only by the counter: a `2xx`/`3xx` calls +`StreakTracker.ResetIfTracked`, which costs one dictionary lookup for a source +the map has never seen and no MMDB read for anyone. Before that, the sentence +above was true in the domain object and false on the wire — a visitor +alternating a 404 with a normal page view accumulated refusals across every +honest request and still matured a ban. `A_clean_answer_between_refusals_ends_the_run…` +in the integration suite is the test for that sentence. + ### The toggle Automatic banning is a mode, not a replacement: @@ -146,7 +154,8 @@ POST /admin-api/blocks {"ip","reason","redirectTo"} DELETE /admin-api/blocks?source=engine[&key=…] GET /admin-api/allow POST {"match","note","expiresInMinutes"} DELETE /admin-api/allow/{id} GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…} -GET /admin-api/observations per-source streaks, durable +GET /admin-api/observations per-source streaks, durable — the maximum ever seen +GET /admin-api/streaks the streak standing right now, in this process, with the threshold GET /admin-api/alerts server_error_streak | candidate_ban GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false GET /admin-api/countries/summary sources and refusals per country, from the aggregates diff --git a/dotnet/OpenWaf.Domain/Engine/LiveStreak.cs b/dotnet/OpenWaf.Domain/Engine/LiveStreak.cs new file mode 100644 index 0000000..d54bfb2 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/LiveStreak.cs @@ -0,0 +1,18 @@ +namespace OpenWaf.Domain.Engine; + +/// +/// What the streak map holds for one source right now, in this process. +/// +/// The current consecutive count is the point. The durable observation +/// row keeps only the maximum ever seen, which tells an operator what already +/// happened and says nothing about what is about to — and the number that +/// decides a ban is the current one, not the record. +/// +public sealed record LiveStreak( + string SourceKey, + int ConsecutiveRefusals, + int ConsecutiveServerErrors, + int? LastStatusCode, + string? LastPath, + string? LastCountryCode, + DateTimeOffset LastSeenAt); diff --git a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs index de03cdc..1079d1c 100644 --- a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs +++ b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs @@ -125,8 +125,58 @@ public sealed class StreakTracker } } + /// + /// The streaks standing in this process right now, worst first. A source + /// whose last answer was clean has nothing standing and is left out: an + /// operator reading this is looking for the one source about to trip the + /// threshold, and a list of zeroes is how you lose it. + /// + public IReadOnlyList LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit) + { + var take = Math.Max(1, limit); + lock (_gate) + { + EvictIdle(now, policy); + var list = new List(); + foreach (var s in _states.Values) + { + if (s.ConsecutiveRefusals == 0 && s.ConsecutiveServerErrors == 0) continue; + list.Add(new LiveStreak( + s.SourceKey, s.ConsecutiveRefusals, s.ConsecutiveServerErrors, + s.LastStatusCode, s.LastPath, s.LastCountryCode, s.LastSeenAt)); + } + return list + .OrderByDescending(x => x.ConsecutiveRefusals) + .ThenByDescending(x => x.ConsecutiveServerErrors) + .ThenByDescending(x => x.LastSeenAt) + .Take(take) + .ToList(); + } + } + public int TrackedCount { get { lock (_gate) return _states.Count; } } + /// + /// Ends a standing streak when the source just got a clean answer. This is + /// what makes "consecutive" mean what the README says it means: without it + /// a visitor who alternates a 404 with a normal page view still matures a + /// ban, because nothing ever told the tracker the run ended. + /// + /// Cheap on purpose — it is called for every 2xx/3xx, which is most of the + /// traffic. A source the map has never seen costs one dictionary lookup and + /// nothing else; no evidence, no MMDB read, no write. + /// + public void ResetIfTracked(string sourceKey) + { + if (string.IsNullOrEmpty(sourceKey)) return; + lock (_gate) + { + if (!_states.TryGetValue(sourceKey, out var s)) return; + s.ConsecutiveRefusals = 0; + s.ConsecutiveServerErrors = 0; + } + } + public void Forget(string sourceKey) { lock (_gate) diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 8bcfdb5..2797a6a 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -85,6 +85,10 @@ internal static class AdminConsole

Sources the edge is watching

sourceconsec.refusalslast statuspathgeo
+

Streaks standing in this edge

+
+
sourceconsecutiveserver errorslast statuspathgeolast seen
+

Countries seen

codesourcesrefusalsrule
@@ -121,10 +125,10 @@ function row(cells) { async function load() { if (!token) { note('no token', true); return; } try { - const [state, blocksRes, obs, countries, rules] = await Promise.all([ + const [state, blocksRes, obs, streaks, countries, rules] = await Promise.all([ api('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'), - api('/admin-api/observations?limit=25'), api('/admin-api/countries/summary'), - api('/admin-api/countries') + api('/admin-api/observations?limit=25'), api('/admin-api/streaks'), + api('/admin-api/countries/summary'), api('/admin-api/countries') ]); const blocks = blocksRes.body; // The listing is capped server-side. Saying so is the difference between a @@ -150,6 +154,18 @@ async function load() { { v: o.sourceKey }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, { v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') } ])).join('') || row([{ v: 'none' }]); + el('streaks').tBodies[0].innerHTML = (streaks.streaks || []).map((st) => row([ + { v: st.sourceKey }, { v: st.consecutiveRefusals + ' / ' + streaks.threshold, n: true }, + { v: st.consecutiveServerErrors, n: true }, { v: st.lastStatusCode }, { v: st.lastPath }, + { v: st.lastCountryCode }, + { v: (st.lastSeenAt || '').replace('T', ' ').slice(0, 19) } + ])).join('') || row([{ v: 'nothing standing — every tracked source last saw a clean answer' }]); + el('streaknote').textContent = + streaks.scope === 'this-process' + ? 'this edge process only — ' + (streaks.streaks || []).length + ' of ' + streaks.trackedSources + + ' tracked sources have a streak standing; threshold ' + streaks.threshold + + ' within ' + streaks.windowMinutes + ' min; map capped at ' + streaks.maxTrackedSources + : 'unknown scope'; el('countries').tBodies[0].innerHTML = (countries || []).map((c) => row([ { v: c.code }, { v: c.sources, n: true }, { v: c.refusals, n: true }, { v: allowed.has(c.code) ? (allowed.get(c.code) ? 'allowed' : 'denied') : '—' } diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index 88f2759..a039060 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -20,6 +20,15 @@ internal sealed record BlockDto( internal sealed record NewBlockRequest(string Ip, string? Reason, string? RedirectTo); +internal sealed record StreakDto( + string SourceKey, + int ConsecutiveRefusals, + int ConsecutiveServerErrors, + int? LastStatusCode, + string? LastPath, + string? LastCountryCode, + DateTimeOffset LastSeenAt); + internal sealed record AllowDto(long Id, string Match, string? Note, DateTimeOffset CreatedAt, DateTimeOffset? ExpiresAt); internal sealed record NewAllowRequest(string Match, string? Note, int? ExpiresInMinutes); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index c9e5fd9..e42131c 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -145,6 +145,31 @@ internal static class AdminEndpoints o.LastCountryCode, o.LastCity)) .ToListAsync(ct))); + // The streak map is per process, so the answer says which process it + // came from instead of letting a console behind a load balancer imply + // it read the whole deployment. research/2026-10-01-multi-instance + // measured what that assumption costs: round-robin over two edges + // multiplied the effective threshold, and four refusals split 2+2 at a + // threshold of 3 produced no ban at all. + group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit) => + { + var now = DateTimeOffset.UtcNow; + var policy = policyProvider.Current; + var take = Math.Clamp(limit ?? 50, 1, 1000); + var streaks = tracker.LiveStreaks(now, policy, take); + ctx.Response.Headers["X-Truncated"] = (streaks.Count < tracker.TrackedCount).ToString().ToLowerInvariant(); + return Results.Ok(new + { + scope = "this-process", + threshold = policy.StreakThreshold, + windowMinutes = policy.StreakWindow.TotalMinutes, + trackedSources = tracker.TrackedCount, + maxTrackedSources = policy.MaxTrackedSources, + streaks = streaks.Select(st => new StreakDto(st.SourceKey, st.ConsecutiveRefusals, + st.ConsecutiveServerErrors, st.LastStatusCode, st.LastPath, st.LastCountryCode, st.LastSeenAt)) + }); + }); + group.MapGet("/alerts", async (OpenWafDbContext db, int? limit, CancellationToken ct) => Results.Ok(await db.Alerts.AsNoTracking() .OrderByDescending(a => a.CreatedAt) diff --git a/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs index 8271f89..587d0a3 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs @@ -39,7 +39,20 @@ public sealed class ResponseObservationMiddleware( var status = ctx.Response.StatusCode; var responseClass = ResponseClassifier.Classify(status, policy); - if (responseClass == ResponseClass.Neutral) return; + if (responseClass == ResponseClass.Neutral) + { + // A clean answer is the end of a run of refusals, and the tracker + // only knows that if it is told. Returning here — which is what this + // used to do — left the documented mitigation ("one honest click + // resets it", README) unenforced end to end: a visitor alternating + // 404 and a normal page view accumulated refusals across every + // honest request and still got banned. The reset is the only thing + // done for a 2xx: no evidence is built, so no MMDB read is paid. + var neutralIp = ClientIp.Resolve(ctx, policy.TrustProxyHeaders); + if (string.IsNullOrWhiteSpace(neutralIp)) return; + tracker.ResetIfTracked(SourceKey.For(neutralIp, policy)); + return; + } var ip = ClientIp.Resolve(ctx, policy.TrustProxyHeaders); if (string.IsNullOrWhiteSpace(ip)) return; diff --git a/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs b/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs new file mode 100644 index 0000000..07253a0 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs @@ -0,0 +1,86 @@ +using System.Net; +using System.Text.Json; + +namespace OpenWaf.Tests.Integration; + +/// +/// The streak map is the one part of the state that lives only in memory, so +/// until now the console could only say how many sources it was tracking — not +/// which one is three refusals from a ban. These tests pin the read that fixed, +/// and the two properties it inherits: it is behind the admin token, and +/// fumbling it must never ban the person fumbling it. +/// +public sealed class AdminStreaksTests +{ + private const string Building = "203.0.113.180"; + private const string Recovered = "203.0.113.181"; + + private static async Task GetAsync(EdgeFixture f, string path, string sourceIp) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); + using var response = await f.Client.SendAsync(request); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> StreaksAsync( + EdgeFixture f, bool withToken = true) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/streaks"); + if (withToken) request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + var body = response.StatusCode == HttpStatusCode.OK + ? JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement + : default; + return (response.StatusCode, body); + } + + [Fact] + public async Task A_source_mid_streak_is_listed_with_its_current_count_and_the_threshold_it_is_rising_toward() + { + await using var f = new EdgeFixture(threshold: 5); + f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404; + + for (var i = 0; i < 3; i++) await GetAsync(f, "/probe", Building); + await GetAsync(f, "/probe", Recovered); + await GetAsync(f, "/ok", Recovered); + + var (status, root) = await StreaksAsync(f); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("this-process", root.GetProperty("scope").GetString()); + Assert.Equal(5, root.GetProperty("threshold").GetInt32()); + Assert.Equal(2, root.GetProperty("trackedSources").GetInt32()); + + var streaks = root.GetProperty("streaks"); + Assert.Equal(1, streaks.GetArrayLength()); + var only = streaks[0]; + Assert.Equal(Building, only.GetProperty("sourceKey").GetString()); + Assert.Equal(3, only.GetProperty("consecutiveRefusals").GetInt32()); + } + + [Fact] + public async Task The_streak_listing_is_admin_only() + { + await using var f = new EdgeFixture(); + await GetAsync(f, "/probe", Building); + + var (status, _) = await StreaksAsync(f, withToken: false); + Assert.Equal(HttpStatusCode.Unauthorized, status); + } + + [Fact] + public async Task Fumbling_the_streak_listing_never_bans_the_operator_reading_it() + { + await using var f = new EdgeFixture(threshold: 3); + + for (var i = 0; i < 8; i++) + { + var (status, _) = await StreaksAsync(f); + Assert.Equal(HttpStatusCode.OK, status); + } + + using var request = new HttpRequestMessage(HttpMethod.Get, "/probe"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Building); + using var proxied = await f.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.NotFound, proxied.StatusCode); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs b/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs index 7075f14..78bfdc3 100644 --- a/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs @@ -350,6 +350,29 @@ public sealed class EdgeObservationBoundaryTests Assert.Empty(await db.Blocks.AsNoTracking().ToListAsync()); } + [Fact] + public async Task A_clean_answer_between_refusals_ends_the_run_because_consecutive_means_consecutive() + { + await using var f = new EdgeFixture(threshold: 3); + f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404; + const string Visitor = "203.0.113.190"; + + // Five refusals, none of them consecutive. The README names "one honest + // click resets it" as the mitigation for banning honest traffic off a + // shared egress, and the streak tracker agrees — but the observer used + // to return before it ever told the tracker about a 2xx, so the + // mitigation existed in the domain and not on the wire. + foreach (var path in new[] { "/probe", "/ok", "/probe", "/ok", "/probe", "/ok", "/probe", "/ok", "/probe" }) + (await GetAsync(f, path, Visitor)).Dispose(); + + using var stillOpen = await GetAsync(f, "/probe", Visitor); + Assert.Equal(HttpStatusCode.NotFound, stillOpen.StatusCode); + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Empty(await db.Blocks.AsNoTracking().Where(b => b.Source == BlockSource.Engine).ToListAsync()); + } + [Fact] public async Task Two_requests_that_finish_at_the_same_moment_write_one_ban_not_two() { diff --git a/dotnet/OpenWaf.Tests.Unit/LiveStreaksTests.cs b/dotnet/OpenWaf.Tests.Unit/LiveStreaksTests.cs new file mode 100644 index 0000000..7ce4dd8 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/LiveStreaksTests.cs @@ -0,0 +1,86 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; + +namespace OpenWaf.Tests.Unit; + +/// +/// The operator's question is "who is about to be banned", which is answered by +/// the current consecutive count. The durable observation row only keeps the +/// maximum ever seen, so a list built from it would show a source that has been +/// clean for an hour as if it were still standing at the gate. +/// +public sealed class LiveStreaksTests +{ + private static readonly DateTimeOffset T0 = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + + private static readonly EdgePolicy Policy = new() + { + StreakThreshold = 5, + StreakWindow = TimeSpan.FromMinutes(5), + StateIdleTtl = TimeSpan.FromMinutes(10) + }; + + [Fact] + public void A_clean_answer_takes_the_source_out_of_the_list_even_though_the_record_remains() + { + var t = new StreakTracker(); + for (var i = 0; i < 4; i++) t.Observe("1.1.1.1", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i)); + t.Observe("1.1.1.1", 200, ResponseClass.Neutral, Policy, T0.AddSeconds(10)); + + Assert.Empty(t.LiveStreaks(T0.AddSeconds(11), Policy, 10)); + Assert.Equal(4, t.Peek("1.1.1.1")!.MaxConsecutiveRefusals); + } + + [Fact] + public void The_list_is_ordered_by_how_close_a_source_is_to_a_ban_and_capped_by_the_limit() + { + var t = new StreakTracker(); + for (var i = 0; i < 3; i++) t.Observe("3.3.3.3", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i)); + for (var i = 0; i < 2; i++) t.Observe("2.2.2.2", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i)); + t.Observe("1.1.1.1", 404, ResponseClass.Refusal, Policy, T0); + + var live = t.LiveStreaks(T0.AddSeconds(5), Policy, 2); + + Assert.Equal(2, live.Count); + Assert.Equal("3.3.3.3", live[0].SourceKey); + Assert.Equal(3, live[0].ConsecutiveRefusals); + Assert.Equal("2.2.2.2", live[1].SourceKey); + Assert.Equal(2, live[1].ConsecutiveRefusals); + } + + [Fact] + public void Idle_sources_are_dropped_before_the_list_is_read() + { + var t = new StreakTracker(); + t.Observe("9.9.9.9", 404, ResponseClass.Refusal, Policy, T0); + + Assert.Single(t.LiveStreaks(T0.AddMinutes(1), Policy, 10)); + Assert.Empty(t.LiveStreaks(T0.AddMinutes(30), Policy, 10)); + } + + [Fact] + public void ResetIfTracked_ends_a_standing_run_and_creates_nothing_for_a_source_it_has_never_seen() + { + var t = new StreakTracker(); + t.Observe("1.1.1.1", 404, ResponseClass.Refusal, Policy, T0); + + t.ResetIfTracked("9.9.9.9"); + Assert.Equal(1, t.TrackedCount); + + t.ResetIfTracked("1.1.1.1"); + Assert.Empty(t.LiveStreaks(T0.AddSeconds(1), Policy, 10)); + Assert.Equal(1, t.Peek("1.1.1.1")!.MaxConsecutiveRefusals); + } + + [Fact] + public void A_server_error_streak_shows_up_because_it_is_the_other_way_a_source_escalates() + { + var t = new StreakTracker(); + t.Observe("8.8.8.8", 503, ResponseClass.ServerError, Policy, T0); + + var live = t.LiveStreaks(T0.AddSeconds(1), Policy, 10); + Assert.Single(live); + Assert.Equal(0, live[0].ConsecutiveRefusals); + Assert.Equal(1, live[0].ConsecutiveServerErrors); + } +}