Files
openwaf/dotnet/OpenWaf.Edge/Program.cs
T
Pavlo Ratushnyi 12a0f49d0c Make the snapshot TTL a setting, and say what it is for
OPEN-12's option (b) — share the block list and shorten the TTL — was not a
deployment decision, it was a rebuild: EdgeStateStore.RefreshTtl was a
property initialised to 30 s with no configuration binding anywhere in the
tree. The measurement in research/2026-10-01-multi-instance/ showed why that
matters: the TTL is not a tuning knob, it is the propagation delay between
edges (23.7 s under ~36 req/s, 1.7 s on an idle one), so an operator who
runs more than one instance is choosing a staleness bound they cannot set
and cannot see.

The key is OpenWaf:State:RefreshTtlSeconds, default 30, and the default is
unchanged so nothing moves for anyone who does not touch it. A value outside
1-300 aborts startup instead of falling back silently, because a typo in the
staleness bound is a security setting failing quietly. /healthz now reports
snapshotTtlSeconds, so an operator can read the TTL they actually got.

Verified on this commit: 49 unit and 23 integration tests pass (13 new unit
cases on the parser; 3 new integration tests that write a ban the way another
instance would — straight into the database, no InvalidateAsync — and show a
1 s TTL closing the window inside 5 s while a 300 s TTL keeps serving a
source the database has already banned); scripts/smoke.sh 19/19;
scripts/compose-smoke.sh 27/27 against the rebuilt image; in a container
RefreshTtlSeconds=5 reports snapshotTtlSeconds:5 on /healthz, and =0 aborts
the process with the key named in the log.

One thing the check taught and the README now says instead of hiding: when
startup aborts inside the image, the container stays Up with nothing
listening until the HEALTHCHECK goes unhealthy. That is how every startup
failure in this image looks, not something this change introduces.
2026-10-01 12:57:24 +02:00

126 lines
5.2 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
{
await db.Database.CanConnectAsync(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;