diff --git a/README.md b/README.md index 5e7cd52..e6db09e 100644 --- a/README.md +++ b/README.md @@ -409,6 +409,9 @@ GET /admin-api/netblocks the blocks the edge's own bans point at, wit GET /admin-api/rules path patterns, in the order they are enforced POST {"pattern","action":"observe|block","note","expiresInMinutes"} DELETE /admin-api/rules/{id} +GET /admin-api/rate-rules per-path request budgets, with what each is counting + POST {"pattern","limitPerWindow","windowSeconds","note","expiresInMinutes"} + DELETE /admin-api/rate-rules/{id} GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false GET /admin-api/countries/summary sources and refusals per country, from the aggregates GET /admin-api/geo which database is loaded and how old it is @@ -1085,6 +1088,63 @@ What it costs: one scan every five minutes over a table the edge already keeps, off the request path. Nothing on the request path changed — a candidate is read by a surface, not by a guard. +### A request budget for one path + +The volume budget is one number for the whole edge, and for a login path that +number is always wrong: a hundred requests a minute does not stop a +credential-stuffing run that makes twenty attempts a minute — twenty looks like a +person — while five a minute locks an honest office behind one NAT out of every +page they own. The only way to make both statements true is to price the paths +differently. + +`rate_rules` is that row: a glob over the request path — the same `PathPattern` +matcher as a path rule, anchored, case-insensitive, `*` and `?` only — with its +own `limitPerWindow` and `windowSeconds`. The window is per source and starts when +that source first asks, exactly as the edge-wide window does; the request that +crosses the limit is the breach, and it is the only one that alerts. + +What it is not, and the difference is the whole feature: + +* **It is not a path rule.** A path rule refuses a request because of what it + asked for; a budget refuses it because of how often that source asked. +* **It is not a ban.** Crossing a path budget pauses that source on that path for + the rest of that window and writes nothing that outlives it: no engine ban row, + the rest of the site stays open, and the answer is `429` with a `Retry-After` + naming the rest of the window. The reason names the rule, its count, its limit + and the pattern it was written for (`rate_rule_1_4_of_2_for_/login*`), so a log + line says which budget fired without opening the console. +* **It is not a second switch.** The budgets hang off `rateMode`: `Enforce` + refuses, `Observe` counts and raises one `rate_breach` alert per source per + window naming the pattern, `Off` counts nothing at all. An operator deciding + whether a number is a defence or their own traffic writes it in observe first, + and the listing answers with `trackedSources`, `liveWindows` and + `overBudgetNow` — the pair that separates "nobody has blown this" from "nobody + can". + +The bounds are the policy's own (`1..100000` requests, `1..3600` seconds), so one +vocabulary of numbers covers both budgets. A second live budget for one pattern is +refused with `409` — two live numbers for one path mean the stricter one wins by +accident rather than by the operator's choice — and at most +`PathPattern.MaxRules` (500) live budgets, because every request is checked +against each of them. A budget expires on its own (`expiresInMinutes`) and the +listing keeps showing it as `live: false` until it is deleted. + +Counters are per process, so N edges allow N times the budget — the same +documented seam as the edge-wide counter, and the reason both share +`maxTrackedSources`: the cap counts (rule, source) pairs together, the +least-recently-touched evicted first. + +```bash +curl -s -H "X-Admin-Token: $TOKEN" 'http://edge:8080/admin-api/rate-rules' +# [{"id":1,"pattern":"/login*","limitPerWindow":20,"windowSeconds":60, +# "note":"credential stuffing","createdAt":"…","expiresAt":null,"live":true, +# "trackedSources":7,"overBudgetNow":1,"liveWindows":6}] +``` + +What it costs: one glob match per live budget per request, and one counter per +(rule, source) pair inside the cap. A budget travels in the export/import document +as the `rateRules` section, and it is one of the sections the change log records. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1093,7 +1153,13 @@ live bans with their reasons, the streak standing in this process right now being watched, and the countries seen — counted per ISO code, with a bar per 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 +counter holds right now, with the over-budget count marked. Path budgets (OPEN-68) get +their own table beside it: the pattern, its two numbers, and three counters — +sources counted, windows running, over budget now — with the last one marked, and +a form that writes one with a pattern, two numbers, a note and an optional expiry. +The line under the table distinguishes a database with no rate-rule table from an +operator who wrote no budgets, which is the difference between a migration to +apply and a decision not to make. 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 @@ -1288,9 +1354,10 @@ 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-05 with the durable alert-push queue, the config transfer, the second token, the startup refusals, the change -log and that log on the console, the operator's ranges and the netblock watch: -build 0 warnings / 0 errors, unit **353/353**, integration **326/326 in 31 s**, -console **114 assertions, 0 failed**, smoke **passed 149, failed 0**, and compose **293 passed, +log and that log on the console, the operator's ranges, the netblock watch and +the per-path request budgets: +build 0 warnings / 0 errors, unit **361/361**, integration **337/337 in 30 s**, +console **120 assertions, 0 failed**, smoke **passed 169, failed 0**, and compose **300 passed, 0 failed** against the built image at 262 MB, 0 containers left behind. 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 diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs index 96d444e..bc8eefd 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs @@ -37,6 +37,14 @@ public sealed record EdgeSnapshot /// hidden inside a dictionary would be unreadable. public IReadOnlyList RequestRules { get; init; } = []; + /// The operator's per-path budgets (OPEN-68), in the order they were + /// written. They are not part of : a budget is a + /// count, and a count has to be kept while the requests arrive rather than + /// read from a snapshot built between them. The snapshot carries the rules so + /// the guard sees the same list the operator sees, and sees it without a + /// database read. + public IReadOnlyList RateRules { get; init; } = []; + public static EdgeSnapshot Empty(EdgePolicy policy) => new() { GeneratedAt = DateTimeOffset.MinValue, Policy = policy }; } diff --git a/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs b/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs new file mode 100644 index 0000000..de87091 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs @@ -0,0 +1,211 @@ +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Domain.Engine; + +/// +/// The per-path budgets (OPEN-68): how often one source asked for one rule's +/// paths, inside a window that started when that source first asked. +/// +/// A separate counter from rather than a scope inside +/// it, for two reasons. The edge-wide counter reads its limit and window from the +/// policy, and a rule carries its own — one map whose parameters change per +/// entry is a map whose eviction and idle rules stop meaning anything. And the +/// operator's rate listing answers "who is over the site's budget"; a rule's +/// counters are a different question and should not appear in that answer with a +/// composite key the operator cannot read. +/// +/// The same two protections as the edge-wide counter, because they are the same +/// problem: bounded memory (at most +/// source-and-rule pairs, least-recently-touched evicted first, idle sources aged +/// out) and no I/O. The consequence is stated where it is read: the counters are +/// per edge, so N edges allow N times the budget. +/// +/// Fixed windows, same trade as the edge-wide counter, same documented seam. +/// +public sealed class RateRuleTracker +{ + private readonly object _gate = new(); + private readonly Dictionary<(long Rule, string Source), RuleRateState> _states = new(); + private readonly LinkedList<(long Rule, string Source)> _lru = new(); + private int _maxCap = 10_000; + + public void Configure(EdgePolicy policy) => _maxCap = Math.Max(1, policy.MaxTrackedSources); + + /// Count one request against one rule and say what its budget now + /// thinks of this source. + public RuleRateObservation Record( + RateRule rule, string sourceKey, DateTimeOffset now) + { + if (string.IsNullOrEmpty(sourceKey)) + return new RuleRateObservation(0, false, now, now, false); + + var window = rule.Window; + var key = (rule.Id, sourceKey); + + lock (_gate) + { + if (!_states.TryGetValue(key, out var state)) + { + while (_states.Count >= _maxCap) RemoveOldest(); + state = new RuleRateState + { + Rule = rule.Id, + SourceKey = sourceKey, + WindowStart = now, + Count = 0, + LastSeenAt = now + }; + _states[key] = state; + state.LruNode = _lru.AddLast(key); + } + + Touch(key, state); + state.LastSeenAt = now; + // The window length travels with the state, so the listing can say + // when a window ends without being handed the rule again. + state.WindowLength = window; + + if (state.Count == 0 || now >= state.WindowStart + window) + { + state.WindowStart = now; + state.Count = 0; + } + + state.Count++; + var end = state.WindowStart + window; + var over = rule.LimitPerWindow > 0 && state.Count > rule.LimitPerWindow; + + return new RuleRateObservation( + state.Count, over, state.WindowStart, end, + // Exactly one request per window is the one that crossed, and + // only it may alert. Same ruling as the edge-wide budget: an + // alert per request is how a defence becomes write amplification. + BreachStarted: over && state.Count == rule.LimitPerWindow + 1); + } + } + + /// The two numbers the listing shows beside a rule: how many sources + /// still have a running window for it, and how many of those are over the + /// budget right now. Counted in one lock, so the pair cannot describe two + /// different moments — "nothing is over it" next to "nobody is being counted" + /// is the reading that decides whether a budget is worth keeping. + public (int LiveWindows, int OverBudgetNow) LiveCounts( + long ruleId, int limitPerWindow, DateTimeOffset now) + { + lock (_gate) + { + var live = 0; + var over = 0; + foreach (var s in _states.Values) + { + if (s.Rule != ruleId) continue; + if (now >= s.WindowStart + s.WindowLength) continue; + live++; + if (limitPerWindow > 0 && s.Count > limitPerWindow) over++; + } + return (live, over); + } + } + + /// How many sources this rule is holding a window for, live or not — + /// the number that says whether the rule is counting anything at all. + public int TrackedCount(long ruleId) + { + lock (_gate) return _states.Count(s => s.Key.Rule == ruleId); + } + + /// A rule was removed: its counters go with it. Leaving them would + /// keep counting for a budget the operator took off the edge. + public void ForgetRule(long ruleId) + { + lock (_gate) + { + List<(long, string)>? doomed = null; + foreach (var kv in _states) + { + if (kv.Key.Rule != ruleId) continue; + doomed ??= []; + doomed.Add(kv.Key); + } + if (doomed is null) return; + foreach (var key in doomed) + { + if (_states.Remove(key, out var s)) RemoveNode(s); + } + } + } + + /// An operator allowlisted or cleared a source: stop holding its + /// windows, on every rule. + public void ForgetSource(string sourceKey) + { + lock (_gate) + { + List<(long, string)>? doomed = null; + foreach (var kv in _states) + { + if (!string.Equals(kv.Value.SourceKey, sourceKey, StringComparison.Ordinal)) continue; + doomed ??= []; + doomed.Add(kv.Key); + } + if (doomed is null) return; + foreach (var key in doomed) + { + if (_states.Remove(key, out var s)) RemoveNode(s); + } + } + } + + public void Clear() + { + lock (_gate) + { + _states.Clear(); + _lru.Clear(); + } + } + + private void Touch((long, string) key, RuleRateState state) + { + if (state.LruNode is null) return; + _lru.Remove(state.LruNode); + state.LruNode = _lru.AddLast(key); + } + + private void RemoveOldest() + { + var oldest = _lru.First; + if (oldest is null) return; + _lru.RemoveFirst(); + _states.Remove(oldest.Value); + } + + private void RemoveNode(RuleRateState s) + { + if (s.LruNode is not null) + { + _lru.Remove(s.LruNode); + s.LruNode = null; + } + } +} + +internal sealed class RuleRateState +{ + public required long Rule { get; init; } + public required string SourceKey { get; init; } + public DateTimeOffset WindowStart { get; set; } + public int Count { get; set; } + public DateTimeOffset LastSeenAt { get; set; } + public TimeSpan WindowLength { get; set; } = TimeSpan.FromMinutes(1); + public LinkedListNode<(long Rule, string Source)>? LruNode { get; set; } +} + +/// What one counted request says about one source's budget for one rule. +public sealed record RuleRateObservation( + int Count, + bool OverBudget, + DateTimeOffset WindowStart, + DateTimeOffset WindowEnd, + bool BreachStarted); diff --git a/dotnet/OpenWaf.Domain/Security/ConfigChange.cs b/dotnet/OpenWaf.Domain/Security/ConfigChange.cs index d78de4d..aa1c74d 100644 --- a/dotnet/OpenWaf.Domain/Security/ConfigChange.cs +++ b/dotnet/OpenWaf.Domain/Security/ConfigChange.cs @@ -61,12 +61,13 @@ public static class ConfigChangeLog public const string SectionBlocks = "block"; public const string SectionAllow = "allow"; public const string SectionRules = "rule"; + public const string SectionRateRules = "rate rule"; public const string SectionCountries = "country"; public const string SectionPolicy = "policy"; public const string SectionConfig = "config"; public static readonly string[] Sections = - [SectionBlocks, SectionAllow, SectionRules, SectionCountries, SectionPolicy, SectionConfig]; + [SectionBlocks, SectionAllow, SectionRules, SectionRateRules, SectionCountries, SectionPolicy, SectionConfig]; public const string ActionAdded = "added"; public const string ActionRemoved = "removed"; diff --git a/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs index b6a91e6..7253d8b 100644 --- a/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs +++ b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs @@ -1,4 +1,5 @@ using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; namespace OpenWaf.Domain.Security; @@ -32,6 +33,16 @@ public sealed record ExportedAllow(string Match, string? Note, DateTimeOffset? E /// and the order in the document is the order the engine evaluates them in. public sealed record ExportedRule(string Pattern, string? Action, string? Note, DateTimeOffset? ExpiresAt); +/// A request budget for one path (OPEN-68). The numbers are nullable so +/// a document written by a hand that left them out means "use this build's +/// defaults", which is the same thing an absent action means for a path rule. +public sealed record ExportedRateRule( + string Pattern, + int? LimitPerWindow, + int? WindowSeconds, + string? Note, + DateTimeOffset? ExpiresAt); + /// A country decision. public sealed record ExportedCountry(string Code, bool Allowed); @@ -109,6 +120,23 @@ public static class ConfigTransfer return null; } + public static string? ExplainRateRule(ExportedRateRule rule) + { + var patternProblem = PathPattern.ExplainRejection(rule.Pattern); + if (patternProblem is not null) return patternProblem; + if (!EntryLimits.NoteOk(rule.Note)) + return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {rule.Note!.Length}"; + // The same bounds the live endpoint applies to a typed request, so a + // document cannot bring in a budget the API would have refused. + var limit = rule.LimitPerWindow ?? RateRule.DefaultLimitPerWindow; + if (!PolicyBounds.RateLimitPerWindowOk(limit)) + return $"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {limit}"; + var window = rule.WindowSeconds ?? RateRule.DefaultWindowSeconds; + if (!PolicyBounds.RateWindowSecondsOk(window)) + return $"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {window}"; + return null; + } + public static string? ExplainCountry(ExportedCountry country) { if (CountryCode(country.Code) is null) diff --git a/dotnet/OpenWaf.Domain/Security/RateRule.cs b/dotnet/OpenWaf.Domain/Security/RateRule.cs new file mode 100644 index 0000000..79ae112 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/RateRule.cs @@ -0,0 +1,63 @@ +namespace OpenWaf.Domain.Security; + +/// +/// A request budget written for one path rather than for the whole edge (OPEN-68). +/// +/// The edge-wide budget (OPEN-56) is one number for the whole site, and for a +/// login path that number is always wrong: 100 requests a minute does not stop a +/// credential-stuffing run that makes twenty attempts a minute — twenty looks +/// like a person — while 5 a minute locks an honest office behind one NAT out of +/// every page they own. The only way to make both statements true is to price +/// the paths differently, which is what this row does: a glob over the request +/// path, its own limit, its own window. +/// +/// What it is not: +/// * It is not a path rule (). A path rule refuses a +/// request because of what it asked for; a rate rule refuses it because of how +/// often that source asked. The pattern language is shared because the thing +/// being described — "this path and what hangs off it" — is the same. +/// * It is not a ban. Crossing a path budget pauses that source on that path +/// for the rest of that window and nothing more. The claim is about one path, +/// and writing an engine ban for it would refuse the visitor the rest of the +/// site as punishment for a login-page rate. +/// +public sealed class RateRule +{ + public long Id { get; init; } + + /// The budget a rule gets when the request names none. The same + /// numbers the edge-wide pillar ships with, so a rule written without + /// numbers behaves like the pillar the operator already has. + public const int DefaultLimitPerWindow = 20; + + /// And its window, for the same reason. + public const int DefaultWindowSeconds = 60; + + /// Glob over the request path — the same + /// matcher as a path rule: anchored, + /// case-insensitive, * and ? only, never a regular expression. + public string Pattern { get; set; } = string.Empty; + + /// How many requests one source may make to the matched paths inside + /// . The request that crosses it is the breach. + public int LimitPerWindow { get; set; } = DefaultLimitPerWindow; + + /// How long that budget lasts, per source: the window starts when + /// that source first asks, exactly as the edge-wide window does. + public int WindowSeconds { get; set; } = DefaultWindowSeconds; + + public string? Note { get; set; } + + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + + /// A budget written for an incident stops being true when the + /// incident ends. Same rule as a path rule's expiry. + public DateTimeOffset? ExpiresAt { get; set; } + + public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now; + + /// The window as a span, with the same floor the edge-wide budget + /// uses: a zero or negative window is not "no wait", it is a counter that + /// resets between the check and the answer. + public TimeSpan Window => WindowSeconds > 0 ? TimeSpan.FromSeconds(WindowSeconds) : TimeSpan.FromSeconds(1); +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index e2e802c..ba85414 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -112,6 +112,12 @@ internal static class AdminConsole + + + + + +
—
@@ -136,6 +142,10 @@ internal static class AdminConsole
sourcerequests in windowbudgetwindow ends
+

