a source that asks too often is stopped, even when the origin keeps answering
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
This commit is contained in:
@@ -27,6 +27,7 @@ the design, not a side effect of registration order:
|
||||
| 4 | **operator block** (`source=operator`) | 301 to `RedirectTo`, else a honey-pot list | never expires |
|
||||
| 5 | **engine ban** (`source=engine`) | 403 + `Retry-After` + a reason | expires on its own |
|
||||
| 6 | **geo policy** (deny list / allow list) | 451 + a note that says the inference is probabilistic | policy, not data |
|
||||
| 7 | **request budget** (OPEN-56) — N requests per source per window; `observe` or `enforce` | 429 + `Retry-After` for the rest of the window, then an engine ban | counted in this process, window restarts on its own |
|
||||
|
||||
The request rule is the only pillar that looks at the request rather than at
|
||||
what the upstream answered or who sent it. Before it, a known-bad request always
|
||||
@@ -42,6 +43,24 @@ it blocks anything; `block` refuses in `Observe` mode too, because the mode
|
||||
switches off what the edge decides by itself, not what a human wrote down — the
|
||||
same ruling that keeps an operator block live.
|
||||
|
||||
The budget is the pillar about *how often*, and it runs last — after every
|
||||
other pillar has already answered — because it is the only one that needs live
|
||||
state rather than the snapshot: a count has to be kept while the requests are
|
||||
arriving. Sitting below the whole ordered list is also what makes its exemptions
|
||||
exact. An always-pass prefix, an allowlisted address, a matched rule, a block or
|
||||
a geo refusal never reaches the counter, so the budget counts exactly the
|
||||
requests that would have cost the origin.
|
||||
|
||||
It exists because every other defence reads something that already happened. A
|
||||
source asking for a cheap path two hundred times a minute produces no refusal,
|
||||
so no streak matures, no rule names it, and the application serves all two
|
||||
hundred. `observe` counts and raises one `rate_breach` alert per source per
|
||||
window; `enforce` answers the request that crosses with **429 + `Retry-After`**
|
||||
and writes an engine ban, so the stop outlives the window, is visible on the
|
||||
blocks listing, and is shared with the other edges. The 429 is the answer while
|
||||
the window is running; once the ban lands the answer is the ban's own 403. The
|
||||
budget is off until an operator writes one.
|
||||
|
||||
A second middleware, `ResponseObservationMiddleware`, sits *inside* the guard:
|
||||
it awaits the upstream, classifies the status the application actually returned,
|
||||
and feeds a streak counter. Being inside the guard is load-bearing — a refusal
|
||||
@@ -156,6 +175,9 @@ runtime through `PUT /admin-api/policy`, which persists to `policy_settings`.
|
||||
| `Ipv4KeyPrefixLength` / `Ipv6KeyPrefixLength` | `32` / `64` | source-key granularity |
|
||||
| `EngineBlockStatus` / `OperatorBlockStatus` | `403` / `301` | what a block answers |
|
||||
| `DefaultRedirectTargets` | iana example | honey-pot targets for operator blocks |
|
||||
| `Rate` | `Off` | the volume budget: `Off` / `Observe` / `Enforce` (OPEN-56) |
|
||||
| `RateLimitPerWindow` | `100` | requests one source may make per window |
|
||||
| `RateWindowSeconds` | `60` | how long that budget lasts |
|
||||
|
||||
A `PUT` whose value is outside its range is a **400 that names the key and the
|
||||
range**, not a 200 that quietly keeps the old value. Both halves of that matter,
|
||||
@@ -181,6 +203,9 @@ addresses were refused on their first request.
|
||||
| `engineBlockStatus` | 400–599 | a block must answer with a status that means blocked |
|
||||
| `operatorBlockStatus` | 301 or 400–599 | 301 is the redirect; any other 3xx is a redirect with no Location |
|
||||
| `refusalRange` / `serverErrorRange` | `low-high` inside 100–599 | a range matching nothing is a pillar switched off by a typo |
|
||||
| `rateMode` | `off` / `observe` / `enforce` | 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 |
|
||||
| `rateLimitPerWindow` | 1–100000 | 0 is not "no limit" — that is `rateMode: Off`; past 100000 the pillar is switched off by arithmetic while still reading Enforce |
|
||||
| `rateWindowSeconds` | 1–3600 | below a second the counter is stale before it is read (the snapshot TTL is 30 s); past an hour it is a quota, and the lever for a longer sentence is `banDurationMinutes` |
|
||||
| `defaultRedirectTargets` | absolute http(s) URLs | they are written into a `Location` header |
|
||||
|
||||
Two more layers for a value that arrives without the API — a restored backup, a
|
||||
@@ -293,7 +318,8 @@ GET /admin-api/allow?live[=false]&limit&offset POST {"match","note","expire
|
||||
GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…}
|
||||
GET /admin-api/observations per-source streaks, durable — the maximum ever seen
|
||||
GET /admin-api/streaks the streak standing right now, in this process, with the threshold
|
||||
GET /admin-api/alerts server_error_streak | candidate_ban | rule_match
|
||||
GET /admin-api/alerts server_error_streak | candidate_ban | rule_match | rate_breach
|
||||
GET /admin-api/rate what the volume counter holds right now, biggest first
|
||||
GET /admin-api/rules path patterns, in the order they are enforced
|
||||
POST {"pattern","action":"observe|block","note","expiresInMinutes"}
|
||||
DELETE /admin-api/rules/{id}
|
||||
@@ -674,7 +700,12 @@ restored backup or a hand edit.
|
||||
live bans with their reasons, the streak standing in this process right now
|
||||
(current count against the threshold, not the historical maximum), the sources
|
||||
being watched, and the countries seen — counted per ISO code, with a bar per
|
||||
country sized against the busiest one. That bar is the honest limit of the word
|
||||
country sized against the busiest one. The request budget (OPEN-56) is written
|
||||
from the same page: a mode select, the two numbers, and a table of what the
|
||||
counter holds right now, with the over-budget count marked. The line under it
|
||||
says which of the two answers an empty table is — "off, nothing is being
|
||||
counted" or "counting, nobody is over budget yet" — and says plainly that the
|
||||
counting is this process's. That bar is the honest limit of the word
|
||||
"map" here: the admin API exposes counts per country code, not coordinates, and
|
||||
the runtime image is distroless with no external assets, so there is no world
|
||||
outline and no tile server. A geographic map would be a decoration this page
|
||||
@@ -846,10 +877,18 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own.
|
||||
On the head of this file the host suite has been re-run and the container stages
|
||||
have not, so the two sets of numbers are labelled separately rather than merged
|
||||
into one green line. macOS host, this tree, re-measured 2026-10-04 with the
|
||||
path rules on it: build 0 warnings / 0 errors, unit **195/195**, integration
|
||||
**208/208 in 25 s**, console **85 assertions, 0 failed**, smoke **passed 36,
|
||||
request budget on it: build 0 warnings / 0 errors, unit **207/207**, integration
|
||||
**219/219 in 20 s**, console **90 assertions, 0 failed**, smoke **passed 48,
|
||||
failed 0**, and compose **209 passed, 0 failed** against the built image at
|
||||
261 MB — re-run on this tree because a new pillar changes what the shipped stack
|
||||
261 MB. The smoke count moved by more than its new scene: the edge was being
|
||||
started from the repository root, where there is no `appsettings.json`, so it
|
||||
loaded no `ReverseProxy` section, 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 — the gate had been
|
||||
passing on an edge that never proxied anything, because every assertion in it
|
||||
expects a 404 or a refusal. Naming the content root is what makes the first line
|
||||
of `scripts/smoke.sh` true, and the streak scene now waits for the ban row to
|
||||
exist before asking the wire whether it is enforced — re-run on this tree because a new pillar changes what the shipped stack
|
||||
enforces, and because the compose data volume outlives `compose down`: the run
|
||||
after a schema change starts against a database that has every table except the
|
||||
new one, which is the state the rules read is now written to survive and to say
|
||||
@@ -998,6 +1037,17 @@ is pinned with a checksum in the workflow.
|
||||
|
||||
Stated, because a defence that hides its failure modes is not a defence.
|
||||
|
||||
* **The request budget is counted per edge.** The counter is in the process, so
|
||||
N edges behind one load balancer allow N times the budget — the same shape the
|
||||
streak had before `SharedStreaks` (OPEN-52), and the same trade: sharing the
|
||||
count would cost a round trip on every request, not only the observed ones.
|
||||
What *is* shared is the consequence: the breach writes an engine ban, so the
|
||||
stop lands on every edge and survives a restart.
|
||||
* **The budget window is fixed, not sliding.** A sliding counter needs one entry
|
||||
per request, which is a map that grows at attack rate. The cost of a fixed
|
||||
window is the seam: a source can spend the budget at the end of one window and
|
||||
again at the start of the next, so the worst sustained rate is twice the limit
|
||||
across one boundary. `rateWindowSeconds` is the lever, not a smarter counter.
|
||||
* **One shared IPv4 egress is one source.** An office behind one address can
|
||||
accumulate a ban. Mitigations: the streak is *consecutive* (one honest click
|
||||
resets it), the allowlist outranks every pillar, and the ban explains itself
|
||||
@@ -1053,9 +1103,9 @@ dotnet/
|
||||
OpenWaf.Domain/ pure decision core: source key, streak, ordered decision
|
||||
OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo
|
||||
OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode
|
||||
OpenWaf.Tests.Unit/ 195 tests over the decision logic and the durability counters
|
||||
OpenWaf.Tests.Integration/ 208 tests driving the real pipeline against a fake upstream
|
||||
scripts/smoke.sh 36 assertions against a running edge + a real upstream
|
||||
OpenWaf.Tests.Unit/ 207 tests over the decision logic, the budget window and the durability counters
|
||||
OpenWaf.Tests.Integration/ 219 tests driving the real pipeline against a fake upstream
|
||||
scripts/smoke.sh 48 assertions against a running edge + a real upstream
|
||||
scripts/compose-smoke.sh 209 assertions against the built image (compose + nginx)
|
||||
scripts/console-check.cjs 75 assertions against the page, in a real Chromium
|
||||
scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2)
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
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);
|
||||
@@ -59,6 +59,23 @@ public sealed record EdgePolicy
|
||||
/// in the store the old setting chose.</summary>
|
||||
public bool SharedStreaks { get; init; }
|
||||
|
||||
/// <summary>What the edge does with a source that asked more often than the
|
||||
/// budget allows (OPEN-56). Off by default: a limit nobody wrote is a
|
||||
/// defence nobody asked for, and a false positive here locks out a whole
|
||||
/// office behind one address.</summary>
|
||||
public RateMode Rate { get; init; } = RateMode.Off;
|
||||
|
||||
/// <summary>The budget. Requests per source per window; the request that
|
||||
/// crosses it is the breach. Meaningful only when
|
||||
/// <see cref="Rate"/> is not Off, but kept valid regardless so a policy
|
||||
/// that is switched on later cannot come up with a limit of zero, which
|
||||
/// would refuse every request.</summary>
|
||||
public int RateLimitPerWindow { get; init; } = 100;
|
||||
|
||||
/// <summary>How long a source's budget lasts. The window starts at that
|
||||
/// source's first request, not on a global clock.</summary>
|
||||
public TimeSpan RateWindow { get; init; } = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>How long a ban's evidence row survives after it stops being live.</summary>
|
||||
public TimeSpan BanRetention { get; init; } = TimeSpan.FromDays(7);
|
||||
|
||||
|
||||
@@ -53,6 +53,21 @@ public static class PolicyBounds
|
||||
public const int Ipv4KeyPrefixLengthMin = 8, Ipv4KeyPrefixLengthMax = 32;
|
||||
public const int Ipv6KeyPrefixLengthMin = 32, Ipv6KeyPrefixLengthMax = 128;
|
||||
|
||||
/// <summary>The volume budget, requests per source per window (OPEN-56).
|
||||
/// The floor is 1, not 0: 0 is not "no limit", it is "refuse every
|
||||
/// request", and the way to say no limit is rateMode=Off. The ceiling is
|
||||
/// the same argument the streak threshold uses — a number no source will
|
||||
/// ever reach is the pillar switched off by arithmetic, with the mode still
|
||||
/// reading Enforce.</summary>
|
||||
public const int RateLimitPerWindowMin = 1, RateLimitPerWindowMax = 100_000;
|
||||
|
||||
/// <summary>How long that budget lasts, in seconds. Below a second the
|
||||
/// window is shorter than the snapshot's own propagation delay, so the
|
||||
/// limit is enforced by a counter that is already stale when it is read.
|
||||
/// Above an hour it is not a rate limit but a quota, and the lever for a
|
||||
/// longer sentence is the ban duration the breach already writes.</summary>
|
||||
public const double RateWindowSecondsMin = 1, RateWindowSecondsMax = 3_600;
|
||||
|
||||
/// <summary>The status the edge answers for a ban. It has to be a status
|
||||
/// that means "you are not getting this": 400-599. Anything else is either
|
||||
/// unsendable (1000 closed the connection) or a lie (200 says the request
|
||||
@@ -81,6 +96,9 @@ public static class PolicyBounds
|
||||
public static bool MaxTrackedSourcesOk(int v) => v is >= MaxTrackedSourcesMin and <= MaxTrackedSourcesMax;
|
||||
public static bool Ipv4KeyPrefixLengthOk(int v) => v is >= Ipv4KeyPrefixLengthMin and <= Ipv4KeyPrefixLengthMax;
|
||||
public static bool Ipv6KeyPrefixLengthOk(int v) => v is >= Ipv6KeyPrefixLengthMin and <= Ipv6KeyPrefixLengthMax;
|
||||
public static bool RateLimitPerWindowOk(int v) => v is >= RateLimitPerWindowMin and <= RateLimitPerWindowMax;
|
||||
public static bool RateWindowSecondsOk(double v) => v is >= RateWindowSecondsMin and <= RateWindowSecondsMax;
|
||||
|
||||
public static bool EngineBlockStatusOk(int v) => v is >= BlockStatusMin and <= BlockStatusMax;
|
||||
public static bool OperatorBlockStatusOk(int v) =>
|
||||
v == OperatorRedirectStatus || (v is >= BlockStatusMin and <= BlockStatusMax);
|
||||
@@ -96,6 +114,9 @@ public static class PolicyBounds
|
||||
"ipv4KeyPrefixLength" => $"{Ipv4KeyPrefixLengthMin}..{Ipv4KeyPrefixLengthMax}",
|
||||
"ipv6KeyPrefixLength" => $"{Ipv6KeyPrefixLengthMin}..{Ipv6KeyPrefixLengthMax}",
|
||||
"engineBlockStatus" => $"{BlockStatusMin}..{BlockStatusMax}",
|
||||
"rateLimitPerWindow" => $"{RateLimitPerWindowMin}..{RateLimitPerWindowMax}",
|
||||
"rateWindowSeconds" => $"{RateWindowSecondsMin}..{RateWindowSecondsMax}",
|
||||
|
||||
"operatorBlockStatus" => $"{OperatorRedirectStatus} or {BlockStatusMin}..{BlockStatusMax}",
|
||||
"refusalRange" or "serverErrorRange" =>
|
||||
$"low-high with {ClassifiableStatusMin} <= low <= high <= {ClassifiableStatusMax}",
|
||||
@@ -113,6 +134,9 @@ public static class PolicyBounds
|
||||
"ipv4KeyPrefixLength" => int.TryParse(value, out var v) && Ipv4KeyPrefixLengthOk(v),
|
||||
"ipv6KeyPrefixLength" => int.TryParse(value, out var v) && Ipv6KeyPrefixLengthOk(v),
|
||||
"engineBlockStatus" => int.TryParse(value, out var v) && EngineBlockStatusOk(v),
|
||||
"rateLimitPerWindow" => int.TryParse(value, out var v) && RateLimitPerWindowOk(v),
|
||||
"rateWindowSeconds" => double.TryParse(value, out var v) && RateWindowSecondsOk(v),
|
||||
|
||||
"operatorBlockStatus" => int.TryParse(value, out var v) && OperatorBlockStatusOk(v),
|
||||
"refusalRange" or "serverErrorRange" => StatusRange.TryParse(value, out var r)
|
||||
&& r.Low >= ClassifiableStatusMin && r.High <= ClassifiableStatusMax,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace OpenWaf.Domain.Policy;
|
||||
|
||||
/// <summary>
|
||||
/// What the edge does with a source that asked more often than the budget
|
||||
/// allows (OPEN-56).
|
||||
///
|
||||
/// A separate switch from <see cref="EnforcementMode"/> on purpose. Volume is a
|
||||
/// different claim from a run of refusals: the streak reads what the origin
|
||||
/// answered, the rate policy reads how often the origin was asked. An operator
|
||||
/// who has been running the streak in Enforce for a month and wants to find out
|
||||
/// what a volume limit would have done must be able to switch one on without
|
||||
/// touching the other, and the reverse.
|
||||
///
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public enum RateMode
|
||||
{
|
||||
/// <summary>Nothing is counted. The answer to every request is exactly what
|
||||
/// it was before the feature existed.</summary>
|
||||
Off = 0,
|
||||
|
||||
/// <summary>Counted, and said so — one alert per source per window — but
|
||||
/// nothing is refused. This is how an operator learns what the budget would
|
||||
/// have cut before it cuts anything.</summary>
|
||||
Observe = 1,
|
||||
|
||||
/// <summary>The request that crosses the budget is refused for the rest of
|
||||
/// the window, and the source also gets an engine ban so the stop is shared
|
||||
/// with the other edges and survives a restart.</summary>
|
||||
Enforce = 2
|
||||
}
|
||||
@@ -108,6 +108,10 @@ internal static class AdminConsole
|
||||
<input id="ruleNote" placeholder="note" autocomplete="off" size="12">
|
||||
<input id="ruleTtl" placeholder="minutes" autocomplete="off" size="7" inputmode="numeric">
|
||||
<button id="addRule">add path rule</button>
|
||||
<select id="rateMode"><option value="off">budget: off</option><option value="observe">budget: observe</option><option value="enforce">budget: enforce</option></select>
|
||||
<input id="rateLimit" placeholder="requests" size="7" inputmode="numeric">
|
||||
<input id="rateWindow" placeholder="window s" size="7" inputmode="numeric">
|
||||
<button id="setRate">set budget</button>
|
||||
</div>
|
||||
|
||||
<div id="summary" class="muted">—</div>
|
||||
@@ -124,6 +128,10 @@ internal static class AdminConsole
|
||||
<div id="rulenote" class="muted"></div>
|
||||
<div class="scroll"><table id="pathrules"><thead><tr><th>pattern</th><th>action</th><th>note</th><th class="num">matches</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Request budget</h2>
|
||||
<div id="ratenote" class="muted"></div>
|
||||
<div class="scroll"><table id="ratetable"><thead><tr><th>source</th><th class="num">requests in window</th><th class="num">budget</th><th>window ends</th><th></th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Sources the edge is watching</h2>
|
||||
<div class="bar">
|
||||
<input id="srcfilter" placeholder="filter observations and streaks by source key" autocomplete="off" size="28">
|
||||
@@ -245,13 +253,14 @@ function row(cells) {
|
||||
async function load() {
|
||||
if (!token) { note('no token', true); return; }
|
||||
try {
|
||||
const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, alertsRes, geoRes] = await Promise.all([
|
||||
const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, alertsRes, geoRes] = await Promise.all([
|
||||
apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
|
||||
apiRaw(withSrc('/admin-api/observations?limit=25')),
|
||||
apiRaw(withSrc('/admin-api/streaks')),
|
||||
apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'),
|
||||
apiRaw('/admin-api/allow?live=false&limit=500'),
|
||||
apiRaw('/admin-api/rules?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'),
|
||||
apiRaw('/admin-api/rules?live=false&limit=500'), apiRaw('/admin-api/rate?limit=25'),
|
||||
apiRaw('/admin-api/alerts?limit=25'),
|
||||
apiRaw('/admin-api/geo')
|
||||
]);
|
||||
// The core read decides whether there is anything to draw. When the admin
|
||||
@@ -267,7 +276,7 @@ async function load() {
|
||||
const obs = obsRes.body;
|
||||
const alerts = alertsRes.body;
|
||||
const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body,
|
||||
allow = allowRes.body, pathRules = pathRulesRes.body, geo = geoRes.body;
|
||||
allow = allowRes.body, pathRules = pathRulesRes.body, rate = rateRes.body, geo = geoRes.body;
|
||||
// The listing is capped server-side. Saying so is the difference between a
|
||||
// console and a misleading one: the delete beside this table is not capped.
|
||||
el('blocknote').textContent = blocksRes.truncated
|
||||
@@ -404,6 +413,35 @@ async function load() {
|
||||
+ (pathRulesRes.truncated ? ' · showing ' + pathRules.length + ' of ' + pathRulesRes.total + ' rules' : '')
|
||||
+ (expiredRules ? ' · ' + expiredRules + ' EXPIRED: those rules enforce nothing' : '')
|
||||
: 'no path rules — the edge reacts to what the upstream answered, never to the request itself';
|
||||
|
||||
// The volume pillar (OPEN-56). The table is the live counter, so it says
|
||||
// plainly when the pillar is off: an empty table and a disabled budget look
|
||||
// identical otherwise, and only one of them means nothing is being counted.
|
||||
const rateRows = (rate && rate.sources) || [];
|
||||
el('ratetable').tBodies[0].innerHTML = rateRows.length
|
||||
? rateRows.map((r) => row([
|
||||
{ v: r.sourceKey },
|
||||
// The number stays the number; the marking is the colour. A cell that
|
||||
// reads "3 over" cannot be compared against the budget by anyone.
|
||||
{ h: r.overBudget ? '<span class="warn">' + esc(r.count) + '</span>' : esc(r.count) },
|
||||
{ v: rate.limitPerWindow, n: true },
|
||||
{ v: r.windowEnd ? new Date(r.windowEnd).toLocaleTimeString() : '-' }
|
||||
])).join('')
|
||||
: row([{ v: 'nothing counted' }]);
|
||||
el('ratenote').textContent = rate && rate.mode && rate.mode !== 'Off'
|
||||
? rate.mode.toLowerCase() + ' · ' + rate.limitPerWindow + ' requests per '
|
||||
+ rate.windowSeconds + ' s per source, counted in this process (' + rate.trackedSources
|
||||
+ ' sources tracked) · behind more than one edge each edge counts its own traffic'
|
||||
: 'off — the edge never refuses a request for asking too often; nothing is being counted';
|
||||
// The select follows the server, unless the operator is holding it right
|
||||
// now — a five-second refresh that overwrites a half-made choice is how a
|
||||
// page convinces someone they never clicked anything.
|
||||
if (document.activeElement !== el('rateMode'))
|
||||
el('rateMode').value = (rate && rate.mode ? rate.mode.toLowerCase() : 'off');
|
||||
// Placeholders, not values: they say what an empty box means, and an empty
|
||||
// box is "keep what is set".
|
||||
el('rateLimit').placeholder = rate ? 'budget ' + rate.limitPerWindow : 'budget';
|
||||
el('rateWindow').placeholder = rate ? 'window ' + rate.windowSeconds + ' s' : 'window s';
|
||||
el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([
|
||||
{ h: srcBtn(o.sourceKey) }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true },
|
||||
{ v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') }
|
||||
@@ -670,6 +708,26 @@ el('setMode').onclick = async () => {
|
||||
if (!failed(r)) done('mode → ' + wanted);
|
||||
load();
|
||||
};
|
||||
el('setRate').onclick = async () => {
|
||||
// The budget is a policy write, not a data write, and the two number fields
|
||||
// are optional: leaving them empty means "keep what is set", because a PUT
|
||||
// that sends 0 would be refused and an operator who only wants to switch the
|
||||
// mode on should not have to retype both numbers.
|
||||
const body = { rateMode: el('rateMode').value };
|
||||
const limit = el('rateLimit').value.trim();
|
||||
const window = el('rateWindow').value.trim();
|
||||
if (limit && !/^\d+$/.test(limit)) { note('the budget must be a whole number of requests'); return; }
|
||||
if (window && !/^\d+$/.test(window)) { note('the window must be a whole number of seconds'); return; }
|
||||
if (limit) body.rateLimitPerWindow = parseInt(limit, 10);
|
||||
if (window) body.rateWindowSeconds = parseInt(window, 10);
|
||||
rateHold = true;
|
||||
const r = await apiRaw('/admin-api/policy', { method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
if (!failed(r)) done('budget → ' + body.rateMode
|
||||
+ (limit ? ', ' + limit + ' requests' : '') + (window ? ' per ' + window + ' s' : ''));
|
||||
load();
|
||||
};
|
||||
|
||||
el('clearEngine').onclick = async () => {
|
||||
// The most destructive button on the page, and it used to fire the DELETE and
|
||||
// read nothing back: whatever the edge answered — cleared 7, cleared 0, or
|
||||
|
||||
@@ -76,7 +76,10 @@ internal sealed record PolicyDto(
|
||||
int OperatorBlockStatus,
|
||||
IReadOnlyList<string> DefaultRedirectTargets,
|
||||
int ObservationRetentionDays,
|
||||
int BanRetentionDays);
|
||||
int BanRetentionDays,
|
||||
string RateMode,
|
||||
int RateLimitPerWindow,
|
||||
double RateWindowSeconds);
|
||||
|
||||
/// <summary>Every field is optional and null means "leave it alone" — a
|
||||
/// partial update is the only sane shape for a live policy knob.</summary>
|
||||
@@ -94,7 +97,19 @@ internal sealed record PolicyUpdateRequest(
|
||||
int? Ipv6KeyPrefixLength,
|
||||
int? EngineBlockStatus,
|
||||
int? OperatorBlockStatus,
|
||||
string[]? DefaultRedirectTargets);
|
||||
string[]? DefaultRedirectTargets,
|
||||
string? RateMode,
|
||||
int? RateLimitPerWindow,
|
||||
double? RateWindowSeconds);
|
||||
|
||||
/// <summary>One source's live volume window, as the limiter is counting it
|
||||
/// right now (OPEN-56).</summary>
|
||||
internal sealed record RateSourceDto(
|
||||
string SourceKey,
|
||||
int Count,
|
||||
DateTimeOffset WindowStart,
|
||||
DateTimeOffset WindowEnd,
|
||||
bool OverBudget);
|
||||
|
||||
internal sealed record ObservationDto(
|
||||
string SourceKey,
|
||||
|
||||
@@ -318,7 +318,8 @@ internal static class AdminEndpoints
|
||||
return Results.Ok(ToDto(policy.Current));
|
||||
});
|
||||
|
||||
group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, HttpContext ctx, CancellationToken ct) =>
|
||||
group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state,
|
||||
IStreakTracker streaks, RateTracker rates, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
var overrides = new Dictionary<string, string?>();
|
||||
@@ -334,6 +335,12 @@ internal static class AdminEndpoints
|
||||
return Results.BadRequest(new { error = "geo must be Off|DenyList|AllowList" });
|
||||
overrides["geo"] = geo.ToString();
|
||||
}
|
||||
if (req.RateMode is not null)
|
||||
{
|
||||
if (!Enum.TryParse<RateMode>(req.RateMode, true, out var rateMode))
|
||||
return Results.BadRequest(new { error = "rateMode must be one of Off|Observe|Enforce" });
|
||||
overrides["rateMode"] = rateMode.ToString();
|
||||
}
|
||||
// A field that is present but out of range is a 400, not a silent
|
||||
// no-op. The old shape — `if (req.X is > 0)` — answered 200 with the
|
||||
// old policy in the body for streakThreshold=0, maxTrackedSources=0,
|
||||
@@ -356,6 +363,8 @@ internal static class AdminEndpoints
|
||||
if (req.EngineBlockStatus is { } engineStatus) overrides["engineBlockStatus"] = engineStatus.ToString();
|
||||
if (req.OperatorBlockStatus is { } operatorStatus) overrides["operatorBlockStatus"] = operatorStatus.ToString();
|
||||
if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets);
|
||||
if (req.RateLimitPerWindow is { } rateLimit) overrides["rateLimitPerWindow"] = rateLimit.ToString();
|
||||
if (req.RateWindowSeconds is { } rateWindow) overrides["rateWindowSeconds"] = rateWindow.ToString();
|
||||
|
||||
// The toggle is a policy change, never a data change: switching
|
||||
// automatic banning off must leave every row — manual or engine —
|
||||
@@ -372,9 +381,53 @@ internal static class AdminEndpoints
|
||||
// it without refreshing the snapshot would leave the toggle
|
||||
// appearing to work in the API and not on the wire.
|
||||
await state.InvalidateAsync(ct);
|
||||
// maxTrackedSources bounds the two live maps, and both read the
|
||||
// bound once rather than per request — so a policy write that
|
||||
// changes it has to be pushed into them here, or the new number
|
||||
// would only take effect on the next restart while the API already
|
||||
// answers with it.
|
||||
streaks.Configure(policy.Current);
|
||||
rates.Configure(policy.Current);
|
||||
return Results.Ok(ToDto(policy.Current));
|
||||
});
|
||||
|
||||
group.MapGet("/rate", (RateTracker rates, IStreakTracker streaks, EdgePolicyProvider policyProvider,
|
||||
HttpContext ctx, int? limit, int? offset, string? source) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "limit", "offset", "source")) return Results.BadRequest(new { error = unknown });
|
||||
if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit,
|
||||
out var take, out var skip, out var pagingError))
|
||||
return Results.BadRequest(new { error = pagingError });
|
||||
if (source is not null && string.IsNullOrWhiteSpace(source))
|
||||
return Results.BadRequest(new { error = "source must not be empty; omit the parameter to list every source" });
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var policy = policyProvider.Current;
|
||||
var rows = rates.LiveRates(now, policy, take, skip, source, out var live);
|
||||
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < live).ToString().ToLowerInvariant();
|
||||
return Results.Ok(new
|
||||
{
|
||||
// The budget the numbers below are measured against, in the same
|
||||
// answer. A count without the limit it is compared to is a
|
||||
// number an operator cannot read, and the mode says whether
|
||||
// anything is being done about it at all.
|
||||
mode = policy.Rate.ToString(),
|
||||
limitPerWindow = policy.RateLimitPerWindow,
|
||||
windowSeconds = policy.RateWindow.TotalSeconds,
|
||||
// Counted here, in this process. The budget is per edge — the
|
||||
// README says so plainly — and a listing that did not name the
|
||||
// scope would read like the fleet's.
|
||||
scope = "this-process",
|
||||
trackedSources = rates.TrackedCount,
|
||||
liveWindows = live,
|
||||
sourceFilter = source,
|
||||
maxTrackedSources = policy.MaxTrackedSources,
|
||||
trackedIdleMinutes = policy.StateIdleTtl.TotalMinutes,
|
||||
sources = rows.Select(r => new RateSourceDto(
|
||||
r.SourceKey, r.Count, r.WindowStart, r.WindowEnd, r.OverBudget))
|
||||
});
|
||||
});
|
||||
|
||||
group.MapGet("/observations", async (OpenWafDbContext db, string? source, int? limit, int? offset,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
@@ -562,7 +615,7 @@ internal static class AdminEndpoints
|
||||
});
|
||||
});
|
||||
|
||||
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, HttpContext ctx) =>
|
||||
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, HttpContext ctx) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
@@ -662,6 +715,14 @@ internal static class AdminEndpoints
|
||||
// and "the rules table is not there" have to be different answers.
|
||||
requestRulesAvailable = state.RulesAvailable,
|
||||
requestRulesError = state.RulesError,
|
||||
// The volume pillar (OPEN-56): what the budget is, and whether this
|
||||
// process is counting anything. "No source is over budget" and "the
|
||||
// pillar is off" look identical in a listing, and only one of them is
|
||||
// a defence.
|
||||
rateMode = state.Current.Policy.Rate.ToString(),
|
||||
rateLimitPerWindow = state.Current.Policy.RateLimitPerWindow,
|
||||
rateWindowSeconds = state.Current.Policy.RateWindow.TotalSeconds,
|
||||
rateTrackedSources = rateTracker.TrackedCount,
|
||||
observationRetentionDays = (int)state.Current.Policy.ObservationRetention.TotalDays,
|
||||
banRetentionDays = (int)state.Current.Policy.BanRetention.TotalDays,
|
||||
mode = state.Current.Policy.Mode.ToString()
|
||||
@@ -806,6 +867,10 @@ internal static class AdminEndpoints
|
||||
return $"streakWindowMinutes must be {PolicyBounds.RangeOf("streakWindowMinutes")}; got {m}";
|
||||
if (req.BanDurationMinutes is { } b && !PolicyBounds.BanDurationMinutesOk(b))
|
||||
return $"banDurationMinutes must be {PolicyBounds.RangeOf("banDurationMinutes")}; got {b}";
|
||||
if (req.RateLimitPerWindow is { } rl && !PolicyBounds.RateLimitPerWindowOk(rl))
|
||||
return $"rateLimitPerWindow must be {PolicyBounds.RangeOf("rateLimitPerWindow")}; got {rl}";
|
||||
if (req.RateWindowSeconds is { } rw && !PolicyBounds.RateWindowSecondsOk(rw))
|
||||
return $"rateWindowSeconds must be {PolicyBounds.RangeOf("rateWindowSeconds")}; got {rw}";
|
||||
if (req.MaxTrackedSources is { } t && !PolicyBounds.MaxTrackedSourcesOk(t))
|
||||
return $"maxTrackedSources must be {PolicyBounds.RangeOf("maxTrackedSources")}; got {t}";
|
||||
if (req.Ipv4KeyPrefixLength is { } v4 && !PolicyBounds.Ipv4KeyPrefixLengthOk(v4))
|
||||
@@ -843,7 +908,8 @@ internal static class AdminEndpoints
|
||||
p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders,
|
||||
p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus,
|
||||
p.OperatorBlockStatus, p.DefaultRedirectTargets,
|
||||
(int)p.ObservationRetention.TotalDays, (int)p.BanRetention.TotalDays);
|
||||
(int)p.ObservationRetention.TotalDays, (int)p.BanRetention.TotalDays,
|
||||
p.Rate.ToString(), p.RateLimitPerWindow, p.RateWindow.TotalSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// The provenance filter, parsed honestly. The old shape mapped any unrecognised
|
||||
|
||||
@@ -26,6 +26,14 @@ internal sealed class EdgePolicyOptions
|
||||
public int EngineBlockStatus { get; set; } = 403;
|
||||
public int OperatorBlockStatus { get; set; } = 301;
|
||||
|
||||
// The volume pillar (OPEN-56). Off by default, and the limit is validated
|
||||
// at startup rather than defaulted: a deployment that writes
|
||||
// rateLimitPerWindow=0 meant something, and reading it as "100" or as
|
||||
// "refuse everything" are both a lie about what was asked for.
|
||||
public string Rate { get; set; } = "Off";
|
||||
public int RateLimitPerWindow { get; set; } = 100;
|
||||
public double RateWindowSeconds { get; set; } = 60;
|
||||
|
||||
// Where the streak counters live. Not a runtime knob: it selects which
|
||||
// store the process registers at startup, so changing it is a redeploy.
|
||||
// Off by default — the in-process map costs nothing on the request path,
|
||||
@@ -70,6 +78,9 @@ internal sealed class EdgePolicyOptions
|
||||
EngineBlockStatus = EngineBlockStatus,
|
||||
OperatorBlockStatus = OperatorBlockStatus,
|
||||
SharedStreaks = SharedStreaks,
|
||||
Rate = Enum.TryParse<RateMode>(Rate, true, out var rm) ? rm : RateMode.Off,
|
||||
RateLimitPerWindow = RateWindowLimit(RateLimitPerWindow),
|
||||
RateWindow = TimeSpan.FromSeconds(RateWindow(RateWindowSeconds)),
|
||||
DefaultRedirectTargets = DefaultRedirectTargets.Length == 0
|
||||
? new[] { "https://www.iana.org/help/example-domains" }
|
||||
: DefaultRedirectTargets,
|
||||
@@ -77,6 +88,22 @@ internal sealed class EdgePolicyOptions
|
||||
BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays")
|
||||
};
|
||||
|
||||
private static int RateWindowLimit(int v)
|
||||
{
|
||||
if (v < PolicyBounds.RateLimitPerWindowMin || v > PolicyBounds.RateLimitPerWindowMax)
|
||||
throw new InvalidOperationException(
|
||||
$"OpenWaf:Policy:RateLimitPerWindow must be {PolicyBounds.RangeOf("rateLimitPerWindow")}; got {v}");
|
||||
return v;
|
||||
}
|
||||
|
||||
private static double RateWindow(double v)
|
||||
{
|
||||
if (v < PolicyBounds.RateWindowSecondsMin || v > PolicyBounds.RateWindowSecondsMax)
|
||||
throw new InvalidOperationException(
|
||||
$"OpenWaf:Policy:RateWindowSeconds must be {PolicyBounds.RangeOf("rateWindowSeconds")}; got {v}");
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>Whole days, 1..365. Anything else is a deployment mistake and
|
||||
/// is named as one at startup.</summary>
|
||||
private static TimeSpan RetentionDays(int days, string configKey)
|
||||
|
||||
@@ -21,6 +21,8 @@ public sealed class EdgeGuardMiddleware(
|
||||
EdgeStateStore state,
|
||||
IGeoIpLookup geo,
|
||||
RuleMatchLedger ledger,
|
||||
RateTracker rates,
|
||||
BlockStore blocks,
|
||||
AlertWriter alerts,
|
||||
ILogger<EdgeGuardMiddleware> log)
|
||||
{
|
||||
@@ -41,6 +43,69 @@ public sealed class EdgeGuardMiddleware(
|
||||
$"since {since:O}: {decision.RulePattern} (action=observe, nothing was blocked)", ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Count this source's request and, over the budget, answer it here.
|
||||
/// True means the answer is already written and the request must not reach
|
||||
/// the origin; false means it may go through.
|
||||
/// </summary>
|
||||
private async Task<bool> RatePillarAsync(
|
||||
HttpContext ctx, EdgePolicy policy, string key, string path, string? country, DateTimeOffset now)
|
||||
{
|
||||
var rate = rates.Record(key, policy, now);
|
||||
if (!rate.OverBudget) return false;
|
||||
|
||||
if (policy.Rate == RateMode.Observe)
|
||||
{
|
||||
// The dry run says so once per source per window, and lets the
|
||||
// request through. This is how an operator finds out whether the
|
||||
// budget is a defence or a denial of their own traffic before it
|
||||
// refuses anything.
|
||||
if (rate.BreachStarted)
|
||||
await alerts.RaiseAsync(
|
||||
"rate_breach", key, rate.Count, null, path,
|
||||
$"{rate.Count} requests in {policy.RateWindow.TotalSeconds:0.#} s against a budget of "
|
||||
+ $"{policy.RateLimitPerWindow} (mode=Observe, nothing was blocked)", ctx.RequestAborted);
|
||||
return false;
|
||||
}
|
||||
|
||||
ctx.Response.StatusCode = 429;
|
||||
var seconds = Math.Max(1, (int)Math.Ceiling((rate.WindowEnd - now).TotalSeconds));
|
||||
ctx.Response.Headers.RetryAfter = seconds.ToString();
|
||||
await ctx.Response.WriteAsJsonAsync(new BlockedBody(
|
||||
"rate_limited",
|
||||
$"rate_{rate.Count}_of_{policy.RateLimitPerWindow}",
|
||||
rate.WindowEnd.ToString("O"),
|
||||
"This source asked more often than this site allows. The pause ends on its own; "
|
||||
+ "if it is wrong, an operator can raise the budget or allowlist the address."));
|
||||
|
||||
if (!rate.BreachStarted) return true;
|
||||
|
||||
// One breach, one alert, one ban. Everything else in the same window is
|
||||
// the same news, and a write per request is how a defence turns into
|
||||
// write amplification for the attacker to aim at the database.
|
||||
var userAgent = ctx.Request.Headers.UserAgent.ToString();
|
||||
if (userAgent.Length > 256) userAgent = userAgent[..256];
|
||||
|
||||
// Deliberately not ctx.RequestAborted: the 429 has already been
|
||||
// written, so the client is free to hang up at this exact moment, and a
|
||||
// cancelled token would drop the one row that makes the stop outlast the
|
||||
// window. Same ruling as the streak ban in ResponseObservationMiddleware.
|
||||
await alerts.RaiseAsync(
|
||||
"rate_breach", key, rate.Count, null, path,
|
||||
$"{rate.Count} requests in {policy.RateWindow.TotalSeconds:0.#} s against a budget of "
|
||||
+ $"{policy.RateLimitPerWindow} (mode=Enforce, 429 for the rest of the window)",
|
||||
CancellationToken.None);
|
||||
|
||||
var ban = await blocks.BanForRateAsync(
|
||||
key, rate.Count, policy.RateLimitPerWindow, policy.RateWindow,
|
||||
path.Length == 0 ? null : path, userAgent.Length == 0 ? null : userAgent,
|
||||
country, null, null, now, CancellationToken.None);
|
||||
if (ban is not null)
|
||||
log.LogWarning("edge: rate ban {Key} until {Until} — {Count} over a budget of {Limit}",
|
||||
key, ban.ExpiresAt, rate.Count, policy.RateLimitPerWindow);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
var snapshot = state.GetOrRefresh();
|
||||
@@ -58,6 +123,27 @@ public sealed class EdgeGuardMiddleware(
|
||||
{
|
||||
if (decision.Verdict == EdgeVerdict.PassRuleObserved)
|
||||
await ObserveRuleMatchAsync(decision, path, ctx.RequestAborted);
|
||||
|
||||
// 7. rate — the volume pillar (OPEN-56), and the last thing that
|
||||
// runs before the origin is asked. It sits here rather than inside
|
||||
// DecisionEngine for one reason: every other pillar reads the
|
||||
// snapshot, which is built off the request path, while a count has
|
||||
// to be kept while the requests are arriving. Sitting below the
|
||||
// whole ordered list is also what makes the exemptions exact — an
|
||||
// always-pass prefix, an allowlisted address, a matched rule, a
|
||||
// block or a geo refusal has already been answered, so it never
|
||||
// reaches the counter and the budget counts exactly the requests
|
||||
// that would have cost the origin.
|
||||
if (snapshot.Policy.Rate != RateMode.Off && decision.Verdict == EdgeVerdict.Pass)
|
||||
{
|
||||
var rateKey = string.IsNullOrWhiteSpace(ip)
|
||||
? string.Empty
|
||||
: SourceKey.For(ip, snapshot.Policy);
|
||||
if (rateKey.Length > 0
|
||||
&& await RatePillarAsync(ctx, snapshot.Policy, rateKey, path, country, now))
|
||||
return;
|
||||
}
|
||||
|
||||
await next(ctx);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -63,6 +63,13 @@ builder.Services.AddSingleton(sp => new EdgeStateStore(
|
||||
});
|
||||
builder.Services.AddSingleton<BlockStore>();
|
||||
builder.Services.AddSingleton<OpenWaf.Edge.Pipeline.RuleMatchLedger>();
|
||||
// The volume counter (OPEN-56). One per process, on purpose: the budget is a
|
||||
// count of requests this edge saw, and there is no shared implementation to
|
||||
// choose the way there is for the streak — sharing a counter would mean a
|
||||
// round trip on a path whose measured p95 is ~3 ms, for every request, not
|
||||
// only the observed ones. The stop a breach writes IS shared, because it is a
|
||||
// ban row.
|
||||
builder.Services.AddSingleton<OpenWaf.Domain.Engine.RateTracker>();
|
||||
builder.Services.AddSingleton<DurabilityHealth>();
|
||||
// Alerts used to end at a table: the row is correct and read by nobody until
|
||||
// someone opens the page. One optional endpoint pushes each raised alert
|
||||
|
||||
@@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OpenWaf.Domain.Engine;
|
||||
using OpenWaf.Infrastructure.Persistence;
|
||||
|
||||
namespace OpenWaf.Edge.Startup;
|
||||
@@ -18,6 +19,8 @@ namespace OpenWaf.Edge.Startup;
|
||||
internal sealed class EdgeStateWarmer(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
EdgeStateStore state,
|
||||
IStreakTracker streaks,
|
||||
RateTracker rates,
|
||||
ILogger<EdgeStateWarmer> log) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
@@ -50,6 +53,14 @@ internal sealed class EdgeStateWarmer(
|
||||
}
|
||||
|
||||
await state.WarmUpAsync(cancellationToken);
|
||||
|
||||
// The map bounds come from the policy, and both trackers read them once
|
||||
// rather than dereferencing the policy record per request. The streak
|
||||
// tracker's cap used to be set by nobody outside its own tests, so
|
||||
// maxTrackedSources bounded nothing in a running edge — the map grew to
|
||||
// the built-in 10 000 whatever the operator had asked for.
|
||||
streaks.Configure(state.Current.Policy);
|
||||
rates.Configure(state.Current.Policy);
|
||||
log.LogInformation(
|
||||
"edge: warmed up — {Operator} operator blocks, {Engine} engine bans, {Allow} allow entries",
|
||||
state.Current.OperatorBlocks.Count, state.Current.EngineBans.Count, state.Current.AllowEntries.Count);
|
||||
|
||||
@@ -76,7 +76,13 @@ public sealed class BlockStore
|
||||
/// </summary>
|
||||
public sealed record PendingBan(
|
||||
string SourceKey, int ConsecutiveRefusals, int StatusCode, string? Path, string? UserAgent,
|
||||
string? CountryCode, string? City, string? Region, DateTimeOffset DecidedAt)
|
||||
string? CountryCode, string? City, string? Region, DateTimeOffset DecidedAt,
|
||||
/// <summary>Set when the ban was not decided by a streak. The default
|
||||
/// wording below says "consecutive refusals", which is true of the
|
||||
/// streak and a lie about a volume breach, and an operator reading a
|
||||
/// ban's reason is reading the explanation of why they are locked
|
||||
/// out.</summary>
|
||||
string? ReasonText = null)
|
||||
{
|
||||
public static PendingBan From(StreakSnapshot s, int statusCode, DateTimeOffset now) => new(
|
||||
s.SourceKey, s.MaxConsecutiveRefusals, statusCode, s.LastPath, s.LastUserAgent,
|
||||
@@ -127,13 +133,33 @@ public sealed class BlockStore
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Issue or refresh an engine ban decided by the volume pillar (OPEN-56).
|
||||
///
|
||||
/// The refusal itself is answered by the guard, immediately, with a 429 —
|
||||
/// this write is what makes the stop outlast the window it was counted in:
|
||||
/// it is a row, so the other edges see it and a restart does not forget
|
||||
/// it, and it appears on the blocks listing where an operator can see and
|
||||
/// clear it. It goes through the same gate and the same "a live ban is not
|
||||
/// extended" rule as a streak ban, because a flood that keeps arriving must
|
||||
/// not be able to lengthen its own sentence.
|
||||
/// </summary>
|
||||
public Task<BlockEntry?> BanForRateAsync(
|
||||
string sourceKey, int count, int limit, TimeSpan window,
|
||||
string? path, string? userAgent, string? countryCode, string? city, string? region,
|
||||
DateTimeOffset now, CancellationToken ct = default)
|
||||
=> WriteBanAsync(new PendingBan(
|
||||
sourceKey, 0, 429, path, userAgent, countryCode, city, region, now,
|
||||
$"{count} requests from this source in {window.TotalSeconds:0.#} s against a budget of "
|
||||
+ $"{limit}; the {limit + 1}th was refused (rate policy)"), now, ct);
|
||||
|
||||
private async Task<BlockEntry?> WriteBanAsync(PendingBan ban, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var policy = _policy.Current;
|
||||
// From when the ban was decided, not from when a retry landed: a write
|
||||
// that arrives late must not silently lengthen the sentence.
|
||||
var expiresAt = ban.DecidedAt + policy.BanDuration;
|
||||
var reason = $"{ban.ConsecutiveRefusals} consecutive refusals " +
|
||||
var reason = ban.ReasonText ?? $"{ban.ConsecutiveRefusals} consecutive refusals " +
|
||||
$"({policy.RefusalRange}) within {policy.StreakWindow.TotalMinutes:0.#} min; " +
|
||||
$"last {ban.StatusCode} {(ban.Path is null ? "" : ban.Path)}";
|
||||
|
||||
@@ -158,7 +184,7 @@ public sealed class BlockStore
|
||||
CreatedAt = now,
|
||||
ExpiresAt = expiresAt,
|
||||
Reason = reason,
|
||||
ConsecutiveRefusals = ban.ConsecutiveRefusals
|
||||
ConsecutiveRefusals = ban.ConsecutiveRefusals > 0 ? ban.ConsecutiveRefusals : null
|
||||
};
|
||||
db.Blocks.Add(existing);
|
||||
}
|
||||
@@ -167,7 +193,7 @@ public sealed class BlockStore
|
||||
existing.CreatedAt = now;
|
||||
existing.ExpiresAt = expiresAt;
|
||||
existing.Reason = reason;
|
||||
existing.ConsecutiveRefusals = ban.ConsecutiveRefusals;
|
||||
if (ban.ConsecutiveRefusals > 0) existing.ConsecutiveRefusals = ban.ConsecutiveRefusals;
|
||||
}
|
||||
|
||||
existing.LastStatusCode = ban.StatusCode;
|
||||
|
||||
@@ -137,6 +137,9 @@ public sealed class EdgePolicyProvider
|
||||
if (Usable("serverErrorRange") && map.TryGetValue("serverErrorRange", out var sr)) p = p with { ServerErrorRange = StatusRange.Parse(sr, p.ServerErrorRange) };
|
||||
if (map.TryGetValue("trustProxyHeaders", out var tph) && bool.TryParse(tph, out var tphv)) p = p with { TrustProxyHeaders = tphv };
|
||||
if (map.TryGetValue("geo", out var geo) && Enum.TryParse<GeoMode>(geo, true, out var gm)) p = p with { Geo = gm };
|
||||
if (map.TryGetValue("rateMode", out var rm) && Enum.TryParse<RateMode>(rm, true, out var rmode)) p = p with { Rate = rmode };
|
||||
if (Usable("rateLimitPerWindow") && map.TryGetValue("rateLimitPerWindow", out var rl) && int.TryParse(rl, out var rlv)) p = p with { RateLimitPerWindow = rlv };
|
||||
if (Usable("rateWindowSeconds") && map.TryGetValue("rateWindowSeconds", out var rw) && double.TryParse(rw, out var rwv)) p = p with { RateWindow = TimeSpan.FromSeconds(rwv) };
|
||||
if (Usable("maxTrackedSources") && map.TryGetValue("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv };
|
||||
if (Usable("ipv6KeyPrefixLength") && map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v };
|
||||
if (Usable("ipv4KeyPrefixLength") && map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v };
|
||||
|
||||
@@ -39,7 +39,10 @@ internal sealed class EdgeFixture : IAsyncDisposable
|
||||
string? dbPath = null,
|
||||
bool sharedStreaks = false,
|
||||
string? alertWebhookPath = null,
|
||||
int? alertWebhookTimeoutSeconds = null)
|
||||
int? alertWebhookTimeoutSeconds = null,
|
||||
string rate = "Off",
|
||||
int rateLimitPerWindow = 100,
|
||||
double rateWindowSeconds = 60)
|
||||
{
|
||||
_sharedDb = dbPath is not null;
|
||||
_dbPath = dbPath ?? Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
|
||||
@@ -81,6 +84,12 @@ internal sealed class EdgeFixture : IAsyncDisposable
|
||||
Upstream.Address.TrimEnd('/') + alertWebhookPath);
|
||||
if (alertWebhookTimeoutSeconds is { } wts)
|
||||
builder.UseSetting("OpenWaf:Alerts:WebhookTimeoutSeconds", wts.ToString());
|
||||
// The volume pillar (OPEN-56). Off by default here exactly as in the
|
||||
// shipped default, so every other test in this suite proves the
|
||||
// counter costs nothing when the pillar is not asked for.
|
||||
builder.UseSetting("OpenWaf:Policy:Rate", rate);
|
||||
builder.UseSetting("OpenWaf:Policy:RateLimitPerWindow", rateLimitPerWindow.ToString());
|
||||
builder.UseSetting("OpenWaf:Policy:RateWindowSeconds", rateWindowSeconds.ToString());
|
||||
builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OpenWaf.Infrastructure.Persistence;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// The volume pillar, end to end (OPEN-56).
|
||||
///
|
||||
/// Every other defence in this edge reads something that already happened: the
|
||||
/// status the application answered, the country the address sits in, a list a
|
||||
/// human wrote. A source that asks for a cheap path over and over produces no
|
||||
/// refusal, so no streak ever matures and the application serves every request.
|
||||
/// These tests run the upstream answering 200 on purpose — the whole claim is
|
||||
/// about the traffic that the origin is happy to serve.
|
||||
/// </summary>
|
||||
public sealed class RatePolicyTests
|
||||
{
|
||||
private const string Visitor = "203.0.113.161";
|
||||
|
||||
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip = Visitor)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
|
||||
return await f.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> AdminAsync(
|
||||
EdgeFixture f, HttpMethod method, string url, object? body = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url);
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
if (body is not null) request.Content = JsonContent.Create(body);
|
||||
return await f.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<string> BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync();
|
||||
|
||||
/// <summary>An origin that answers, so nothing in this file can be credited
|
||||
/// to the streak pillar.</summary>
|
||||
private static void OriginAnswersEverything(EdgeFixture f) => f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
||||
|
||||
[Fact]
|
||||
public async Task Over_the_budget_the_edge_answers_429_and_the_origin_never_sees_the_surplus()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 3);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var ok = await GetAsync(f, "/catalog");
|
||||
Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
}
|
||||
|
||||
using (var over = await GetAsync(f, "/catalog"))
|
||||
{
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
var body = await BodyAsync(over);
|
||||
Assert.Contains("rate_limited", body);
|
||||
// The answer says when the pause ends, in the header the verb means.
|
||||
Assert.True(over.Headers.TryGetValues("Retry-After", out var values));
|
||||
Assert.True(int.Parse(values!.First()) >= 1);
|
||||
Assert.Contains("rate_4_of_3", body);
|
||||
}
|
||||
|
||||
// The crossing also wrote an engine ban, and the ban is the part that
|
||||
// outlives the window: from here the answer is the ban's own 403, not a
|
||||
// "slow down" that expires with the window. Both refusals keep the
|
||||
// origin out of it, which is the claim under test.
|
||||
using (var over = await GetAsync(f, "/other"))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, over.StatusCode);
|
||||
Assert.Contains("blocked_by_policy", await BodyAsync(over));
|
||||
}
|
||||
|
||||
lock (f.Upstream.Paths)
|
||||
{
|
||||
Assert.Equal(3, f.Upstream.Paths.Count(p => p == "/catalog"));
|
||||
Assert.DoesNotContain("/other", f.Upstream.Paths);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_different_source_gets_its_own_budget()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 2; i++)
|
||||
(await GetAsync(f, "/catalog", "203.0.113.161")).Dispose();
|
||||
|
||||
using (var over = await GetAsync(f, "/catalog", "203.0.113.161"))
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
|
||||
using (var neighbour = await GetAsync(f, "/catalog", "203.0.113.162"))
|
||||
Assert.Equal(HttpStatusCode.OK, neighbour.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_breach_also_writes_an_engine_ban_the_operator_can_see_and_clear()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
(await GetAsync(f, "/catalog")).Dispose();
|
||||
|
||||
using (var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine"))
|
||||
{
|
||||
var rows = JsonDocument.Parse(await BodyAsync(blocks)).RootElement;
|
||||
Assert.Equal(1, rows.GetArrayLength());
|
||||
var row = rows[0];
|
||||
Assert.Equal(Visitor, row.GetProperty("sourceKey").GetString());
|
||||
// The reason says volume, not refusals: an operator reading why a
|
||||
// source is locked out is reading the explanation.
|
||||
Assert.Contains("rate policy", row.GetProperty("reason").GetString());
|
||||
Assert.Contains("budget of 2", row.GetProperty("reason").GetString());
|
||||
Assert.NotNull(row.GetProperty("expiresAt").GetString());
|
||||
}
|
||||
|
||||
// The ban is the part that outlives the window: the next request is
|
||||
// refused by the engine-ban pillar, with the ban's own answer.
|
||||
using (var later = await GetAsync(f, "/catalog"))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, later.StatusCode);
|
||||
Assert.Contains("blocked_by_policy", await BodyAsync(later));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observe_mode_counts_and_says_so_once_without_refusing_anything()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 2);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var probe = await GetAsync(f, "/catalog");
|
||||
Assert.Equal(HttpStatusCode.OK, probe.StatusCode);
|
||||
}
|
||||
|
||||
lock (f.Upstream.Paths)
|
||||
Assert.Equal(5, f.Upstream.Paths.Count(p => p == "/catalog"));
|
||||
|
||||
using var scope = f.Factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||
var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "rate_breach").ToListAsync();
|
||||
|
||||
// One alert for the crossing, not one per request: a flood is exactly
|
||||
// the traffic that turns a per-request write into the attack.
|
||||
Assert.Single(alerts);
|
||||
Assert.Equal(3, alerts[0].Count);
|
||||
Assert.Contains("budget of 2", alerts[0].Detail);
|
||||
Assert.Contains("mode=Observe, nothing was blocked", alerts[0].Detail);
|
||||
|
||||
// And nothing was banned in observe mode.
|
||||
using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine");
|
||||
Assert.Equal(0, JsonDocument.Parse(await BodyAsync(blocks)).RootElement.GetArrayLength());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Off_is_the_default_and_nothing_is_counted()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 6; i++)
|
||||
(await GetAsync(f, "/catalog")).Dispose();
|
||||
|
||||
using (var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state"))
|
||||
{
|
||||
var root = JsonDocument.Parse(await BodyAsync(state)).RootElement;
|
||||
Assert.Equal("Off", root.GetProperty("rateMode").GetString());
|
||||
Assert.Equal(0, root.GetProperty("rateTrackedSources").GetInt32());
|
||||
}
|
||||
|
||||
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate");
|
||||
var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement;
|
||||
Assert.Equal("Off", rows.GetProperty("mode").GetString());
|
||||
Assert.Equal(0, rows.GetProperty("trackedSources").GetInt32());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_allowlist_and_the_admin_surface_are_outside_the_budget()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (var allow = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
|
||||
new { match = Visitor, note = "the office" }))
|
||||
Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode);
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var probe = await GetAsync(f, "/catalog");
|
||||
Assert.Equal(HttpStatusCode.OK, probe.StatusCode);
|
||||
}
|
||||
|
||||
// The recovery hatch stays open at any budget: the page that raises the
|
||||
// limit is served from the same edge that is refusing everyone else.
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var admin = await AdminAsync(f, HttpMethod.Get, "/admin-api/state");
|
||||
Assert.Equal(HttpStatusCode.OK, admin.StatusCode);
|
||||
}
|
||||
|
||||
// A source that is not allowlisted still hits the budget.
|
||||
using (var stranger = await GetAsync(f, "/catalog", "203.0.113.163"))
|
||||
Assert.Equal(HttpStatusCode.OK, stranger.StatusCode);
|
||||
using (var stranger2 = await GetAsync(f, "/catalog", "203.0.113.163"))
|
||||
Assert.Equal((HttpStatusCode)429, stranger2.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_request_the_guard_already_refused_is_not_counted_again()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (var rule = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
||||
new { pattern = "/probe*", action = "block" }))
|
||||
Assert.Equal(HttpStatusCode.NoContent, rule.StatusCode);
|
||||
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
using var probe = await GetAsync(f, "/probe.php");
|
||||
Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode);
|
||||
}
|
||||
|
||||
// The rule refused them, so the budget never saw them: the same source
|
||||
// still has its whole budget for the paths the rule does not name.
|
||||
using (var page = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
|
||||
using (var page2 = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal(HttpStatusCode.OK, page2.StatusCode);
|
||||
using (var page3 = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal((HttpStatusCode)429, page3.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_window_restarts_and_the_source_flows_again()
|
||||
{
|
||||
// A ban as short as the window, so this test asks about the window and
|
||||
// not about the ban the breach also wrote.
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1, rateWindowSeconds: 1,
|
||||
banDuration: "00:00:01");
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (var first = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
|
||||
using (var over = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(1.4));
|
||||
|
||||
using (var after = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal(HttpStatusCode.OK, after.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_rate_value_outside_its_range_is_refused_by_name_and_changes_nothing()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
|
||||
using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
|
||||
new { rateLimitPerWindow = 0 }))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
|
||||
Assert.Contains("rateLimitPerWindow must be 1..100000", await BodyAsync(bad));
|
||||
}
|
||||
using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
|
||||
new { rateWindowSeconds = 0 }))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
|
||||
Assert.Contains("rateWindowSeconds must be 1..3600", await BodyAsync(bad));
|
||||
}
|
||||
using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
|
||||
new { rateMode = "sometimes" }))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
|
||||
Assert.Contains("rateMode must be one of Off|Observe|Enforce", await BodyAsync(bad));
|
||||
}
|
||||
|
||||
using (var policy = await AdminAsync(f, HttpMethod.Get, "/admin-api/policy"))
|
||||
{
|
||||
var root = JsonDocument.Parse(await BodyAsync(policy)).RootElement;
|
||||
Assert.Equal("Off", root.GetProperty("rateMode").GetString());
|
||||
Assert.Equal(100, root.GetProperty("rateLimitPerWindow").GetInt32());
|
||||
Assert.Equal(60, root.GetProperty("rateWindowSeconds").GetDouble());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_written_budget_is_live_on_the_wire_without_a_restart()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (var put = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
|
||||
new { rateMode = "enforce", rateLimitPerWindow = 2, rateWindowSeconds = 60 }))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, put.StatusCode);
|
||||
var root = JsonDocument.Parse(await BodyAsync(put)).RootElement;
|
||||
Assert.Equal("Enforce", root.GetProperty("rateMode").GetString());
|
||||
Assert.Equal(2, root.GetProperty("rateLimitPerWindow").GetInt32());
|
||||
}
|
||||
|
||||
for (var i = 0; i < 2; i++)
|
||||
(await GetAsync(f, "/catalog")).Dispose();
|
||||
using var over = await GetAsync(f, "/catalog");
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_listing_says_what_the_limiter_is_counting_right_now()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 10);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
for (var i = 0; i < 4; i++)
|
||||
(await GetAsync(f, "/catalog", "203.0.113.161")).Dispose();
|
||||
for (var i = 0; i < 2; i++)
|
||||
(await GetAsync(f, "/catalog", "203.0.113.164")).Dispose();
|
||||
|
||||
using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate"))
|
||||
{
|
||||
var root = JsonDocument.Parse(await BodyAsync(list)).RootElement;
|
||||
Assert.Equal("Observe", root.GetProperty("mode").GetString());
|
||||
Assert.Equal(10, root.GetProperty("limitPerWindow").GetInt32());
|
||||
Assert.Equal(60, root.GetProperty("windowSeconds").GetDouble());
|
||||
Assert.Equal(2, root.GetProperty("trackedSources").GetInt32());
|
||||
Assert.Equal(2, root.GetProperty("liveWindows").GetInt32());
|
||||
|
||||
var rows = root.GetProperty("sources");
|
||||
Assert.Equal(2, rows.GetArrayLength());
|
||||
// Biggest first: the operator is looking for the source that is
|
||||
// about to cross, not for an alphabetical roll call.
|
||||
Assert.Equal(4, rows[0].GetProperty("count").GetInt32());
|
||||
Assert.False(rows[0].GetProperty("overBudget").GetBoolean());
|
||||
Assert.NotNull(rows[0].GetProperty("windowEnd").GetString());
|
||||
}
|
||||
|
||||
using (var filtered = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate?source=203.0.113.164"))
|
||||
{
|
||||
var root = JsonDocument.Parse(await BodyAsync(filtered)).RootElement;
|
||||
Assert.Equal(1, root.GetProperty("liveWindows").GetInt32());
|
||||
Assert.Equal(2, root.GetProperty("trackedSources").GetInt32());
|
||||
Assert.Equal(1, root.GetProperty("sources").GetArrayLength());
|
||||
}
|
||||
|
||||
using var emptyFilter = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate?source=");
|
||||
Assert.Equal(HttpStatusCode.BadRequest, emptyFilter.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using OpenWaf.Domain.Engine;
|
||||
using OpenWaf.Domain.Policy;
|
||||
using Xunit;
|
||||
|
||||
namespace OpenWaf.Tests.Unit;
|
||||
|
||||
/// <summary>
|
||||
/// The volume counter's arithmetic (OPEN-56). The enforcement is the guard's
|
||||
/// business and is tested end to end; what lives here is the part that has to
|
||||
/// be exactly right and cannot be seen from the outside: when a window starts,
|
||||
/// which single request is allowed to call itself the breach, and what happens
|
||||
/// to the map when the traffic is the kind that exists to grow it.
|
||||
/// </summary>
|
||||
public sealed class RateTrackerTests
|
||||
{
|
||||
private static readonly DateTimeOffset T0 = new(2026, 10, 4, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static EdgePolicy Policy(int limit = 3, int windowSeconds = 60) => new()
|
||||
{
|
||||
Rate = RateMode.Enforce,
|
||||
RateLimitPerWindow = limit,
|
||||
RateWindow = TimeSpan.FromSeconds(windowSeconds)
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void The_budget_counts_requests_and_not_responses()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 3);
|
||||
|
||||
for (var i = 1; i <= 3; i++)
|
||||
{
|
||||
var seen = tracker.Record("1.2.3.4", policy, T0.AddSeconds(i));
|
||||
Assert.Equal(i, seen.Count);
|
||||
Assert.False(seen.OverBudget);
|
||||
Assert.False(seen.BreachStarted);
|
||||
}
|
||||
|
||||
var fourth = tracker.Record("1.2.3.4", policy, T0.AddSeconds(10));
|
||||
Assert.Equal(4, fourth.Count);
|
||||
Assert.True(fourth.OverBudget);
|
||||
Assert.True(fourth.BreachStarted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_the_request_that_crosses_is_the_breach()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 2);
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
tracker.Record("1.2.3.4", policy, T0.AddSeconds(i));
|
||||
|
||||
// One alert and one ban write per source per window, not one per
|
||||
// request: a flood is precisely the traffic that turns a per-request
|
||||
// durable write into the thing that takes the database down.
|
||||
var breaches = Enumerable.Range(0, 10)
|
||||
.Select(i => tracker.Record("9.9.9.9", policy, T0.AddSeconds(i)))
|
||||
.Count(r => r.BreachStarted);
|
||||
Assert.Equal(1, breaches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_window_starts_at_the_sources_first_request_not_on_a_global_clock()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 1, windowSeconds: 60);
|
||||
|
||||
var late = tracker.Record("1.2.3.4", policy, T0.AddSeconds(59));
|
||||
Assert.False(late.OverBudget);
|
||||
Assert.Equal(T0.AddSeconds(59), late.WindowStart);
|
||||
Assert.Equal(T0.AddSeconds(119), late.WindowEnd);
|
||||
|
||||
// A source that arrives just before the imaginary global boundary is not
|
||||
// handed a one-second window: the limit is not a lottery on arrival time.
|
||||
var over = tracker.Record("1.2.3.4", policy, T0.AddSeconds(60));
|
||||
Assert.True(over.OverBudget);
|
||||
Assert.Equal(T0.AddSeconds(59), over.WindowStart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_new_window_restarts_the_count_and_the_source_flows_again()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 2, windowSeconds: 30);
|
||||
|
||||
tracker.Record("1.2.3.4", policy, T0);
|
||||
tracker.Record("1.2.3.4", policy, T0.AddSeconds(1));
|
||||
Assert.True(tracker.Record("1.2.3.4", policy, T0.AddSeconds(2)).OverBudget);
|
||||
|
||||
var next = tracker.Record("1.2.3.4", policy, T0.AddSeconds(31));
|
||||
Assert.Equal(1, next.Count);
|
||||
Assert.False(next.OverBudget);
|
||||
Assert.Equal(T0.AddSeconds(31), next.WindowStart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_source_has_its_own_window_and_its_own_count()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 1);
|
||||
|
||||
Assert.False(tracker.Record("1.2.3.4", policy, T0).OverBudget);
|
||||
Assert.True(tracker.Record("1.2.3.4", policy, T0).OverBudget);
|
||||
Assert.False(tracker.Record("5.6.7.8", policy, T0).OverBudget);
|
||||
Assert.Equal(2, tracker.TrackedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_budget_of_zero_is_not_a_limit_and_refuses_nothing()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = new EdgePolicy { Rate = RateMode.Enforce, RateLimitPerWindow = 0 };
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
Assert.False(tracker.Record("1.2.3.4", policy, T0.AddSeconds(i)).OverBudget);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_map_is_bounded_so_a_farm_of_new_addresses_cannot_grow_the_process()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 5);
|
||||
tracker.Configure(policy with { MaxTrackedSources = 10 });
|
||||
|
||||
for (var i = 0; i < 500; i++)
|
||||
tracker.Record($"10.0.0.{i % 251}", policy, T0.AddSeconds(i / 251));
|
||||
|
||||
Assert.Equal(10, tracker.TrackedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_idle_source_stops_being_counted()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 5);
|
||||
|
||||
tracker.Record("1.2.3.4", policy, T0);
|
||||
Assert.Equal(1, tracker.TrackedCount);
|
||||
|
||||
tracker.LiveRates(T0.AddHours(3), policy with { StateIdleTtl = TimeSpan.FromMinutes(10) },
|
||||
10, 0, out var live);
|
||||
Assert.Equal(0, live);
|
||||
Assert.Equal(0, tracker.TrackedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_listing_shows_only_windows_that_are_still_running_biggest_first()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 10, windowSeconds: 30);
|
||||
|
||||
for (var i = 0; i < 4; i++) tracker.Record("1.2.3.4", policy, T0);
|
||||
for (var i = 0; i < 2; i++) tracker.Record("5.6.7.8", policy, T0);
|
||||
// A window that has already run out is about to restart at zero.
|
||||
tracker.Record("9.9.9.9", policy, T0.AddSeconds(-120));
|
||||
|
||||
var rows = tracker.LiveRates(T0.AddSeconds(10), policy, 10, 0, out var total);
|
||||
Assert.Equal(2, total);
|
||||
Assert.Equal(2, rows.Count);
|
||||
Assert.Equal("1.2.3.4", rows[0].SourceKey);
|
||||
Assert.Equal(4, rows[0].Count);
|
||||
Assert.False(rows[0].OverBudget);
|
||||
Assert.Equal(T0.AddSeconds(30), rows[0].WindowEnd);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_filtered_listing_counts_only_what_it_shows()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 10);
|
||||
|
||||
tracker.Record("1.2.3.4", policy, T0);
|
||||
tracker.Record("5.6.7.8", policy, T0);
|
||||
|
||||
var rows = tracker.LiveRates(T0, policy, 10, 0, "5.6.7.8", out var total);
|
||||
Assert.Single(rows);
|
||||
Assert.Equal(1, total);
|
||||
Assert.Equal(2, tracker.TrackedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Forgetting_a_source_clears_its_window()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 1);
|
||||
|
||||
tracker.Record("1.2.3.4", policy, T0);
|
||||
Assert.True(tracker.Record("1.2.3.4", policy, T0).OverBudget);
|
||||
|
||||
tracker.Forget("1.2.3.4");
|
||||
Assert.Equal(0, tracker.TrackedCount);
|
||||
Assert.False(tracker.Record("1.2.3.4", policy, T0).OverBudget);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_source_without_an_address_costs_nothing_and_claims_nothing()
|
||||
{
|
||||
var tracker = new RateTracker();
|
||||
var policy = Policy(limit: 1);
|
||||
|
||||
var seen = tracker.Record("", policy, T0);
|
||||
Assert.Equal(0, seen.Count);
|
||||
Assert.False(seen.OverBudget);
|
||||
Assert.False(seen.BreachStarted);
|
||||
Assert.Equal(0, tracker.TrackedCount);
|
||||
}
|
||||
}
|
||||
@@ -481,6 +481,56 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||||
check('removing the rule from the page lets the path flow again',
|
||||
flowed === 404, `after removal: ${flowed}`);
|
||||
|
||||
// The volume pillar (OPEN-56). Its own address, and the budget is switched
|
||||
// back off at the end: a left-behind budget of two requests would refuse the
|
||||
// probes every later scene makes, and the failure would read as a page bug.
|
||||
const RATE_IP = '203.0.113.199';
|
||||
const rateNoteOf = async () => (await page.textContent('#ratenote')).replace(/\s+/g, ' ').trim();
|
||||
const offNote = await rateNoteOf();
|
||||
check('the budget line says off means nothing is counted',
|
||||
/^off/.test(offNote) && /nothing is being counted/.test(offNote), JSON.stringify(offNote));
|
||||
|
||||
await page.selectOption('#rateMode', 'enforce');
|
||||
await page.fill('#rateLimit', '2');
|
||||
await page.fill('#rateWindow', '120');
|
||||
await page.click('#setRate');
|
||||
await page.waitForFunction(
|
||||
() => /enforce · 2 requests per 120 s/.test(document.getElementById('ratenote').textContent),
|
||||
null, { timeout: 15000 }).catch(() => {});
|
||||
const onNote = await rateNoteOf();
|
||||
check('the page can write a budget and the line reads back what is in force',
|
||||
/enforce · 2 requests per 120 s per source/.test(onNote) && /this process/.test(onNote),
|
||||
JSON.stringify(onNote));
|
||||
|
||||
const rateProbe1 = await probePath('/gate-rate-probe', RATE_IP);
|
||||
const rateProbe2 = await probePath('/gate-rate-probe', RATE_IP);
|
||||
const rateProbe3 = await probePath('/gate-rate-probe', RATE_IP);
|
||||
check('the request that crosses the budget is answered by the edge, not the application',
|
||||
rateProbe3.status === 429 && /rate_limited/.test(rateProbe3.text)
|
||||
&& rateProbe1.status === 404 && rateProbe2.status === 404,
|
||||
`${rateProbe1.status} ${rateProbe2.status} ${rateProbe3.status} `
|
||||
+ JSON.stringify(rateProbe3.text.slice(0, 120)));
|
||||
|
||||
await page.click('#refresh');
|
||||
await page.waitForFunction(
|
||||
(ip) => [...document.querySelectorAll('#ratetable tbody tr')]
|
||||
.some((r) => r.children[0].textContent === ip),
|
||||
RATE_IP, { timeout: 15000 }).catch(() => {});
|
||||
const rateRows = await cells('#ratetable tbody tr');
|
||||
check('the budget table counts the source and marks it over budget',
|
||||
rateRows.some((r) => r[0] === RATE_IP && Number(r[1]) >= 3 && r[2] === '2'),
|
||||
JSON.stringify(rateRows.map((r) => [r[0], r[1], r[2]])));
|
||||
|
||||
await page.selectOption('#rateMode', 'off');
|
||||
await page.click('#setRate');
|
||||
await page.waitForFunction(
|
||||
() => /^off/.test(document.getElementById('ratenote').textContent),
|
||||
null, { timeout: 15000 }).catch(() => {});
|
||||
await clearEngineBan(RATE_IP);
|
||||
const backOff = await rateNoteOf();
|
||||
check('the budget can be switched off from the page',
|
||||
/^off/.test(backOff), JSON.stringify(backOff));
|
||||
|
||||
// The failure mode worth asserting on a write form is the quiet one: the
|
||||
// operator believes they blocked an address and did not. A typo in the field
|
||||
// must come back as the API's own error, not as a status line that says
|
||||
|
||||
+71
-1
@@ -21,6 +21,17 @@ TOKEN=smoketoken
|
||||
BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Release/net10.0/OpenWaf.Edge.dll"
|
||||
[ -f "$BIN" ] || BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Debug/net10.0/OpenWaf.Edge.dll"
|
||||
|
||||
# The content root is the directory that holds appsettings.json, and ASP.NET
|
||||
# Core takes it from the current directory — which here is the repository root,
|
||||
# where there is no appsettings.json. Measured: started this way the edge 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
|
||||
# smoke assertion below expects 404 or a refusal, so the gate kept passing on an
|
||||
# edge that never proxied anything. Naming the content root is what makes the
|
||||
# first line of this file's comment — "proxies to a real upstream" — true.
|
||||
BIN_DIR="$(dirname "$BIN")"
|
||||
|
||||
export HEALTHCHECK_PORT="$EDGE_PORT"
|
||||
|
||||
SCANNER=203.0.113.66
|
||||
@@ -33,6 +44,11 @@ Bystander=198.51.100.99
|
||||
BLOCK_JSON='{"ip":"198.51.100.7","reason":"confirmed scraper","redirectTo":"https://honeypot.example.org/"}'
|
||||
ALLOW_JSON='{"match":"198.51.100.0/24","note":"office"}'
|
||||
POLICY_OFF_JSON='{"mode":"Off"}'
|
||||
# The volume pillar (OPEN-56). A window long enough that the scene below cannot
|
||||
# race it, and a budget small enough to cross in three requests.
|
||||
RATE_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":2,"rateWindowSeconds":120}'
|
||||
RATE_OFF_JSON='{"rateMode":"Off"}'
|
||||
RATE_BAD_JSON='{"rateLimitPerWindow":0}'
|
||||
|
||||
|
||||
cleanup() {
|
||||
@@ -55,7 +71,7 @@ OpenWaf__Policy__Mode=Enforce \
|
||||
OpenWaf__Policy__BanDuration="00:00:06" \
|
||||
OpenWaf__Policy__TrustProxyHeaders=true \
|
||||
ReverseProxy__Clusters__upstream__Destinations__upstream1__Address="http://127.0.0.1:$UP_PORT/" \
|
||||
dotnet "$BIN" >/tmp/openwaf-smoke.log 2>&1 &
|
||||
dotnet "$BIN" --contentRoot "$BIN_DIR" >/tmp/openwaf-smoke.log 2>&1 &
|
||||
EDGE_PID=$!
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
@@ -78,6 +94,17 @@ for i in 1 2 3; do
|
||||
check "probe $i from the scanner reaches the upstream" 404 \
|
||||
"$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")"
|
||||
done
|
||||
# The ban is written out of band, after the response that proved it has been
|
||||
# sent, and the snapshot the guard reads is refreshed by that write. So the
|
||||
# gate has to wait for the row to exist before it asks the wire whether the ban
|
||||
# is enforced — otherwise it is racing a durable write and the answer depends on
|
||||
# how busy the disk is. The wait is bounded, and a timeout leaves the ban
|
||||
# missing, which is exactly what the assertion below then reports.
|
||||
for _ in $(seq 1 40); do
|
||||
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
|
||||
| grep -q "$SCANNER" && break
|
||||
sleep 0.25
|
||||
done
|
||||
check '4th request from the scanner is refused by the edge' 403 \
|
||||
"$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")"
|
||||
check 'a bystander is untouched' 404 \
|
||||
@@ -146,6 +173,49 @@ check 'the rule can be removed by id' 204 \
|
||||
check 'and the path flows again once it is gone' 404 \
|
||||
"$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")"
|
||||
|
||||
# The volume pillar, and the one claim it exists to make: the origin is happy to
|
||||
# serve this traffic, so no streak, no rule and no list says anything about it —
|
||||
# only the count does. index.html is the 200 this upstream will give.
|
||||
echo 'openwaf smoke' > /tmp/openwaf-upstream/index.html
|
||||
RATE_IP=203.0.113.88
|
||||
echo '- volume budget'
|
||||
STATE0_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")"
|
||||
check 'the budget is off until an operator writes one' Off \
|
||||
"$(printf '%s' "$STATE0_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
|
||||
check 'a written budget is live without a restart' Enforce \
|
||||
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$RATE_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
|
||||
check 'a budget outside its range is refused by name' 400 \
|
||||
"$(code -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$RATE_BAD_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy")"
|
||||
check 'the first request inside the budget is proxied' 200 \
|
||||
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
|
||||
check 'so is the second' 200 \
|
||||
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
|
||||
check 'the third crosses the budget and is answered by the edge' 429 \
|
||||
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
|
||||
check 'the refusal says when the pause ends' yes \
|
||||
"$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $RATE_IP" "$(from index.html)" \
|
||||
| grep -qi '^retry-after:' && echo yes || echo no)"
|
||||
check 'the breach wrote an engine ban the operator can see' 1 \
|
||||
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
|
||||
| python3 -c "import sys,json;print(len([b for b in json.load(sys.stdin) if b['sourceKey']=='$RATE_IP']))")"
|
||||
check 'and the ban says volume, not refusals' rate \
|
||||
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
|
||||
| python3 -c "import sys,json;print('rate' if any('rate policy' in (b.get('reason') or '') for b in json.load(sys.stdin) if b['sourceKey']=='$RATE_IP') else 'none')")"
|
||||
check 'the listing says what the limiter counted' 3 \
|
||||
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate?source=$RATE_IP" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)["sources"][0]["count"])')"
|
||||
check 'the operator can clear the ban the breach wrote' '{"deleted":1}' \
|
||||
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
|
||||
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine&key=$RATE_IP" | tr -d ' ')"
|
||||
check 'the budget can be switched off again' Off \
|
||||
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
|
||||
rm -f /tmp/openwaf-upstream/index.html
|
||||
|
||||
echo '- expiry and clearing'
|
||||
sleep 7
|
||||
check 'the engine ban lifted itself' 404 "$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")"
|
||||
|
||||
Reference in New Issue
Block a user