Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that decides from what the upstream answered. Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6): - one short-circuit point, ordered: always-pass prefixes -> allowlist -> operator block (301) -> engine ban (403 + Retry-After) -> geo (451) - a post-response observer feeds a consecutive-refusal streak; N refusals in M minutes ban for BanDuration; 5xx alerts and never bans - provenance on the block row, so clearing engine bans cannot touch an operator's entries; the toggle is Off/Observe/Enforce and changes no rows - inherited protections from the reference deployment: one durable write per source per 30s, LRU-bounded streak map, no DB on the request path Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19 assertions against a running edge and a real upstream, including the distroless --healthcheck mode). Findings worth keeping (documented in docs/ARCHITECTURE.md): - ctx.RequestAborted silently cancelled the ban write, because the observer runs after the response is written - SQLite cannot translate DateTimeOffset comparisons; timestamps are stored as integers there and stay timestamptz on PostgreSQL - CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16) - an empty string in appsettings.json defeats the env fallback (?? on "") - concurrent ban writes raced into the unique index and lost evidence Also moves the unrelated 2026-09-30 inference benchmarks out of the project root into research/.
116 lines
4.3 KiB
C#
116 lines
4.3 KiB
C#
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>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();
|
|
}
|
|
}
|
|
}
|