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.
164 lines
8.4 KiB
C#
164 lines
8.4 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<OpenWafDbContext>();
|
|
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<HttpStatusCode> 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<EdgeStateStore>().InvalidateAsync();
|
|
await f.Service<EdgeStateStore>().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<EdgeStateStore>().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<EdgeStateStore>().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<EdgeStateStore>().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));
|
|
}
|
|
}
|