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.
212 lines
7.4 KiB
C#
212 lines
7.4 KiB
C#
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Domain.Engine;
|
|
|
|
/// <summary>
|
|
/// The per-path budgets (OPEN-68): how often one source asked for one rule's
|
|
/// paths, inside a window that started when that source first asked.
|
|
///
|
|
/// A separate counter from <see cref="RateTracker"/> rather than a scope inside
|
|
/// it, for two reasons. The edge-wide counter reads its limit and window from the
|
|
/// policy, and a rule carries its own — one map whose parameters change per
|
|
/// entry is a map whose eviction and idle rules stop meaning anything. And the
|
|
/// operator's rate listing answers "who is over the site's budget"; a rule's
|
|
/// counters are a different question and should not appear in that answer with a
|
|
/// composite key the operator cannot read.
|
|
///
|
|
/// The same two protections as the edge-wide counter, because they are the same
|
|
/// problem: bounded memory (at most <see cref="EdgePolicy.MaxTrackedSources"/>
|
|
/// source-and-rule pairs, least-recently-touched evicted first, idle sources aged
|
|
/// out) and no I/O. The consequence is stated where it is read: the counters are
|
|
/// per edge, so N edges allow N times the budget.
|
|
///
|
|
/// Fixed windows, same trade as the edge-wide counter, same documented seam.
|
|
/// </summary>
|
|
public sealed class RateRuleTracker
|
|
{
|
|
private readonly object _gate = new();
|
|
private readonly Dictionary<(long Rule, string Source), RuleRateState> _states = new();
|
|
private readonly LinkedList<(long Rule, string Source)> _lru = new();
|
|
private int _maxCap = 10_000;
|
|
|
|
public void Configure(EdgePolicy policy) => _maxCap = Math.Max(1, policy.MaxTrackedSources);
|
|
|
|
/// <summary>Count one request against one rule and say what its budget now
|
|
/// thinks of this source.</summary>
|
|
public RuleRateObservation Record(
|
|
RateRule rule, string sourceKey, DateTimeOffset now)
|
|
{
|
|
if (string.IsNullOrEmpty(sourceKey))
|
|
return new RuleRateObservation(0, false, now, now, false);
|
|
|
|
var window = rule.Window;
|
|
var key = (rule.Id, sourceKey);
|
|
|
|
lock (_gate)
|
|
{
|
|
if (!_states.TryGetValue(key, out var state))
|
|
{
|
|
while (_states.Count >= _maxCap) RemoveOldest();
|
|
state = new RuleRateState
|
|
{
|
|
Rule = rule.Id,
|
|
SourceKey = sourceKey,
|
|
WindowStart = now,
|
|
Count = 0,
|
|
LastSeenAt = now
|
|
};
|
|
_states[key] = state;
|
|
state.LruNode = _lru.AddLast(key);
|
|
}
|
|
|
|
Touch(key, state);
|
|
state.LastSeenAt = now;
|
|
// The window length travels with the state, so the listing can say
|
|
// when a window ends without being handed the rule again.
|
|
state.WindowLength = window;
|
|
|
|
if (state.Count == 0 || now >= state.WindowStart + window)
|
|
{
|
|
state.WindowStart = now;
|
|
state.Count = 0;
|
|
}
|
|
|
|
state.Count++;
|
|
var end = state.WindowStart + window;
|
|
var over = rule.LimitPerWindow > 0 && state.Count > rule.LimitPerWindow;
|
|
|
|
return new RuleRateObservation(
|
|
state.Count, over, state.WindowStart, end,
|
|
// Exactly one request per window is the one that crossed, and
|
|
// only it may alert. Same ruling as the edge-wide budget: an
|
|
// alert per request is how a defence becomes write amplification.
|
|
BreachStarted: over && state.Count == rule.LimitPerWindow + 1);
|
|
}
|
|
}
|
|
|
|
/// <summary>The two numbers the listing shows beside a rule: how many sources
|
|
/// still have a running window for it, and how many of those are over the
|
|
/// budget right now. Counted in one lock, so the pair cannot describe two
|
|
/// different moments — "nothing is over it" next to "nobody is being counted"
|
|
/// is the reading that decides whether a budget is worth keeping.</summary>
|
|
public (int LiveWindows, int OverBudgetNow) LiveCounts(
|
|
long ruleId, int limitPerWindow, DateTimeOffset now)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
var live = 0;
|
|
var over = 0;
|
|
foreach (var s in _states.Values)
|
|
{
|
|
if (s.Rule != ruleId) continue;
|
|
if (now >= s.WindowStart + s.WindowLength) continue;
|
|
live++;
|
|
if (limitPerWindow > 0 && s.Count > limitPerWindow) over++;
|
|
}
|
|
return (live, over);
|
|
}
|
|
}
|
|
|
|
/// <summary>How many sources this rule is holding a window for, live or not —
|
|
/// the number that says whether the rule is counting anything at all.</summary>
|
|
public int TrackedCount(long ruleId)
|
|
{
|
|
lock (_gate) return _states.Count(s => s.Key.Rule == ruleId);
|
|
}
|
|
|
|
/// <summary>A rule was removed: its counters go with it. Leaving them would
|
|
/// keep counting for a budget the operator took off the edge.</summary>
|
|
public void ForgetRule(long ruleId)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
List<(long, string)>? doomed = null;
|
|
foreach (var kv in _states)
|
|
{
|
|
if (kv.Key.Rule != ruleId) continue;
|
|
doomed ??= [];
|
|
doomed.Add(kv.Key);
|
|
}
|
|
if (doomed is null) return;
|
|
foreach (var key in doomed)
|
|
{
|
|
if (_states.Remove(key, out var s)) RemoveNode(s);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>An operator allowlisted or cleared a source: stop holding its
|
|
/// windows, on every rule.</summary>
|
|
public void ForgetSource(string sourceKey)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
List<(long, string)>? doomed = null;
|
|
foreach (var kv in _states)
|
|
{
|
|
if (!string.Equals(kv.Value.SourceKey, sourceKey, StringComparison.Ordinal)) continue;
|
|
doomed ??= [];
|
|
doomed.Add(kv.Key);
|
|
}
|
|
if (doomed is null) return;
|
|
foreach (var key in doomed)
|
|
{
|
|
if (_states.Remove(key, out var s)) RemoveNode(s);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_states.Clear();
|
|
_lru.Clear();
|
|
}
|
|
}
|
|
|
|
private void Touch((long, string) key, RuleRateState state)
|
|
{
|
|
if (state.LruNode is null) return;
|
|
_lru.Remove(state.LruNode);
|
|
state.LruNode = _lru.AddLast(key);
|
|
}
|
|
|
|
private void RemoveOldest()
|
|
{
|
|
var oldest = _lru.First;
|
|
if (oldest is null) return;
|
|
_lru.RemoveFirst();
|
|
_states.Remove(oldest.Value);
|
|
}
|
|
|
|
private void RemoveNode(RuleRateState s)
|
|
{
|
|
if (s.LruNode is not null)
|
|
{
|
|
_lru.Remove(s.LruNode);
|
|
s.LruNode = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
internal sealed class RuleRateState
|
|
{
|
|
public required long Rule { get; init; }
|
|
public required string SourceKey { get; init; }
|
|
public DateTimeOffset WindowStart { get; set; }
|
|
public int Count { get; set; }
|
|
public DateTimeOffset LastSeenAt { get; set; }
|
|
public TimeSpan WindowLength { get; set; } = TimeSpan.FromMinutes(1);
|
|
public LinkedListNode<(long Rule, string Source)>? LruNode { get; set; }
|
|
}
|
|
|
|
/// <summary>What one counted request says about one source's budget for one rule.</summary>
|
|
public sealed record RuleRateObservation(
|
|
int Count,
|
|
bool OverBudget,
|
|
DateTimeOffset WindowStart,
|
|
DateTimeOffset WindowEnd,
|
|
bool BreachStarted);
|