using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
///
/// The engine's ban write is the one durable write on the enforcement path, and
/// the shipped image treated its failure as a benign concurrency race.
///
/// Measured on the shipped image (openwaf:ci, head 68bec5b), one stand with a
/// real upstream, writes to block_entries aborted by SQLite triggers while reads
/// kept working:
/// threshold 3, five refusals from 203.0.113.12 → 404, 404, 404, 404, 404
/// GET /admin-api/blocks?source=engine → the one pre-existing ban, nothing new
/// GET /admin-api/state → no field about ban writes at all
/// /readyz → 200 {"status":"ready"}
/// the log, four times: "BlockStore: concurrent ban on 203.0.113.12; keeping
/// the winner." over "SQLite Error 19: 'gate: ban write blocked'"
/// restart → still 404: the source was never banned anywhere.
///
/// Nothing was in force, and the only sentence in the log said the opposite —
/// that another edge had won a race and its ban stood. Enforcement reads the
/// snapshot, and the snapshot is built from storage, so a ban that cannot be
/// written is a ban that does not exist: not on this edge, not on any other.
///
public sealed class BanWriteFailureTests
{
private static async Task RunSql(EdgeFixture f, string sql)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
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 UnblockBanWrites(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var names = await db.Database
.SqlQueryRaw(""""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 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);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
}
private static async Task<(HttpStatusCode Status, string Text)> ReadyzAsync(EdgeFixture f)
{
using var response = await f.Client.GetAsync("/readyz");
return (response.StatusCode, await response.Content.ReadAsStringAsync());
}
private static async Task> EngineBanKeys(EdgeFixture f)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/blocks?source=engine");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement
.EnumerateArray().Select(r => r.GetProperty("sourceKey").GetString() ?? "").ToList();
}
private static async Task StatusFor(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);
return (int)response.StatusCode;
}
[Fact]
public async Task A_ban_that_cannot_be_written_is_counted_as_a_storage_failure_and_readiness_names_it()
{
await using var f = new EdgeFixture(threshold: 3);
Assert.Equal(HttpStatusCode.OK, (await ReadyzAsync(f)).Status);
await BlockBanWrites(f);
for (var i = 0; i < 5; i++) Assert.Equal(404, await StatusFor(f, $"/miss-{i}", "203.0.113.12"));
var state = await StateAsync(f);
Assert.True(state.GetProperty("banWriteFailures").GetInt32() >= 1,
$"/state did not count a ban write that failed: {state}");
Assert.True(state.GetProperty("bansNotWritten").GetInt64() >= 1, $"/state: {state}");
Assert.Contains("ban write blocked", state.GetProperty("banLastWriteError").GetString());
// The consequence, asserted rather than implied: nothing is in force.
Assert.DoesNotContain("203.0.113.12", await EngineBanKeys(f));
var (status, text) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.ServiceUnavailable, status);
Assert.Contains("engine bans are not being persisted", text);
Assert.Contains("not enforcing them", text);
}
[Fact]
public async Task A_real_cross_process_race_is_still_the_winner_s_row_and_is_not_counted_as_a_failure()
{
await using var f = new EdgeFixture(threshold: 3);
// Somebody else already wrote the ban. This is the case the unique index
// exists for, and the one the old code confused with a storage failure.
var until = DateTimeOffset.UtcNow.AddHours(1);
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService();
db.Blocks.Add(new BlockEntry
{
SourceKey = "203.0.113.13",
Source = BlockSource.Engine,
CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = until,
Reason = "written by the other edge"
});
await db.SaveChangesAsync();
}
await BlockBanWrites(f);
for (var i = 0; i < 4; i++) await StatusFor(f, $"/race-{i}", "203.0.113.13");
var state = await StateAsync(f);
Assert.Equal(0, state.GetProperty("banWriteFailures").GetInt32());
Assert.Equal(HttpStatusCode.OK, (await ReadyzAsync(f)).Status);
}
[Fact]
public async Task The_ban_lands_on_a_later_refusal_and_readiness_clears_with_it()
{
await using var f = new EdgeFixture(threshold: 3);
await BlockBanWrites(f);
for (var i = 0; i < 4; i++) await StatusFor(f, $"/late-{i}", "203.0.113.14");
Assert.Equal(HttpStatusCode.ServiceUnavailable, (await ReadyzAsync(f)).Status);
await UnblockBanWrites(f);
// The streak is still mature in memory, so the next refusal retries the
// write — the behaviour the code comment has always claimed and that was
// never asserted until now.
for (var i = 0; i < 2; i++) await StatusFor(f, $"/retry-{i}", "203.0.113.14");
Assert.Contains("203.0.113.14", await EngineBanKeys(f));
var state = await StateAsync(f);
Assert.Equal(0, state.GetProperty("banWriteFailures").GetInt32());
Assert.True(state.GetProperty("bansNotWritten").GetInt64() >= 1,
"bans that were never written stay counted even after the path heals");
var (status, _) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
}
}