OPEN-34, measured on the shipped image before this change. With writes to block_entries aborted, five refusals produced counted write failures and /readyz 503. The triggers were then REMOVED — write path healthy, zero triggers left — and no further request was sent from that source: t+30 s /readyz 503 /state: banWriteFailures 3, bansNotWritten 3 t+60 s /readyz 503 unchanged t+90 s /readyz 503 unchanged t+120 s /readyz 503 unchanged The ban pillar clears only on a successful ban write, and the only thing that produced one was the source crossing the threshold again. Readiness — the signal an orchestrator uses to keep an edge in rotation — was therefore coupled to attack traffic: the quieter the site, the longer a repaired edge sat out of service, enforcing everything except one ban nobody had written. The fix is on the write side, not on the gate. A ban the engine decided and could not write is kept as a PendingBan and re-attempted by a hosted loop on the same 15 s cadence the other writers use; the sentence still runs from the moment the ban was decided, so a retry that lands late cannot quietly lengthen it, and a pending ban whose sentence expired before it could be written is counted (bansNeverEnforced) and reported rather than rewritten as a fresh, longer ban. /state gained bansPendingRetry and bansNeverEnforced, because without the first a healed storage failure is indistinguishable from a quiet site. Teeth: PendingBanRetryTests (3) — the retry landing with no further request, the hosted loop doing it on its own (nobody calls it in that test), and an expired pending ban reported rather than written late. Compose gate gained a 5-assertion scene against the shipped image: the failed ban is queued, readiness returns after the repair with no traffic from that source, the ban reaches storage, the queue empties, and the source that was never banned during the break answers 403 afterwards. Gates at this commit — macOS host: unit 128/128, integration 141/141, smoke 28/0, compose 86/0, console 58/0, 0 containers left behind. Linux rehearsal, all three stages: PASS — source (128/128, 141/141, 28/0), compose 86/0 with enforcement lag 13 ms, console 58/0, 0 containers left behind.
206 lines
11 KiB
C#
206 lines
11 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<DurabilityHealth>();
|
|
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.AddHostedService<PendingBanRetryWorker>();
|
|
|
|
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, DurabilityHealth durability, 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);
|
|
|
|
// The read side was made honest first; the write side was still silent.
|
|
// Measured on the shipped image with SQLite triggers aborting every
|
|
// INSERT/UPDATE on source_observations and edge_alerts while reads kept
|
|
// working: /admin-api/observations answered 200 with the same
|
|
// X-Total-Count as before the break (4 — three new sources never
|
|
// arrived), /admin-api/alerts still showed its one row after a six
|
|
// request 5xx storm, and /readyz answered {"status":"ready"} the whole
|
|
// 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.
|
|
// 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: $"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
|
|
// privacy and disk-space problem, and one an operator has to be told
|
|
// about — but it does not change what this edge enforces or what it
|
|
// tells the operator about what it enforced. Pulling every edge out of
|
|
// rotation because a 30-minute cleanup loop is failing would trade a
|
|
// data-retention defect for an outage.
|
|
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;
|