Files
openwaf/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs
T
Pavlo Ratushnyi f516b3fc85 Show the streak that is standing, and make a clean answer end it
Two things, found in that order, and the second one is the reason the first
was worth building.

The console could say how many sources the edge was tracking but not which one
was three refusals from a ban. GET /admin-api/streaks now answers that with the
current consecutive count — not the maximum the durable observation row keeps,
which reports a source that has been clean for an hour as if it were still at
the gate. The payload names its own scope ("this-process") and carries the
threshold, the window and the map cap, because the number is meaningless
without them; the console says so above the table. This is the same fact the
two-edge measurement in research/2026-10-01-multi-instance/ cost real time to
establish, now visible to whoever is operating the box.

Reading that endpoint is what exposed the bug. The README promises "a 2xx/3xx
resets the streak to zero" and lists it as the mitigation for banning honest
traffic off a shared egress. StreakTracker honours that. The observer never
told it: ResponseObservationMiddleware returned early for every neutral
response, so on the wire a visitor alternating a 404 with a normal page view
accumulated refusals across every honest request and still matured a ban. The
documented mitigation existed in the domain object and not in the pipeline.

Fix: the observer calls StreakTracker.ResetIfTracked for a 2xx/3xx. No evidence
is built and no MMDB read is paid for a clean answer; an untracked source costs
one dictionary lookup. Measured in the image, 600 proxied clean answers, before
and after: p50 1.45 -> 1.50 ms, p95 2.98 -> 2.96 ms. Nothing to see.

Gates on this commit: build 0 warnings; unit 54/54; integration 27/27;
scripts/smoke.sh 19/19; scripts/compose-smoke.sh 27/27. The new tests have
teeth, checked by removing the fix: with ResetIfTracked commented out, exactly
two tests fail - the wire-level one and the streaks listing - and all 27 pass
when it is put back. On the wire in the container, threshold 3: probe, clean,
probe, clean, probe leaves a streak of 1; three consecutive probes take it to
4; one clean answer empties the list.
2026-10-01 13:19:56 +02:00

401 lines
18 KiB
C#

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<HttpResponseMessage> 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<JsonElement> 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<OpenWafDbContext>();
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<OpenWafDbContext>();
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 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<OpenWafDbContext>();
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<EdgeStateStore>();
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<IServiceScopeFactory>().CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
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<HttpResponseMessage> 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<OpenWafDbContext>();
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<OpenWafDbContext>();
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<OpenWafDbContext>();
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));
}
}