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(builder.Configuration.GetSection("OpenWaf:Policy")); builder.Services.AddSingleton(sp => sp.GetRequiredService>().Value.ToPolicy()); var provider = builder.Configuration["Database:Provider"] ?? "sqlite"; var connectionString = builder.Configuration.GetConnectionString("OpenWaf") ?? "Data Source=openwaf.db"; builder.Services.AddDbContext(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(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => new EdgeStateStore( sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>()) { // 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(); builder.Services.AddSingleton(); // 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(sp => new MaxMindGeoIpLookup( geoPath, sp.GetRequiredService>())); builder.Services.AddHostedService(); // 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(); builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddHostedService(sp => sp.GetRequiredService()); 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(); app.UseMiddleware(); 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; /// Marker for WebApplicationFactory in the integration tests. public partial class Program;