Files
openwaf/dotnet/OpenWaf.Edge/Program.cs
T
Pavlo Ratushnyi 1e0d11df1c
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
the first query moves off ef, and the aot edge reads its own policy from the database
Wall 3 starts. Two projects, one query path, measured.

dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an
ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common
and carries no provider package; the driver is supplied at composition, which is
how the neighbouring deployment ships it too. Query<T> renders SQL by walking the
expression tree rather than compiling it — that is the exact difference from EF's
pipeline, and the reason it survives a NativeAOT link where EF does not. The
supported grammar is a closed set that refuses by name: joins, subqueries,
aggregates other than COUNT, updates, deletes, JSON columns and method calls each
raise UnsupportedQueryNodeException naming the node, because a renderer that
guesses is a renderer that ships wrong SQL.

dotnet/OpenWaf.Data.Generator is a Roslyn incremental generator attached to
OpenWaf.Infrastructure as an analyzer. For a [Table] class it emits the column
map, the row materializer and an OrmMeta.Register call inside a
[ModuleInitializer], so the question a NativeAOT binary cannot answer — what are
this type's properties — is never asked. The generated file is ordinary C#,
readable in obj/ and asserted against.

PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call
site, which was the first refusal in the probe log. Program.cs composes the
driver and dialect on the same Database:Provider switch EF uses, so one generated
query serves sqlite (the shipped image) and PostgreSQL (the migrations'
provider). EF still owns every write and every other read; the two layers
coexist on one composition root, which is what makes this incremental rather than
a rewrite.

Measured on the AOT binary, same probe, same window, before and after:
queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0;
native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by
their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync,
1 BlockStore.AddOperatorAsync, 1 admin endpoint.

The sqlite timestamp column turned out to be a contract, not a detail. The model
puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row
already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the
formula was derived by probing EF's converter and is now pinned by
SqliteTimestampEncodingTests against that converter over five instants including
+05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond
truncation the /1000 imposes, which is EF's behaviour and is now a test rather
than a future surprise.

Two build traps, both paid for and both recorded where the next person will hit
them. -p:PublishAot on the command line is a global property, so it reaches every
project in the graph including a netstandard2.0 Roslyn analyzer, and the publish
dies with NETSDK1207; AOT is now switched by OpenWafAot=true, which only
OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing
OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs
SQLitePCL.Batteries.Init() before its first open, because the order in which
EF's provider and this data source are first used is not guaranteed.

Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both
dialects, null tests, the captured-null case, the refusals, the timestamp
encoding), integration 408/408, smoke 256/256, and the AOT probe above. One
earlier run of the 408 carried a single failure in AdminConsoleTests at a host
load average near 30 and the next run was clean; recorded rather than hidden, in
the same family as the load-sensitive compose gates this README already
documents.
2026-10-07 21:48:01 +02:00

