Files
openwaf/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs
T
Pavlo Ratushnyi bcfc83db40 one address in, and the edge answers everything it knows about it
An operator investigating one source had to open six admin calls — blocks,
allow, streaks, observations, alerts, the dry run — and hold the join in their
head. The join is where the wrong answers are: a v6 address looked up in full
when the ban is filed on the /64, a CIDR ban looked up by equality that never
finds it, an exemption that expired last week read as a live one, a streak
counted in one process read as the deployment's.

GET /admin-api/source?ip=<address>[&path=<path>] answers it in one call, by
asking the same objects the request path asks rather than a second copy of
their logic. Three rulings hold it together:

  * Containment, not equality. operatorBlock carries cameFromRange and the
    match that covered the address, through the same NetworkBanIndex the wire
    matches with (longest prefix first) and NetworkMatch for the allowlist.
    There is no second matcher in this build to drift.
  * The key, not the address. sourceKey and the prefix lengths that produced
    it travel in the answer: bans, streaks and budgets are filed under the key,
    the allowlist and the range bans are matched against the address, and the
    answer separates them.
  * `none` and "not visible here" are different words. A live engine ban under
    Observe mode reports applies: false with a verdict of none; an expired row
    reports live: false rather than null, because "this address used to be
    exempt" is a fact an operator acts on.

Nothing is written and nothing is spent — the dry run's rule applied to the
whole dossier. RateRuleTracker.WindowsFor is a new read that lists every path
budget a source is already inside without being handed a path, so the dossier
does not have to guess from a path it was not given, and N dossiers leave every
counter where they found it. ip is required and must be a full address: a typo
is a 400 naming the value, never a none. The read-only token may ask it.

What the run caught, on this tree: the console scene waited for "an answer is
in the box", which the previous answer still sitting there satisfies — three
assertions read the address asked one click earlier. The scene now empties the
box and waits for the address it asked by name, and matches a range row by the
key its delete button holds rather than by a cell that prints a `range` badge.

build 0 warnings / 0 errors, unit 374/374, integration 356/356 in 39 s,
console 126 assertions / 0 failed, smoke passed 192 / failed 0, compose 311
passed / 0 failed against the built image at 262 MB.

Refs OPEN-70.
2026-10-05 09:43:39 +02:00

236 lines
9.4 KiB
C#

