Files
openwaf/dotnet/OpenWaf.Tests.Integration/EdgeBlockingTests.cs
T
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00

341 lines
15 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);
}
}
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 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));
}
}