401 lines
22 KiB
C#

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization.Metadata;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Security;
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);
// The source-generated JSON contract, at the head of the resolver chain. Without
// it a NativeAOT edge never reaches the query wall: the host refuses to start
// over a missing JsonTypeInfo for an admin request DTO (measured 2026-10-06,
// 3 refusals, first type NewBlockRequest). On a non-AOT build the chain still
// ends at the reflection resolver, so an unregistered type behaves exactly as it
// did before — which is why the 22 anonymous response literals still standing
// (measured 2026-10-07, plus 7 more that live inside an EF query's Select and are
// the query wall's problem rather than this one) are a debt this records rather
// than a break it causes.
builder.Services.ConfigureHttpJsonOptions(o =>
{
o.SerializerOptions.TypeInfoResolverChain.Insert(0, OpenWaf.Edge.Admin.EdgeJson.Default);
// Two measurements, both made against this wiring, decide its shape.
//
// (1) A non-empty chain REPLACES the reflection resolver rather than
// extending it. With only the context above in the chain, a type it does not
// know fails on a JIT build with the same sentence the AOT probe reports —
// `JsonTypeInfo metadata for type '<>f__AnonymousType0`1[System.String]' was
// not provided by TypeInfoResolver of type '[EdgeJson]'` (standalone probe,
// 2026-10-06). Twenty-two anonymous response literals are still in this
// project (the rest of the JSON wall, OPEN-79), so on a build that can
// reflect, reflection stays at the end of the chain: the debt kept served and
// visible rather than a break introduced in the middle of a slice.
//
// (2) That fallback is not free on the other side. Naming
// DefaultJsonTypeInfoResolver in an AOT publish drags the reflection-based
// JSON stack into the native image: measured 2026-10-07, the publish step ran
// 66 minutes and never finished, against 232 s for the same Dockerfile
// without it. `RuntimeFeature.IsDynamicCodeCompiled` is a constant the AOT
// compiler substitutes, so on the shipped binary this branch — and the
// resolver it names — is not there at all, and the chain is exactly the
// compiled contract.
if (RuntimeFeature.IsDynamicCodeCompiled)
o.SerializerOptions.TypeInfoResolverChain.Add(new DefaultJsonTypeInfoResolver());
});
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";
// The generated query layer, on the same provider switch as EF: one composition
// root decides the driver and the dialect for both halves (OPEN-79, wall 3).
builder.Services.AddOpenWafData(provider, connectionString);
builder.Services.AddDbContext<OpenWafDbContext>(options =>
{
if (provider.Equals("postgres", StringComparison.OrdinalIgnoreCase)) options.UseNpgsql(connectionString);
else options.UseSqlite(connectionString);
});
// Where the streak counters live. The default is one map per process, which
// counts each instance's traffic separately — measured, not hidden: four
// refusals from one address, two per edge, at a threshold of 3 produced no ban
// anywhere (research/2026-10-01-multi-instance/, D1).
//
// OpenWaf:Policy:SharedStreaks=true moves the same rules onto a database row so
// N edges mature one streak, at the cost of a round trip per observed response
// on a path whose measured p95 is ~3 ms. It is read here, once, because it
// selects which store the process registers; a policy PUT cannot move the
// counters from one store to the other underneath a running process.
if (builder.Configuration.GetValue("OpenWaf:Policy:SharedStreaks", false))
builder.Services.AddSingleton<IStreakTracker>(sp => new SharedStreakTracker(
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<ILogger<SharedStreakTracker>>()));
else
builder.Services.AddSingleton<IStreakTracker>(_ => new 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>();
// Requests by verdict, counted at the one place that decides (OPEN-58). Per
// process, like the rate counter: a Prometheus query sums the instances, which
// is the right answer for "how many did this fleet refuse", and a shared
// counter would cost a round trip on a path whose measured p95 is ~3 ms.
builder.Services.AddSingleton<OpenWaf.Edge.Observability.EdgeCounterLedger>();
builder.Services.AddSingleton<OpenWaf.Edge.Pipeline.RuleMatchLedger>();
// The volume counter (OPEN-56). One per process, on purpose: the budget is a
// count of requests this edge saw, and there is no shared implementation to
// choose the way there is for the streak — sharing a counter would mean a
// round trip on a path whose measured p95 is ~3 ms, for every request, not
// only the observed ones. The stop a breach writes IS shared, because it is a
// ban row.
builder.Services.AddSingleton<OpenWaf.Domain.Engine.RateTracker>();
builder.Services.AddSingleton<OpenWaf.Domain.Engine.RateRuleTracker>();
builder.Services.AddSingleton<DurabilityHealth>();
// Alerts used to end at a table: the row is correct and read by nobody until
// someone opens the page. One optional endpoint pushes each raised alert
// somewhere that can act at 03:00. The timeout is validated at startup rather
// than defaulted, for the same reason the refresh TTL is: 0 drops every push
// and 600 parks a worker on a dead endpoint, and neither is what the operator
// meant.
var alertWebhookUrl = builder.Configuration["OpenWaf:Alerts:WebhookUrl"];
if (string.IsNullOrWhiteSpace(alertWebhookUrl))
alertWebhookUrl = Environment.GetEnvironmentVariable("OPENWAF_ALERT_WEBHOOK_URL");
// The three alert bounds are parsed here, before the host exists, so they need
// the same clean exit as the refusals that surface during host start (OPEN-63):
// an unhandled exception on the shipped image prints the reason and then spins
// at full CPU instead of leaving.
int alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds;
try
{
alertWebhookTimeout = AlertNotifier.ParseTimeoutSeconds(
builder.Configuration["OpenWaf:Alerts:WebhookTimeoutSeconds"]);
// How hard to try, and how long to wait between tries (OPEN-60). Validated
// here rather than defaulted: MaxPushAttempts=0 means "never tell anybody"
// and a 0-second retry against a dead endpoint is a busy loop, and neither
// is what the operator meant when they wrote the number.
alertPushAttempts = PushRetryPolicy.ParseMaxAttempts(
builder.Configuration["OpenWaf:Alerts:MaxPushAttempts"]);
alertPushRetrySeconds = PushRetryPolicy.ParseRetrySeconds(
builder.Configuration["OpenWaf:Alerts:PushRetrySeconds"]);
}
catch (Exception ex)
{
return RefuseStartup(ex.Message);
}
builder.Services.AddSingleton<AlertNotifier>(sp => new AlertNotifier(
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<DurabilityHealth>(),
sp.GetRequiredService<ILogger<AlertNotifier>>(),
alertWebhookUrl, alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds));
builder.Services.AddSingleton<AlertWriter>();
// The record of a deliberate config change (OPEN-64). Best-effort by design:
// the change has already been applied when this writes, and a change refused
// because its record would not land is a change the operator believes they
// have and does not have.
builder.Services.AddSingleton<ConfigChangeWriter>();
// 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>>()));
// What the schema step did at startup, read back on /admin-api/state (OPEN-55).
builder.Services.AddSingleton<SchemaUpgradeReport>();
builder.Services.AddHostedService<EdgeStateWarmer>();
// Hosted services are started in registration order, and the warmer is the step
// that creates the tables. The notifier used to be registered above it, so its
// first queue read ran against a database this same process had not created yet:
// measured on a cold start, the queue sweep failed with SQLite Error 1:
// 'no such table: alert_push_queue', and that sentence became
// alertWebhookLastError — the state page blaming the endpoint for the edge's own
// startup order. Every worker that touches durable state is registered below the
// warmer for that reason; the singleton stays where the endpoints resolve it.
builder.Services.AddHostedService(sp => sp.GetRequiredService<AlertNotifier>());
// 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>();
// The netblock watch (OPEN-67) is reachable as itself as well as hosted: the
// admin surface reads its last scan, and the tests force a scan rather than
// waiting five minutes for the timer.
builder.Services.AddSingleton<NetblockWatcher>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<ObservationWriter>());
builder.Services.AddHostedService(sp => sp.GetRequiredService<RetentionWorker>());
builder.Services.AddHostedService(sp => sp.GetRequiredService<NetblockWatcher>());
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 HealthDto(
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 ReadinessDto("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");
// The second token, for a thing that has to be able to look and must not be
// able to change (OPEN-62): a Prometheus scrape, a dashboard, a second operator
// checking why a visitor was refused. Unset is the default and the whole of
// today's behaviour.
var readOnlyToken = builder.Configuration["OpenWaf:Admin:ReadOnlyToken"];
if (string.IsNullOrWhiteSpace(readOnlyToken))
readOnlyToken = Environment.GetEnvironmentVariable("OPENWAF_READ_ONLY_TOKEN");
// Refused at startup rather than logged, for the same reason the TTL and the
// retention windows are: a read-only token that is also the admin token is a
// security promise that is false, and a process that serves traffic on a false
// promise is worse than one that will not start. The message names the two keys
// and never the secret, because this line is written into whatever the operator
// pipes startup output to.
if (AdminTokenPolicy.ExplainConfigurationProblem(adminToken, readOnlyToken) is { } tokenProblem)
{
// A clean exit, not a throw - see RefuseStartup for the measurement.
return RefuseStartup(tokenProblem);
}
app.MapAdminApi(adminToken, readOnlyToken);
// The operator's numbers, in the format their alerting reads (OPEN-58). Same
// tokens as the admin API, and on an always-pass prefix like /healthz — an edge
// that has blocked the operator's own address still has to be watchable.
app.MapMetrics(adminToken, readOnlyToken);
app.MapAdminConsole();
if (!app.Environment.IsProduction())
{
app.MapOpenApi();
}
app.MapReverseProxy();
// Did this process ever reach the point of serving? It decides what an
// exception leaving app.Run means.
var startedServing = false;
app.Lifetime.ApplicationStarted.Register(() => startedServing = true);
try
{
app.Run();
return 0;
}
catch (Exception ex) when (!startedServing)
{
// A startup refusal. Most of them are not written here: the TTL, the two
// retention windows, the push-attempt and retry bounds and the webhook
// timeout are validated by the types that own them, and they surface during
// host start, when a hosted service resolves the service whose factory
// parsed the value.
//
// Catching it here rather than letting it go was measured, not guessed. On
// the shipped image an unhandled exception during host start prints the
// reason and then the process sits at 100% CPU inside the runtime's crash
// path: the container stays "Up (unhealthy)" forever, there is no exit code,
// and the supervisor - compose, k8s, a systemd unit - sees a running edge
// and restarts nothing. The refusal sentence itself was already correct;
// only its form was unreadable.
//
// The startedServing guard is what keeps "refused to start" and "an edge
// that died while serving" from collapsing into one exit code. After the
// application has started, an exception leaving app.Run is not a
// configuration the operator mistyped, and it must not be reported as one.
return RefuseStartup(ex.Message);
}
/// <summary>
/// The one way this process says "I will not start": the reason on stderr and
/// exit code 1. Every startup refusal goes through here so the exit code is the
/// same for all of them, which is what lets a supervisor and a script tell
/// "refused to start" from "crashed later" - the crash path leaves a different
/// code and a stack trace, and a spinning container leaves neither.
///
/// The reason is written as given. The validators own their sentences and each
/// one names the key and the offending value; none of them prints a secret.
/// </summary>
static int RefuseStartup(string reason)
{
Console.Error.WriteLine($"the edge refused to start: {reason}");
return 1;
}
/// <summary>Marker for <c>WebApplicationFactory</c> in the integration tests.</summary>
public partial class Program;