using System.Net; using System.Net.Http.Json; using Microsoft.AspNetCore.Http; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Security; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; public sealed class EdgeBlockingTests { private const string Scanner = "203.0.113.66"; private const string Bystander = "198.51.100.7"; private static async Task GetAsync( EdgeFixture f, string path, string sourceIp, string? country = null, string? token = null) { var client = f.Client; using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); if (country is not null) request.Headers.TryAddWithoutValidation("CF-IPCountry", country); if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); return await client.SendAsync(request); } private static async Task JsonAsync(HttpResponseMessage response) => JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; [Fact] public async Task A_run_of_refusals_bans_that_source_and_nobody_else() { await using var f = new EdgeFixture(threshold: 3); for (var i = 0; i < 3; i++) { using var probe = await GetAsync(f, "/wp-login.php", Scanner); Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); } using var banned = await GetAsync(f, "/anything", Scanner); Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); Assert.True(banned.Headers.RetryAfter is not null, "a ban must tell the client how long it lasts"); var body = await JsonAsync(banned); Assert.Equal("blocked_by_policy", body.GetProperty("error").GetString()); Assert.Contains("consecutive refusals", body.GetProperty("reason").GetString()); using var bystander = await GetAsync(f, "/anything", Bystander); Assert.Equal(HttpStatusCode.NotFound, bystander.StatusCode); } [Fact] public async Task Observe_mode_records_the_ban_it_would_have_made_and_blocks_nobody() { await using var f = new EdgeFixture(mode: "Observe", threshold: 3); for (var i = 0; i < 6; i++) { using var probe = await GetAsync(f, "/.env", Scanner); Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); } using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "candidate_ban").ToListAsync(); Assert.NotEmpty(alerts); Assert.Contains("not enforced", alerts[0].Detail); Assert.Empty(await db.Blocks.Where(b => b.Source == BlockSource.Engine).ToListAsync()); } [Fact] public async Task A_server_error_streak_alerts_and_never_bans_because_a_bad_deploy_must_not_lock_out_visitors() { await using var f = new EdgeFixture(threshold: 3); f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway; for (var i = 0; i < 6; i++) { using var probe = await GetAsync(f, "/checkout", Scanner); Assert.Equal(HttpStatusCode.BadGateway, probe.StatusCode); } using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.NotEmpty(await db.Alerts.AsNoTracking().Where(a => a.Kind == "server_error_streak").ToListAsync()); Assert.Empty(await db.Blocks.AsNoTracking().ToListAsync()); } [Fact] public async Task A_server_error_storm_alerts_on_the_crossing_and_the_doublings_not_once_per_request() { await using var f = new EdgeFixture(threshold: 3); f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway; // Twelve broken answers from one source. The upstream never bans them, // so every one of the twelve is observed, and every one of them used to // write its own alert row: the alerts table grew at request rate, for // the whole retention window, and the operator's alert list (newest // 100) was one source deep. for (var i = 0; i < 12; i++) { using var probe = await GetAsync(f, "/checkout", Scanner); Assert.Equal(HttpStatusCode.BadGateway, probe.StatusCode); } using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.Alerts.AsNoTracking() .Where(a => a.Kind == "server_error_streak" && a.SourceKey == Scanner) .OrderBy(a => a.Count) .ToListAsync(); Assert.Equal([3, 6, 12], rows.Select(r => r.Count).ToList()); Assert.Empty(await db.Blocks.AsNoTracking().ToListAsync()); } [Fact] public async Task A_dry_run_announces_each_candidate_ban_twice_at_most_rather_than_once_per_request() { await using var f = new EdgeFixture(mode: "Observe", threshold: 3); // Nothing blocks in Observe mode, so this source is observed on every // request and the ban threshold is "triggered" on eight of these ten. // The dry run still has to be visible, so it announces the crossing and // the first doubling, and stops growing the table after that. for (var i = 0; i < 10; i++) { using var probe = await GetAsync(f, "/.env", Scanner); Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); } using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.Alerts.AsNoTracking() .Where(a => a.Kind == "candidate_ban" && a.SourceKey == Scanner) .OrderBy(a => a.Count) .ToListAsync(); Assert.Equal([3, 6], rows.Select(r => r.Count).ToList()); Assert.Contains("not enforced", rows[0].Detail); Assert.Empty(await db.Blocks.Where(b => b.Source == BlockSource.Engine).ToListAsync()); } [Fact] public async Task An_operator_block_answers_301_and_survives_clearing_the_engine_bans() { await using var f = new EdgeFixture(threshold: 2); // First let the engine ban somebody, so there is something to clear. for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); using (var banned = await GetAsync(f, "/probe", Scanner)) Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); var client = f.Client; using (var created = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Bystander, reason = "operator: confirmed scraper", redirectTo = "https://honeypot.example.org/" })) { Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); } using (var blocked = await GetAsync(f, "/anything", Bystander)) { Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); Assert.Equal("https://honeypot.example.org/", blocked.Headers.Location?.ToString()); } using (var cleared = await client.DeleteAsync($"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) { var payload = await JsonAsync(cleared); Assert.True(payload.GetProperty("deleted").GetInt32() >= 1); } using (var stillBlocked = await GetAsync(f, "/anything", Bystander)) Assert.Equal(HttpStatusCode.MovedPermanently, stillBlocked.StatusCode); using (var unblocked = await GetAsync(f, "/anything", Scanner)) Assert.Equal(HttpStatusCode.NotFound, unblocked.StatusCode); } [Fact] public async Task The_allowlist_outranks_an_operator_block() { await using var f = new EdgeFixture(); var client = f.Client; using (var allow = await client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", new { match = "203.0.113.0/24", note = "office" })) Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); using (var block = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Scanner, reason = "oops" })) Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); using var request = await GetAsync(f, "/anything", Scanner); Assert.Equal(HttpStatusCode.NotFound, request.StatusCode); } [Fact] public async Task A_blocked_operator_can_still_reach_the_admin_api() { await using var f = new EdgeFixture(); var client = f.Client; using (var block = await client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Scanner, reason = "self-inflicted" })) Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); using (var publicSide = await GetAsync(f, "/", Scanner)) Assert.Equal(HttpStatusCode.MovedPermanently, publicSide.StatusCode); using var admin = await GetAsync(f, "/admin-api/blocks", Scanner, token: EdgeFixture.AdminToken); Assert.Equal(HttpStatusCode.OK, admin.StatusCode); } [Fact] public async Task The_admin_surface_is_closed_until_a_token_is_configured_and_sent() { await using var f = new EdgeFixture(); using (var anonymous = await f.Client.GetAsync("/admin-api/blocks")) Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); using (var authorized = await f.Client.GetAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}")) Assert.Equal(HttpStatusCode.OK, authorized.StatusCode); await using var noToken = new EdgeFixture(); // A fixture without a token would be an open admin API; the fixture // always sets one, so assert the guard's shape instead: a wrong token // is refused exactly like no token at all. using (var wrong = await noToken.Client.GetAsync("/admin-api/blocks?token=nope")) Assert.Equal(HttpStatusCode.Unauthorized, wrong.StatusCode); } [Fact] public async Task A_ban_lifts_itself_when_it_expires() { await using var f = new EdgeFixture(threshold: 2, banDuration: "00:00:02"); for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); using (var banned = await GetAsync(f, "/probe", Scanner)) Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); await Task.Delay(TimeSpan.FromSeconds(3)); using var afterExpiry = await GetAsync(f, "/probe", Scanner); Assert.Equal(HttpStatusCode.NotFound, afterExpiry.StatusCode); } [Fact] public async Task Switching_the_engine_off_stops_enforcement_and_touches_no_rows() { await using var f = new EdgeFixture(threshold: 2); for (var i = 0; i < 2; i++) (await GetAsync(f, "/probe", Scanner)).Dispose(); using (var banned = await GetAsync(f, "/probe", Scanner)) Assert.Equal(HttpStatusCode.Forbidden, banned.StatusCode); var client = f.Client; using (var off = await client.PutAsJsonAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}", new { mode = "Off" })) { Assert.Equal(HttpStatusCode.OK, off.StatusCode); Assert.Equal("Off", (await JsonAsync(off)).GetProperty("mode").GetString()); } using (var passing = await GetAsync(f, "/probe", Scanner)) Assert.Equal(HttpStatusCode.NotFound, passing.StatusCode); using (var list = await client.GetAsync($"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) Assert.True((await JsonAsync(list)).GetArrayLength() >= 1, "turning the toggle off must not erase the ban record"); } [Fact] public async Task A_denied_country_is_rejected_with_451_and_an_allow_entry_still_gets_through() { await using var f = new EdgeFixture(geo: "DenyList"); var client = f.Client; using (var deny = await client.PutAsync("/admin-api/countries/DE?allowed=false&token=" + EdgeFixture.AdminToken, null)) Assert.Equal(HttpStatusCode.NoContent, deny.StatusCode); using (var rejected = await GetAsync(f, "/anything", Scanner, country: "DE")) { Assert.Equal((HttpStatusCode)451, rejected.StatusCode); var body = await JsonAsync(rejected); Assert.Equal("region_not_supported", body.GetProperty("error").GetString()); Assert.False(string.IsNullOrWhiteSpace(body.GetProperty("note").GetString())); } using (var uncountryd = await GetAsync(f, "/anything", Scanner)) Assert.Equal(HttpStatusCode.NotFound, uncountryd.StatusCode); using (var allow = await client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", new { match = Scanner, note = "customer behind a VPN" })) Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); using var allowed = await GetAsync(f, "/anything", Scanner, country: "DE"); Assert.Equal(HttpStatusCode.NotFound, allowed.StatusCode); } [Fact] public async Task Observations_are_persisted_once_per_source_not_once_per_request() { await using var f = new EdgeFixture(threshold: 1000); for (var i = 0; i < 500; i++) (await GetAsync(f, $"/probe-{i}", Scanner)).Dispose(); await f.FlushObservationsAsync(); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.Observations.AsNoTracking().Where(o => o.SourceKey == Scanner).ToListAsync(); Assert.Single(rows); Assert.Equal(500, rows[0].TotalRefusals); Assert.Equal(500, f.Upstream.RequestCount); } [Fact] public async Task Rotating_ipv6_addresses_inside_one_allocation_are_one_source() { await using var f = new EdgeFixture(threshold: 3); using (var first = await GetAsync(f, "/probe", "2001:db8:1234:5678::11")) Assert.Equal(HttpStatusCode.NotFound, first.StatusCode); using (var second = await GetAsync(f, "/probe", "2001:db8:1234:5678::22")) Assert.Equal(HttpStatusCode.NotFound, second.StatusCode); using (var third = await GetAsync(f, "/probe", "2001:db8:1234:5678:0:0:0:33")) Assert.Equal(HttpStatusCode.NotFound, third.StatusCode); using var fourth = await GetAsync(f, "/probe", "2001:db8:1234:5678::ff"); Assert.Equal(HttpStatusCode.Forbidden, fourth.StatusCode); using var neighbour = await GetAsync(f, "/probe", "2001:db8:1234:5679::11"); Assert.Equal(HttpStatusCode.NotFound, neighbour.StatusCode); } [Fact] public async Task A_failed_snapshot_refresh_keeps_the_previous_picture_of_the_operators_list() { await using var f = new EdgeFixture(); const string Blocked = "198.51.100.200"; using (var block = await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked, reason = "operator list under test" })) Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); using (var before = await GetAsync(f, "/anything", Blocked)) Assert.Equal(HttpStatusCode.MovedPermanently, before.StatusCode); var state = f.Service(); var generatedAt = state.Current.GeneratedAt; // Break what a refresh reads, the way a restart or a lost volume does: // the table the snapshot selects from is simply not there any more. using (var scope = f.Service().CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await db.Database.ExecuteSqlRawAsync("DROP TABLE block_entries"); } await state.InvalidateAsync(); Assert.Single(state.Current.OperatorBlocks); Assert.Equal(generatedAt, state.Current.GeneratedAt); // Fail closed: the point is that a database that is briefly unreachable // does not hand the gate to whoever is probing it. using var stillBlocked = await GetAsync(f, "/anything", Blocked); Assert.Equal(HttpStatusCode.MovedPermanently, stillBlocked.StatusCode); } } public sealed class EdgeObservationBoundaryTests { private const string Operator = "203.0.113.20"; private static async Task GetAsync( EdgeFixture f, string path, string sourceIp, string? token = null) { using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp); if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); return await f.Client.SendAsync(request); } [Fact] public async Task Fumbling_the_admin_api_never_bans_the_operator_who_is_fumbling_it() { await using var f = new EdgeFixture(threshold: 2); // Six refusals on the recovery hatch — a wrong token, a missing // parameter. If these counted, the admin's own syntax error would be // the thing that locks them out. for (var i = 0; i < 6; i++) { using var refused = await GetAsync(f, "/admin-api/blocks", Operator); Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); } using var publicSide = await GetAsync(f, "/anything", Operator); Assert.Equal(HttpStatusCode.NotFound, publicSide.StatusCode); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); 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() { await using var f = new EdgeFixture(threshold: 2); // The observer runs after the response is written, so the next request // from the same source can arrive while the ban is still landing. Two // readers that both see "no ban yet" used to produce a unique-index // loser and a lost evidence row. var inParallel = Enumerable.Range(0, 4) .Select(_ => GetAsync(f, "/probe", Operator)) .ToArray(); foreach (var response in await Task.WhenAll(inParallel)) response.Dispose(); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var bans = await db.Blocks.AsNoTracking().Where(b => b.Source == BlockSource.Engine).ToListAsync(); Assert.Single(bans); Assert.Equal(Operator, bans[0].SourceKey); Assert.False(string.IsNullOrWhiteSpace(bans[0].Reason)); } }