Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.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

136 lines
5.3 KiB
C#

using System.Globalization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Holds the snapshot the decision point reads and refreshes it off the
/// request path.
///
/// The reference repo blocks the request thread on a stale cache
/// (<c>RefreshAsync().GetAwaiter().GetResult()</c>). This does not: a stale
/// snapshot is served while a single background refresh runs, because a
/// database hiccup should not add latency to every request, and a snapshot
/// that is 30 seconds old is a documented, accepted state. The very first load
/// is awaited at startup, so the edge never serves traffic with an empty
/// picture of the operator's list.
///
/// On refresh failure the previous snapshot is kept — fail closed for blocks.
/// A bot probing during a database restart must not skate past the gate.
/// </summary>
public sealed class EdgeStateStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly ILogger<EdgeStateStore> _log;
private readonly SemaphoreSlim _refreshLock = new(1, 1);
private EdgeSnapshot _snapshot;
private int _refreshInFlight;
public EdgeStateStore(
IServiceScopeFactory scopeFactory,
EdgePolicyProvider policy,
ILogger<EdgeStateStore> log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_log = log;
_snapshot = EdgeSnapshot.Empty(policy.Current);
}
public EdgeSnapshot Current => _snapshot;
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);
/// <summary>Serve now, refresh in the background if the TTL has expired.</summary>
public EdgeSnapshot GetOrRefresh()
{
var snapshot = _snapshot;
if (DateTimeOffset.UtcNow - snapshot.GeneratedAt > RefreshTtl && Interlocked.CompareExchange(ref _refreshInFlight, 1, 0) == 0)
{
_ = Task.Run(async () =>
{
try { await RefreshAsync(CancellationToken.None); }
finally { Interlocked.Exchange(ref _refreshInFlight, 0); }
});
}
return snapshot;
}
/// <summary>Admin mutations call this so the operator's change lands on the
/// next request rather than after the TTL.</summary>
public Task InvalidateAsync(CancellationToken ct = default) => RefreshAsync(ct);
private async Task RefreshAsync(CancellationToken ct)
{
if (!await _refreshLock.WaitAsync(TimeSpan.FromSeconds(10), ct)) return;
try
{
var policy = await _policy.ReloadAsync(ct);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var blocks = await db.Blocks.AsNoTracking().ToListAsync(ct);
var allow = await db.AllowEntries.AsNoTracking().ToListAsync(ct);
var countries = await db.CountryRules.AsNoTracking().ToListAsync(ct);
var operatorBlocks = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
var engineBans = new Dictionary<string, BlockEntry>(StringComparer.Ordinal);
foreach (var b in blocks)
{
if (b.Source == BlockSource.Operator) operatorBlocks[b.SourceKey] = b;
else engineBans[b.SourceKey] = b;
}
var countryMap = new Dictionary<string, CountryRule>(StringComparer.OrdinalIgnoreCase);
foreach (var c in countries) countryMap[c.Code] = c;
_snapshot = new EdgeSnapshot
{
GeneratedAt = DateTimeOffset.UtcNow,
Policy = policy,
OperatorBlocks = operatorBlocks,
EngineBans = engineBans,
AllowEntries = allow,
Countries = countryMap
};
}
catch (Exception ex)
{
_log.LogWarning(ex, "EdgeStateStore: refresh failed; keeping the previous snapshot.");
}
finally
{
_refreshLock.Release();
}
}
}