Files
Pavlo Ratushnyi 992a7b795b
ci / lint the workflow and the shell (push) Successful in 10s
ci / build, test, smoke (push) Successful in 2m11s
ci / the operator page in a real browser (push) Successful in 2m16s
ci / build the image and smoke it (push) Successful in 3m33s
the console job stops owing the runner an artifact it cannot accept, and the snapshot-age test gets a bound start-up cannot blow
actions/upload-artifact@v4 is not a step this runner can run. Run 2370
(head 36d9338) drove the page through every assertion — console check: all
assertions passed — and the job went red one step later on
`@actions/artifact v2.0.0+ … not currently supported on GHES`. The step now
names each screenshot with its size and sha256 in the log, which is what the
gate's own output already describes assertion by assertion.

PillarFailureVisibilityTests.The_snapshot_age_is_measured_against_the_ttl_it_is_supposed_to_respect
asked whether a snapshot was older than a one-second TTL, and the age at the
first read already includes however long the fixture took to come up. On a
loaded machine that bound is blown before the assertion runs (OPEN-76). The TTL
is now 10 with a 13 s wait: the bound is one the fixture controls, and the
assertion still says stale and failing are different claims.

README: the blast-radius preview had no section — /admin-api/impact was the only
admin surface with none — and the Shape counts had drifted (unit 256 -> 378,
integration 245 -> 405, smoke 52 -> 256, console 90 -> 164), measured on this
tree: unit 378/378, integration 405/405, smoke 256/0, compose 348/0, console
164/0.
2026-10-05 22:08:28 +02:00

173 lines
9.1 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 short TTL 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 while nobody is
// asking. The TTL is 10 rather than 1 because the first assertion is about
// the age at the moment of the first read, and that age already includes
// however long the fixture took to come up: measured on a loaded machine
// (OPEN-76), a one-second bound was already blown by WebApplicationFactory
// start-up before the assertion ran, and the test went red on a snapshot
// that was honestly stale. Ten seconds is a bound start-up cannot blow and
// still short enough that the wait below is a wait and not a fixture.
await using var f = new EdgeFixture(refreshTtlSeconds: 10);
var first = await StateAsync(f);
Assert.False(first.Body.GetProperty("snapshotStale").GetBoolean());
Assert.Equal(0, first.Body.GetProperty("snapshotRefreshFailures").GetInt32());
// Past the TTL, and by enough margin that scheduling cannot land this read
// inside the window it is supposed to have left.
await Task.Delay(13_000);
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));
}
}