Measured on two shipped images of the same stand — openwaf:prefix built from
72d37ad and openwaf:ci built from this tree — with the block table and the
policy table dropped out from under a running edge that held 3 blocks and 1
policy row:
DELETE /admin-api/blocks?source=operator 200 {"deleted":0} -> 503 "NOTHING was deleted"
DELETE /admin-api/blocks?key=203.0.113.201 200 {"deleted":0} -> 503 "NOTHING was deleted"
POST /admin-api/blocks 400 database error -> 503 "the block is NOT in effect"
PUT /admin-api/policy {"mode":"Enforce"} 200, body mode=Observe -> 503 "the change is NOT in effect"
GET /admin-api/blocks 500 -> 500 (unchanged)
GET /readyz 200 ready -> 503
GET /healthz 200 -> 200 (unchanged: the recovery hatch)
Four separate lies, one class:
* BlockStore.DeleteAsync caught everything, logged a warning and returned 0, so
the endpoint answered {"deleted":0} — the same bytes an empty list produces.
A destructive command that could not run told the operator there was nothing
to remove.
* BlockStore.AddOperatorAsync returned the string "database error" and the
endpoint mapped it to 400, next to the real validation errors. A storage
failure arrived as "your request is wrong", which invites a retry of the
request while no block is in effect.
* PUT /admin-api/policy threw away SaveAsync's false and answered 200 with the
policy body — showing the mode that had NOT been saved.
* /readyz used CanConnectAsync, which only proves the file opens. It kept
answering 200 through all of the above.
The same stand, six concurrent POSTs for one address (no broken storage):
4x 204 and 2x 400 {"error":"database error"} before; 6x 204 after. The unique
index on (source key, provenance) made the loser of a race the API itself
started look like a caller who sent a bad request — which is what a double-click
on "block" in the console is. The write now retries against the winner's row.
The console had its own copy of the bug: every destructive row button wrote its
green note whatever came back, so a refused delete read as "deleted ? block(s)",
and load() — which runs after every action and on a 5 s interval — replaced the
error line with "refreshed" inside a second. The note now waits for an answer
that did not carry an error, and the refresh that follows a failed action holds
it. An empty 5xx body is now reported as an empty 5xx body instead of throwing
inside apiRaw and being swallowed.
Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 106/106 (7 new in StorageFailureHonestyTests), smoke 19/0,
compose 43/0, image 261 MB, console 45/45 (1 new assertion).
Dents: delete answers deleted:0 -> 2 fail; POST answers 400 -> 1; readyz trusts
CanConnectAsync -> 1; no retry after the unique-index loser -> 1; delete
swallows into a bare 0 -> 2; PUT /policy discards the save answer -> 1; console
writes the note whatever came back -> the console gate fails that assertion.
132 lines
5.6 KiB
C#
132 lines
5.6 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, 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);
|
|
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;
|