Files
openwaf-agent 17b764ec29 Two test names claimed a readiness verdict their bodies no longer assert
A_flush_that_cannot_write_is_counted_and_readiness_names_the_pillar and
An_alert_that_never_reached_the_table_is_counted_and_readiness_names_it
both end with Assert.Equal(HttpStatusCode.OK, readyz). They were written
when a failed reporting write did make the edge unready, and the boundary
moved — the enforcement path gates, the reporting path is stated in
numbers — but the names stayed where the old rule was. A reader picking
one of these up to check "does a lost alert take an edge out of service?"
would have got the answer from the name and the opposite answer from the
body.

Names only; no assertion changed. Re-measured at this commit: unit
128/128, integration 170/170.
2026-10-02 12:50:16 +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_reported_without_gating_readiness()
{
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_without_taking_the_edge_out_of_service()
{
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);
}
}