using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The per-path budget counter (OPEN-68), on its own. The integration tests ask
/// whether the edge refuses; these ask whether the counting itself is the thing
/// the operator wrote — one window per source, one breach per window, and a
/// memory bound that holds when the source keys do not stop coming.
/// </summary>
public sealed class RateRuleTrackerTests
{
private static readonly DateTimeOffset T0 = new(2026, 10, 5, 12, 0, 0, TimeSpan.Zero);
private static RateRule Rule(long id, string pattern, int limit, int windowSeconds = 60) =>
new() { Id = id, Pattern = pattern, LimitPerWindow = limit, WindowSeconds = windowSeconds };
[Fact]
public void The_window_starts_at_the_first_request_and_restarts_after_it_runs_out()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 3);
var first = tracker.Record(rule, "203.0.113.1", T0);
Assert.Equal(1, first.Count);
Assert.Equal(T0, first.WindowStart);
Assert.Equal(T0.AddSeconds(60), first.WindowEnd);
tracker.Record(rule, "203.0.113.1", T0.AddSeconds(10));
var inside = tracker.Record(rule, "203.0.113.1", T0.AddSeconds(20));
Assert.Equal(3, inside.Count);
Assert.False(inside.OverBudget);
// Still the same window: the budget is per window, not per minute.
var last = tracker.Record(rule, "203.0.113.1", T0.AddSeconds(59));
Assert.Equal(4, last.Count);
Assert.Equal(T0, last.WindowStart);
var after = tracker.Record(rule, "203.0.113.1", T0.AddSeconds(61));
Assert.Equal(1, after.Count);
Assert.Equal(T0.AddSeconds(61), after.WindowStart);
Assert.False(after.OverBudget);
}
[Fact]
public void Only_the_request_that_crosses_the_budget_starts_a_breach()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 2);
Assert.False(tracker.Record(rule, "a", T0).OverBudget);
Assert.False(tracker.Record(rule, "a", T0.AddSeconds(1)).OverBudget);
var crossed = tracker.Record(rule, "a", T0.AddSeconds(2));
Assert.True(crossed.OverBudget);
Assert.True(crossed.BreachStarted);
// Over budget is a state that goes on for the rest of the window; the
// breach is the one event in it. An alert per request is how a defence
// turns into write amplification.
var later = tracker.Record(rule, "a", T0.AddSeconds(3));
Assert.True(later.OverBudget);
Assert.False(later.BreachStarted);
}
[Fact]
public void Two_rules_count_the_same_source_separately()
{
var tracker = new RateRuleTracker();
var login = Rule(1, "/login*", 2);
var api = Rule(2, "/api/*", 5);
tracker.Record(login, "a", T0);
tracker.Record(login, "a", T0.AddSeconds(1));
var overLogin = tracker.Record(login, "a", T0.AddSeconds(2));
Assert.True(overLogin.OverBudget);
var underApi = tracker.Record(api, "a", T0.AddSeconds(3));
Assert.Equal(1, underApi.Count);
Assert.False(underApi.OverBudget);
// One window per (rule, source), not one per request: the count inside
// that window is what the budget is measured against.
Assert.Equal(1, tracker.TrackedCount(login.Id));
Assert.Equal(1, tracker.TrackedCount(api.Id));
}
[Fact]
public void The_cap_holds_the_newest_pairs_and_says_nothing_about_the_rest()
{
var tracker = new RateRuleTracker();
tracker.Configure(new EdgePolicy { MaxTrackedSources = 3 });
var rule = Rule(1, "/x*", 10);
for (var i = 0; i < 5; i++)
tracker.Record(rule, $"10.0.0.{i}", T0.AddSeconds(i));
Assert.Equal(3, tracker.TrackedCount(rule.Id));
// The two oldest sources were dropped, so their next request starts a
// fresh window. That is the documented cost of a bounded counter, and it
// is the reason the cap is a policy key rather than a constant.
Assert.Equal(1, tracker.Record(rule, "10.0.0.0", T0.AddSeconds(10)).Count);
Assert.Equal(2, tracker.Record(rule, "10.0.0.4", T0.AddSeconds(11)).Count);
}
[Fact]
public void Removing_a_rule_takes_its_counters_with_it()
{
var tracker = new RateRuleTracker();
var rule = Rule(7, "/login*", 2);
tracker.Record(rule, "a", T0);
Assert.Equal(1, tracker.TrackedCount(7));
tracker.ForgetRule(7);
Assert.Equal(0, tracker.TrackedCount(7));
// A later rule reusing the id must not inherit a window it never started.
Assert.Equal(1, tracker.Record(Rule(7, "/login*", 2), "a", T0.AddSeconds(1)).Count);
}
[Fact]
public void An_allowlisted_source_stops_being_counted()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 2);
tracker.Record(rule, "a", T0);
tracker.Record(rule, "b", T0);
Assert.Equal(2, tracker.TrackedCount(1));
tracker.ForgetSource("a");
Assert.Equal(1, tracker.TrackedCount(1));
}
[Fact]
public void The_live_listing_reports_the_windows_that_are_still_running()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 2);
tracker.Record(rule, "quiet", T0);
tracker.Record(rule, "loud", T0);
tracker.Record(rule, "loud", T0.AddSeconds(1));
tracker.Record(rule, "loud", T0.AddSeconds(2));
tracker.Record(rule, "loud", T0.AddSeconds(3));
// A window that has already run out is not "over budget now".
tracker.Record(rule, "early", T0.AddSeconds(-120));
var (live, over) = tracker.LiveCounts(1, 2, T0.AddSeconds(10));
// The run-out window is not "running", and the quiet source is running
// but not over: the pair is what tells an operator whether the number
// they wrote is a defence or their own traffic.
Assert.Equal(2, live);
Assert.Equal(1, over);
// Past every window, nothing is running and nothing is over.
Assert.Equal((0, 0), tracker.LiveCounts(1, 2, T0.AddSeconds(120)));
}
// The dossier (OPEN-70) asks "which path budgets is this source already
// inside" without naming a path, because the operator is asking about the
// source, not about a request.
[Fact]
public void One_source_can_be_asked_which_budgets_are_counting_it()
{
var tracker = new RateRuleTracker();
var login = Rule(1, "/login*", 2);
var api = Rule(7, "/api/*", 5, windowSeconds: 120);
var other = Rule(9, "/other*", 5);
tracker.Record(login, "203.0.113.1", T0);
tracker.Record(login, "203.0.113.1", T0.AddSeconds(1));
tracker.Record(api, "203.0.113.1", T0.AddSeconds(2));
tracker.Record(login, "someone-else", T0);
tracker.Record(other, "someone-else", T0);
var rows = tracker.WindowsFor("203.0.113.1", T0.AddSeconds(3));
// Only this source's windows, ordered by rule id so two calls answer in
// the same order, and the window length travels with the row.
Assert.Equal(2, rows.Count);
Assert.Equal(1L, rows[0].RuleId);
Assert.Equal(2, rows[0].Count);
Assert.Equal(T0.AddSeconds(60), rows[0].WindowEnd);
Assert.Equal(60, rows[0].WindowSeconds);
Assert.Equal(7L, rows[1].RuleId);
Assert.Equal(1, rows[1].Count);
Assert.Equal(120, rows[1].WindowSeconds);
}
[Fact]
public void A_window_that_has_run_out_is_not_a_budget_this_source_is_inside()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 5);
tracker.Record(rule, "203.0.113.1", T0);
Assert.Single(tracker.WindowsFor("203.0.113.1", T0.AddSeconds(59)));
// "0 of 5" from a dead window is a different claim from "nothing yet", and
// the dossier has to be able to tell them apart — so it reports neither.
Assert.Empty(tracker.WindowsFor("203.0.113.1", T0.AddSeconds(61)));
// A source nobody ever counted answers with nothing, not with a row at
// zero, and an empty key never reaches into the map at all.
Assert.Empty(tracker.WindowsFor("never-seen", T0));
Assert.Empty(tracker.WindowsFor("", T0));
}
[Fact]
public void Asking_which_budgets_are_counting_a_source_spends_none_of_them()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 2);
tracker.Record(rule, "203.0.113.1", T0);
tracker.Record(rule, "203.0.113.1", T0.AddSeconds(1));
tracker.WindowsFor("203.0.113.1", T0.AddSeconds(2));
tracker.WindowsFor("203.0.113.1", T0.AddSeconds(2));
// The dossier's whole rule: a page that answers by counting its own
// question would refuse the next real request because somebody looked.
var next = tracker.Record(rule, "203.0.113.1", T0.AddSeconds(3));
Assert.Equal(3, next.Count);
Assert.Equal(T0, next.WindowStart);
}
[Fact]
public void An_unidentifiable_source_is_not_counted()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 1);
var blank = tracker.Record(rule, "", T0);
Assert.Equal(0, blank.Count);
Assert.False(blank.OverBudget);
Assert.Equal(0, tracker.TrackedCount(1));
}
}