diff --git a/README.md b/README.md index 9a6ddf5..21bb99d 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,13 @@ runtime through `PUT /admin-api/policy`, which persists to `policy_settings`. | `EngineBlockStatus` / `OperatorBlockStatus` | `403` / `301` | what a block answers | | `DefaultRedirectTargets` | iana example | honey-pot targets for operator blocks | +One key is not policy and cannot be changed at runtime, because it decides how +long this process may keep enforcing a list that is already out of date: + +| key | default | meaning | +|-----|---------|---------| +| `OpenWaf:State:RefreshTtlSeconds` | `30` | how stale the in-memory block list may get. On a single edge this is invisible; behind a load balancer it **is** the propagation delay — 23.7 s measured at ~36 req/s in `research/2026-10-01-multi-instance/`. Anything outside 1–300 aborts startup: the process exits non-zero and the log names the key. In Docker the container stays `Up` with nothing listening until the image `HEALTHCHECK` marks it unhealthy — that is what any startup failure in this image looks like, not a special case. `/healthz` reports the value an operator actually got, as `snapshotTtlSeconds`. | + Database: `Database:Provider` = `sqlite` (default) or `postgres`, `ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 74aa87d..2881e90 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -37,7 +37,18 @@ builder.Services.AddDbContext(options => // OPEN-2 architecture decision, not hidden. builder.Services.AddSingleton(); 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 @@ -75,6 +86,7 @@ app.MapGet("/healthz", (IGeoIpLookup geo, EdgeStateStore state) => Results.Ok(ne 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, diff --git a/dotnet/OpenWaf.Edge/appsettings.json b/dotnet/OpenWaf.Edge/appsettings.json index d1b6eb0..18ad77d 100644 --- a/dotnet/OpenWaf.Edge/appsettings.json +++ b/dotnet/OpenWaf.Edge/appsettings.json @@ -20,6 +20,9 @@ "Admin": { "Token": "" }, + "State": { + "RefreshTtlSeconds": 30 + }, "Policy": { "Mode": "Observe", "StreakThreshold": 10, diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index bdce9d1..622b575 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -46,6 +47,25 @@ public sealed class EdgeStateStore public TimeSpan RefreshTtl { get; set; } = TimeSpan.FromSeconds(30); + /// + /// Reads the configured TTL. The TTL is the bound on how stale the block + /// list may be, which makes it a security setting: an unparseable or + /// out-of-range value stops the process at startup instead of quietly + /// falling back to the default behind the operator's back. Unset means 30 s. + /// + public static TimeSpan ParseRefreshTtl(string? configured) + { + if (string.IsNullOrWhiteSpace(configured)) return TimeSpan.FromSeconds(30); + if (!int.TryParse(configured.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds) + || seconds < 1 || seconds > 300) + { + throw new InvalidOperationException( + "OpenWaf:State:RefreshTtlSeconds must be a whole number of seconds between 1 and 300; " + + $"got \"{configured}\". Refusing to start rather than run with a block list of unknown staleness."); + } + return TimeSpan.FromSeconds(seconds); + } + /// Blocking load, used once at startup. public Task WarmUpAsync(CancellationToken ct = default) => RefreshAsync(ct); diff --git a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs index bea729d..cacdb29 100644 --- a/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs +++ b/dotnet/OpenWaf.Tests.Integration/EdgeFixture.cs @@ -25,7 +25,8 @@ internal sealed class EdgeFixture : IAsyncDisposable int threshold = 3, string streakWindow = "00:05:00", string banDuration = "01:00:00", - string geo = "Off") + string geo = "Off", + int? refreshTtlSeconds = null) { Factory = new WebApplicationFactory().WithWebHostBuilder(builder => { @@ -40,6 +41,8 @@ internal sealed class EdgeFixture : IAsyncDisposable // The only way to give a TestServer request a source address is a // header, so these tests exercise the trusted-proxy path too. builder.UseSetting("OpenWaf:Policy:TrustProxyHeaders", "true"); + if (refreshTtlSeconds is { } ttl) + builder.UseSetting("OpenWaf:State:RefreshTtlSeconds", ttl.ToString()); builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address); }); } diff --git a/dotnet/OpenWaf.Tests.Integration/SnapshotStalenessTests.cs b/dotnet/OpenWaf.Tests.Integration/SnapshotStalenessTests.cs new file mode 100644 index 0000000..4668647 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/SnapshotStalenessTests.cs @@ -0,0 +1,93 @@ +using System.Diagnostics; +using System.Net; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// What the snapshot TTL buys and what it costs, in one process. The block is +/// written straight into the database — the way a *different* instance would +/// write it — because the admin API invalidates this process's snapshot on +/// purpose, which would hide the exact delay these tests are about. +/// +public sealed class SnapshotStalenessTests +{ + private const string Banned = "203.0.113.140"; + + // The threshold is pushed out of reach on purpose: these tests ask when the + // *snapshot* catches up with a ban written elsewhere. If the streak engine + // banned the source itself half way through the polling, the assertion + // would pass for a reason that has nothing to do with the TTL. + + + private static async Task WriteBanAsAnotherInstanceWould(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Blocks.Add(new BlockEntry + { + SourceKey = Banned, + Source = BlockSource.Engine, + ExpiresAt = DateTimeOffset.UtcNow.AddHours(1), + Reason = "written by another instance" + }); + await db.SaveChangesAsync(); + } + + private static async Task Ask(EdgeFixture f) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Banned); + using var response = await f.Client.SendAsync(request); + return response.StatusCode; + } + + [Fact] + public async Task A_short_ttl_closes_the_window_on_a_block_this_process_did_not_write() + { + await using var f = new EdgeFixture(threshold: 1000, refreshTtlSeconds: 1); + await WriteBanAsAnotherInstanceWould(f); + + // The first request is served from the snapshot taken at startup, which + // has never heard of this ban. That is the documented, accepted state. + Assert.Equal(HttpStatusCode.NotFound, await Ask(f)); + + var clock = Stopwatch.StartNew(); + var answer = HttpStatusCode.NotFound; + while (clock.Elapsed < TimeSpan.FromSeconds(10) && answer != HttpStatusCode.Forbidden) + { + await Task.Delay(100); + answer = await Ask(f); + } + + Assert.Equal(HttpStatusCode.Forbidden, answer); + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(5), + $"a 1 s TTL should have closed the window inside 5 s; it took {clock.Elapsed.TotalSeconds:F1} s"); + } + + [Fact] + public async Task A_long_ttl_keeps_serving_a_source_the_database_has_already_banned() + { + await using var f = new EdgeFixture(threshold: 1000, refreshTtlSeconds: 300); + await WriteBanAsAnotherInstanceWould(f); + + // Same write, same request, different TTL. This is the propagation + // delay measured across two containers in + // research/2026-10-01-multi-instance/, reproduced in one process: the + // block is in the database and the edge still lets the source through. + for (var i = 0; i < 10; i++) + { + await Task.Delay(100); + Assert.Equal(HttpStatusCode.NotFound, await Ask(f)); + } + } + + [Fact] + public async Task Healthz_reports_the_ttl_the_operator_actually_got() + { + await using var f = new EdgeFixture(refreshTtlSeconds: 7); + Assert.Contains("\"snapshotTtlSeconds\":7", await f.Client.GetStringAsync("/healthz")); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/SnapshotRefreshTtlTests.cs b/dotnet/OpenWaf.Tests.Unit/SnapshotRefreshTtlTests.cs new file mode 100644 index 0000000..9d1637a --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/SnapshotRefreshTtlTests.cs @@ -0,0 +1,37 @@ +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Unit; + +/// +/// The snapshot TTL is the bound on how stale an enforced block list may be, +/// which makes it a security setting rather than a tuning knob. The parsing is +/// therefore the gate: a typo has to stop the process, not become a silent +/// thirty seconds. +/// +public sealed class SnapshotRefreshTtlTests +{ + [Theory] + [InlineData(null, 30)] + [InlineData("", 30)] + [InlineData(" ", 30)] + [InlineData("5", 5)] + [InlineData(" 7 ", 7)] + [InlineData("1", 1)] + [InlineData("300", 300)] + public void Unset_means_thirty_and_a_whole_number_means_what_it_says(string? configured, int expected) + => Assert.Equal(expected, EdgeStateStore.ParseRefreshTtl(configured).TotalSeconds); + + [Theory] + [InlineData("0")] + [InlineData("-1")] + [InlineData("301")] + [InlineData("abc")] + [InlineData("5.5")] + [InlineData("30s")] + public void Anything_else_names_the_key_and_refuses_to_start(string configured) + { + var ex = Assert.Throws(() => EdgeStateStore.ParseRefreshTtl(configured)); + Assert.Contains("OpenWaf:State:RefreshTtlSeconds", ex.Message); + Assert.Contains(configured, ex.Message); + } +}