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; /// Whether the last refresh could read the request-rule table. /// False means the edge is enforcing everything except the rules, and says /// so — see . public bool RulesAvailable { get; private set; } = true; /// Whether the operator's range bans (OPEN-66) could be read on the /// last refresh. Same rule as the rules flag: a database that predates the /// table enforces everything it has and says what it cannot see. public bool RangesAvailable { get; private set; } = true; public string? RangesError => Volatile.Read(ref _rangesError); /// Whether the per-path budgets (OPEN-68) could be read on the last /// refresh. False means the edge is enforcing everything except the path /// budgets, and the surface says which. public bool RateRulesAvailable { get; private set; } = true; public string? RateRulesError => Volatile.Read(ref _rateRulesError); private string? _rateRulesError; private string? _rangesError; /// Why the rules could not be read, for the operator surface. public string? RulesError => Volatile.Read(ref _rulesError); private string? _rulesError; /// /// 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 token = ct; var blocks = await db.Blocks.AsNoTracking().ToListAsync(token); var allow = await db.AllowEntries.AsNoTracking().ToListAsync(token); var countries = await db.CountryRules.AsNoTracking().ToListAsync(token); // The rules read stands alone, on purpose. `request_rules` is the // newest table in the schema, and a database created before the // feature has every other table — so reading it in the same block // as the rest would let one missing table stop a ban written a // minute ago from ever being enforced, which is exactly the failure // this file warns about two paragraphs down. When it fails, the // snapshot is still the operator's list and the surface says the // rules pillar is reading nothing. IReadOnlyList rules; try { // Ordered by id: the listing an operator reads and the order the // engine evaluates are the same thing, so "which rule wins" has // one answer that is visible on the page. rules = await db.RequestRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token); RulesAvailable = true; Volatile.Write(ref _rulesError, null); } catch (Exception ex) when (!ct.IsCancellationRequested) { rules = []; RulesAvailable = false; Volatile.Write(ref _rulesError, ex.Message); _log.LogWarning(ex, "EdgeStateStore: the request-rule table could not be read; enforcing the rest of the list without it."); } // The per-path budgets (OPEN-68) read alone, for the same reason the // rule and range reads do: rate_rules is the newest table in the // schema, and a database that predates it must keep enforcing // everything else. A pillar that cannot read its table says so on the // surface rather than answering "no budgets". IReadOnlyList rateRules; try { rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token); RateRulesAvailable = true; Volatile.Write(ref _rateRulesError, null); } catch (Exception ex) when (!ct.IsCancellationRequested) { rateRules = []; RateRulesAvailable = false; Volatile.Write(ref _rateRulesError, ex.Message); _log.LogWarning(ex, "EdgeStateStore: the rate-rule table could not be read; enforcing the rest of the config without it."); } 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; } // The range read stands alone for the same reason the rule read does: // `network_bans` is the newest table in the schema, and a database // created before it has every other table. Failing this read must not // take a ban written a minute ago down with it. NetworkBanIndex ranges; try { ranges = new NetworkBanIndex(await db.NetworkBans.AsNoTracking().ToListAsync(token)); RangesAvailable = true; Volatile.Write(ref _rangesError, null); } catch (Exception ex) when (!ct.IsCancellationRequested) { ranges = NetworkBanIndex.Empty; RangesAvailable = false; Volatile.Write(ref _rangesError, ex.Message); _log.LogWarning(ex, "EdgeStateStore: the range-ban table could not be read; enforcing the rest of the list without it."); } 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, RequestRules = rules, OperatorRanges = ranges, RateRules = rateRules }; } 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(); } } }