diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 73f2e7f..37e5a5b 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -245,6 +245,9 @@ async function load() { // table stayed at 1 row through a six-request 5xx storm, and /readyz said // "ready". Each number is escaped on its own, so the join stays raw. const writeProblems = []; + if (Number(state.banWriteFailures) > 0) + writeProblems.push('bans not written \u00d7' + esc(state.banWriteFailures) + + ' (' + esc(state.bansNotWritten) + ' not enforced)'); if (Number(state.observationWriteFailures) > 0) writeProblems.push('observations not persisted \u00d7' + esc(state.observationWriteFailures) + ' (' + esc(state.observationsLost) + ' rows lost)'); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index faca379..04284c1 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -454,6 +454,12 @@ internal static class AdminEndpoints // "flush failed, 4 entries dropped" plus two "could not persist". // EntriesLost is cumulative on purpose: a dropped row is not // recovered by a later successful write. + // The enforcement-path write, counted separately because it gates + // readiness, unlike the reporting pillars below it. + banWriteFailures = durability.Get(DurabilityHealth.Bans).Failures, + bansNotWritten = durability.Get(DurabilityHealth.Bans).EntriesLost, + banLastWriteError = durability.Get(DurabilityHealth.Bans).LastError, + banLastWriteAt = durability.Get(DurabilityHealth.Bans).LastSuccessAt, observationWriteFailures = durability.Get(DurabilityHealth.Observations).Failures, observationsLost = durability.Get(DurabilityHealth.Observations).EntriesLost, observationLastWriteError = durability.Get(DurabilityHealth.Observations).LastError, diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 5c7c358..3b75e84 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -139,23 +139,36 @@ app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePoli // time. A failed read keeps a stale value; a failed write loses a row // that no later request can bring back, and the operator's listings // quietly stop being the set the edge actually saw. - var observations = durability.Get(DurabilityHealth.Observations); - if (observations.Failures > 0) + // The engine's ban writes are the one write on the enforcement path, and + // they gate. A ban that never reaches storage is enforced by nobody: the + // guard decides from the snapshot, and the snapshot is built from + // storage. Measured on the shipped image with writes to block_entries + // aborted: five refusals from one source at a threshold of 3 answered + // 404 five times, the ban appeared neither in storage nor in /state, + // /readyz answered 200, and the log called the failure a concurrency + // race four times over. + var bans = durability.Get(DurabilityHealth.Bans); + if (bans.Failures > 0) return Results.Problem( - detail: $"the streak history is not being persisted: {observations.Failures} consecutive failed " - + $"writes, {observations.EntriesLost} source rows lost (last error: " - + $"{observations.LastError}); the observation listings are missing sources this edge " - + $"saw, and the last write that succeeded was " - + $"{observations.LastSuccessAt?.ToString("O") ?? "never"}", - statusCode: StatusCodes.Status503ServiceUnavailable); - var alerts = durability.Get(DurabilityHealth.Alerts); - if (alerts.Failures > 0) - return Results.Problem( - detail: $"alerts are not being persisted: {alerts.Failures} consecutive failed writes, " - + $"{alerts.EntriesLost} alerts lost (last error: {alerts.LastError}); the alerting " - + $"pillar is not reaching the operator, so a failing upstream is invisible", + detail: $"engine bans are not being persisted: {bans.Failures} consecutive failed ban writes, " + + $"{bans.EntriesLost} bans never written (last error: {bans.LastError}); this edge is " + + $"not enforcing them and no other edge sharing the database can see them", statusCode: StatusCodes.Status503ServiceUnavailable); + // The reporting pillars — observations, alerts, retention — are counted + // and reported on /admin-api/state and on the console, and deliberately + // do NOT gate readiness. This revises the first version of this code, and + // the measurement that forced the revision: with writes to edge_alerts + // aborted, one lost alert left alertWriteFailures at 3 and /readyz at + // 503; the triggers were then 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", and an orchestrator + // would have pulled a working edge out of rotation over a reporting + // side-channel. Losing observations and alerts is an operator problem the + // console now states in numbers; it is not a reason to stop serving + // traffic. The counters stay on /admin-api/state either way. + // Retention is counted and reported on /admin-api/state, and is // deliberately NOT a readiness failure. A prune that cannot run keeps // aggregates past the age the README promises they age out at — a diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs index f066854..321e90d 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -25,17 +25,20 @@ public sealed class BlockStore /// send the next request while the previous one's ban is still landing. private readonly SemaphoreSlim _banGate = new(1, 1); private readonly EdgePolicyProvider _policy; + private readonly DurabilityHealth _health; private readonly ILogger _log; public BlockStore( IServiceScopeFactory scopeFactory, EdgeStateStore state, EdgePolicyProvider policy, + DurabilityHealth health, ILogger log) { _scopeFactory = scopeFactory; _state = state; _policy = policy; + _health = health; _log = log; } @@ -97,22 +100,53 @@ public sealed class BlockStore existing.LastRegion = streak.LastRegion; await db.SaveChangesAsync(ct); + // Clears the counter only when a ban actually reached storage, so + // readiness comes back on evidence rather than on the passage of + // time. + _health.RecordSuccess(DurabilityHealth.Bans, 1); await _state.InvalidateAsync(ct); return existing; } catch (DbUpdateException ex) { - // Still possible across processes — two edges sharing one database. - // The winner's row is the one that matters; the loser's evidence is - // already in the observation stream. - _log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", streak.SourceKey); + // Two opposite failures arrive here, and the shipped image called + // both of them the benign one. The benign one is the cross-process + // race the unique index exists to settle: the winner's row is in + // storage, the ban is in force, this edge has nothing to do. The + // other one is storage failing, and it was measured being reported + // as a race — with writes to block_entries aborted by a SQLite + // trigger, five refusals from one source at a threshold of 3 + // answered 404 five times, no ban ever reached storage (engine bans + // stayed at 1), /readyz answered 200, and the log said "concurrent + // ban on 203.0.113.12; keeping the winner" four times while the + // inner exception was SQLite Error 19: 'gate: ban write blocked'. + // + // Storage itself is the discriminator: re-read the row. A live row + // for this source and provenance means somebody won the race; no + // row — or a read that cannot run either — means the write never + // happened and the ban is not in force anywhere. + if (await HasLiveEngineBanAsync(streak.SourceKey, now, ct)) + { + _log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", streak.SourceKey); + return null; + } + + _health.RecordFailure(DurabilityHealth.Bans, ex, 1); + _log.LogWarning(ex, + "BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement " + + "reads the snapshot, and the snapshot is built from storage — so no edge is. The next refusal " + + "from this source retries the write.", streak.SourceKey); return null; } catch (Exception ex) { // A ban that could not be written must not take the request down. // The streak is still in memory, so the next refusal retries. - _log.LogWarning(ex, "BlockStore: could not persist a ban for {Key}.", streak.SourceKey); + _health.RecordFailure(DurabilityHealth.Bans, ex, 1); + _log.LogWarning(ex, + "BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement " + + "reads the snapshot, and the snapshot is built from storage — so no edge is. The next refusal " + + "from this source retries the write.", streak.SourceKey); return null; } finally @@ -121,6 +155,29 @@ public sealed class BlockStore } } + /// + /// Is there a live engine ban for this source in storage right now? Used to + /// tell a lost unique-index race from a storage failure. A read that itself + /// fails answers "no", which routes the caller to the storage-failure path — + /// the conservative direction, because claiming a race won when nothing was + /// written is exactly the lie this method exists to stop. + /// + private async Task HasLiveEngineBanAsync(string sourceKey, DateTimeOffset now, CancellationToken ct) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Blocks.AsNoTracking() + .AnyAsync(b => b.SourceKey == sourceKey && b.Source == BlockSource.Engine && b.ExpiresAt > now, ct); + } + catch (Exception ex) + { + _log.LogDebug(ex, "BlockStore: the ban re-read used to settle a race could not run either."); + return false; + } + } + /// What a write to the block list ended as. The caller has to be /// able to tell "your input was wrong" from "the storage failed", because /// those two arrive at the operator as different answers and different diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs b/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs index 2fe1de1..77c9f2f 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/DurabilityHealth.cs @@ -37,6 +37,15 @@ public sealed class DurabilityHealth public const string Alerts = "alerts"; public const string Retention = "retention"; + /// + /// The engine's ban writes. Counted separately from the reporting pillars + /// because it is the only write on the enforcement path: a ban that never + /// reaches storage is not enforced by this edge either (enforcement reads + /// the snapshot), and it is invisible to every other edge sharing the + /// database until the write is retried. + /// + public const string Bans = "bans"; + /// /// One pillar's write state. is consecutive /// failures since the last success; is diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs index 2c0037b..ca0b518 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs @@ -56,10 +56,20 @@ public sealed class ObservationWriter : BackgroundService var snapshots = _tracker.Snapshot(now, policy); if (snapshots.Count == 0) return 0; + // The write-amplification bound protects against load, not against + // retries. While this pillar has an outstanding failure, every flush + // re-attempts every tracked source: the rows the failed flush was + // carrying would otherwise be lost until each source happened to be due + // again a full interval later, and the counter would stop being a live + // signal. The flush rate is unchanged (one per 15 s) and the source count + // is already capped by the LRU bound on the map, so retrying cannot turn + // into write amplification. + var retrying = _health.Get(DurabilityHealth.Observations).Failures > 0; var due = new List(); foreach (var s in snapshots) { - if (_lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval) + if (!retrying + && _lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval) continue; due.Add(s); _lastWrittenAt[s.SourceKey] = now; diff --git a/dotnet/OpenWaf.Tests.Integration/BanWriteFailureTests.cs b/dotnet/OpenWaf.Tests.Integration/BanWriteFailureTests.cs new file mode 100644 index 0000000..515f28e --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/BanWriteFailureTests.cs @@ -0,0 +1,166 @@ +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); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs b/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs index c93bfc1..b4873a2 100644 --- a/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs @@ -115,10 +115,12 @@ public sealed class WriteFailureVisibilityTests $"/state did not say how many rows were lost: {state}"); Assert.Contains("gate: durable write blocked", state.GetProperty("observationLastWriteError").GetString()); - var (status, text) = await ReadyzAsync(f); - Assert.Equal(HttpStatusCode.ServiceUnavailable, status); - Assert.Contains("streak history is not being persisted", text); - Assert.Contains("rows lost", text); + // 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] @@ -167,9 +169,14 @@ public sealed class WriteFailureVisibilityTests $"/state did not count the lost alert: {state}"); Assert.True(state.GetProperty("alertsLost").GetInt64() >= 1, $"/state: {state}"); - var (status, text) = await ReadyzAsync(f); - Assert.Equal(HttpStatusCode.ServiceUnavailable, status); - Assert.Contains("alerts are not being persisted", text); + // 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. @@ -181,23 +188,24 @@ public sealed class WriteFailureVisibilityTests } [Fact] - public async Task A_write_that_succeeds_clears_the_counters_and_readiness_comes_back() + 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)); - Assert.Equal(HttpStatusCode.ServiceUnavailable, (await ReadyzAsync(f)).Status); + // 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); - // A fresh source, not the same one: the writer stamps its - // last-written-at before it attempts the write, so the row it lost is - // not retried until that source is due again a write interval later - // (ObservationWriteInterval, 30 s by default). That is the write - // amplification bound doing its job, and it is why EntriesLost is - // cumulative rather than a gauge. - await f.SendAsync(f.Client, "/healed", "203.0.113.32"); - Assert.True(await Flush(f) >= 1, "the recovery flush wrote nothing"); + // 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()); diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index f1dc441..07671a6 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -393,9 +393,15 @@ TOTAL_AFTER=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/obse | grep -i '^x-total-count:' | tr -d '\r' | awk '{print $2}') printf ' info X-Total-Count across the break: %s -> %s (three new sources saw, none stored)\n' "$TOTAL_BEFORE" "$TOTAL_AFTER" check 'the listing still answers with the count it had before the break' "$TOTAL_BEFORE" "$TOTAL_AFTER" -check 'readiness names the write pillar that is failing' '503' "$(code "$EDGE/readyz")" -check 'the failure it names is the real reason, not an EF wrapper' 'yes' \ +check 'the failure it reports is the real reason, not an EF wrapper' 'yes' \ "$(admin "$EDGE/admin-api/state" | jval observationLastWriteError | grep -qi 'durable write blocked' && echo yes || echo no)" +# Reporting-path failures are stated, not gated. The first version of this gate +# asserted 503 here, and the boundary moved after measuring what that cost: one +# lost alert left /readyz at 503 for two idle minutes with the write path already +# healthy, because an alert pillar only writes when an alert happens to be +# raised. An orchestrator would have pulled a working edge out of rotation over a +# reporting side-channel. The enforcement-path failure below is the one that gates. +check 'a reporting-path write failure does not make the edge unready' '200' "$(code "$EDGE/readyz")" sidecar <<'PYSQL' import sqlite3 c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) @@ -412,22 +418,70 @@ for _ in $(seq 1 12); do done check 'the observation pillar heals on its next successful write' '0' \ "$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)" -# Readiness does not come back yet, and that is the semantics being asserted: a -# counter clears only on a successful write of its own pillar, so the alert -# pillar — which has had nothing to write since the break — keeps the edge -# unready. A gauge that reset on any write would have said "ready" here while -# the alerting pillar had still not produced a single row. -check 'readiness still refuses until the alert pillar writes again' '503' "$(code "$EDGE/readyz")" +# The alert pillar has still written nothing since the break, so its counter +# stays exactly where it was: a counter clears on evidence, not on the clock. It +# is reported for as long as it is unproven, and it does not gate. +check 'an unproven alert pillar stays reported without gating readiness' '200' "$(code "$EDGE/readyz")" # Twelve 502s from a fresh source: the alerting threshold this run set is 3, # and the escalation alerts at 3 and 6, so this is enough to raise one for sure. for i in $(seq 1 12); do code -H "$(xff 203.0.113.230)" "$EDGE/boom" >/dev/null; done -for _ in $(seq 1 12); do +check 'the alert counter clears once an alert is actually written' '0' \ + "$(admin "$EDGE/admin-api/state" | jval alertWriteFailures)" + +echo '- a ban that cannot be written is not enforced, and says so' +# The one durable write on the enforcement path. Measured on the shipped image +# with writes to block_entries aborted and reads left working: five refusals from +# one source at a threshold of 3 answered 404 five times, no ban reached storage +# or /state, /readyz said ready, and the log said "concurrent ban on +# 203.0.113.12; keeping the winner" four times over an inner "SQLite Error 19: +# 'gate: ban write blocked'". Nothing was in force, and the only sentence about +# it in the log said the opposite. +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +for op in ("INSERT", "UPDATE"): + c.execute(f'CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" ' + "BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END") +print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")]) +PYSQL +BAN_SRC=203.0.113.241 +# Counted before and after, not in total: an earlier scene in this same run may +# legitimately have produced a race line, and a total would blame this scene for +# it. +RACES_BEFORE=$(docker compose logs edge 2>/dev/null | grep -c 'concurrent ban on') +BAN_CODES="" +for i in $(seq 1 5); do BAN_CODES="$BAN_CODES $(code -H "$(xff "$BAN_SRC")" "$EDGE/unbanned-$i")"; done +printf ' info answers from a scanner at threshold 3 while ban writes are blocked:%s\n' "$BAN_CODES" +check 'the scanner is never banned while the ban write fails' '404 404 404 404 404' "${BAN_CODES# }" +check 'and no engine ban for it reached storage' 'yes' \ + "$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0==0)?0:1}' && echo yes || echo no)" +check 'the state counts the ban write that failed' 'yes' \ + "$(admin "$EDGE/admin-api/state" | jval banWriteFailures | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)" +check 'and says how many bans were never written' 'yes' \ + "$(admin "$EDGE/admin-api/state" | jval bansNotWritten | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)" +check 'readiness names the ban writes, because this is the enforcement path' '503' "$(code "$EDGE/readyz")" +check 'the reason it quotes is the storage error, not a concurrency race' 'yes' \ + "$(admin "$EDGE/admin-api/state" | jval banLastWriteError | grep -qi 'ban write blocked' && echo yes || echo no)" +RACES_AFTER=$(docker compose logs edge 2>/dev/null | grep -c 'concurrent ban on') +printf ' info lines calling a ban write a race, before/after this scene: %s/%s\n' "$RACES_BEFORE" "$RACES_AFTER" +check 'the log no longer calls a storage failure a race' "$RACES_BEFORE" "$RACES_AFTER" +check 'and the log says what actually happened' 'yes' \ + "$(docker compose logs edge 2>/dev/null | grep -qi 'could not persist a ban for' && echo yes || echo no)" +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +for r in list(c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")): + c.execute(f'DROP TRIGGER "{r[0]}"') +print("triggers after cleanup:", c.execute("SELECT count(*) FROM sqlite_master WHERE type='trigger'").fetchone()[0]) +PYSQL +for i in $(seq 1 3); do code -H "$(xff "$BAN_SRC")" "$EDGE/retried-$i" >/dev/null; done +for _ in $(seq 1 10); do [ "$(code "$EDGE/readyz")" = "200" ] && break sleep 3 done -check 'and readiness returns once every failing pillar has written again' '200' "$(code "$EDGE/readyz")" -check 'the rows the edge sees now land again' 'yes' \ - "$([ "$(admin "$EDGE/admin-api/state" | jval alertWriteFailures)" = "0" ] && echo yes || echo no)" +check 'the ban lands on a later refusal once the write path heals' 'yes' \ + "$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)" +check 'and readiness returns on that write, not on a timer' '200' "$(code "$EDGE/readyz")" echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index e5fcb57..ae9e85f 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -516,6 +516,9 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); snapshotAgeSeconds: 0.4, snapshotTtlSeconds: 30, snapshotStale: false, snapshotRefreshFailures: 0, snapshotLastRefreshError: null, policyReloadFailures: 0, policyLastReadAt: '2026-10-02T05:12:07.0000000+00:00', + banWriteFailures: 2, bansNotWritten: 2, + banLastWriteError: 'gate: ban write blocked', + banLastWriteAt: '2026-10-02T05:11:40.0000000+00:00', observationWriteFailures: 3, observationsLost: 4, observationLastWriteError: 'gate: durable write blocked', observationLastWriteAt: '2026-10-02T05:11:52.0000000+00:00', @@ -547,6 +550,12 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); && /4 rows lost/.test(writePill.text) && /alerts not persisted/.test(writePill.text) && /warn/.test(writePill.cls), JSON.stringify(writePill)); + // The enforcement-path failure gets named separately, because it is the one + // that also makes the edge unready: a ban that never reached storage is not + // enforced by this edge either. + check('and the page names bans that were never written, apart from the reporting losses', + !!writePill && /bans not written ×2 \(2 not enforced\)/.test(writePill.text), + JSON.stringify(writePill)); check('and it is shown as a write failure, not folded into the snapshot pill', !!snapshotPill && !/warn/.test(snapshotPill.cls) && !/not persisted/.test(snapshotPill.text) && /retention not running/.test(writePill.text || ''), diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 82dab50..26f716a 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -147,10 +147,10 @@ check 'the policy answer carries its provenance header' 0 \ # counters exist even in a clean run, where they read 0 0 0. A surface that # answers "0" for a field it never publishes is indistinguishable from one that # publishes it and means it, which is why the keys are asserted too. -check 'the state counts writes it could not persist, and there are none' '0 0 0' \ - "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["observationWriteFailures"], d["alertWriteFailures"], d["retentionPruneFailures"])')" +check 'the state counts writes it could not persist, and there are none' '0 0 0 0' \ + "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["banWriteFailures"], d["observationWriteFailures"], d["alertWriteFailures"], d["retentionPruneFailures"])')" check 'and it carries what was lost and when a write last landed' True \ - "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("observationsLost","alertsLost","observationLastWriteAt","alertLastWriteAt","retentionLastPruneAt")))')" + "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("bansNotWritten","banLastWriteAt","observationsLost","alertsLost","observationLastWriteAt","alertLastWriteAt","retentionLastPruneAt")))')" check 'readiness is ready while the write path is healthy' 200 \ "$(code "http://127.0.0.1:$EDGE_PORT/readyz")" check 'switching the engine off is accepted' Off \