Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs
T
Pavlo Ratushnyi 5e6a840731 a path rule refuses the request itself, before the upstream ever sees it
Every pillar this edge had until now judged the response or the source: a streak
of refusals the upstream produced, a country, an operator's list of addresses.
The request itself was never looked at. A known-bad request therefore always
reached the origin and cost it something, and became a defence only if the
origin's answer happened to fall in the refusal range three times in a row.

A request rule is a path pattern an operator writes: `GET/POST/DELETE
/admin-api/rules`, listed in the order they are enforced, with an action.
`observe` counts matches (one alert per rule per 15 minutes, the tally on the
listing) and lets the request through, which is how an operator learns what a
rule would have blocked before it blocks anything; `block` answers 403 naming the
rule id — the id, not the pattern, because a 403 body that quotes the pattern
tells the visitor which payload to change. It fires in Observe mode too: the mode
switches off what the edge decides by itself, not what a human wrote down. It
sits below the allowlist and above the two source-level lists, because "this path
is refused" is the more specific claim about this request.

The pattern language is a glob — `*` and `?`, anchored, case-insensitive, `*`
crossing `/` — and deliberately not a regex: the operator writes the pattern and
an anonymous visitor writes the path, and `(a+)+$` against 400 a's is a ReDoS
with the edge's CPU. A pattern that can only silently do nothing (no leading
`/`, `/*`, a control character, over 256 characters) is refused with the reason,
and at most 500 live rules exist because every request is checked against each.

Two things the run caught rather than the design assumed:

 * The rules read shared one statement block with the rest of the snapshot.
   `request_rules` is the newest table in the schema, and the default schema step
   is EnsureCreated, which creates a missing database and changes nothing about
   an existing one — so every database created before this feature has every
   table except that one, and the first refresh after startup would have thrown,
   frozen the operator's block list at its old contents, and looked healthy. The
   rules read is a statement of its own now: a missing table costs the rules
   pillar and says so (`requestRulesAvailable`, `requestRulesError`, a NOT READ
   line over the rules table) while every other pillar keeps enforcing. The
   migration set was stale in the same direction — it never had `source_streaks`
   either, so the `migrate` path could not create the table OPEN-52 added;
   `AddRequestRules` adds both.
 * The console gate banned its own probe address. The seed sets the streak
   threshold to 3 and the gate probes 404 paths, so the last assertion in the new
   scene read a `blocked_by_policy` as "the rule is still in force" — and the
   ban, unlike the rule, outlives `compose down` in the data volume. The scene
   probes its own address now and the cleanup clears engine bans.

Measured on this tree: build 0 warnings / 0 errors, unit 195/195 (44 new: the
glob's semantics and rejections, and where the new pillar sits in the order),
integration 208/208 in 25 s (14 new, including a fixture that drops the rules
table and asserts the operator block is still enforced), smoke 36/0 (7 new
against a running edge), console 85 assertions 0 failed (6 new, driving the rule
form in a real browser), compose 209/0 against the built image at 261 MB.
2026-10-04 19:48:52 +02:00

201 lines
8.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>Whether the last refresh could read the request-rule table.
/// False means the edge is enforcing everything except the rules, and says
/// so — see <see cref="RefreshAsync"/>.</summary>
public bool RulesAvailable { get; private set; } = true;
/// <summary>Why the rules could not be read, for the operator surface.</summary>
public string? RulesError => Volatile.Read(ref _rulesError);
private string? _rulesError;
/// <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);
// 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<RequestRule> 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(ct);
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.");
}
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,
RequestRules = rules
};
}
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();
}
}
}