Measured on the shipped image with writes to block_entries aborted by SQLite triggers while reads kept working: five refusals from one source at a threshold of 3 answered 404 five times, no ban reached storage or /state, /readyz answered 200, and the log said "BlockStore: concurrent ban on 203.0.113.12; keeping the winner" four times over an inner "SQLite Error 19: 'gate: ban write blocked'". Enforcement reads the snapshot and the snapshot is built from storage, so a ban that cannot be written is a ban that exists nowhere - and the only sentence the log offered said the opposite. BlockStore now asks storage which case it is: re-read the row. A live engine ban for that source means somebody won the unique-index race and nothing is wrong; no row, or a read that cannot run either, means the write never happened. The second case is counted (DurabilityHealth.Bans), logged with its real reason and its consequence, and gates /readyz - the enforcement path is the path that gates. That also moved the boundary drawn last cycle. Observations, alerts and retention are reporting pillars: counted, shown on /state and on the console, and no longer gating readiness. The measurement that forced it: with the gate in place, one lost alert left alertWriteFailures at 3 and /readyz at 503; the triggers were removed and the stand left idle for 120 s, and it answered 503 the whole time with the write path healthy. An alert pillar writes only when an alert happens to be raised, so "not yet proven healthy" had become "unready forever". ObservationWriter now retries every tracked source while it has an outstanding failure: the write-amplification bound protects against load, not against retries, and without this the lost rows waited for each source to be due again a full interval later. Teeth: BanWriteFailureTests (3) - 3 failed / 0 passed before the fix; two WriteFailureVisibilityTests assertions re-drawn for the new boundary. Gates: compose-smoke 63 -> 72 (the ban scene asserts 404x5, no row in storage, 503 naming bans, race lines 0/0 and the honest line present, then the ban landing on a later refusal), smoke.sh counters now include bans, console-check 57 -> 58.
167 lines
7.5 KiB
C#
167 lines
7.5 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<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 UnblockBanWrites(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);
|
|
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<List<string>> 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<int> 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<OpenWafDbContext>();
|
|
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);
|
|
}
|
|
}
|