Files
openwaf/dotnet/OpenWaf.Edge/Program.cs
T
Pavlo Ratushnyi 39d08eca51 A pillar that stopped reading its table kept answering, and nothing on the surface said so
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.
2026-10-02 07:07:25 +02:00

155 lines
7.3 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OpenWaf.Domain.Engine;
using OpenWaf.Edge.Admin;
using OpenWaf.Edge.Configuration;
using OpenWaf.Edge.Health;
using OpenWaf.Edge.Pipeline;
using OpenWaf.Edge.Startup;
using OpenWaf.Infrastructure.Geo;
using OpenWaf.Infrastructure.Persistence;
// Distroless images have no shell, no curl and no wget, so the container
// HEALTHCHECK re-executes this binary in --healthcheck mode and reads its exit
// code. Handled before any host is built: it must work when the host is the
// thing that is broken.
if (args.Length > 0 && args[0] == "--healthcheck")
{
return await HealthcheckRunner.RunAsync(args);
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<EdgePolicyOptions>(builder.Configuration.GetSection("OpenWaf:Policy"));
builder.Services.AddSingleton(sp => sp.GetRequiredService<IOptions<EdgePolicyOptions>>().Value.ToPolicy());
var provider = builder.Configuration["Database:Provider"] ?? "sqlite";
var connectionString = builder.Configuration.GetConnectionString("OpenWaf")
?? "Data Source=openwaf.db";
builder.Services.AddDbContext<OpenWafDbContext>(options =>
{
if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString);
else options.UseSqlite(connectionString);
});
// One streak map per process. A multi-instance deployment therefore counts
// each instance's traffic separately — recorded as an evolution trigger in the
// OPEN-2 architecture decision, not hidden.
builder.Services.AddSingleton<StreakTracker>();
builder.Services.AddSingleton<EdgePolicyProvider>();
builder.Services.AddSingleton(sp => new EdgeStateStore(
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<EdgePolicyProvider>(),
sp.GetRequiredService<ILogger<EdgeStateStore>>())
{
// The TTL is how long this process may keep enforcing a block list that is
// already out of date. On one instance that is invisible; behind a load
// balancer it is the propagation delay measured in
// research/2026-10-01-multi-instance/, which is why it is configuration and
// not a constant.
RefreshTtl = EdgeStateStore.ParseRefreshTtl(builder.Configuration["OpenWaf:State:RefreshTtlSeconds"])
});
builder.Services.AddSingleton<BlockStore>();
builder.Services.AddSingleton<AlertWriter>();
// An empty string in appsettings.json is not the same as "unset" to the
// configuration system, and it silently defeats the environment fallback —
// which is exactly how a geo database ends up missing in production.
var geoPath = builder.Configuration["GeoIp:DatabasePath"];
if (string.IsNullOrWhiteSpace(geoPath)) geoPath = Environment.GetEnvironmentVariable("GEOIP_MAXMIND_DB_PATH");
builder.Services.AddSingleton<IGeoIpLookup>(sp => new MaxMindGeoIpLookup(
geoPath, sp.GetRequiredService<ILogger<MaxMindGeoIpLookup>>()));
builder.Services.AddHostedService<EdgeStateWarmer>();
// Registered as themselves as well as hosted services: the admin surface and
// the tests need to reach the writer to force a flush, and AddHostedService
// alone does not make the implementation resolvable.
builder.Services.AddSingleton<ObservationWriter>();
builder.Services.AddSingleton<RetentionWorker>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<ObservationWriter>());
builder.Services.AddHostedService(sp => sp.GetRequiredService<RetentionWorker>());
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
builder.Services.AddOpenApi();
var app = builder.Build();
// Order is the design. The guard decides and may short-circuit; the observer
// sits inside it, so it only ever sees responses the upstream actually
// produced — a refusal the edge generated itself must never feed the streak
// that produced the ban.
app.UseMiddleware<EdgeGuardMiddleware>();
app.UseMiddleware<ResponseObservationMiddleware>();
app.MapGet("/healthz", (IGeoIpLookup geo, EdgeStateStore state) => Results.Ok(new
{
status = "ok",
mode = state.Current.Policy.Mode.ToString(),
snapshotAgeSeconds = Math.Round((DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds, 1),
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
geoLoaded = geo.IsLoaded,
geoDatabase = geo.Info?.DatabaseType,
geoBuiltAt = geo.Info?.BuildDate,
geoStale = geo.Info is not null && geo.Info.IsStale(TimeSpan.FromDays(90))
}));
app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, CancellationToken ct) =>
{
try
{
// CanConnectAsync only proves the file opens. Measured on the shipped
// image with the block table dropped out from under a running edge:
// every block write, delete and listing failed, and /readyz kept
// answering 200. "Ready" has to mean the table the operator's commands
// 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)
{
return Results.Problem(detail: ex.Message, statusCode: StatusCodes.Status503ServiceUnavailable);
}
});
var adminToken = builder.Configuration["OpenWaf:Admin:Token"];
if (string.IsNullOrWhiteSpace(adminToken)) adminToken = Environment.GetEnvironmentVariable("OPENWAF_ADMIN_TOKEN");
app.MapAdminApi(adminToken);
app.MapAdminConsole();
if (!app.Environment.IsProduction())
{
app.MapOpenApi();
}
app.MapReverseProxy();
app.Run();
return 0;
/// <summary>Marker for <c>WebApplicationFactory</c> in the integration tests.</summary>
public partial class Program;