Files
openwaf/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs
T
Pavlo Ratushnyi 3f24c5d31c A ban that could not be written was logged as a concurrency race, and nothing was in force
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.
2026-10-02 09:24:43 +02:00

267 lines
13 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// The write side of the edge catches everything it throws, logs one line and
/// keeps the process alive. That posture is right — a database restart must not
/// take the gate down — but the write side paid for it with the same blindness
/// the read side had before the pillar-health work: a failed write loses a row
/// permanently, and no surface said anything.
///
/// Measured on the shipped image (openwaf:ci, the head tree), one stand with a
/// real upstream, breaking only the write path with SQLite triggers so the
/// reads stayed honest:
/// before the break GET /admin-api/observations → X-Total-Count: 4
/// GET /admin-api/alerts → 1 row
/// CREATE TRIGGER … BEFORE INSERT/UPDATE ON source_observations, edge_alerts
/// BEGIN SELECT RAISE(ABORT,'gate'); END
/// three new sources refused, six more 502s from one address
/// GET /admin-api/observations → 200, X-Total-Count: 4
/// GET /admin-api/alerts → 200, 1 row
/// /healthz 200, /readyz 200 {"status":"ready"}
/// /admin-api/state → no write-side field at all
/// log: "ObservationWriter: flush failed, 4 entries
/// dropped." + two "AlertWriter: could not persist…"
/// DROP TRIGGER X-Total-Count: 9
///
/// The listings were not stale. They were complete about a set that had quietly
/// stopped being the set the edge saw, and the alert table — the whole point of
/// the alerting pillar — showed nothing about a 5xx storm that was happening.
/// </summary>
public sealed class WriteFailureVisibilityTests
{
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);
}
/// <summary>
/// Aborts writes without touching reads, which is the point: a dropped
/// table would break the listing too and the listing would then be honest
/// about being broken. A trigger leaves the listing answering 200.
/// </summary>
private static async Task BlockWrites(EdgeFixture f, string table, string operation = "INSERT|UPDATE")
{
foreach (var op in operation.Split('|'))
await RunSql(f, $"""CREATE TRIGGER "gate_{table}_{op}" BEFORE {op} ON "{table}" BEGIN SELECT RAISE(ABORT, 'gate: durable 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}" """);
}
// The fixture's own flush helper discards the count, and the count is the
// assertion here: 0 means the flush carried nothing into storage.
private static Task<int> Flush(EdgeFixture f) =>
f.Service<ObservationWriter>().FlushAsync(CancellationToken.None);
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<(int Total, bool Truncated)> ObservationsTotalAsync(EdgeFixture f)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/observations?limit=1");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
string Header(string name)
=> response.Headers.TryGetValues(name, out var a) ? string.Join(",", a) : "";
return (int.Parse(Header("X-Total-Count")), Header("X-Truncated") == "true");
}
[Fact]
public async Task A_flush_that_cannot_write_is_counted_and_readiness_names_the_pillar()
{
await using var f = new EdgeFixture();
Assert.Equal(HttpStatusCode.OK, (await ReadyzAsync(f)).Status);
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/nope-{i}", "203.0.113.11");
await BlockWrites(f, "source_observations");
Assert.Equal(0, await Flush(f));
var state = await StateAsync(f);
Assert.True(state.GetProperty("observationWriteFailures").GetInt32() >= 1,
$"/state did not count the failed flush: {state}");
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 1,
$"/state did not say how many rows were lost: {state}");
Assert.Contains("gate: durable write blocked", state.GetProperty("observationLastWriteError").GetString());
// Reported, not gating. The first version of this code made a failed
// observation write an unready edge; that was the wrong boundary, and the
// measurement that moved it is in BanWriteFailureTests and in Program.cs:
// the enforcement path gates, the reporting path is stated in numbers.
var (status, _) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
}
[Fact]
public async Task The_listing_keeps_answering_its_old_count_while_the_edge_is_still_seeing_sources()
{
await using var f = new EdgeFixture();
// One honest write first, so the number in the header is a real one.
await f.SendAsync(f.Client, "/one", "203.0.113.12");
await f.FlushObservationsAsync();
var (before, _) = await ObservationsTotalAsync(f);
Assert.Equal(1, before);
await BlockWrites(f, "source_observations");
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/two-{i}", "203.0.113.13");
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/three-{i}", "203.0.113.14");
Assert.Equal(0, await Flush(f));
var (after, truncated) = await ObservationsTotalAsync(f);
// This is the lie, asserted directly: the answer is a 200 with a total
// that no longer describes what this edge saw, and it says nothing about
// the difference.
Assert.Equal(before, after);
Assert.False(truncated);
// The counters are what makes the 200 interpretable at all.
var state = await StateAsync(f);
Assert.True(state.GetProperty("observationWriteFailures").GetInt32() >= 1);
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 2,
$"two sources were dropped and /state said {state.GetProperty("observationsLost")}");
}
[Fact]
public async Task An_alert_that_never_reached_the_table_is_counted_and_readiness_names_it()
{
await using var f = new EdgeFixture();
await BlockWrites(f, "edge_alerts");
// Raised through the writer's own API, which is what the guard calls
// when a server-error streak crosses the threshold.
await f.Service<AlertWriter>().RaiseAsync(
"server_error_streak", "203.0.113.21", 3, StatusCodes.Status502BadGateway, "/boom", "gate test");
var state = await StateAsync(f);
Assert.True(state.GetProperty("alertWriteFailures").GetInt32() >= 1,
$"/state did not count the lost alert: {state}");
Assert.True(state.GetProperty("alertsLost").GetInt64() >= 1, $"/state: {state}");
// A lost alert is an operator-facing hole in the reporting path, not a
// reason to stop serving traffic: an alert pillar writes only when an
// alert happens to be raised, so gating on it turns one transient failure
// into an edge that is unready until the next alert. Measured: with the
// gate in place, one lost alert left /readyz at 503 for two idle minutes
// after the write path was already healthy again.
var (status, _) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
// And the alert listing itself still looks fine — that is the whole
// reason the counter has to exist.
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/alerts?limit=500");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(0, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetArrayLength());
}
[Fact]
public async Task A_write_that_succeeds_clears_the_counters_that_report_the_loss()
{
await using var f = new EdgeFixture();
await f.SendAsync(f.Client, "/heal", "203.0.113.31");
await BlockWrites(f, "source_observations");
Assert.Equal(0, await Flush(f));
// The reporting pillar is counted and does not gate; the gate belongs to
// the enforcement path (BanWriteFailureTests).
Assert.Equal(HttpStatusCode.OK, (await ReadyzAsync(f)).Status);
Assert.True((await StateAsync(f)).GetProperty("observationWriteFailures").GetInt32() >= 1);
await UnblockWrites(f);
// No new source: while the pillar has an outstanding failure every flush
// re-attempts every tracked source, so the row the failed flush was
// carrying lands on the next one. The write-amplification bound protects
// against load, not against retries — the flush rate is unchanged and the
// source count is already capped by the LRU bound on the map.
Assert.True(await Flush(f) >= 1, "the recovery flush did not retry the source it had lost");
var state = await StateAsync(f);
Assert.Equal(0, state.GetProperty("observationWriteFailures").GetInt32());
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 1,
"entries lost is cumulative: a later success does not bring the row back");
Assert.Equal(JsonValueKind.Null, state.GetProperty("observationLastWriteError").ValueKind);
var (status, text) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
Assert.Contains("ready", text);
var (total, _) = await ObservationsTotalAsync(f);
Assert.Equal(1, total);
}
[Fact]
public async Task A_prune_that_cannot_run_is_counted_and_deliberately_does_not_make_the_edge_unready()
{
await using var f = new EdgeFixture();
// A row the prune genuinely wants to delete. Without one, the prune
// deletes zero rows, the DELETE trigger never fires and the test passes
// for the wrong reason — which is exactly the shape of assertion this
// project keeps having to rewrite.
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var aged = DateTimeOffset.UtcNow.AddDays(-400);
db.Observations.Add(new SourceObservation
{
SourceKey = "203.0.113.98",
FirstSeenAt = aged,
LastSeenAt = aged,
MaxConsecutiveRefusals = 1,
TotalRefusals = 1,
TotalServerErrorStreak = 0
});
await db.SaveChangesAsync();
}
// Retention deletes; blocking DELETE breaks the prune and nothing else.
await BlockWrites(f, "source_observations", "DELETE");
await Assert.ThrowsAnyAsync<Exception>(
async () => await f.Service<RetentionWorker>().PruneAsync(CancellationToken.None));
var state = await StateAsync(f);
Assert.True(state.GetProperty("retentionPruneFailures").GetInt32() >= 1, $"/state: {state}");
Assert.Contains("gate: durable write blocked", state.GetProperty("retentionLastError").GetString());
// The other pillars are untouched, so the boundary is testable rather
// than asserted in a comment: a retention failure is reported, not
// acted on by pulling the edge out of rotation.
Assert.Equal(0, state.GetProperty("observationWriteFailures").GetInt32());
Assert.Equal(0, state.GetProperty("alertWriteFailures").GetInt32());
var (status, _) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
}
}