Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs
T
Pavlo Ratushnyi 7beaa7e463 a source's request budget can be written for one path
The edge-wide budget is one number for the whole site, and for a login path that
number is always wrong: a hundred requests a minute does not stop a
credential-stuffing run that makes twenty attempts a minute — twenty looks like
a person — while five a minute locks an honest office behind one NAT out of every
page they own. The only way to make both statements true is to price the paths
differently.

The rulings this had to make, and the answer each one got:

* A rate rule is not a path rule. A path rule refuses a request because of what
  it asked for; a budget refuses it because of how often that source asked. The
  pattern language is shared because the thing being described — this path and
  what hangs off it — is the same.
* Crossing a budget writes no engine ban. The claim is about one path, so a ban
  would refuse the rest of the site as punishment for a login-page rate. The
  answer is 429 with Retry-After for the rest of that source's window, and the
  reason names the rule, its count, its limit and the pattern it was written for.
* The counters are a separate tracker, not a scope inside RateTracker. The
  edge-wide counter reads its limit and window from the policy; a rule carries
  its own. One map whose parameters change per entry is a map whose eviction and
  idle rules stop meaning anything.
* The budgets hang off rateMode rather than getting a switch of their own:
  Enforce refuses, Observe counts and raises one rate_breach alert per source per
  window naming the pattern, Off counts nothing at all. A half-counting edge is
  the state an operator cannot reason about.
* A second live budget for one pattern is a 409 — two live numbers for one path
  mean the stricter one wins by accident rather than by the operator's choice.
* The bounds are the policy's own (1..100000 requests, 1..3600 seconds), so one
  vocabulary of numbers covers both budgets and a document cannot bring in a
  budget the API would have refused.
* The listing answers with three counters — sources counted, windows running,
  over budget now — because "nobody has blown this" and "nobody can" look
  identical on paper and are different decisions.

What the runs caught, in order:

* The smoke scene first ran on 198.51.100.0/24, which an earlier scene of the
  same gate allowlists. An allowlisted source never reaches the counter, so the
  scene would have printed a row of 200s while measuring nothing. It runs on
  TEST-NET-1 now.
* The console scene drew three 404s of its own and the streak pillar banned the
  address, so the reopen assertion read the streak's 403 instead of the absence
  of the budget. The engine list is cleared before that probe and the comment
  says which pillar the clearing belongs to.
* The compose assertion compared a JSON boolean against the word "yes".
* The change-log vocabulary test still listed six sections; there are seven now.
* A unit expectation counted requests where the tracker holds windows: one
  (rule, source) pair is one window, and the count inside it is what the budget
  is measured against.

Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit
361/361, integration 337/337 in 30 s, console 120 assertions 0 failed, smoke
passed 169 failed 0, compose 300 passed 0 failed against the built image at
262 MB, 0 containers left behind.

Refs OPEN-68.
2026-10-05 08:40:58 +02:00

262 lines
12 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>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.</summary>
public bool RangesAvailable { get; private set; } = true;
public string? RangesError => Volatile.Read(ref _rangesError);
/// <summary>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.</summary>
public bool RateRulesAvailable { get; private set; } = true;
public string? RateRulesError => Volatile.Read(ref _rateRulesError);
private string? _rateRulesError;
private string? _rangesError;
/// <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.");
}
// 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<RateRule> rateRules;
try
{
rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(ct);
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<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;
}
// 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(ct));
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<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,
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();
}
}
}