The budget listing has carried three numbers per budget since OPEN-68 — sources
counted, windows running, over budget now — and no name. "3 over budget" is the
half an operator cannot act on, and the only lever for one of those three was
`DELETE /admin-api/rate-rules/{id}`: take the budget off every source on the site
to release one office behind one NAT. The edge-wide budget never had this hole,
because /admin-api/rate names its sources.
* GET /admin-api/rate-rules/{id}/sources — who this budget is inside right now:
sourceKey, count against the limit, when the window ends and how many seconds
are left, overBudget. Busiest first, live windows only, paged with
X-Total-Count / X-Truncated like every other listing. `total` is the same
number the listing's `liveWindows` reports and the over-budget count matches
`overBudgetNow`: the names come from the same state as the three counters,
not from a second ledger.
* DELETE /admin-api/rate-rules/{id}/sources?source=<key> — drop one source's
window on one budget. Not an exemption, and the answer says so: the window
restarts at zero and the budget counts this source again from there, while
every other source stays paused. An operator who types an address gets the
key this edge files it under, and the answer names the key it dropped,
because the others sharing it are still paused. A second clear answers
`cleared: false` and writes no second record; the first is in the change log
under `rate rule / changed`.
* Console: a `who` button per budget row, and a `let out` button per source.
Rulings kept: the entries are source keys with the prefix rule printed beside
them (a /24 in the list is the point, not a bug); the limit is passed in from the
rule row rather than copied into the counter, so one number is enforced once;
reading spends nothing, so the page that exists to show a pause cannot cause one;
an empty list says which kind of empty it is — "counting, nobody inside a window"
and "this budget has expired" are different answers; and the read-only token gets
a 403 on the clear, not a 401, because the token is known and its level is the
answer.
What the run caught, on this tree: two console scenes failed with `answered 403`
because the gate's own probes are refusals and the streak pillar had banned the
probe addresses — a correct edge, and a scene that cannot retry past a one-hour
ban. Both now clear that one ban by name, leaving the engine bans the netblock
scene reads standing. The first run of the feature also caught the clear
reporting `cleared: false` after actually dropping the window: the derived-key
branch dropped the state and never set the flag.
build 0 warnings / 0 errors, unit 377/377, integration 365/365 in 31 s,
console 129 assertions / 0 failed, smoke passed 202 / failed 0, compose 317
passed / 0 failed against the built image at 262 MB.
Refs OPEN-71.
374 lines
15 KiB
C#
374 lines
15 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>What the counters already say about one source for one rule,
|
|
/// without moving them. The dry run (OPEN-69) has to be able to ask "is this
|
|
/// source over its path budget right now" — and a preview that answered by
|
|
/// counting the question itself would spend the budget it is asking about, so
|
|
/// the next real request would be refused because someone pressed a button.
|
|
/// Null means there is no running window for this pair: not "zero requests",
|
|
/// which is a different answer and the one an operator acts on differently.</summary>
|
|
public RuleRateObservation? Peek(RateRule rule, string sourceKey, DateTimeOffset now)
|
|
{
|
|
if (string.IsNullOrEmpty(sourceKey)) return null;
|
|
lock (_gate)
|
|
{
|
|
if (!_states.TryGetValue((rule.Id, sourceKey), out var state)) return null;
|
|
var end = state.WindowStart + state.WindowLength;
|
|
if (now >= end) return null;
|
|
return new RuleRateObservation(
|
|
state.Count,
|
|
rule.LimitPerWindow > 0 && state.Count > rule.LimitPerWindow,
|
|
state.WindowStart, end,
|
|
// A peek has no crossing: the crossing is an event on a counted
|
|
// request, and this call counts nothing.
|
|
BreachStarted: false);
|
|
}
|
|
}
|
|
|
|
/// <summary>Every rule this source currently has a running window on, without
|
|
/// moving a single counter. The source dossier (OPEN-70) needs it because it
|
|
/// answers "what does this edge know about this address" without being handed
|
|
/// a path: <see cref="Peek"/> is aimed at one rule and the preview's path
|
|
/// matcher is aimed at one path, and a dossier that had neither would have to
|
|
/// say "no path budgets" for a source that is three requests from a 429.
|
|
///
|
|
/// Live windows only, for the same reason the preview lists only live ones: a
|
|
/// window that has already run out restarts at zero, and "2 of 20" read off a
|
|
/// dead window is a different claim from "2 of 20". The rule's limit is not
|
|
/// here — the caller holds the rule and its own limit, and a limit copied into
|
|
/// this row is a second number that can disagree with the first.</summary>
|
|
public IReadOnlyList<RuleWindowObservation> WindowsFor(string sourceKey, DateTimeOffset now)
|
|
{
|
|
if (string.IsNullOrEmpty(sourceKey)) return [];
|
|
lock (_gate)
|
|
{
|
|
List<RuleWindowObservation>? rows = null;
|
|
foreach (var s in _states.Values)
|
|
{
|
|
if (!string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal)) continue;
|
|
var end = s.WindowStart + s.WindowLength;
|
|
if (now >= end) continue;
|
|
rows ??= [];
|
|
rows.Add(new RuleWindowObservation(
|
|
s.Rule, s.Count, s.WindowStart, end, (int)s.WindowLength.TotalSeconds));
|
|
}
|
|
if (rows is null) return [];
|
|
rows.Sort((a, b) => a.RuleId.CompareTo(b.RuleId));
|
|
return rows;
|
|
}
|
|
}
|
|
|
|
/// <summary>The sources one budget is currently holding a window for, busiest
|
|
/// first, with what each window says right now (OPEN-71).
|
|
///
|
|
/// The listing has shown three numbers per budget since OPEN-68 — sources
|
|
/// counted, windows running, over budget now — and no name. "3 over budget"
|
|
/// is the half an operator cannot act on: the only lever for one of those
|
|
/// three was to delete the budget for the whole site. The edge-wide budget
|
|
/// never had this hole, because <see cref="RateTracker.LiveRates"/> names its
|
|
/// sources.
|
|
///
|
|
/// The limit travels in as an argument rather than being stored with the
|
|
/// window, so there is exactly one copy of the number a budget enforces: the
|
|
/// row's. A second copy inside the counter is a second number that can
|
|
/// disagree with the first, and the disagreement would be invisible.
|
|
///
|
|
/// Live windows only, and nothing is spent: this is the same state the guard
|
|
/// reads, read without moving it.</summary>
|
|
public IReadOnlyList<RuleSourceWindow> SourcesFor(
|
|
long ruleId, int limitPerWindow, DateTimeOffset now, int limit, int offset)
|
|
{
|
|
var take = Math.Max(1, limit);
|
|
var skip = Math.Max(0, offset);
|
|
lock (_gate)
|
|
{
|
|
List<RuleSourceWindow>? rows = null;
|
|
foreach (var s in _states.Values)
|
|
{
|
|
if (s.Rule != ruleId) continue;
|
|
var end = s.WindowStart + s.WindowLength;
|
|
if (now >= end) continue;
|
|
rows ??= [];
|
|
rows.Add(new RuleSourceWindow(
|
|
s.SourceKey, s.Count,
|
|
limitPerWindow > 0 && s.Count > limitPerWindow,
|
|
s.WindowStart, end));
|
|
}
|
|
if (rows is null) return [];
|
|
// Busiest first: the source nearest a refusal is the one an operator
|
|
// reads about, and a stable tie-break on the key keeps two calls
|
|
// showing the same order across a page boundary.
|
|
rows.Sort((a, b) => b.Count != a.Count
|
|
? b.Count.CompareTo(a.Count)
|
|
: string.CompareOrdinal(a.SourceKey, b.SourceKey));
|
|
return rows.Skip(skip).Take(take).ToList();
|
|
}
|
|
}
|
|
|
|
/// <summary>How many live windows this budget holds — the same count the
|
|
/// listing's <c>windowsRunning</c> reports, so a paged source list can say
|
|
/// whether it is complete.</summary>
|
|
public int LiveWindowCount(long ruleId, DateTimeOffset now)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
var n = 0;
|
|
foreach (var s in _states.Values)
|
|
{
|
|
if (s.Rule != ruleId) continue;
|
|
if (now >= s.WindowStart + s.WindowLength) continue;
|
|
n++;
|
|
}
|
|
return n;
|
|
}
|
|
}
|
|
|
|
/// <summary>Drop one source's window on one budget: the control for "my office
|
|
/// is caught by the login budget, let them through" that is not "delete the
|
|
/// budget for every source on the site" (OPEN-71).
|
|
///
|
|
/// What it is not, stated because the difference is the whole point: it is not
|
|
/// an exemption. The window restarts at zero on the next request, and the
|
|
/// budget starts counting this source again from there — an exemption is the
|
|
/// allowlist, which outranks every pillar. True means a window was dropped;
|
|
/// false means there was none to drop, which is a different answer from
|
|
/// "the source is not being paused".</summary>
|
|
public bool ForgetRuleSource(long ruleId, string sourceKey)
|
|
{
|
|
if (string.IsNullOrEmpty(sourceKey)) return false;
|
|
lock (_gate)
|
|
{
|
|
if (!_states.Remove((ruleId, sourceKey), out var s)) return false;
|
|
RemoveNode(s);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
|
|
/// <summary>One running window this source holds on one rule, as counted by this
|
|
/// process. No limit and no over-budget flag: the caller has the rule.</summary>
|
|
public sealed record RuleWindowObservation(
|
|
long RuleId,
|
|
int Count,
|
|
DateTimeOffset WindowStart,
|
|
DateTimeOffset WindowEnd,
|
|
int WindowSeconds);
|
|
|
|
/// <summary>One source inside one budget right now: what it has spent, whether
|
|
/// that is past the limit, and when its window ends.</summary>
|
|
public sealed record RuleSourceWindow(
|
|
string SourceKey,
|
|
int Count,
|
|
bool OverBudget,
|
|
DateTimeOffset WindowStart,
|
|
DateTimeOffset WindowEnd);
|