Every defence this edge had reads something that already happened: the status the application answered, the country the address sits in, a list a human wrote. A source asking for a cheap path two hundred times a minute produces no refusal, so no streak matures, no path rule names it, and the origin serves all two hundred. The only signal is the count, and a count has to be kept while the requests are arriving — which is why this pillar is the one piece of live state on the request path, and why it runs after the ordered decision instead of inside it. `rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds` (policy_settings, so no schema change). Off is the default: a limit nobody wrote is a defence nobody asked for, and a false positive here locks out a whole office behind one address. `observe` counts and raises one `rate_breach` alert per source per window. `enforce` answers the request that crosses with 429 + Retry-After — the surplus never reaches the origin — and writes an engine ban, so the stop outlives the window, is shared with the other edges and survives a restart; from then on the answer is the ban's own 403. One breach, one alert, one ban write per source per window: a flood is exactly the traffic that turns a per-request durable write into the thing that takes the database down. Exempt by construction rather than by a second copy of the precedence rules: the counter runs only on a plain Pass, so an always-pass prefix, an allowlisted address, a matched rule, a block or a geo refusal never reaches it. The budget counts exactly the requests that would have cost the origin. Costs, stated rather than hidden: the counter is per process, so N edges allow N times the budget (the same trade `SharedStreaks` made for the streak, at a round trip per request instead of per observed response); the window is fixed, not sliding, so the worst sustained rate is twice the limit across one boundary — a sliding counter needs one entry per request, which is a map that grows at attack rate. Two things the run caught rather than the design assumed: * The guard wrote the 429 and then called next() anyway, so YARP answered "the request cannot be forwarded, the response has already started". The pillar now says whether the request may go through. * `StreakTracker.Configure` was called by nobody outside its own tests, so `maxTrackedSources` bounded nothing in a running edge — the map grew to the built-in 10000 whatever the operator had asked for. Both maps are configured at warm-up and on a policy write now. And the smoke gate was not testing what its first line says. The edge was started from the repository root, where there is no appsettings.json, so it loaded no ReverseProxy section at all, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, and answered 404 for a path the upstream was serving with 200. Every assertion in the file expects a 404 or a refusal, so the gate kept passing on an edge that never proxied anything. Naming the content root fixes it; the streak scene also waits for the ban row to exist before asking the wire whether it is enforced, because the ban is written out of band after the response that proved it. Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219 in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209 passed 0 failed, image 261 MB. OPEN-56
252 lines
9.2 KiB
C#
252 lines
9.2 KiB
C#
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Domain.Engine;
|
|
|
|
/// <summary>
|
|
/// The volume counter (OPEN-56): how often one source asked, inside a window
|
|
/// that started when that source first asked.
|
|
///
|
|
/// This is the pillar the rest of the edge cannot give, because every other
|
|
/// one reads something that already happened — the status the origin answered,
|
|
/// the country the address sits in, a list a human wrote. A source that asks
|
|
/// for a cheap path two hundred times a minute produces no refusal, so no
|
|
/// streak matures and the origin serves all two hundred. The only signal is the
|
|
/// count itself, and a count has to be kept somewhere while the requests are
|
|
/// arriving. That is what this is: the one piece of live state on the request
|
|
/// path, next to the snapshot the other pillars read.
|
|
///
|
|
/// Two protections, both copied from <see cref="StreakTracker"/> because they
|
|
/// are the same problem:
|
|
/// * <b>Bounded memory.</b> At most <see cref="EdgePolicy.MaxTrackedSources"/>
|
|
/// sources are held, least-recently-touched evicted first, idle sources aged
|
|
/// out. A scanner farm with a fresh address per request cannot grow the
|
|
/// process.
|
|
/// * <b>No I/O.</b> The counters are in this process. The consequence is
|
|
/// stated in the README rather than hidden: the budget is per edge, so N
|
|
/// edges behind a load balancer allow N times the budget. The ban a breach
|
|
/// writes is shared, so the stop is the fleet's even when the counting is
|
|
/// not.
|
|
///
|
|
/// A fixed window, not a sliding one. A sliding counter needs one entry per
|
|
/// request, which is a map that grows at attack rate — the exact shape this
|
|
/// class exists to avoid. The cost of a fixed window is the documented edge
|
|
/// case: a source can spend the whole budget at the end of one window and the
|
|
/// whole budget again at the start of the next, so the worst sustained rate is
|
|
/// twice the limit across one boundary. A limit of 100/60s can therefore let
|
|
/// 200 through in 60 seconds straddling the seam. Accepted, and named, because
|
|
/// the alternative is unbounded memory.
|
|
/// </summary>
|
|
public sealed class RateTracker
|
|
{
|
|
private readonly object _gate = new();
|
|
private readonly Dictionary<string, RateState> _states = new(StringComparer.Ordinal);
|
|
private readonly LinkedList<string> _lru = new();
|
|
|
|
// Read from the policy once per configuration change so the hot path never
|
|
// dereferences the policy record for a bound. Same trick, same reason as
|
|
// StreakTracker.MaxCap.
|
|
private int _maxCap = 10_000;
|
|
|
|
public void Configure(EdgePolicy policy) => _maxCap = Math.Max(1, policy.MaxTrackedSources);
|
|
|
|
/// <summary>
|
|
/// Count one request and say what the budget now thinks of this source.
|
|
/// </summary>
|
|
public RateObservation Record(string sourceKey, EdgePolicy policy, DateTimeOffset now)
|
|
{
|
|
if (string.IsNullOrEmpty(sourceKey))
|
|
return new RateObservation(0, false, now, now, false);
|
|
|
|
var window = policy.RateWindow > TimeSpan.Zero ? policy.RateWindow : TimeSpan.FromMinutes(1);
|
|
var limit = policy.RateLimitPerWindow;
|
|
|
|
lock (_gate)
|
|
{
|
|
var state = GetOrCreate(sourceKey, now);
|
|
Touch(state);
|
|
state.LastSeenAt = now;
|
|
|
|
// The window starts at this source's first request, not on a global
|
|
// clock. A global epoch would make every source that arrives just
|
|
// after the boundary share one short window, which turns the limit
|
|
// into a lottery on arrival time.
|
|
if (state.Count == 0 || now >= state.WindowStart + window)
|
|
{
|
|
state.WindowStart = now;
|
|
state.Count = 0;
|
|
}
|
|
|
|
state.Count++;
|
|
var end = state.WindowStart + window;
|
|
var over = limit > 0 && state.Count > limit;
|
|
|
|
return new RateObservation(
|
|
state.Count, over, state.WindowStart, end,
|
|
// Exactly one request per window gets to be the one that says
|
|
// so: the one that crossed. Everything after it in the same
|
|
// window is the same news, and an alert or a ban write per
|
|
// request is how a defence becomes a write-amplification bug.
|
|
BreachStarted: over && state.Count == limit + 1);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// What is being counted right now, biggest first. A window that has
|
|
/// already run out is left out: it is about to restart at zero, and an
|
|
/// operator reading this is looking for the source that is over budget
|
|
/// now, not for a record of everyone who ever asked.
|
|
/// </summary>
|
|
public IReadOnlyList<LiveRate> LiveRates(
|
|
DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int liveTotal)
|
|
=> LiveRates(now, policy, limit, offset, null, out liveTotal);
|
|
|
|
public IReadOnlyList<LiveRate> LiveRates(
|
|
DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey,
|
|
out int liveTotal)
|
|
{
|
|
var take = Math.Max(1, limit);
|
|
var skip = Math.Max(0, offset);
|
|
var window = policy.RateWindow > TimeSpan.Zero ? policy.RateWindow : TimeSpan.FromMinutes(1);
|
|
|
|
lock (_gate)
|
|
{
|
|
EvictIdle(now, policy);
|
|
var list = new List<LiveRate>();
|
|
foreach (var s in _states.Values)
|
|
{
|
|
if (sourceKey is not null
|
|
&& !string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal))
|
|
continue;
|
|
var end = s.WindowStart + window;
|
|
if (now >= end) continue;
|
|
list.Add(new LiveRate(s.SourceKey, s.Count, s.WindowStart, end,
|
|
policy.RateLimitPerWindow > 0 && s.Count > policy.RateLimitPerWindow));
|
|
}
|
|
// The total is the filtered set, so a page that shows one address
|
|
// cannot claim the whole map's counts — the rule every other listing
|
|
// in this project already learned.
|
|
liveTotal = list.Count;
|
|
return list
|
|
.OrderByDescending(x => x.Count)
|
|
.ThenByDescending(x => x.WindowStart)
|
|
.Skip(skip)
|
|
.Take(take)
|
|
.ToList();
|
|
}
|
|
}
|
|
|
|
public int TrackedCount
|
|
{
|
|
get { lock (_gate) return _states.Count; }
|
|
}
|
|
|
|
/// <summary>Stop counting one source — used when an operator clears it, and
|
|
/// by the tests that need a known-empty map.</summary>
|
|
public void Forget(string sourceKey)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_states.Remove(sourceKey, out var s)) RemoveNode(s);
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_states.Clear();
|
|
_lru.Clear();
|
|
}
|
|
}
|
|
|
|
private RateState GetOrCreate(string sourceKey, DateTimeOffset now)
|
|
{
|
|
if (_states.TryGetValue(sourceKey, out var existing)) return existing;
|
|
|
|
// Before insertion, so the cap is a cap and not a target the map
|
|
// drifts past.
|
|
while (_states.Count >= _maxCap) RemoveOldest();
|
|
|
|
var created = new RateState
|
|
{
|
|
SourceKey = sourceKey,
|
|
WindowStart = now,
|
|
Count = 0,
|
|
LastSeenAt = now
|
|
};
|
|
_states[sourceKey] = created;
|
|
created.LruNode = _lru.AddLast(sourceKey);
|
|
return created;
|
|
}
|
|
|
|
private void Touch(RateState state)
|
|
{
|
|
if (state.LruNode is null) return;
|
|
_lru.Remove(state.LruNode);
|
|
state.LruNode = _lru.AddLast(state.SourceKey);
|
|
}
|
|
|
|
private void RemoveOldest()
|
|
{
|
|
var oldest = _lru.First;
|
|
if (oldest is null) return;
|
|
_lru.RemoveFirst();
|
|
_states.Remove(oldest.Value);
|
|
}
|
|
|
|
private void RemoveNode(RateState s)
|
|
{
|
|
if (s.LruNode is not null)
|
|
{
|
|
_lru.Remove(s.LruNode);
|
|
s.LruNode = null;
|
|
}
|
|
}
|
|
|
|
private void EvictIdle(DateTimeOffset now, EdgePolicy policy)
|
|
{
|
|
if (_states.Count == 0) return;
|
|
List<string>? stale = null;
|
|
foreach (var kv in _states)
|
|
{
|
|
if (now - kv.Value.LastSeenAt > policy.StateIdleTtl)
|
|
{
|
|
stale ??= [];
|
|
stale.Add(kv.Key);
|
|
}
|
|
}
|
|
if (stale is null) return;
|
|
foreach (var key in stale)
|
|
{
|
|
if (_states.Remove(key, out var s)) RemoveNode(s);
|
|
}
|
|
}
|
|
}
|
|
|
|
internal sealed class RateState
|
|
{
|
|
public required string SourceKey { get; init; }
|
|
public DateTimeOffset WindowStart { get; set; }
|
|
public int Count { get; set; }
|
|
public DateTimeOffset LastSeenAt { get; set; }
|
|
public LinkedListNode<string>? LruNode { get; set; }
|
|
}
|
|
|
|
/// <summary>What one counted request says about its source's budget.</summary>
|
|
public sealed record RateObservation(
|
|
int Count,
|
|
bool OverBudget,
|
|
DateTimeOffset WindowStart,
|
|
DateTimeOffset WindowEnd,
|
|
/// <summary>True on exactly the request that crossed the budget in this
|
|
/// window — the one allowed to raise the alert and write the ban.</summary>
|
|
bool BreachStarted);
|
|
|
|
/// <summary>One source's live window, as the operator reads it.</summary>
|
|
public sealed record LiveRate(
|
|
string SourceKey,
|
|
int Count,
|
|
DateTimeOffset WindowStart,
|
|
DateTimeOffset WindowEnd,
|
|
bool OverBudget);
|