OPEN-34, measured on the shipped image before this change. With writes to block_entries aborted, five refusals produced counted write failures and /readyz 503. The triggers were then REMOVED — write path healthy, zero triggers left — and no further request was sent from that source: t+30 s /readyz 503 /state: banWriteFailures 3, bansNotWritten 3 t+60 s /readyz 503 unchanged t+90 s /readyz 503 unchanged t+120 s /readyz 503 unchanged The ban pillar clears only on a successful ban write, and the only thing that produced one was the source crossing the threshold again. Readiness — the signal an orchestrator uses to keep an edge in rotation — was therefore coupled to attack traffic: the quieter the site, the longer a repaired edge sat out of service, enforcing everything except one ban nobody had written. The fix is on the write side, not on the gate. A ban the engine decided and could not write is kept as a PendingBan and re-attempted by a hosted loop on the same 15 s cadence the other writers use; the sentence still runs from the moment the ban was decided, so a retry that lands late cannot quietly lengthen it, and a pending ban whose sentence expired before it could be written is counted (bansNeverEnforced) and reported rather than rewritten as a fresh, longer ban. /state gained bansPendingRetry and bansNeverEnforced, because without the first a healed storage failure is indistinguishable from a quiet site. Teeth: PendingBanRetryTests (3) — the retry landing with no further request, the hosted loop doing it on its own (nobody calls it in that test), and an expired pending ban reported rather than written late. Compose gate gained a 5-assertion scene against the shipped image: the failed ban is queued, readiness returns after the repair with no traffic from that source, the ban reaches storage, the queue empties, and the source that was never banned during the break answers 403 afterwards. Gates at this commit — macOS host: unit 128/128, integration 141/141, smoke 28/0, compose 86/0, console 58/0, 0 containers left behind. Linux rehearsal, all three stages: PASS — source (128/128, 141/141, 28/0), compose 86/0 with enforcement lag 13 ms, console 58/0, 0 containers left behind.
170 lines
7.8 KiB
C#
170 lines
7.8 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// A ban the engine decided and could not write used to be repaired only by the
|
|
/// attacker coming back. Measured on the shipped image (2026-10-02): writes to
|
|
/// block_entries aborted by SQLite triggers, five refusals from one source at a
|
|
/// threshold of 3, then the triggers REMOVED — write path healthy, zero
|
|
/// triggers — and no further traffic sent:
|
|
///
|
|
/// t+30 s GET /readyz → 503 /state: banWriteFailures 3, bansNotWritten 3
|
|
/// t+60 s GET /readyz → 503 (unchanged)
|
|
/// t+90 s GET /readyz → 503 (unchanged)
|
|
/// t+120 s GET /readyz → 503 (unchanged)
|
|
///
|
|
/// The ban pillar's counter clears only on a successful ban write, and the only
|
|
/// thing that produced one was a fresh threshold crossing. So readiness — the
|
|
/// signal an orchestrator uses to keep an edge in rotation — was coupled to
|
|
/// attack traffic: the quieter the site, the longer a healed edge stayed out of
|
|
/// service, enforcing everything except one ban nobody had written.
|
|
/// </summary>
|
|
public sealed class PendingBanRetryTests
|
|
{
|
|
private const string Scanner = "203.0.113.241";
|
|
|
|
private static async Task RunSql(EdgeFixture f, string sql)
|
|
{
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
await db.Database.ExecuteSqlRawAsync(sql);
|
|
}
|
|
|
|
private static async Task BlockBanWrites(EdgeFixture f)
|
|
{
|
|
foreach (var op in new[] { "INSERT", "UPDATE" })
|
|
await RunSql(f, $"""CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END""");
|
|
}
|
|
|
|
private static async Task UnblockWrites(EdgeFixture f)
|
|
{
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var names = await db.Database
|
|
.SqlQueryRaw<string>(""""SELECT name FROM sqlite_master WHERE type='trigger'"""")
|
|
.ToListAsync();
|
|
foreach (var name in names) await RunSql(f, $"""DROP TRIGGER IF EXISTS "{name}" """);
|
|
}
|
|
|
|
private static async Task<JsonElement> StateAsync(EdgeFixture f)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
|
|
}
|
|
|
|
private static async Task<HttpStatusCode> ReadyAsync(EdgeFixture f)
|
|
=> (await f.Client.GetAsync("/readyz")).StatusCode;
|
|
|
|
private static async Task<string> BlocksRawAsync(EdgeFixture f)
|
|
{
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var rows = await db.Blocks.AsNoTracking().ToListAsync();
|
|
return string.Join(" | ", rows.Select(b =>
|
|
$"{b.SourceKey}/{b.Source} created={b.CreatedAt:HH:mm:ss} expires={b.ExpiresAt:HH:mm:ss} now={DateTimeOffset.UtcNow:HH:mm:ss}"));
|
|
}
|
|
|
|
private static async Task<int> EngineBansAsync(EdgeFixture f)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/blocks?source=engine&limit=1000");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetArrayLength();
|
|
}
|
|
|
|
private static async Task RefuseAsync(EdgeFixture f, int times)
|
|
{
|
|
for (var i = 1; i <= times; i++) await f.SendAsync(f.Client, $"/probe-{i}", Scanner);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_ban_that_failed_to_write_lands_without_the_source_offending_again()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
await BlockBanWrites(f);
|
|
await RefuseAsync(f, 4);
|
|
|
|
Assert.Equal(HttpStatusCode.ServiceUnavailable, await ReadyAsync(f));
|
|
var broken = await StateAsync(f);
|
|
Assert.True(broken.GetProperty("banWriteFailures").GetInt32() >= 1, $"/state: {broken}");
|
|
Assert.True(broken.GetProperty("bansPendingRetry").GetInt32() >= 1,
|
|
$"the failed ban was not queued for retry: {broken}");
|
|
Assert.Equal(0, await EngineBansAsync(f));
|
|
|
|
// The storage failure is repaired. Nothing else happens: no further
|
|
// request from this source, no new threshold crossing.
|
|
await UnblockWrites(f);
|
|
|
|
await f.Service<BlockStore>().RetryPendingBansAsync();
|
|
|
|
Assert.Equal(1, await EngineBansAsync(f));
|
|
Assert.Equal(HttpStatusCode.OK, await ReadyAsync(f));
|
|
var healed = await StateAsync(f);
|
|
Assert.Equal(0, healed.GetProperty("banWriteFailures").GetInt32());
|
|
Assert.Equal(0, healed.GetProperty("bansPendingRetry").GetInt32());
|
|
|
|
// And the ban is actually in force on the wire, which is the whole point
|
|
// of writing it: this request is the proof, not the trigger.
|
|
// The request has to carry the same source address the ban was written
|
|
// for: the fixture trusts proxy headers, and a request without one is a
|
|
// different source and answers 404 honestly.
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/probe-1");
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", Scanner);
|
|
using var blocked = await f.Client.SendAsync(request);
|
|
var rows = await BlocksRawAsync(f);
|
|
Assert.True(blocked.StatusCode == HttpStatusCode.Forbidden,
|
|
$"expected the retried ban to be in force on the wire; got {(int)blocked.StatusCode}; "
|
|
+ $"raw block rows: {rows}; state: {await StateAsync(f)}");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_retry_loop_runs_on_its_own_so_readiness_does_not_wait_for_traffic()
|
|
{
|
|
await using var f = new EdgeFixture(threshold: 3);
|
|
await BlockBanWrites(f);
|
|
await RefuseAsync(f, 4);
|
|
Assert.Equal(HttpStatusCode.ServiceUnavailable, await ReadyAsync(f));
|
|
await UnblockWrites(f);
|
|
|
|
// Nobody calls RetryPendingBansAsync here: the assertion is that the
|
|
// hosted loop does, on the same cadence the other writers use.
|
|
var status = HttpStatusCode.ServiceUnavailable;
|
|
for (var attempt = 0; attempt < 12 && status != HttpStatusCode.OK; attempt++)
|
|
{
|
|
await Task.Delay(2000);
|
|
status = await ReadyAsync(f);
|
|
}
|
|
Assert.Equal(HttpStatusCode.OK, status);
|
|
Assert.Equal(1, await EngineBansAsync(f));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_pending_ban_whose_sentence_expired_is_reported_rather_than_written_late()
|
|
{
|
|
// One second of ban duration, so the sentence really does expire while the
|
|
// write is pending. Writing it after that would hand the operator a ban
|
|
// that starts later than the one the engine decided — a different, longer
|
|
// sentence wearing the old decision's clothes.
|
|
await using var f = new EdgeFixture(threshold: 3, banDuration: "00:00:01");
|
|
await BlockBanWrites(f);
|
|
await RefuseAsync(f, 4);
|
|
await UnblockWrites(f);
|
|
await Task.Delay(2000);
|
|
|
|
await f.Service<BlockStore>().RetryPendingBansAsync();
|
|
|
|
var state = await StateAsync(f);
|
|
Assert.Equal(0, state.GetProperty("bansPendingRetry").GetInt32());
|
|
Assert.True(state.GetProperty("bansNeverEnforced").GetInt64() >= 1,
|
|
$"an expired pending ban was dropped without being counted: {state}");
|
|
Assert.Equal(0, await EngineBansAsync(f));
|
|
}
|
|
}
|