Path budgets

+
+
patternrequestswindow ssources countedwindows runningover budget nownoteexpires
+

Sources the edge is watching

@@ -261,13 +271,14 @@ function row(cells) { async function load() { if (!token) { note('no token', true); return; } try { - const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, alertsRes, geoRes, changesRes, netblocksRes] = await Promise.all([ + const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, rateRes, pathBudgetsRes, alertsRes, geoRes, changesRes, netblocksRes] = 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/rate?limit=25'), + apiRaw('/admin-api/rate-rules?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'), apiRaw('/admin-api/geo'), apiRaw('/admin-api/changes?limit=25'), @@ -287,7 +298,8 @@ async function load() { const alerts = alertsRes.body; const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body, allow = allowRes.body, pathRules = pathRulesRes.body, rate = rateRes.body, geo = geoRes.body, - changes = changesRes.body, netblocks = netblocksRes.body; + changes = changesRes.body, netblocks = netblocksRes.body, + pathBudgets = pathBudgetsRes.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 @@ -474,6 +486,36 @@ async function load() { + (expiredRules ? ' · ' + expiredRules + ' EXPIRED: those rules enforce nothing' : '') : 'no path rules — the edge reacts to what the upstream answered, never to the request itself'; + // The per-path budgets (OPEN-68). The two counters are the reason this table + // exists: "sources counted" says the rule is seeing traffic at all, and + // "over budget now" says what an observe-mode rule would have refused. A + // budget nobody has blown and a budget nobody can blow look the same on + // paper, and only one of them is worth keeping. + const expiredBudgets = (pathBudgets || []).filter((r) => r.live === false).length; + el('raterules').tBodies[0].innerHTML = (pathBudgets || []).map((r) => row([ + { v: r.pattern }, + { v: r.limitPerWindow, n: true }, + { v: r.windowSeconds, n: true }, + { v: r.trackedSources, n: true }, + { v: r.liveWindows, n: true }, + { h: r.overBudgetNow + ? '' + esc(r.overBudgetNow) + '' + : esc(r.overBudgetNow) }, + { v: r.note }, + { v: r.live === false + ? (r.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it' + : (r.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, + { h: '' } + ])).join('') || row([{ v: 'none — every path shares the one edge-wide budget above' }]); + el('raterulenote').textContent = state.rateRulesAvailable === false + ? 'NOT READ — this database has no rate-rule table (' + (state.rateRulesError || 'no reason given') + + '), so no path budget is in force. Apply the schema migration; every other pillar is enforcing.' + : (pathBudgets || []).length + ? 'a path budget pauses one source on one path for the rest of its window — it is not a ban, the rest of the site stays open' + + (pathBudgetsRes.truncated ? ' · showing ' + pathBudgets.length + ' of ' + pathBudgetsRes.total + ' rules' : '') + + (expiredBudgets ? ' · ' + expiredBudgets + ' EXPIRED: those budgets enforce nothing' : '') + : 'no path budgets — the edge-wide budget above is the only one being counted'; + // 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. @@ -727,6 +769,37 @@ el('addRule').onclick = async () => { } }; +el('addRateRule').onclick = async () => { + const pattern = el('rateRulePattern').value.trim(); + if (!pattern) { note('a path pattern first, e.g. /login*', true); return; } + // Both numbers are optional here and mean "this build's default" when left + // out — unlike the edge-wide budget above, where an empty field means "keep + // what is set", because this is a POST of a new row and not a PUT of one. + const rawLimit = el('rateRuleLimit').value.trim(); + const rawWindow = el('rateRuleWindow').value.trim(); + if (rawLimit && !/^\d+$/.test(rawLimit)) { note('the budget must be a whole number of requests', true); return; } + if (rawWindow && !/^\d+$/.test(rawWindow)) { note('the window must be a whole number of seconds', true); return; } + const rawTtl = el('rateRuleTtl').value.trim(); + let ttl = null; + if (rawTtl !== '') { + const parsed = Number(rawTtl); + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) { + note('a TTL in minutes (1..5256000), or leave it empty for never', true); + return; + } + ttl = parsed; + } + const body = { pattern, note: el('rateRuleNote').value.trim() || 'written from the console', expiresInMinutes: ttl }; + if (rawLimit) body.limitPerWindow = parseInt(rawLimit, 10); + if (rawWindow) body.windowSeconds = parseInt(rawWindow, 10); + if (await postJson('/admin-api/rate-rules', body)) { + el('rateRulePattern').value = ''; el('rateRuleLimit').value = ''; el('rateRuleWindow').value = ''; + el('rateRuleNote').value = ''; el('rateRuleTtl').value = ''; + done('path budget added for ' + pattern); + load(); + } +}; + // One delegated handler for every row button, so no key or country code is ever // spliced into an inline onclick string. The values live in data attributes, // which went through esc() on the way in. @@ -756,6 +829,9 @@ document.addEventListener('click', async (e) => { } else if (b.dataset.act === 'delrule') { const r = await apiRaw('/admin-api/rules/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); if (!failed(r)) done('path rule removed'); + } else if (b.dataset.act === 'delraterule') { + const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); + if (!failed(r)) done('path budget removed'); } else if (b.dataset.act === 'country') { const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' }); if (!failed(r)) done('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied')); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index ae649d0..2db3c24 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -66,6 +66,29 @@ internal sealed record RuleDto( internal sealed record NewRuleRequest(string Pattern, string? Action, string? Note, int? ExpiresInMinutes); +/// A request budget written for one path, with what it is counting +/// right now: a budget nobody has blown yet and a budget nobody can blow look +/// the same on paper, and only one of them is worth keeping. +internal sealed record RateRuleDto( + long Id, + string Pattern, + int LimitPerWindow, + int WindowSeconds, + string? Note, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + bool Live, + int TrackedSources, + int OverBudgetNow, + int LiveWindows); + +internal sealed record NewRateRuleRequest( + string Pattern, + int? LimitPerWindow, + int? WindowSeconds, + string? Note, + int? ExpiresInMinutes); + internal sealed record PolicyDto( string Mode, int StreakThreshold, diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs index 7c0c12b..4f3fecc 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs @@ -88,6 +88,16 @@ internal static partial class AdminEndpoints .Select(r => new { r.Pattern, r.Action, r.Note, r.ExpiresAt }) .ToListAsync(ct); + // The per-path budgets (OPEN-68). Ordered by id for the same reason + // the path rules are: on the receiving edge these become rows in this + // order, and a document that shuffled them would describe a different + // edge than the one it came from. + var rateRuleRows = await db.RateRules.AsNoTracking() + .Where(r => r.ExpiresAt == null || r.ExpiresAt > now) + .OrderBy(r => r.Id) + .Select(r => new { r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note, r.ExpiresAt }) + .ToListAsync(ct); + var countryRows = await db.CountryRules.AsNoTracking() .OrderBy(c => c.Code) .Select(c => new { c.Code, c.IsAllowed }) @@ -104,6 +114,7 @@ internal static partial class AdminEndpoints blocks = blockRows.Count + rangeRows.Count, allow = allowRows.Count, rules = ruleRows.Count, + rateRules = rateRuleRows.Count, countries = countryRows.Count }, // The sentence the AC asks for: what this document deliberately @@ -121,6 +132,8 @@ internal static partial class AdminEndpoints allow = allowRows.Select(a => new ExportedAllow(a.Match, a.Note, a.ExpiresAt)), rules = ruleRows.Select(r => new ExportedRule( r.Pattern, r.Action.ToString().ToLowerInvariant(), r.Note, r.ExpiresAt)), + rateRules = rateRuleRows.Select(r => new ExportedRateRule( + r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note, r.ExpiresAt)), countries = countryRows.Select(c => new ExportedCountry(c.Code, c.IsAllowed)) }); }); @@ -131,7 +144,7 @@ internal static partial class AdminEndpoints + "read-only one")); group.MapPost("/import", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, - IStreakTracker streaks, RateTracker rates, BlockStore blocks, ConfigChangeWriter changes, + IStreakTracker streaks, RateTracker rates, RateRuleTracker rateRules, BlockStore blocks, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); @@ -166,11 +179,13 @@ internal static partial class AdminEndpoints var blocksIn = doc.Blocks ?? []; var allowIn = doc.Allow ?? []; var rulesIn = doc.Rules ?? []; + var rateRulesIn = doc.RateRules ?? []; var countriesIn = doc.Countries ?? []; foreach (var (section, count) in new[] { ("blocks", blocksIn.Length), ("allow", allowIn.Length), - ("rules", rulesIn.Length), ("countries", countriesIn.Length) + ("rules", rulesIn.Length), ("rate rules", rateRulesIn.Length), + ("countries", countriesIn.Length) }) { var sizeProblem = ConfigTransfer.ExplainSectionSize(section, count); @@ -199,6 +214,7 @@ internal static partial class AdminEndpoints await state.InvalidateAsync(ct); streaks.Configure(policy.Current); rates.Configure(policy.Current); + rateRules.Configure(policy.Current); policyApplied = true; } else @@ -331,6 +347,61 @@ internal static partial class AdminEndpoints storageFailure ??= $"the rule table could not be written: {ex.Message}"; } + // --- rate rules ------------------------------------------------- + var (rateRulesAdded, rateRulesThere, rateRulesExpired, rateRulesRejected) = (0, 0, 0, 0); + try + { + var liveRateRules = await db.RateRules.AsNoTracking() + .CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct); + for (var i = 0; i < rateRulesIn.Length; i++) + { + var item = rateRulesIn[i]; + if (ConfigTransfer.ExplainRateRule(item) is { } why) + { + rateRulesRejected++; + rejected.Add(new RejectedItem("rate rules", i, item.Pattern, why)); + continue; + } + if (ConfigTransfer.IsExpired(item.ExpiresAt, now)) + { + rateRulesExpired++; + continue; + } + var pattern = item.Pattern.Trim(); + // Two live budgets for one path is refused here exactly as the + // endpoint refuses it: the stricter one would win by accident. + if (await db.RateRules.AsNoTracking() + .AnyAsync(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now), ct)) + { + rateRulesThere++; + continue; + } + if (liveRateRules >= PathPattern.MaxRules) + { + rateRulesRejected++; + rejected.Add(new RejectedItem("rate rules", i, pattern, + $"at most {PathPattern.MaxRules} live rate rules; every request is checked against each of them")); + continue; + } + db.RateRules.Add(new RateRule + { + Pattern = pattern, + LimitPerWindow = item.LimitPerWindow ?? RateRule.DefaultLimitPerWindow, + WindowSeconds = item.WindowSeconds ?? RateRule.DefaultWindowSeconds, + Note = item.Note, ExpiresAt = item.ExpiresAt, CreatedAt = now + }); + liveRateRules++; + rateRulesAdded++; + } + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException ex) + { + rateRulesRejected += rateRulesAdded; + rateRulesAdded = 0; + storageFailure ??= $"the rate rule table could not be written: {ex.Message}"; + } + // --- countries -------------------------------------------------- var (countriesAdded, countriesThere, countriesExpired, countriesRejected) = (0, 0, 0, 0); try @@ -379,7 +450,8 @@ internal static partial class AdminEndpoints // the policy section failed — every other mutation invalidates here, // and an import that lands rows the wire does not obey is the bug // this API already refuses to have. - if (blocksAdded + allowAdded + rulesAdded + countriesAdded > 0) await state.InvalidateAsync(ct); + if (blocksAdded + allowAdded + rulesAdded + rateRulesAdded + countriesAdded > 0) + await state.InvalidateAsync(ct); // The change log (OPEN-64): one record per section that carried // something, not one per imported item. A 2 000-row document would @@ -391,6 +463,7 @@ internal static partial class AdminEndpoints (ConfigChangeLog.SectionBlocks, blocksAdded, blocksThere, blocksExpired, blocksRejected), (ConfigChangeLog.SectionAllow, allowAdded, allowThere, allowExpired, allowRejected), (ConfigChangeLog.SectionRules, rulesAdded, rulesThere, rulesExpired, rulesRejected), + (ConfigChangeLog.SectionRateRules, rateRulesAdded, rateRulesThere, rateRulesExpired, rateRulesRejected), (ConfigChangeLog.SectionCountries, countriesAdded, countriesThere, countriesExpired, countriesRejected) }) { @@ -412,6 +485,7 @@ internal static partial class AdminEndpoints blocks = new { added = blocksAdded, alreadyThere = blocksThere, skippedExpired = blocksExpired, rejected = blocksRejected }, allow = new { added = allowAdded, alreadyThere = allowThere, skippedExpired = allowExpired, rejected = allowRejected }, rules = new { added = rulesAdded, alreadyThere = rulesThere, skippedExpired = rulesExpired, rejected = rulesRejected }, + rateRules = new { added = rateRulesAdded, alreadyThere = rateRulesThere, skippedExpired = rateRulesExpired, rejected = rateRulesRejected }, countries = new { added = countriesAdded, alreadyThere = countriesThere, skippedExpired = countriesExpired, rejected = countriesRejected }, rejected = rejected.Take(ConfigTransfer.MaxReportedRejections), rejectedTruncated = rejected.Count > ConfigTransfer.MaxReportedRejections, @@ -551,6 +625,7 @@ internal sealed record ConfigImportDocument( OpenWaf.Domain.Security.ExportedBlock[]? Blocks, OpenWaf.Domain.Security.ExportedAllow[]? Allow, OpenWaf.Domain.Security.ExportedRule[]? Rules, + OpenWaf.Domain.Security.ExportedRateRule[]? RateRules, OpenWaf.Domain.Security.ExportedCountry[]? Countries); /// One item the document carried that this edge would not take, named diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 07631f8..b559dfe 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -293,6 +293,102 @@ internal static partial class AdminEndpoints return Results.NoContent(); }); + // Rate rules: the same path language as a request rule, but the claim is + // about how often one source asks, not about what it asked for. The + // counters are per (rule, source) and live in the process, so the listing + // reports what is being counted next to what is configured — an + // observe-mode budget that is being blown quietly is the whole reason to + // write one. + group.MapGet("/rate-rules", async (bool? live, int? limit, int? offset, + OpenWafDbContext db, RateRuleTracker rateRules, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "live", "limit", "offset")) return Results.BadRequest(new { error = unknown }); + if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit, + out var take, out var skip, out var pagingError)) + return Results.BadRequest(new { error = pagingError }); + var now = DateTimeOffset.UtcNow; + var liveOnly = live ?? true; + IQueryable Query() => + liveOnly + ? db.RateRules.AsNoTracking().Where(r => r.ExpiresAt == null || r.ExpiresAt > now) + : db.RateRules.AsNoTracking(); + var rows = await Query().OrderBy(r => r.Id).Skip(skip).Take(take).ToListAsync(ct); + var total = await Query().CountAsync(ct); + ctx.Response.Headers["X-Total-Count"] = total.ToString(); + ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); + return Results.Ok(rows.Select(r => + { + var (liveWindows, overNow) = rateRules.LiveCounts(r.Id, r.LimitPerWindow, now); + return new RateRuleDto(r.Id, r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note, + r.CreatedAt, r.ExpiresAt, r.ExpiresAt == null || r.ExpiresAt > now, + rateRules.TrackedCount(r.Id), overNow, liveWindows); + }).ToList()); + }); + + group.MapPost("/rate-rules", async (NewRateRuleRequest req, OpenWafDbContext db, EdgeStateStore state, + ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + var patternProblem = PathPattern.ExplainRejection(req.Pattern); + if (patternProblem is not null) return Results.BadRequest(new { error = patternProblem }); + // The same bounds the edge-wide budget uses, on purpose: two words for + // "requests per window" with two different ceilings would make one of + // them a lie, and the operator reads both off the same page. + var limit = req.LimitPerWindow ?? RateRule.DefaultLimitPerWindow; + if (!PolicyBounds.RateLimitPerWindowOk(limit)) + return Results.BadRequest(new { error = $"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {limit}" }); + var window = req.WindowSeconds ?? RateRule.DefaultWindowSeconds; + if (!PolicyBounds.RateWindowSecondsOk(window)) + return Results.BadRequest(new { error = $"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {window}" }); + if (!EntryLimits.NoteOk(req.Note)) + return Results.BadRequest(new { error = $"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}" }); + if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes)) + return Results.BadRequest(new { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}" }); + + var pattern = req.Pattern.Trim(); + var now = DateTimeOffset.UtcNow; + var clash = await db.RateRules.AsNoTracking() + .Where(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now)) + .Select(r => r.Id).FirstOrDefaultAsync(ct); + if (clash != 0) + return Results.Conflict(new { error = $"rate rule {clash} already sets a budget for {pattern} — two live budgets for one path mean the stricter one wins by accident, not by the operator's choice" }); + + var live = await db.RateRules.AsNoTracking() + .CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct); + if (live >= PathPattern.MaxRules) + return Results.BadRequest(new { error = $"at most {PathPattern.MaxRules} live rate rules; every request is checked against each of them" }); + + db.RateRules.Add(new RateRule + { + Pattern = pattern, + LimitPerWindow = limit, + WindowSeconds = window, + Note = req.Note, + ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null + }); + await db.SaveChangesAsync(ct); + await state.InvalidateAsync(ct); + await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionAdded, + pattern, $"{limit} per {window}s{(string.IsNullOrWhiteSpace(req.Note) ? "" : $": {req.Note}")}", ct: ct); + return Results.NoContent(); + }); + + group.MapDelete("/rate-rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, + RateRuleTracker rateRules, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + var n = await db.RateRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct); + // The counters go with the row: leaving them would keep counting for a + // budget the operator took off this edge, and a later rule reusing the + // id would inherit a window it never started. + rateRules.ForgetRule(id); + await state.InvalidateAsync(ct); + if (n == 0) return Results.NotFound(new { error = $"no rate rule with id {id}" }); + await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionRemoved, + id.ToString(), ct: ct); + return Results.NoContent(); + }); + // The policy answer carries its provenance in headers, the same way a // capped listing carries its completeness there. The body is the policy // this edge is enforcing — that is what the operator asked for and what @@ -309,7 +405,7 @@ internal static partial class AdminEndpoints }); group.MapPut("/policy", async (PolicyUpdateRequest req, EdgePolicyProvider policy, EdgeStateStore state, - IStreakTracker streaks, RateTracker rates, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => + IStreakTracker streaks, RateTracker rates, RateRuleTracker rateRules, ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); // The same path an imported document's `policy` section goes through: @@ -352,6 +448,7 @@ internal static partial class AdminEndpoints // answers with it. streaks.Configure(policy.Current); rates.Configure(policy.Current); + rateRules.Configure(policy.Current); await changes.RecordAsync(ConfigChangeLog.SectionPolicy, ConfigChangeLog.ActionChanged, "policy", PolicyChangeSentence(policyBefore, policy.Current), ct: ct); return Results.Ok(ToDto(policy.Current)); @@ -907,6 +1004,14 @@ note = t.Note requestRulesAvailable = state.RulesAvailable, operatorRangesAvailable = state.RangesAvailable, requestRulesError = state.RulesError, + // The per-path budgets (OPEN-68): how many are live in the snapshot + // the guard is actually holding, and whether that snapshot could read + // the table at all. A database that predates rate_rules answers "no + // budgets" the same way an operator who wrote none does, and only one + // of those is a problem. + rateRules = state.Current.RateRules.Count, + rateRulesAvailable = state.RateRulesAvailable, + rateRulesError = state.RateRulesError, // The netblock watch (OPEN-67). Three answers, not one: whether the // watch is switched on at all, what it last saw, and whether the scan // that produced that number actually ran. "0 candidates" from a watch diff --git a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs index 6a438c4..03d1d96 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs @@ -1,5 +1,6 @@ using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; using OpenWaf.Domain.Responses; using OpenWaf.Edge.Observability; using OpenWaf.Infrastructure.Geo; @@ -24,6 +25,7 @@ public sealed class EdgeGuardMiddleware( IGeoIpLookup geo, RuleMatchLedger ledger, RateTracker rates, + RateRuleTracker rateRules, BlockStore blocks, AlertWriter alerts, EdgeCounterLedger counters, @@ -115,6 +117,79 @@ public sealed class EdgeGuardMiddleware( return true; } + /// + /// One source against one path budget (OPEN-68). True means the answer is + /// already written. The refusal is a pause on that path for the rest of that + /// rule's window and nothing more: no engine ban is written, because the + /// claim a path budget makes is about one path, and banning the source would + /// refuse the rest of the site for a login-page rate. + /// + /// Every live path budget whose pattern covers this path. The scan + /// is the same linear loop the path rules already pay, over a list capped by + /// the same bound, so the cost on a request is bounded by what the operator + /// wrote rather than by what the visitor sent. + private async Task RateRulePillarAsync( + HttpContext ctx, EdgeSnapshot snapshot, string key, string path, DateTimeOffset now) + { + foreach (var rule in snapshot.RateRules) + { + if (!rule.IsLive(now)) continue; + if (!PathPattern.Matches(rule.Pattern, path)) continue; + if (await RateRulePillarAsync(ctx, rule, key, path, now)) return true; + } + return false; + } + + private async Task RateRulePillarAsync( + HttpContext ctx, RateRule rule, string key, string path, DateTimeOffset now) + { + var counted = rateRules.Record(rule, key, now); + if (!counted.OverBudget) return false; + + if (ctx.Items.TryGetValue("openwaf.rateMode", out var mode) && mode is RateMode.Observe) + { + // The dry run for a path budget, same as the edge-wide one: the + // operator finds out whether the number is a defence or their own + // traffic before it refuses anything. + if (counted.BreachStarted) + await alerts.RaiseAsync( + "rate_breach", key, counted.Count, null, path, + $"{counted.Count} requests in {rule.WindowSeconds} s against a path budget of " + + $"{rule.LimitPerWindow} for {rule.Pattern} (mode=Observe, nothing was blocked)", + ctx.RequestAborted); + return false; + } + + ctx.Response.StatusCode = 429; + var seconds = Math.Max(1, (int)Math.Ceiling((counted.WindowEnd - now).TotalSeconds)); + ctx.Response.Headers.RetryAfter = seconds.ToString(); + var reason = $"rate_rule_{rule.Id}_{counted.Count}_of_{rule.LimitPerWindow}_for_{rule.Pattern}"; + log.LogInformation("edge: {Verdict} {Ip} {Path} ({Count} over a path budget of {Limit} for {Pattern})", + EdgeVerdict.BlockRate, ctx.Connection.RemoteIpAddress, path, counted.Count, + rule.LimitPerWindow, rule.Pattern); + await WriteRefusalAsync(ctx, BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString()), + EdgeVerdict.BlockRate, reason, counted.WindowEnd, seconds, now, + () => ctx.Response.WriteAsJsonAsync(new BlockedBody( + "rate_limited", + reason, + counted.WindowEnd.ToString("O"), + "This source asked for this part of the site more often than it allows. " + + "The pause ends on its own and covers only this path; an operator can raise " + + "or remove the budget, or allowlist the address."))); + + if (!counted.BreachStarted) return true; + + // One breach per source per window, one alert. No ban row: see the + // comment on this method. + await alerts.RaiseAsync( + "rate_breach", key, counted.Count, null, path, + $"{counted.Count} requests in {rule.WindowSeconds} s against a path budget of " + + $"{rule.LimitPerWindow} for {rule.Pattern} (mode=Enforce, 429 on that path for the rest " + + "of the window; no ban was written, the pause is for this path only)", + CancellationToken.None); + return true; + } + public async Task InvokeAsync(HttpContext ctx) { var snapshot = state.GetOrRefresh(); @@ -148,11 +223,15 @@ public sealed class EdgeGuardMiddleware( 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)) + if (rateKey.Length > 0) { - counters.Record(EdgeVerdict.BlockRate); - return; + ctx.Items["openwaf.rateMode"] = snapshot.Policy.Rate; + if (await RatePillarAsync(ctx, snapshot.Policy, rateKey, path, country, now) + || await RateRulePillarAsync(ctx, snapshot, rateKey, path, now)) + { + counters.Record(EdgeVerdict.BlockRate); + return; + } } } diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index ddc9c59..d2348c1 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -76,6 +76,7 @@ builder.Services.AddSingleton(); // only the observed ones. The stop a breach writes IS shared, because it is a // ban row. builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); // 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 diff --git a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs index f401016..cfd57c5 100644 --- a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs +++ b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs @@ -21,6 +21,7 @@ internal sealed class EdgeStateWarmer( EdgeStateStore state, IStreakTracker streaks, RateTracker rates, + RateRuleTracker rateRules, SchemaUpgradeReport schema, IConfiguration configuration, ILogger log) : IHostedService @@ -88,6 +89,7 @@ internal sealed class EdgeStateWarmer( // the built-in 10 000 whatever the operator had asked for. streaks.Configure(state.Current.Policy); rates.Configure(state.Current.Policy); + rateRules.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); diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index 2e7a93e..8a5647c 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -77,6 +77,15 @@ public sealed class EdgeStateStore public string? RangesError => Volatile.Read(ref _rangesError); + /// Whether the per-path budgets (OPEN-68) could be read on the last + /// refresh. False means the edge is enforcing everything except the path + /// budgets, and the surface says which. + public bool RateRulesAvailable { get; private set; } = true; + + public string? RateRulesError => Volatile.Read(ref _rateRulesError); + + private string? _rateRulesError; + private string? _rangesError; /// Why the rules could not be read, for the operator surface. @@ -165,6 +174,27 @@ public sealed class EdgeStateStore "EdgeStateStore: the request-rule table could not be read; enforcing the rest of the list without it."); } + // The per-path budgets (OPEN-68) read alone, for the same reason the + // rule and range reads do: rate_rules is the newest table in the + // schema, and a database that predates it must keep enforcing + // everything else. A pillar that cannot read its table says so on the + // surface rather than answering "no budgets". + IReadOnlyList rateRules; + try + { + rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(ct); + RateRulesAvailable = true; + Volatile.Write(ref _rateRulesError, null); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + rateRules = []; + RateRulesAvailable = false; + Volatile.Write(ref _rateRulesError, ex.Message); + _log.LogWarning(ex, + "EdgeStateStore: the rate-rule table could not be read; enforcing the rest of the config without it."); + } + var operatorBlocks = new Dictionary(StringComparer.Ordinal); var engineBans = new Dictionary(StringComparer.Ordinal); foreach (var b in blocks) @@ -208,7 +238,8 @@ public sealed class EdgeStateStore AllowEntries = allow, Countries = countryMap, RequestRules = rules, - OperatorRanges = ranges + OperatorRanges = ranges, + RateRules = rateRules }; } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.Designer.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.Designer.cs new file mode 100644 index 0000000..1647b08 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.Designer.cs @@ -0,0 +1,554 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenWaf.Infrastructure.Persistence; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(OpenWafDbContext))] + [Migration("20261005060201_AddRateRules")] + partial class AddRateRules + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OpenWaf.Domain.Policy.CountryRule", b => + { + b.Property("Code") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("IsAllowed") + .HasColumnType("boolean"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Code"); + + b.ToTable("country_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AlertPush", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AlertCreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AlertId") + .HasColumnType("bigint"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ClaimedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ClaimedBy") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("GivenUpAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastError") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PushedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("AlertId"); + + b.HasIndex("PushedAt", "GivenUpAt", "NextAttemptAt"); + + b.ToTable("alert_pushes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AllowEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("allow_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.BlockEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("SourceKey", "Source") + .IsUnique(); + + b.ToTable("block_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.ConfigChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Section") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("At"); + + b.HasIndex("Section"); + + b.ToTable("config_changes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.EdgeAlert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.ToTable("edge_alerts", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.NetworkBan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("network_bans", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.RateRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LimitPerWindow") + .HasColumnType("integer"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("WindowSeconds") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Pattern"); + + b.ToTable("rate_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Pattern"); + + b.ToTable("request_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceObservation", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("FirstSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("TotalServerErrorStreak") + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_observations", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceStreak", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("ConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("LastAlertedRefusals") + .HasColumnType("integer"); + + b.Property("LastAlertedServerErrors") + .HasColumnType("integer"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRefusalAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("MaxConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_streaks", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Infrastructure.Persistence.PolicySetting", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.ToTable("policy_settings", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.cs new file mode 100644 index 0000000..2f500cf --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005060201_AddRateRules.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + /// + public partial class AddRateRules : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "rate_rules", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Pattern = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), + LimitPerWindow = table.Column(type: "integer", nullable: false), + WindowSeconds = table.Column(type: "integer", nullable: false), + Note = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_rate_rules", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_rate_rules_ExpiresAt", + table: "rate_rules", + column: "ExpiresAt"); + + migrationBuilder.CreateIndex( + name: "IX_rate_rules_Pattern", + table: "rate_rules", + column: "Pattern"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "rate_rules"); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs index 87635fe..8ceba0f 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs @@ -336,6 +336,44 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations b.ToTable("network_bans", (string)null); }); + modelBuilder.Entity("OpenWaf.Domain.Security.RateRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LimitPerWindow") + .HasColumnType("integer"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("WindowSeconds") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Pattern"); + + b.ToTable("rate_rules", (string)null); + }); + modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b => { b.Property("Id") diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index 7dd13cd..9a86f2d 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs @@ -5,7 +5,7 @@ using OpenWaf.Domain.Security; namespace OpenWaf.Infrastructure.Persistence; /// -/// Eleven tables, all small. The edge never queries them on the request path — +/// Twelve tables, all small. The edge never queries them on the request path — /// holds the snapshot it reads — so the schema is /// sized for operator inspection and for explaining a ban after the fact, not /// for throughput. @@ -23,6 +23,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) public DbSet AlertPushes => Set(); public DbSet ConfigChanges => Set(); public DbSet NetworkBans => Set(); + public DbSet RateRules => Set(); protected override void OnModelCreating(ModelBuilder mb) { @@ -156,6 +157,26 @@ public sealed class OpenWafDbContext(DbContextOptions options) e.Property(r => r.Action).HasConversion(); }); + mb.Entity(e => + { + // A request budget written for one path (OPEN-68). Its own table + // rather than a kind of request_rules: a path rule refuses a request + // for what it asked for, a rate rule refuses it for how often that + // source asked, and the two have different parameters, different + // counters and different reasons to expire. + e.ToTable("rate_rules"); + e.HasKey(r => r.Id); + // Not unique, for the same reason request_rules is not: an expired + // budget keeps its row, and a unique index would let a rule that + // stopped being true last month refuse the same pattern forever. Two + // live rules for one pattern is the real mistake, and the API refuses + // that one by name. + e.HasIndex(r => r.Pattern); + e.HasIndex(r => r.ExpiresAt); + e.Property(r => r.Pattern).HasMaxLength(PathPattern.MaxLength).IsRequired(); + e.Property(r => r.Note).HasMaxLength(512); + }); + mb.Entity(e => { e.ToTable("alert_pushes"); diff --git a/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs b/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs index 6671c18..1d4ce59 100644 --- a/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs @@ -176,7 +176,7 @@ public sealed class ConfigChangeRecordTests $"/admin-api/changes?section=traffic&token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); - Assert.Contains("block, allow, rule, country, policy, config", body); + Assert.Contains("block, allow, rule, rate rule, country, policy, config", body); Assert.Contains("traffic", body); } diff --git a/dotnet/OpenWaf.Tests.Integration/RateRuleTests.cs b/dotnet/OpenWaf.Tests.Integration/RateRuleTests.cs new file mode 100644 index 0000000..adf3ec9 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/RateRuleTests.cs @@ -0,0 +1,428 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.AspNetCore.Http; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// A request budget written for one path instead of for the whole edge (OPEN-68). +/// +/// The edge-wide budget forces one number on every path, and for a login page +/// that number is always wrong: high enough for an office behind one NAT, and +/// useless against a credential-stuffing run. These tests hold the claim the +/// feature makes — the pause is for that path and for nothing else, and it is +/// not a ban. +/// +public sealed class RateRuleTests +{ + private const string Visitor = "203.0.113.140"; + + private static async Task 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 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 BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync(); + + private static void OriginAnswersEverything(EdgeFixture f) => + f.Upstream.StatusFor = _ => StatusCodes.Status200OK; + + [Fact] + public async Task A_path_budget_refuses_that_path_and_leaves_the_rest_of_the_site_open() + { + // The edge-wide budget is set far above the path budget on purpose: the + // 429 below has to be the path rule's answer, not the site's. + await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60, note = "credential stuffing" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var first = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + using (var second = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + + using (var over = await GetAsync(f, "/login")) + { + Assert.Equal((HttpStatusCode)429, over.StatusCode); + var body = await BodyAsync(over); + Assert.Contains("rate_limited", body); + // The reason names the rule, its count, its limit and the pattern it + // was written for, so an operator reading a log line can tell which + // budget fired without opening the console. + Assert.Contains("rate_rule_", body); + Assert.Contains("_3_of_2_for_/login*", body); + Assert.True(over.Headers.TryGetValues("Retry-After", out var values)); + Assert.True(int.Parse(values!.First()) >= 1); + } + + // The path the budget names but does not match still flows, and so does + // every other path. This is the whole point of the feature: the pause is + // about one part of the site. + using (var other = await GetAsync(f, "/index.html")) + Assert.Equal(HttpStatusCode.OK, other.StatusCode); + + lock (f.Upstream.Paths) + { + Assert.Equal(2, f.Upstream.Paths.Count(p => p == "/login")); + Assert.Contains("/index.html", f.Upstream.Paths); + } + } + + [Fact] + public async Task Crossing_a_path_budget_writes_no_ban_so_the_visitor_keeps_the_rest_of_the_site() + { + await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/reset", limitPerWindow = 1, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + for (var i = 0; i < 4; i++) + { + using var probe = await GetAsync(f, "/reset"); + Assert.True(probe.StatusCode is HttpStatusCode.OK or HttpStatusCode.TooManyRequests); + } + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + // The edge-wide budget answers a rate breach with a ban, because + // there the claim is about the whole site. A path budget makes a + // narrower claim, so it writes nothing that outlives the window. + var written = await db.Blocks.AsNoTracking().ToListAsync(); + Assert.Empty(written); + } + } + + [Fact] + public async Task An_observe_budget_refuses_nothing_and_says_what_it_would_have_blocked() + { + await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + for (var i = 0; i < 5; i++) + { + using var probe = await GetAsync(f, "/login"); + Assert.Equal(HttpStatusCode.OK, probe.StatusCode); + } + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "rate_breach").ToListAsync(); + + // One alert for the crossing, and it names the pattern: an operator who + // set the number too low has to be able to tell which budget is wrong. + Assert.Single(alerts); + Assert.Equal(3, alerts[0].Count); + Assert.Contains("path budget of 2", alerts[0].Detail); + Assert.Contains("/login*", alerts[0].Detail); + Assert.Contains("mode=Observe, nothing was blocked", alerts[0].Detail); + } + + [Fact] + public async Task With_the_volume_pillar_off_no_path_budget_is_counted() + { + // The documented seam: the path budgets hang off the same switch as the + // edge-wide one, so "off" means off for both rather than a half-counting + // edge whose listings say one thing and whose counters another. + await using var f = new EdgeFixture(); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + for (var i = 0; i < 6; i++) + { + using var probe = await GetAsync(f, "/login"); + Assert.Equal(HttpStatusCode.OK, probe.StatusCode); + } + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(0, await db.Alerts.AsNoTracking().CountAsync(a => a.Kind == "rate_breach")); + } + + [Fact] + public async Task A_budget_that_expires_stops_enforcing_without_being_deleted() + { + await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60, expiresInMinutes = 1 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var first = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + using (var second = await GetAsync(f, "/login")) + Assert.Equal((HttpStatusCode)429, second.StatusCode); + + long id; + using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) + { + Assert.Equal(HttpStatusCode.OK, list.StatusCode); + using var doc = JsonDocument.Parse(await BodyAsync(list)); + id = doc.RootElement[0].GetProperty("id").GetInt64(); + Assert.True(doc.RootElement[0].GetProperty("live").GetBoolean()); + } + + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.RateRules.FirstAsync(r => r.Id == id); + row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); + await db.SaveChangesAsync(); + } + // A direct row edit is not something the operator can do, so nothing + // invalidated the guard's snapshot on the way here. This is the same + // refresh any admin mutation triggers, and it is what makes "the next + // request" the honest answer rather than "after the TTL". + await f.Service().InvalidateAsync(); + + using (var after = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, after.StatusCode); + + using (var all = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules?live=false")) + { + using var doc = JsonDocument.Parse(await BodyAsync(all)); + Assert.Equal(id, doc.RootElement[0].GetProperty("id").GetInt64()); + Assert.False(doc.RootElement[0].GetProperty("live").GetBoolean()); + } + } + + [Fact] + public async Task Removing_a_budget_stops_enforcing_on_the_next_request() + { + await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var first = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + using (var second = await GetAsync(f, "/login")) + Assert.Equal((HttpStatusCode)429, second.StatusCode); + + long id; + using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) + using (var body = JsonDocument.Parse(await BodyAsync(list))) + id = body.RootElement[0].GetProperty("id").GetInt64(); + + using (var removed = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}")) + Assert.Equal(HttpStatusCode.NoContent, removed.StatusCode); + + // A fresh source, and the same one: the counters go with the row, so a + // source that was paused a moment ago is not still paused by a budget + // that no longer exists. + using (var again = await GetAsync(f, "/login")) + Assert.Equal(HttpStatusCode.OK, again.StatusCode); + + using (var missing = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}")) + Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode); + } + + [Fact] + public async Task The_surface_refuses_a_budget_it_could_not_enforce() + { + await using var f = new EdgeFixture(); + + using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "login*", limitPerWindow = 5 })) + { + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + Assert.Contains("must start with /", await BodyAsync(bad)); + } + + using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 0 })) + { + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + Assert.Contains("limitPerWindow must be 1..100000", await BodyAsync(bad)); + } + + using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", windowSeconds = 99999 })) + { + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + Assert.Contains("windowSeconds must be 1..3600", await BodyAsync(bad)); + } + + using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", expiresInMinutes = 0 })) + { + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + Assert.Contains("expiresInMinutes", await BodyAsync(bad)); + } + + using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) + { + Assert.Equal(HttpStatusCode.OK, list.StatusCode); + Assert.Equal("0", list.Headers.GetValues("X-Total-Count").First()); + } + } + + [Fact] + public async Task Two_live_budgets_for_one_path_are_refused_rather_than_resolved_by_accident() + { + await using var f = new EdgeFixture(); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 5 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var clash = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 50 })) + { + Assert.Equal(HttpStatusCode.Conflict, clash.StatusCode); + Assert.Contains("already sets a budget for /login*", await BodyAsync(clash)); + } + + // An expired budget is not live, so it does not hold the pattern open. + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + foreach (var row in await db.RateRules.ToListAsync()) + { + row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); + await db.SaveChangesAsync(); + } + } + + using (var again = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 50 })) + Assert.Equal(HttpStatusCode.NoContent, again.StatusCode); + } + + [Fact] + public async Task The_state_answer_says_whether_the_budgets_are_being_read_at_all() + { + await using var f = new EdgeFixture(); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state"); + Assert.Equal(HttpStatusCode.OK, state.StatusCode); + using var doc = JsonDocument.Parse(await BodyAsync(state)); + Assert.Equal(1, doc.RootElement.GetProperty("rateRules").GetInt32()); + Assert.True(doc.RootElement.GetProperty("rateRulesAvailable").GetBoolean()); + Assert.Equal(JsonValueKind.Null, doc.RootElement.GetProperty("rateRulesError").ValueKind); + } + + [Fact] + public async Task The_listing_reports_what_a_budget_is_counting_right_now() + { + await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + OriginAnswersEverything(f); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (await GetAsync(f, "/login")) { } + using (await GetAsync(f, "/login")) { } + using (await GetAsync(f, "/login", "203.0.113.141")) { } + using (await GetAsync(f, "/index.html")) { } + + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules"); + using var doc = JsonDocument.Parse(await BodyAsync(list)); + var rule = doc.RootElement[0]; + // Two sources have a window for this rule; one of them is over it now. + // The path the budget does not name is not counted at all, which is the + // difference between this and the edge-wide budget. This is the pair of + // numbers that tells an operator whether a budget is a defence or their + // own traffic — and in observe mode it is the only pair that does. + Assert.Equal(2, rule.GetProperty("trackedSources").GetInt32()); + Assert.Equal(2, rule.GetProperty("liveWindows").GetInt32()); + Assert.Equal(1, rule.GetProperty("overBudgetNow").GetInt32()); + Assert.Equal(1, rule.GetProperty("limitPerWindow").GetInt32()); + Assert.Equal(60, rule.GetProperty("windowSeconds").GetInt32()); + } + + [Fact] + public async Task A_budget_travels_to_another_edge_in_one_call() + { + // The document carries the policy too, so the source edge is one with the + // volume pillar on: an import that switched the target off would import a + // row and no defence, and the test would be measuring the wrong thing. + await using var source = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + using (var created = await AdminAsync(source, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 4, windowSeconds = 30, note = "staging" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + JsonElement document; + using (var exportResponse = await source.Client.GetAsync( + $"/admin-api/export?token={EdgeFixture.AdminToken}")) + { + Assert.Equal(HttpStatusCode.OK, exportResponse.StatusCode); + using var export = JsonDocument.Parse(await BodyAsync(exportResponse)); + document = export.RootElement.Clone(); + Assert.Equal(1, document.GetProperty("counts").GetProperty("rateRules").GetInt32()); + Assert.Equal("/login*", document.GetProperty("rateRules")[0].GetProperty("pattern").GetString()); + Assert.Equal(4, document.GetProperty("rateRules")[0].GetProperty("limitPerWindow").GetInt32()); + Assert.Equal(30, document.GetProperty("rateRules")[0].GetProperty("windowSeconds").GetInt32()); + } + + // The receiving edge has its own volume switch, and a path budget hangs + // off it like the edge-wide one does: importing a budget into an edge + // with the pillar off imports a row, not a defence. + await using var target = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); + using (var importResponse = await target.Client.PostAsync( + $"/admin-api/import?token={EdgeFixture.AdminToken}", + new StringContent(document.GetRawText(), Encoding.UTF8, "application/json"))) + { + Assert.Equal(HttpStatusCode.OK, importResponse.StatusCode); + using var imported = JsonDocument.Parse(await BodyAsync(importResponse)); + Assert.Equal(1, imported.RootElement.GetProperty("rateRules").GetProperty("added").GetInt32()); + } + + using (var list = await AdminAsync(target, HttpMethod.Get, "/admin-api/rate-rules")) + using (var body = JsonDocument.Parse(await BodyAsync(list))) + { + Assert.Equal(1, body.RootElement.GetArrayLength()); + Assert.Equal("/login*", body.RootElement[0].GetProperty("pattern").GetString()); + Assert.Equal(4, body.RootElement[0].GetProperty("limitPerWindow").GetInt32()); + } + + // And the imported budget enforces, not merely lists. + OriginAnswersEverything(target); + using (var first = await GetAsync(target, "/login")) + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + using (var second = await GetAsync(target, "/login")) + Assert.Equal(HttpStatusCode.OK, second.StatusCode); + using (var third = await GetAsync(target, "/login")) + Assert.Equal(HttpStatusCode.OK, third.StatusCode); + using (var fourth = await GetAsync(target, "/login")) + Assert.Equal(HttpStatusCode.OK, fourth.StatusCode); + using (var fifth = await GetAsync(target, "/login")) + Assert.Equal((HttpStatusCode)429, fifth.StatusCode); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs b/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs new file mode 100644 index 0000000..70480ae --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs @@ -0,0 +1,170 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// 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. +/// +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))); + } + + [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)); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 7200a24..dd54a21 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1695,6 +1695,38 @@ check 'the range and the bans that produced it are cleaned, so the volume stays "$EDGE/admin-api/policy" >/dev/null; \ code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")" +# A request budget for one path (OPEN-68), on the image an operator would +# actually ship. The scene is short because the claim is short: the pause covers +# the path it names, writes no ban, and stops the moment the row is gone. +echo '- the shipped edge holds a request budget for one path' +PATH_BUDGET_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}' +PATH_BUDGET_JSON='{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":120,"note":"compose scene"}' +PATH_BUDGET_IP=198.51.100.91 +# The engine's list is cleared first: a path budget must not be judged against a +# ban some earlier scene left on this source. +admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null +admin -X PUT -H 'Content-Type: application/json' --data-binary "$PATH_BUDGET_ON_JSON" \ + "$EDGE/admin-api/policy" >/dev/null +check 'the shipped edge takes a path budget' '204' \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_JSON" "$EDGE/admin-api/rate-rules")" +check 'the first two requests on that path are proxied' '404 404' \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted") $(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")" +check 'the third crosses the budget and the edge answers it' '429' \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")" +check 'the rest of the site stays open to that source' '404' \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/anything")" +check 'the shipped state counts the budgets it is enforcing' '1 yes' \ + "$(admin "$EDGE/admin-api/state" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("rateRules"), "yes" if d.get("rateRulesAvailable") and d.get("rateRulesError") is None else "no")')" +check 'the shipped listing says who is over the budget now' '1' \ + "$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["overBudgetNow"])')" +PATH_BUDGET_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')" +check 'removing the budget reopens the path, and the volume is left as it was' '404' \ + "$(admin -X DELETE "$EDGE/admin-api/rate-rules/$PATH_BUDGET_ID" >/dev/null; \ + admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \ + "$EDGE/admin-api/policy" >/dev/null; \ + code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 14004a3..6019026 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -473,6 +473,88 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); check('the range and the bans that produced it are cleaned, so the stack stays clean', cleanedWire.status === 404, `probe from ${NET_FRESH} answered ${cleanedWire.status}`); + // A request budget for one path (OPEN-68). The edge-wide budget above is one + // number for the whole site; this is the same switch with a path on it. What + // the page has to get right is the pair of counters next to the row: they are + // the only answer to "is this budget a defence or my own traffic", and in + // observe mode they are the only answer to that question at all. + const PATH_BUDGET_PATH = process.env.SEED_PATH_BUDGET_PATH || '/budget-probe'; + const PATH_BUDGET_IP = process.env.SEED_PATH_BUDGET_IP || '192.0.2.210'; + // (the file already has a probePath further down; this one is aimed at a path + // of this scene's own and returns only the status) + const askPath = async (ip, path) => { + const r = await fetch(`${EDGE}${path}`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' }); + await r.body.cancel(); + return r.status; + }; + + await page.selectOption('#rateMode', 'enforce'); + await page.fill('#rateLimit', '1000'); + await page.fill('#rateWindow', '120'); + await page.click('#setRate'); + await page.waitForFunction(() => /budget/.test(document.getElementById('status').textContent), + null, { timeout: 15000 }).catch(() => {}); + + await page.fill('#rateRulePattern', `${PATH_BUDGET_PATH}*`); + await page.fill('#rateRuleLimit', '2'); + await page.fill('#rateRuleWindow', '120'); + await page.fill('#rateRuleNote', 'console gate: path budget'); + await page.click('#addRateRule'); + await page.waitForFunction((pat) => [...document.querySelectorAll('#raterules tbody tr')] + .some((tr) => tr.children[0].textContent === pat), `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {}); + const budgetRows = await cells('#raterules tbody tr'); + const budgetRow = budgetRows.find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`); + check('the page writes a budget for one path and lists its own numbers', + !!budgetRow && budgetRow[1] === '2' && budgetRow[2] === '120' && /console gate/.test(budgetRow[6] || ''), + JSON.stringify(budgetRow || budgetRows.map((r) => r[0]))); + + const firstAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + const secondAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + const thirdAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + check('the third request on that path is answered by the edge, not the upstream', + firstAsked === 404 && secondAsked === 404 && thirdAsked === 429, + `${firstAsked} ${secondAsked} ${thirdAsked}`); + check('the same source is still served on a path the budget does not name', + (await askPath(PATH_BUDGET_IP, '/probe')) === 404, `probe from ${PATH_BUDGET_IP} answered the other path`); + + await page.click('#refresh'); + await page.waitForFunction((pat) => { + const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat); + return !!tr && Number(tr.children[5].textContent) >= 1; + }, `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {}); + // The probes this scene drew were refusals (the upstream has no such path), so + // the streak pillar has by now banned this address on its own — three + // consecutive 404s is its rule, and it is nothing to do with the budget. The + // reopen assertion below is about the budget, so the engine's list is cleared + // first: otherwise the answer is the streak's 403 and the scene proves + // nothing about the row it removed. + await adminDelete('/admin-api/blocks?source=engine'); + const countedRow = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`); + check('the page says who the budget counted and who is over it now', + !!countedRow && Number(countedRow[3]) >= 1 && Number(countedRow[4]) >= 1 && Number(countedRow[5]) >= 1, + JSON.stringify(countedRow || 'no row')); + + await page.evaluate((pat) => { + const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat); + const b = tr && tr.querySelector('button[data-act="delraterule"]'); + if (b) b.click(); + }, `${PATH_BUDGET_PATH}*`); + await page.waitForFunction((pat) => ![...document.querySelectorAll('#raterules tbody tr')] + .some((tr) => tr.children[0].textContent === pat), `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {}); + let reopened = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + for (let i = 0; i < 10 && reopened !== 404; i++) { + await new Promise((r) => setTimeout(r, 1000)); reopened = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + } + check('one remove button reopens the path for a source that was paused a moment ago', + reopened === 404, `probe from ${PATH_BUDGET_IP} answered ${reopened}`); + + await page.selectOption('#rateMode', 'off'); + await page.click('#setRate'); + await page.waitForFunction(() => /budget/.test(document.getElementById('status').textContent), + null, { timeout: 15000 }).catch(() => {}); + check('the volume switch is left off, as the stack was seeded', + (await page.$$eval('#rateMode', (s) => s[0].value)) === 'off', await page.$$eval('#rateMode', (s) => s[0].value)); + await page.fill('#allowMatch', WRITE_CIDR); await page.fill('#allowNote', 'console gate: allow entry'); diff --git a/scripts/console-smoke.sh b/scripts/console-smoke.sh index 0f6b8de..6989f5c 100755 --- a/scripts/console-smoke.sh +++ b/scripts/console-smoke.sh @@ -28,7 +28,7 @@ SEED_ERROR="203.0.113.$(( 140 + RANDOM % 60 ))" # still in the table, the edge stopped honouring it a minute ago. Chosen per run, # so a leftover row in the data volume cannot satisfy the assertion. SEED_EXPIRED_CIDR="203.0.113.$(( 240 + RANDOM % 10 ))/32" -export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK SEED_EXPIRED_CIDR SEED_NETBLOCK SEED_NETBLOCK_FRESH +export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK SEED_EXPIRED_CIDR SEED_NETBLOCK SEED_NETBLOCK_FRESH SEED_PATH_BUDGET_PATH SEED_PATH_BUDGET_IP admin() { curl -s -m 10 -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; } @@ -115,6 +115,12 @@ admin -X POST -H 'Content-Type: application/json' \ # whole block for the length of the scene. SEED_NETBLOCK=192.0.2.0/24 SEED_NETBLOCK_FRESH=192.0.2.203 + +# A request budget for one path (OPEN-68). The path is chosen per run so the row +# the page writes is this run's even on a volume that kept an earlier one, and the +# address is one no other scene of this gate probes. +SEED_PATH_BUDGET_PATH="/budget-probe-$(( RANDOM % 32768 ))" +SEED_PATH_BUDGET_IP=192.0.2.210 curl -s -X PUT -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ -d '{"netblockCandidateBans":2}' "$EDGE/admin-api/policy" >/dev/null for src in 192.0.2.201 192.0.2.202; do @@ -142,8 +148,9 @@ if [ "${SEED_ONLY:-0}" = 1 ]; then # page in a browser image), so it cannot inherit these values. Writing them out # is what keeps the alert assertion honest: SEED_ERROR is chosen per run, and an # empty one on the driver side would silently weaken the check to "any alert". - printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\nSEED_EXPIRED_CIDR=%s\nSEED_NETBLOCK=%s\nSEED_NETBLOCK_FRESH=%s\n' \ - "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" "$SEED_EXPIRED_CIDR" "$SEED_NETBLOCK" "$SEED_NETBLOCK_FRESH" > "${SEED_FILE:-console-seed.env}" + printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\nSEED_EXPIRED_CIDR=%s\nSEED_NETBLOCK=%s\nSEED_NETBLOCK_FRESH=%s\nSEED_PATH_BUDGET_PATH=%s\nSEED_PATH_BUDGET_IP=%s\n' \ + "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" "$SEED_EXPIRED_CIDR" "$SEED_NETBLOCK" "$SEED_NETBLOCK_FRESH" \ + "$SEED_PATH_BUDGET_PATH" "$SEED_PATH_BUDGET_IP" > "${SEED_FILE:-console-seed.env}" echo "- SEED_ONLY=1: stack is up and seeded at $EDGE; seed values in ${SEED_FILE:-console-seed.env}" trap - EXIT exit 0 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index a351174..05307c9 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -656,6 +656,87 @@ check 'the watch is off again and offers nothing' 0 \ "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \ | python3 -c 'import sys,json;print(len(json.load(sys.stdin)["netblocks"]))')" +# A request budget for one path (OPEN-68). The edge-wide budget above is one +# number for the whole site; this is the same switch with a path on it, and the +# claim worth testing is the narrow one: the pause covers the path it names and +# nothing else, and it writes no ban. +echo '- a request budget for one path' +echo 'path budget' > /tmp/openwaf-upstream/login.txt +PATH_BUDGET_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}' +PATH_BUDGET_JSON='{"pattern":"/login*","limitPerWindow":2,"windowSeconds":120,"note":"smoke scene"}' +PATH_BUDGET_CLASH_JSON='{"pattern":"/login*","limitPerWindow":50}' +PATH_BUDGET_BADPATTERN_JSON='{"pattern":"login*","limitPerWindow":2}' +PATH_BUDGET_ZEROLIMIT_JSON='{"pattern":"/login*","limitPerWindow":0}' +PATH_BUDGET_BADWINDOW_JSON='{"pattern":"/login*","windowSeconds":99999}' +# TEST-NET-1, and deliberately not 198.51.100.0/24: an earlier scene allowlists +# that whole range, and an allowlisted source never reaches the counter — which +# would make this scene measure nothing and still print 200s. +PATH_BUDGET_IP=192.0.2.77 +PATH_BUDGET_OTHER=192.0.2.78 +check 'the path budgets hang off the same volume switch' Enforce \ + "$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_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 pattern with no leading slash is refused by name' yes \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_BADPATTERN_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | grep -q 'must start with /' && echo yes || echo no)" +check 'a budget of zero is refused by name' yes \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_ZEROLIMIT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | grep -q 'limitPerWindow must be 1..100000' && echo yes || echo no)" +check 'a window outside its bounds is refused by name' yes \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_BADWINDOW_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | grep -q 'windowSeconds must be 1..3600' && echo yes || echo no)" +check 'a written budget is live without a restart' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")" +check 'a second live budget for one path is refused, not resolved by accident' 409 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$PATH_BUDGET_CLASH_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")" +check 'the first request inside the path budget is proxied' 200 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")" +check 'so is the second' 200 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")" +check 'the third crosses it and is answered by the edge' 429 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")" +check 'the refusal says when the pause ends' yes \ + "$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)" \ + | grep -qi '^retry-after:' && echo yes || echo no)" +check 'the refusal names the budget it crossed' yes \ + "$(curl -s -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)" \ + | grep -q 'rate_rule_' && echo yes || echo no)" +check 'the rest of the site stays open to the same source' 404 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from wp-admin)")" +check 'and the pause wrote no ban' 0 \ + "$(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']=='$PATH_BUDGET_IP']))")" +check 'a second source has its own window on the same path' 200 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_OTHER" "$(from login.txt)")" +check 'the listing says what the budget counted and who is over it' '2 1' \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | python3 -c 'import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])')" +check 'the state says the budgets are being read' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["rateRules"]==1 and d["rateRulesAvailable"] and d["rateRulesError"] is None else "no")')" +check 'the budget travels in an exported document' 1 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export" \ + | python3 -c 'import sys,json;print(len(json.load(sys.stdin)["rateRules"]))')" +PATH_BUDGET_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')" +check 'removing it stops enforcing on the next request' 204 \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$PATH_BUDGET_ID")" +check 'the same source is proxied again' 200 \ + "$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")" +check 'and the listing is empty again' 0 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +rm -f /tmp/openwaf-upstream/login.txt +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" >/dev/null + echo '- admin surface' check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" check 'the policy is readable' Enforce \