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.
This commit is contained in:
@@ -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`.
|
||||
|
||||
|
||||
@@ -37,7 +37,18 @@ builder.Services.AddDbContext<OpenWafDbContext>(options =>
|
||||
// OPEN-2 architecture decision, not hidden.
|
||||
builder.Services.AddSingleton<StreakTracker>();
|
||||
builder.Services.AddSingleton<EdgePolicyProvider>();
|
||||
builder.Services.AddSingleton<EdgeStateStore>();
|
||||
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
|
||||
@@ -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,
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
"Admin": {
|
||||
"Token": ""
|
||||
},
|
||||
"State": {
|
||||
"RefreshTtlSeconds": 30
|
||||
},
|
||||
"Policy": {
|
||||
"Mode": "Observe",
|
||||
"StreakThreshold": 10,
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Blocking load, used once at startup.</summary>
|
||||
public Task WarmUpAsync(CancellationToken ct = default) => RefreshAsync(ct);
|
||||
|
||||
|
||||
@@ -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<Program>().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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<OpenWafDbContext>();
|
||||
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<HttpStatusCode> 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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using OpenWaf.Infrastructure.Persistence;
|
||||
|
||||
namespace OpenWaf.Tests.Unit;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<InvalidOperationException>(() => EdgeStateStore.ParseRefreshTtl(configured));
|
||||
Assert.Contains("OpenWaf:State:RefreshTtlSeconds", ex.Message);
|
||||
Assert.Contains(configured, ex.Message);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user