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; /// /// 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 /// (RefreshAsync().GetAwaiter().GetResult()). 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. /// public sealed class EdgeStateStore { private readonly IServiceScopeFactory _scopeFactory; private readonly EdgePolicyProvider _policy; private readonly ILogger _log; private readonly SemaphoreSlim _refreshLock = new(1, 1); private EdgeSnapshot _snapshot; private int _refreshInFlight; public EdgeStateStore( IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, ILogger log) { _scopeFactory = scopeFactory; _policy = policy; _log = log; _snapshot = EdgeSnapshot.Empty(policy.Current); } public EdgeSnapshot Current => _snapshot; public TimeSpan RefreshTtl { get; set; } = TimeSpan.FromSeconds(30); /// /// 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. /// public bool IsStale => DateTimeOffset.UtcNow - _snapshot.GeneratedAt > RefreshTtl; /// Consecutive refresh failures; zero means the last one worked. public int RefreshFailures => Volatile.Read(ref _refreshFailures); /// The last refresh error, or null when the last refresh succeeded. public string? LastRefreshError => Volatile.Read(ref _lastRefreshError); private int _refreshFailures; private string? _lastRefreshError; /// /// 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); /// Serve now, refresh in the background if the TTL has expired. 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; } /// Admin mutations call this so the operator's change lands on the /// next request rather than after the TTL. 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(); 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(StringComparer.Ordinal); var engineBans = new Dictionary(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(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(); } } }