From 39d08eca5157f729b567fedb53071dd0b271d768 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 07:07:25 +0200 Subject: [PATCH] A pillar that stopped reading its table kept answering, and nothing on the surface said so MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured on the shipped image (openwaf:ci, the head tree), one stand with a real upstream: PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200 404 404 from 203.0.113.79, third request -> 403 (the threshold is in force) 04:44:43 DROP TABLE policy_settings, from outside the process 04:45:2x GET /admin-api/policy -> still "streakThreshold": 2, answered plainly GET /admin-api/state -> "snapshotAgeSeconds":0 — the refresh "succeeded", because the tables it also reads were still there /healthz 200, /readyz 200, and exactly 1 line in the log docker restart -> GET /admin-api/policy -> "streakThreshold": 10, "trustProxyHeaders": false four 404s from 203.0.113.81, fifth -> 404: nothing banned Both pillars — the policy provider and the guard's snapshot store — catch everything their read throws, keep the last value they had, and log one line. Keeping the last good value is the right failure posture: a database restart must not open the gate. Keeping it unmentioned is not: for a minute the operator's page showed a threshold that no longer existed anywhere in storage, readiness said ready, and after a restart the defence silently came back at the default N=10. Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep the last error; /admin-api/state answers snapshotStale (age against the TTL the process refuses to start without), snapshotRefreshFailures, snapshotLastRefreshError, policyReloadFailures and policyLastReadAt; /admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read alongside the policy it is enforcing, the same way a capped listing carries its completeness in headers; /readyz answers 503 while either counter is non-zero, naming the pillar and the age of the snapshot it is running on; and the console's summary line goes warn and says "older than the ttl", "snapshot refresh failing xN", "policy not re-read from storage xN". Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4 failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the point: the numbers did not exist. The refresh test drops country_rules rather than block_entries on purpose — only one of them is what /readyz probes, so before the fix that test saw the refresh failing and readiness still answering 200. Gates: compose-smoke now drops policy_settings from the running stand through a --volumes-from sidecar, waits for the failure to be counted, asserts the counters, the 503 and the header, puts the table back and asserts the recovery (+6 assertions; the counters are consecutive, not cumulative, so recovery is part of the claim). smoke.sh asserts the healthy case with numbers rather than silence (+3). console-check drives the page against that state answer and requires the summary line to be marked and to name both pillars (+3); the state body is served through a route because the guard refreshes the snapshot on every request — a live stand cannot be left to age — while the contract being rendered is the one compose-smoke measures end to end against the shipped image. Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117, smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions / 0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128, 117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in mcr.microsoft.com/playwright:v1.63.0-noble: 53/0. --- dotnet/OpenWaf.Edge/Admin/AdminConsole.cs | 18 +- dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 31 +++- dotnet/OpenWaf.Edge/Program.cs | 25 ++- .../Persistence/EdgePolicyProvider.cs | 29 ++++ .../Persistence/EdgeStateStore.cs | 28 +++ .../PillarFailureVisibilityTests.cs | 163 ++++++++++++++++++ scripts/compose-smoke.sh | 50 ++++++ scripts/console-check.cjs | 48 ++++++ scripts/smoke.sh | 13 ++ 9 files changed, 400 insertions(+), 5 deletions(-) create mode 100644 dotnet/OpenWaf.Tests.Integration/PillarFailureVisibilityTests.cs diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index f4e7b8d..324ff08 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -240,8 +240,22 @@ async function load() { const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed])); el('summary').innerHTML = 'mode ' + esc(state.mode) + ' ' + - 'snapshot ' + esc(state.snapshotAgeSeconds) + 's / ttl ' - + esc(state.snapshotTtlSeconds) + 's ' + + // The age against the bound it is measured against was half the story, and + // the number alone was the other half: a snapshot can sit at ten times the + // TTL, or a pillar can have stopped reading its table altogether and kept + // answering from memory, and either way this pill used to look normal. + // Marked on both counts, because this is the line an operator reads to + // decide whether the edge is obeying the list they are looking at. + 'snapshot ' + + esc(state.snapshotAgeSeconds) + 's / ttl ' + esc(state.snapshotTtlSeconds) + 's' + + (state.snapshotStale ? ' \u00b7 older than the ttl' : '') + + (Number(state.snapshotRefreshFailures) > 0 + ? ' \u00b7 snapshot refresh failing \u00d7' + esc(state.snapshotRefreshFailures) : '') + + (Number(state.policyReloadFailures) > 0 + ? ' \u00b7 policy not re-read from storage \u00d7' + esc(state.policyReloadFailures) : '') + + ' ' + 'tracked ' + esc(state.trackedSources) + ' ' + 'engine bans ' + esc(state.engineBans) + ' ' + 'operator blocks ' + esc(state.operatorBlocks) + ' ' + diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 36b0a41..451e9f1 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -203,7 +203,19 @@ internal static class AdminEndpoints : Results.NotFound(new { error = $"no allow entry with id {id}" }); }); - group.MapGet("/policy", (EdgePolicyProvider policy) => Results.Ok(ToDto(policy.Current))); + // The policy answer carries its provenance in headers, the same way a + // capped listing carries its completeness there. The body is the policy + // this edge is enforcing — that is what the operator asked for and what + // the page renders — but "enforcing" and "storage confirmed this minute" + // are different claims, and a deleted policy_settings table used to make + // the first look like the second for the whole life of the process. + group.MapGet("/policy", (EdgePolicyProvider policy, HttpContext ctx) => + { + ctx.Response.Headers["X-Policy-Reload-Failures"] = policy.ReloadFailures.ToString(); + ctx.Response.Headers["X-Policy-Last-Read"] = + policy.LastReloadSuccessAt?.ToString("O") ?? "never"; + return Results.Ok(ToDto(policy.Current)); + }); group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, CancellationToken ct) => { @@ -391,7 +403,7 @@ internal static class AdminEndpoints supportsCity = geo.Info?.SupportsCity ?? false })); - group.MapGet("/state", (EdgeStateStore state, StreakTracker tracker) => + group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker) => { var now = DateTimeOffset.UtcNow; var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now)); @@ -416,6 +428,21 @@ internal static class AdminEndpoints // own writes — so they are counted separately rather than hidden. allowEntries = allowLive, allowEntriesExpired = allowExpired, + // Which of these numbers the storage actually confirmed. Both pillars + // keep their last good value when a read fails — the right failure + // posture — and both used to do it invisibly: one log line, a + // snapshot age that still looked fresh because the refresh "succeeded" + // at reading the tables that were still there, and /readyz saying + // ready. Measured on the shipped image with policy_settings dropped: + // /policy kept answering the operator's streakThreshold: 2, /state + // said snapshotAgeSeconds 0, /healthz and /readyz said 200, and after + // a restart the threshold was 10 again with nothing ever having said + // the number on screen was a copy. + snapshotStale = state.IsStale, + snapshotRefreshFailures = state.RefreshFailures, + snapshotLastRefreshError = state.LastRefreshError, + policyReloadFailures = policyProvider.ReloadFailures, + policyLastReadAt = policyProvider.LastReloadSuccessAt, mode = state.Current.Policy.Mode.ToString() }); }); diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 1fdb3f4..4710aa1 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -93,7 +93,7 @@ app.MapGet("/healthz", (IGeoIpLookup geo, EdgeStateStore state) => Results.Ok(ne geoStale = geo.Info is not null && geo.Info.IsStale(TimeSpan.FromDays(90)) })); -app.MapGet("/readyz", async (OpenWafDbContext db, CancellationToken ct) => +app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, CancellationToken ct) => { try { @@ -104,6 +104,29 @@ app.MapGet("/readyz", async (OpenWafDbContext db, CancellationToken ct) => // touch is actually readable, because this is the surface an operator // or an orchestrator consults to decide whether the edge is healthy. await db.Blocks.AsNoTracking().AnyAsync(ct); + + // Reading the block table is necessary and not sufficient. Each pillar + // keeps its last good value when its own read fails, so an edge can be + // enforcing a policy and a block list that its storage stopped + // confirming minutes ago — measured on the shipped image with + // policy_settings dropped, /readyz answered 200 for the whole time, and + // after a restart the operator's streakThreshold of 2 was 10 again. + // "Ready" is the answer an orchestrator acts on; it has to mean every + // pillar read its table. + if (policy.ReloadFailures > 0) + return Results.Problem( + detail: $"the policy has not been re-read from storage: {policy.ReloadFailures} consecutive " + + $"failed reads (last error: {policy.LastReloadError}); the edge is enforcing the last " + + $"value it read, confirmed at {policy.LastReloadSuccessAt?.ToString("O") ?? "never"}", + statusCode: StatusCodes.Status503ServiceUnavailable); + if (state.RefreshFailures > 0) + return Results.Problem( + detail: $"the guard's snapshot has not refreshed: {state.RefreshFailures} consecutive failed " + + $"refreshes (last error: {state.LastRefreshError}); the edge is enforcing the snapshot " + + $"from {state.Current.GeneratedAt:O}, which is " + + $"{(DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds:0.#} s old against " + + $"a ttl of {state.RefreshTtl.TotalSeconds:0.#} s", + statusCode: StatusCodes.Status503ServiceUnavailable); return Results.Ok(new { status = "ready" }); } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs index daba7ef..e017bbe 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs @@ -32,6 +32,30 @@ public sealed class EdgePolicyProvider public EdgePolicy Current => _current; + /// + /// Consecutive reload failures — zero means the last read succeeded. Kept + /// because "keeping the current policy" is the right thing to do and the + /// wrong thing to leave unmentioned: measured on the shipped image, a + /// deleted policy_settings table produced exactly one log line, while + /// GET /admin-api/policy went on answering the operator's own + /// streakThreshold: 2 for as long as the process lived, /admin-api/state + /// reported a snapshot age of 0 (the refresh "succeeded"), and /readyz said + /// ready. After a restart that policy was gone — the threshold silently + /// returned to 10 and trustProxyHeaders to false — and nothing on any + /// surface had ever said the value being shown was an in-memory copy. + /// + public int ReloadFailures => Volatile.Read(ref _reloadFailures); + + /// The last reload error, or null when the last reload succeeded. + public string? LastReloadError => Volatile.Read(ref _lastReloadError); + + /// When storage last confirmed this policy. Null means never. + public DateTimeOffset? LastReloadSuccessAt => _lastReloadSuccessAt; + + private int _reloadFailures; + private string? _lastReloadError; + private DateTimeOffset? _lastReloadSuccessAt; + public async Task ReloadAsync(CancellationToken ct = default) { try @@ -40,9 +64,14 @@ public sealed class EdgePolicyProvider var db = scope.ServiceProvider.GetRequiredService(); var rows = await db.PolicySettings.AsNoTracking().ToListAsync(ct); _current = ApplyOverrides(_current, rows); + Interlocked.Exchange(ref _reloadFailures, 0); + Volatile.Write(ref _lastReloadError, null); + _lastReloadSuccessAt = DateTimeOffset.UtcNow; } catch (Exception ex) { + Interlocked.Increment(ref _reloadFailures); + Volatile.Write(ref _lastReloadError, ex.Message); _log.LogWarning(ex, "EdgePolicyProvider: reload failed; keeping the current policy."); } return _current; diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index 622b575..eaada64 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -47,6 +47,24 @@ public sealed class EdgeStateStore public TimeSpan RefreshTtl { get; set; } = TimeSpan.FromSeconds(30); + /// + /// Older than the TTL. The TTL is documented as the bound on how stale the + /// block list may be, and the process refuses to start with an unparseable + /// one — "rather than run with a block list of unknown staleness". Until now + /// nothing checked that bound after startup, so a snapshot could sit at ten + /// times the bound and every surface still looked normal. + /// + public bool IsStale => DateTimeOffset.UtcNow - _snapshot.GeneratedAt > RefreshTtl; + + /// Consecutive refresh failures; zero means the last one worked. + public int RefreshFailures => Volatile.Read(ref _refreshFailures); + + /// The last refresh error, or null when the last refresh succeeded. + public string? LastRefreshError => Volatile.Read(ref _lastRefreshError); + + private int _refreshFailures; + private string? _lastRefreshError; + /// /// Reads the configured TTL. The TTL is the bound on how stale the block /// list may be, which makes it a security setting: an unparseable or @@ -113,6 +131,9 @@ public sealed class EdgeStateStore var countryMap = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var c in countries) countryMap[c.Code] = c; + Interlocked.Exchange(ref _refreshFailures, 0); + Volatile.Write(ref _lastRefreshError, null); + _snapshot = new EdgeSnapshot { GeneratedAt = DateTimeOffset.UtcNow, @@ -125,6 +146,13 @@ public sealed class EdgeStateStore } catch (Exception ex) { + // Fail closed for the decision, and say so where an operator looks. + // Keeping the previous snapshot is right; keeping it silently is not: + // the snapshot is the operator's list, and a refresh that has been + // failing for an hour means a ban written since then is not being + // enforced — while /readyz, /state and the page all looked normal. + Interlocked.Increment(ref _refreshFailures); + Volatile.Write(ref _lastRefreshError, ex.Message); _log.LogWarning(ex, "EdgeStateStore: refresh failed; keeping the previous snapshot."); } finally diff --git a/dotnet/OpenWaf.Tests.Integration/PillarFailureVisibilityTests.cs b/dotnet/OpenWaf.Tests.Integration/PillarFailureVisibilityTests.cs new file mode 100644 index 0000000..e0a4ab9 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/PillarFailureVisibilityTests.cs @@ -0,0 +1,163 @@ +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Every pillar that reads its table on a background refresh catches everything +/// it throws and keeps the last value it had. That is the right failure posture +/// — a database restart must not open the gate — but until now it was also +/// invisible: the only trace was one log line, and the operator's surface kept +/// answering with the confidence of a fresh read. +/// +/// Measured on the shipped image (openwaf:ci, the head tree), one stand with a +/// real upstream: +/// PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} → 200 +/// two 404s from 203.0.113.79, third request → 403 (the threshold is in force) +/// 04:44:43 DROP TABLE policy_settings (from outside the process) +/// 04:45:2x GET /admin-api/policy → still "streakThreshold": 2, answered plainly +/// GET /admin-api/state → "snapshotAgeSeconds":0 — the refresh "succeeds" +/// /healthz 200, /readyz 200, and exactly 1 line in the log +/// docker restart → GET /admin-api/policy → "streakThreshold": 10, +/// "trustProxyHeaders": false +/// four 404s from 203.0.113.81, fifth → 404: nothing banned, because the +/// threshold the operator set no longer exists and the one now in force is 10. +/// +/// The policy the page showed for a minute was an in-memory copy of a row that +/// was no longer there, and nothing on the page, in /state or in /readyz said so. +/// +public sealed class PillarFailureVisibilityTests +{ + // The DDL the schema is created from, quoted so a test that breaks a pillar + // can put it back and assert the recovery, not just the failure. + private const string CountryRulesDdl = + """CREATE TABLE "country_rules" ("Code" TEXT NOT NULL CONSTRAINT "PK_country_rules" PRIMARY KEY, "Name" TEXT NULL, "IsAllowed" INTEGER NOT NULL, "UpdatedAt" INTEGER NOT NULL)"""; + private const string PolicySettingsDdl = + """CREATE TABLE "policy_settings" ("Key" TEXT NOT NULL CONSTRAINT "PK_policy_settings" PRIMARY KEY, "Value" TEXT NOT NULL, "UpdatedAt" INTEGER NOT NULL)"""; + + 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<(HttpStatusCode Status, JsonElement Body, string Text)> 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); + var text = await response.Content.ReadAsStringAsync(); + return (response.StatusCode, JsonDocument.Parse(text).RootElement, text); + } + + private static async Task<(HttpStatusCode Status, string Text, string? Failures, string? LastRead)> PolicyAsync(EdgeFixture f) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/policy"); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + var text = await response.Content.ReadAsStringAsync(); + string? Header(string name) + => response.Headers.TryGetValues(name, out var a) ? string.Join(",", a) + : response.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b) + : null; + return (response.StatusCode, text, Header("X-Policy-Reload-Failures"), Header("X-Policy-Last-Read")); + } + + private static async Task ReadyzAsync(EdgeFixture f) + { + using var response = await f.Client.GetAsync("/readyz"); + return response.StatusCode; + } + + [Fact] + public async Task A_refresh_that_cannot_read_its_table_is_counted_and_readiness_names_it() + { + await using var f = new EdgeFixture(); + Assert.Equal(HttpStatusCode.OK, await ReadyzAsync(f)); + + // country_rules and block_entries are read by the same refresh, and only + // one of them is what /readyz probes. So this is the case where the + // refresh has been failing for a while and readiness still says ready. + await RunSql(f, "DROP TABLE country_rules"); + await f.Service().InvalidateAsync(); + await f.Service().InvalidateAsync(); + + var state = await StateAsync(f); + Assert.True(state.Body.GetProperty("snapshotRefreshFailures").GetInt32() >= 1, + $"a refresh that threw must be counted, not logged and forgotten: {state.Text}"); + Assert.Contains("country_rules", state.Body.GetProperty("snapshotLastRefreshError").GetString()); + + var ready = await ReadyzAsync(f); + Assert.Equal(HttpStatusCode.ServiceUnavailable, ready); + + // Recovery is part of the claim: the counter is consecutive, not total. + await RunSql(f, CountryRulesDdl); + await f.Service().InvalidateAsync(); + var recovered = await StateAsync(f); + Assert.Equal(0, recovered.Body.GetProperty("snapshotRefreshFailures").GetInt32()); + Assert.Equal(HttpStatusCode.OK, await ReadyzAsync(f)); + } + + [Fact] + public async Task A_policy_that_cannot_be_re_read_is_counted_and_the_policy_answer_says_so() + { + await using var f = new EdgeFixture(); + await RunSql(f, "DROP TABLE policy_settings"); + await f.Service().InvalidateAsync(); + + var state = await StateAsync(f); + Assert.True(state.Body.GetProperty("policyReloadFailures").GetInt32() >= 1, + $"the policy pillar swallows its own failure: {state.Text}"); + + // The answer an operator reads is the one that has to carry the caveat. + var policy = await PolicyAsync(f); + Assert.Equal(HttpStatusCode.OK, policy.Status); + Assert.NotNull(policy.Failures); + Assert.True(int.Parse(policy.Failures!) >= 1, $"X-Policy-Reload-Failures was {policy.Failures}"); + Assert.NotNull(policy.LastRead); + + await RunSql(f, PolicySettingsDdl); + await f.Service().InvalidateAsync(); + Assert.Equal(0, (await StateAsync(f)).Body.GetProperty("policyReloadFailures").GetInt32()); + Assert.Equal("0", (await PolicyAsync(f)).Failures); + } + + [Fact] + public async Task The_snapshot_age_is_measured_against_the_ttl_it_is_supposed_to_respect() + { + // A TTL of one second with no traffic is the honest way to ask "is this + // snapshot older than the bound the process refuses to start without" — + // the refresh is driven off the request path, so nothing refreshes it. + await using var f = new EdgeFixture(refreshTtlSeconds: 1); + var first = await StateAsync(f); + Assert.False(first.Body.GetProperty("snapshotStale").GetBoolean()); + Assert.Equal(0, first.Body.GetProperty("snapshotRefreshFailures").GetInt32()); + + await Task.Delay(2500); + var later = await StateAsync(f); + Assert.True(later.Body.GetProperty("snapshotStale").GetBoolean(), + $"age {later.Body.GetProperty("snapshotAgeSeconds")} over a ttl of {later.Body.GetProperty("snapshotTtlSeconds")}: {later.Text}"); + // Stale and failing are different claims and have to stay different. + Assert.Equal(0, later.Body.GetProperty("snapshotRefreshFailures").GetInt32()); + } + + [Fact] + public async Task A_healthy_edge_says_so_with_numbers_and_not_only_with_silence() + { + await using var f = new EdgeFixture(); + var state = await StateAsync(f); + Assert.Equal(HttpStatusCode.OK, state.Status); + Assert.False(state.Body.GetProperty("snapshotStale").GetBoolean()); + Assert.Equal(0, state.Body.GetProperty("snapshotRefreshFailures").GetInt32()); + Assert.Equal(0, state.Body.GetProperty("policyReloadFailures").GetInt32()); + Assert.True(state.Body.TryGetProperty("snapshotLastRefreshError", out var err) + && err.ValueKind == JsonValueKind.Null, + "no error to report has to be said as null, not by leaving the field out"); + Assert.Equal("0", (await PolicyAsync(f)).Failures); + Assert.Equal(HttpStatusCode.OK, await ReadyzAsync(f)); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 948f544..b748e8c 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -281,6 +281,56 @@ else FAIL=$((FAIL+1)); printf ' FAIL %-54s no country resolved for %s\n' 'geo pillar' "$GEO_IP" fi +echo '- a pillar that stops reading its table says so' +# Measured on the shipped image before this was fixed: with policy_settings +# dropped out from under a running edge, GET /admin-api/policy kept answering the +# operator's own streakThreshold, /admin-api/state reported snapshotAgeSeconds 0 +# (the refresh "succeeded" at reading the tables that were still there), /healthz +# and /readyz answered 200, and the whole system produced exactly one log line. +# After a restart the policy was simply gone — a streakThreshold of 2 came back +# as 10 and trustProxyHeaders as false, and four refusals from a fresh source no +# longer matured a ban. Keeping the last good value is the right failure posture; +# keeping it unmentioned is not. +EDGE_CID=$(docker compose ps -q edge) +sidecar() { docker run --rm -i --volumes-from "$EDGE_CID" python:3.12-slim python -; } +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +c.execute("DROP TABLE policy_settings") +PYSQL +# The refresh runs off the request path on the TTL, so the failure has to be +# allowed to happen at least once before it can be counted. +for _ in $(seq 1 15); do + code "$EDGE/no-such-page" >/dev/null + POLICY_FAILS=$(admin "$EDGE/admin-api/state" | jval policyReloadFailures) + [ "${POLICY_FAILS:-0}" != "0" ] && break + sleep 3 +done +printf ' info policy reload failures counted after the table went away: %s\n' "${POLICY_FAILS:-0}" +check 'the state counts a policy pillar that cannot read its table' 'yes' \ + "$([ "${POLICY_FAILS:-0}" != "0" ] && echo yes || echo no)" +check 'readiness stops saying ready while it cannot' '503' "$(code "$EDGE/readyz")" +check 'the policy answer carries its own provenance' 'yes' \ + "$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/policy" | grep -qi '^x-policy-reload-failures: [1-9]' && echo yes || echo no)" +# The two pillars are counted separately on purpose: here the snapshot is still + # refreshing fine and only the policy read is broken, and a single blended + # "storage is unhappy" flag would lose exactly that. +check 'the snapshot pillar is still reported healthy' '0' \ + "$(admin "$EDGE/admin-api/state" | jval snapshotRefreshFailures)" +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +c.execute('CREATE TABLE IF NOT EXISTS policy_settings ("Key" TEXT NOT NULL CONSTRAINT "PK_policy_settings" PRIMARY KEY, "Value" TEXT NOT NULL, "UpdatedAt" INTEGER NOT NULL)') +PYSQL +for _ in $(seq 1 15); do + code "$EDGE/no-such-page" >/dev/null + [ "$(code "$EDGE/readyz")" = "200" ] && break + sleep 3 +done +check 'putting the table back clears the counters and readiness returns' '200' "$(code "$EDGE/readyz")" +check 'and the policy answer says so again' 'X-Policy-Reload-Failures: 0' \ + "$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/policy" | grep -i '^x-policy-reload-failures:' | tr -d '\r')" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 2d542ac..0ac0507 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -448,6 +448,54 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); check('the button that clears automatic bans says what the edge answered', /engine bans cleared: \d+/.test(clearedStatus), clearedStatus); + // The other honesty fix this round lives in the summary line: a pillar whose + // table stopped being readable keeps its last good value (the right failure + // posture) and used to do it invisibly — one log line, a snapshot age that + // still looked fresh, /readyz saying ready. scripts/compose-smoke.sh proves the + // API half of that against the shipped image, with the table really dropped. + // What is proven here is the page half: given that answer, the summary line has + // to say it. The state body is served through a route rather than produced by + // breaking the stand, because the guard refreshes the snapshot on every request + // — a live stand cannot be left to age — and the contract being rendered is the + // one the other gate already measured end to end. + { + const broken = await browser.newPage(); + const brokenProblems = []; + broken.on('pageerror', (e) => brokenProblems.push('pageerror: ' + e.message)); + await broken.route('**/admin-api/state', (route) => route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + snapshotAgeSeconds: 412.7, snapshotTtlSeconds: 30, snapshotStale: true, + snapshotRefreshFailures: 14, + snapshotLastRefreshError: 'no such table: country_rules', + policyReloadFailures: 14, policyLastReadAt: '2026-10-02T04:44:43.0000000+00:00', + trackedSources: 0, operatorBlocks: 2, engineBans: 0, + allowEntries: 0, allowEntriesExpired: 0, mode: 'Enforce' + }) + })); + await broken.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' }); + await broken.fill('#token', TOKEN); + await broken.click('#save'); + await broken.waitForFunction( + () => /older than the ttl/.test([...document.querySelectorAll('#summary .pill')] + .map((p) => p.textContent).join(' | ')), + null, { timeout: 15000 }).catch(() => {}); + const brokenPill = await broken.evaluate(() => { + const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /snapshot/.test(p.textContent)); + return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null; + }); + check('a snapshot older than its TTL is marked on the page, not only left in the log', + !!brokenPill && /older than the ttl/.test(brokenPill.text) && /warn/.test(brokenPill.cls), + JSON.stringify(brokenPill)); + check('and the page names the pillars that stopped reading their tables', + !!brokenPill && /snapshot refresh failing/.test(brokenPill.text) + && /policy not re-read from storage/.test(brokenPill.text), + JSON.stringify(brokenPill)); + check('the page threw no javascript on that answer', brokenProblems.length === 0, brokenProblems.join(' | ')); + await broken.close(); + } + // A phone in dark mode is the case an operator actually reaches the console // from — the address that got them blocked is the one they are typing about. // Both halves of this used to be broken and measured: the page overflowed a diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 084bb33..d515677 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -129,6 +129,19 @@ echo '- admin surface' check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" check 'the policy is readable' Enforce \ "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')" +# Each pillar keeps its last good value when its own read fails, which is the +# right failure posture and was, until recently, an unmentioned one. The healthy +# case has to be said with numbers too — silence and "0" look the same from +# outside, and only one of them is a claim. +STATE_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")" +check 'the state counts failed pillar reads, and there are none' '0 0' \ + "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["snapshotRefreshFailures"], d["policyReloadFailures"])')" +check 'the state says the snapshot is inside its ttl' False \ + "$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["snapshotStale"])')" +check 'the policy answer carries its provenance header' 0 \ + "$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | tr -d '\r' \ + | sed -n 's/^[Xx]-[Pp]olicy-[Rr]eload-[Ff]ailures: //p')" check 'switching the engine off is accepted' Off \ "$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' --data-binary "$POLICY_OFF_JSON" \ "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')"