Measured on the shipped image (openwaf:ci, the head tree), one stand with a real
upstream:
PUT /admin-api/policy {"streakThreshold":2,"trustProxyHeaders":true} -> 200
404 404 from 203.0.113.79, third request -> 403 (the threshold is in force)
04:44:43 DROP TABLE policy_settings, from outside the process
04:45:2x GET /admin-api/policy -> still "streakThreshold": 2, answered plainly
GET /admin-api/state -> "snapshotAgeSeconds":0 — the refresh "succeeded",
because the tables it also reads were still there
/healthz 200, /readyz 200, and exactly 1 line in the log
docker restart -> GET /admin-api/policy -> "streakThreshold": 10,
"trustProxyHeaders": false
four 404s from 203.0.113.81, fifth -> 404: nothing banned
Both pillars — the policy provider and the guard's snapshot store — catch
everything their read throws, keep the last value they had, and log one line.
Keeping the last good value is the right failure posture: a database restart must
not open the gate. Keeping it unmentioned is not: for a minute the operator's page
showed a threshold that no longer existed anywhere in storage, readiness said
ready, and after a restart the defence silently came back at the default N=10.
Now: EdgePolicyProvider and EdgeStateStore count consecutive failed reads and keep
the last error; /admin-api/state answers snapshotStale (age against the TTL the
process refuses to start without), snapshotRefreshFailures,
snapshotLastRefreshError, policyReloadFailures and policyLastReadAt;
/admin-api/policy carries X-Policy-Reload-Failures and X-Policy-Last-Read
alongside the policy it is enforcing, the same way a capped listing carries its
completeness in headers; /readyz answers 503 while either counter is non-zero,
naming the pillar and the age of the snapshot it is running on; and the console's
summary line goes warn and says "older than the ttl", "snapshot refresh failing
xN", "policy not re-read from storage xN".
Teeth first: PillarFailureVisibilityTests (4) run against the unfixed tree — 4
failed, 0 passed, all four on a missing field (KeyNotFoundException), which is the
point: the numbers did not exist. The refresh test drops country_rules rather than
block_entries on purpose — only one of them is what /readyz probes, so before the
fix that test saw the refresh failing and readiness still answering 200.
Gates: compose-smoke now drops policy_settings from the running stand through a
--volumes-from sidecar, waits for the failure to be counted, asserts the counters,
the 503 and the header, puts the table back and asserts the recovery (+6
assertions; the counters are consecutive, not cumulative, so recovery is part of
the claim). smoke.sh asserts the healthy case with numbers rather than silence
(+3). console-check drives the page against that state answer and requires the
summary line to be marked and to name both pillars (+3); the state body is served
through a route because the guard refreshes the snapshot on every request — a live
stand cannot be left to age — while the contract being rendered is the one
compose-smoke measures end to end against the shipped image.
Numbers on this tree. Host: build 0 warnings, unit 128/128, integration 117/117,
smoke 25 passed / 0 failed, compose 53 passed / 0 failed, console 53 assertions /
0 failed, image 261 MB. Linux rehearsal, each stage on its own — source in
mcr.microsoft.com/dotnet/sdk:10.0 (Ubuntu 24.04.5, SDK 10.0.401): 128/128,
117/117, 25/0; compose in docker:cli: 53/0, enforcement lag 12 ms; console in
mcr.microsoft.com/playwright:v1.63.0-noble: 53/0.
164 lines
6.8 KiB
C#
164 lines
6.8 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>
|
|
/// Older than the TTL. The TTL is documented as the bound on how stale the
|
|
/// block list may be, and the process refuses to start with an unparseable
|
|
/// one — "rather than run with a block list of unknown staleness". Until now
|
|
/// nothing checked that bound after startup, so a snapshot could sit at ten
|
|
/// times the bound and every surface still looked normal.
|
|
/// </summary>
|
|
public bool IsStale => DateTimeOffset.UtcNow - _snapshot.GeneratedAt > RefreshTtl;
|
|
|
|
/// <summary>Consecutive refresh failures; zero means the last one worked.</summary>
|
|
public int RefreshFailures => Volatile.Read(ref _refreshFailures);
|
|
|
|
/// <summary>The last refresh error, or null when the last refresh succeeded.</summary>
|
|
public string? LastRefreshError => Volatile.Read(ref _lastRefreshError);
|
|
|
|
private int _refreshFailures;
|
|
private string? _lastRefreshError;
|
|
|
|
/// <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;
|
|
|
|
Interlocked.Exchange(ref _refreshFailures, 0);
|
|
Volatile.Write(ref _lastRefreshError, null);
|
|
|
|
_snapshot = new EdgeSnapshot
|
|
{
|
|
GeneratedAt = DateTimeOffset.UtcNow,
|
|
Policy = policy,
|
|
OperatorBlocks = operatorBlocks,
|
|
EngineBans = engineBans,
|
|
AllowEntries = allow,
|
|
Countries = countryMap
|
|
};
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Fail closed for the decision, and say so where an operator looks.
|
|
// Keeping the previous snapshot is right; keeping it silently is not:
|
|
// the snapshot is the operator's list, and a refresh that has been
|
|
// failing for an hour means a ban written since then is not being
|
|
// enforced — while /readyz, /state and the page all looked normal.
|
|
Interlocked.Increment(ref _refreshFailures);
|
|
Volatile.Write(ref _lastRefreshError, ex.Message);
|
|
_log.LogWarning(ex, "EdgeStateStore: refresh failed; keeping the previous snapshot.");
|
|
}
|
|
finally
|
|
{
|
|
_refreshLock.Release();
|
|
}
|
|
}
|
|
}
|