diff --git a/README.md b/README.md index 1278368..33fb9a1 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,9 @@ GET /admin-api/rules path patterns, in the order they are enforce 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/rate-rules/{id}/sources which sources this budget is inside + GET is a read; DELETE ?source= drops one + source's window on this budget only 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 @@ -1255,6 +1258,59 @@ 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. +### Who a budget is pausing, and letting one source out + +The budget listing has carried three numbers per budget since the feature landed — +sources counted, windows running, over budget now — and no name. "3 over budget" +is the half an operator cannot act on, and the only lever for one of those three +was `DELETE /admin-api/rate-rules/{id}`: take the budget off every source on the +site to release one office behind one NAT. The edge-wide budget never had this +hole, because `/admin-api/rate` names its sources. + +``` +GET /admin-api/rate-rules/3/sources +{ "id": 3, "pattern": "/login*", "limitPerWindow": 5, "windowSeconds": 120, + "live": true, "scope": "this-process", + "keyRule": { "ipv4PrefixLength": 32, "ipv6PrefixLength": 64 }, + "total": 2, + "sources": [ { "sourceKey": "203.0.113.7", "count": 6, "overBudget": true, + "windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 41 }, + { "sourceKey": "198.51.100.0/24", "count": 2, "overBudget": false, + "windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 88 } ], + "howToRead": "the counters live in this process, so N edges allow N budgets; an over-budget source is answered 429 on this path only, and clearing one source restarts its window at zero rather than exempting it" } +``` + +The entries are **source keys**, not addresses — the same key the budget counts +under, with the prefix rule printed beside it, which is why a /24 can appear in +the list. Busiest first, live windows only, paged with `X-Total-Count` and +`X-Truncated` like every other listing, and `total` is the same number the +listing's `windowsRunning` reports: the names come from the same state as the +three counters, not from a second ledger. `howToRead` says which kind of empty an +empty list is — "counting, nobody inside a window right now" and "this budget has +expired" are different answers, and `sources: []` cannot tell them apart. + +``` +DELETE /admin-api/rate-rules/3/sources?source=203.0.113.7 +{ "id": 3, "sourceKey": "203.0.113.7", "asked": "203.0.113.7", "cleared": true, + "note": "203.0.113.7 starts its window on this budget from zero at its next request: this is a counter reset, not an exemption, and the budget still applies to it and to every other source" } +``` + +**This is not an exemption, and the answer says so.** The window restarts at zero +and the budget starts counting this source again from there; for "let them through +whatever they do" the control is the allowlist, which outranks every pillar. Every +other source stays paused. An operator who types the address instead of the key +gets the key this edge files it under — the answer names the key it actually +dropped, because the others sharing that key are still paused. A second clear +finds nothing to clear and answers `cleared: false` rather than repeating the +first answer, and writes no second record; the first one is in the change log +under `rate rule / changed`, because "why did this source stop being paused" is +the question the log exists for. + +The read-only token reads the list and gets a **403** on the clear — the token is +known and its level is the answer; a 401 would tell the operator to go chase a +secret. Reading the list spends nothing: N reads leave `count` and `overBudgetNow` +where they were, so the page that exists to show a pause cannot cause one. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1273,6 +1329,12 @@ apply and a decision not to make. The page also asks the dry run directly (OPEN-69): an address and a path, and the answer prints the verdict, the path rule that spoke if one did, the edge-wide window with the seconds left in it, and one line per path budget whose pattern matches the asked path. +Each budget row has a **who** button (OPEN-71): the panel names the sources it is +inside, with each one's count against the limit and the seconds left in its +window, and puts a **let out** button beside every one of them — the status line +then repeats what the API says, that the counter restarts at zero and this is not +an exemption. + Beside it sits the dossier (OPEN-70): one address in, and the page prints the key that address is filed under, the verdict, the exemption or block behind it — naming the range when the row is a range and not the address — the engine's ban @@ -1478,11 +1540,11 @@ 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, the netblock watch and -the per-path request budgets, the volume answer of the dry run and one address -answered in one call: -build 0 warnings / 0 errors, unit **374/374**, integration **356/356 in 39 s**, -console **126 assertions, 0 failed**, smoke **passed 192, failed 0**, and compose **311 passed, -0 failed** against the built image at 262 MB, 0 containers left behind. The console run is the one that earned its keep: the dossier scene waited for "an answer is in the box", which the previous answer still sitting there satisfies, so every assertion after the first read the address asked one click earlier — three failures that named it exactly, and a scene that now empties the box and waits for the address it asked by name. The smoke story from the +the per-path request budgets, the volume answer of the dry run, one address +answered in one call and the sources a budget is pausing: +build 0 warnings / 0 errors, unit **377/377**, integration **365/365 in 31 s**, +console **129 assertions, 0 failed**, smoke **passed 202, failed 0**, and compose **317 passed, +0 failed** against the built image at 262 MB, 0 containers left behind. Two console runs earned their keep in a row. The first: the dossier scene waited for "an answer is in the box", which the previous answer still sitting there satisfies, so every assertion after the first read the address asked one click earlier. The second: two scenes failed with `answered 403`, because the gate's own probes are refusals and the streak pillar had by then banned the probe addresses — a correct edge and a scene that could not retry past a one-hour ban. Both now clear that one ban by name (`?source=engine&key=`), which leaves the engine bans the netblock scene reads standing. The smoke story from the previous cycle is kept here because the numbers are read next to it: the edge used to be 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/RateRuleTracker.cs b/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs index 006e08f..359dc1f 100644 --- a/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs +++ b/dotnet/OpenWaf.Domain/Engine/RateRuleTracker.cs @@ -166,6 +166,92 @@ public sealed class RateRuleTracker } } + /// The sources one budget is currently holding a window for, busiest + /// first, with what each window says right now (OPEN-71). + /// + /// The listing has shown three numbers per budget since OPEN-68 — sources + /// counted, windows running, over budget now — and no name. "3 over budget" + /// is the half an operator cannot act on: the only lever for one of those + /// three was to delete the budget for the whole site. The edge-wide budget + /// never had this hole, because names its + /// sources. + /// + /// The limit travels in as an argument rather than being stored with the + /// window, so there is exactly one copy of the number a budget enforces: the + /// row's. A second copy inside the counter is a second number that can + /// disagree with the first, and the disagreement would be invisible. + /// + /// Live windows only, and nothing is spent: this is the same state the guard + /// reads, read without moving it. + public IReadOnlyList SourcesFor( + long ruleId, int limitPerWindow, DateTimeOffset now, int limit, int offset) + { + var take = Math.Max(1, limit); + var skip = Math.Max(0, offset); + lock (_gate) + { + List? rows = null; + foreach (var s in _states.Values) + { + if (s.Rule != ruleId) continue; + var end = s.WindowStart + s.WindowLength; + if (now >= end) continue; + rows ??= []; + rows.Add(new RuleSourceWindow( + s.SourceKey, s.Count, + limitPerWindow > 0 && s.Count > limitPerWindow, + s.WindowStart, end)); + } + if (rows is null) return []; + // Busiest first: the source nearest a refusal is the one an operator + // reads about, and a stable tie-break on the key keeps two calls + // showing the same order across a page boundary. + rows.Sort((a, b) => b.Count != a.Count + ? b.Count.CompareTo(a.Count) + : string.CompareOrdinal(a.SourceKey, b.SourceKey)); + return rows.Skip(skip).Take(take).ToList(); + } + } + + /// How many live windows this budget holds — the same count the + /// listing's windowsRunning reports, so a paged source list can say + /// whether it is complete. + public int LiveWindowCount(long ruleId, DateTimeOffset now) + { + lock (_gate) + { + var n = 0; + foreach (var s in _states.Values) + { + if (s.Rule != ruleId) continue; + if (now >= s.WindowStart + s.WindowLength) continue; + n++; + } + return n; + } + } + + /// Drop one source's window on one budget: the control for "my office + /// is caught by the login budget, let them through" that is not "delete the + /// budget for every source on the site" (OPEN-71). + /// + /// What it is not, stated because the difference is the whole point: it is not + /// an exemption. The window restarts at zero on the next request, and the + /// budget starts counting this source again from there — an exemption is the + /// allowlist, which outranks every pillar. True means a window was dropped; + /// false means there was none to drop, which is a different answer from + /// "the source is not being paused". + public bool ForgetRuleSource(long ruleId, string sourceKey) + { + if (string.IsNullOrEmpty(sourceKey)) return false; + lock (_gate) + { + if (!_states.Remove((ruleId, sourceKey), out var s)) return false; + RemoveNode(s); + return true; + } + } + /// 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) @@ -276,3 +362,12 @@ public sealed record RuleWindowObservation( DateTimeOffset WindowStart, DateTimeOffset WindowEnd, int WindowSeconds); + +/// One source inside one budget right now: what it has spent, whether +/// that is past the limit, and when its window ends. +public sealed record RuleSourceWindow( + string SourceKey, + int Count, + bool OverBudget, + DateTimeOffset WindowStart, + DateTimeOffset WindowEnd); diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index fb66695..3f2df66 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -145,6 +145,7 @@ internal static class AdminConsole

Path budgets

patternrequestswindow ssources countedwindows runningover budget nownoteexpires
+

Ask what the edge would answer

@@ -520,7 +521,8 @@ async function load() { { 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: '' } + { 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') @@ -859,6 +861,39 @@ el('askDecide').onclick = async () => { } }; +async function showBudgetSources(id) { + // Who a path budget is pausing (OPEN-71). The table has always said "3 over + // budget"; this names them, and puts the one lever an operator actually wants + // beside each — drop this source's window, not the budget for everyone. + const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(id) + '/sources'); + const box = el('budgetsources'); + box.textContent = ''; + if (failed(r)) return; + const d = r.body || {}; + const head = document.createElement('div'); + head.textContent = 'budget ' + (d.id || id) + ' ' + (d.pattern || '') + ' — ' + (d.limitPerWindow || '?') + + ' per ' + (d.windowSeconds || '?') + ' s · ' + (d.total || 0) + ' source(s) inside a window · ' + + (d.scope || '?') + (d.live === false ? ' · THIS BUDGET IS EXPIRED, it enforces nothing' : ''); + box.appendChild(head); + const note = document.createElement('div'); + note.textContent = d.howToRead || ''; + box.appendChild(note); + for (const src of (d.sources || [])) { + const line = document.createElement('div'); + line.textContent = src.sourceKey + ' — ' + src.count + ' of ' + (d.limitPerWindow || '?') + + (src.overBudget + ? ' OVER: answered 429 on this path for ' + src.secondsLeft + ' more s' + : ', ' + src.secondsLeft + ' s left in its window') + ' '; + const btn = document.createElement('button'); + btn.dataset.act = 'letout'; + btn.dataset.k = String(d.id || id); + btn.dataset.s = src.sourceKey; + btn.textContent = 'let out'; + line.appendChild(btn); + box.appendChild(line); + } +} + el('askSource').onclick = async () => { // The dossier (OPEN-70). One address in, everything this edge knows about it // out: the exemption that covers it, the operator's block on it or on a network @@ -957,7 +992,22 @@ document.addEventListener('click', async (e) => { 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'); + if (!failed(r)) { done('path budget removed'); el('budgetsources').textContent = ''; } + } else if (b.dataset.act === 'whobudget') { + await showBudgetSources(b.dataset.k); + } else if (b.dataset.act === 'letout') { + // One source out of one budget. The answer says what it is: the counter + // restarts at zero, the budget still applies, and the other sources stay + // where they were. + const r = await apiRaw('/admin-api/rate-rules/' + encodeURIComponent(b.dataset.k) + + '/sources?source=' + encodeURIComponent(b.dataset.s), { method: 'DELETE' }); + if (!failed(r)) { + const d = r.body || {}; + done(d.cleared + ? 'window dropped for ' + d.sourceKey + ' — it counts from zero again, this is not an exemption' + : 'nothing was dropped: ' + (d.note || 'this source has no running window on this budget')); + await showBudgetSources(b.dataset.k); + } } 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/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 9e11d75..3a2c71c 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -389,6 +389,125 @@ internal static partial class AdminEndpoints return Results.NoContent(); }); + // Who a path budget is pausing (OPEN-71). The listing has carried three + // numbers per budget since OPEN-68 — sources counted, windows running, + // over budget now — and no name, so "3 over budget" was the half an + // operator could not act on: the only lever for one of those three was to + // delete the budget for the whole site. The edge-wide budget never had + // this hole, because /admin-api/rate names its sources. + // + // The rows are the same state the guard reads, read without moving it, and + // the limit is passed in from the rule row rather than copied into the + // counter — one copy of the number a budget enforces. + group.MapGet("/rate-rules/{id:long}/sources", async (long id, int? limit, int? offset, + OpenWafDbContext db, RateRuleTracker rateRules, EdgePolicyProvider policyProvider, + HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "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 rule = await db.RateRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct); + if (rule is null) return Results.NotFound(new { error = $"no rate rule with id {id}" }); + var live = rule.ExpiresAt is null || rule.ExpiresAt > now; + var rows = rateRules.SourcesFor(id, rule.LimitPerWindow, now, take, skip); + // The same count the listing's `windowsRunning` reports, so a page can + // say whether it is the whole answer. + var total = rateRules.LiveWindowCount(id, now); + ctx.Response.Headers["X-Total-Count"] = total.ToString(); + ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant(); + var policy = policyProvider.Current; + return Results.Ok(new + { + id = rule.Id, + pattern = rule.Pattern, + limitPerWindow = rule.LimitPerWindow, + windowSeconds = rule.WindowSeconds, + note = rule.Note, + expiresAt = rule.ExpiresAt, + live, + // The windows are keyed on the source key, not on the address the + // operator typed, and the rule that produced the key travels with + // the list — otherwise a /64 entry reads as an address that is not + // the one they are looking for. + scope = "this-process", + keyRule = new + { + ipv4PrefixLength = policy.Ipv4KeyPrefixLength, + ipv6PrefixLength = policy.Ipv6KeyPrefixLength + }, + total, + sources = rows.Select(r => new + { + sourceKey = r.SourceKey, + count = r.Count, + overBudget = r.OverBudget, + windowStartsAt = r.WindowStart, + windowEndsAt = r.WindowEnd, + secondsLeft = SecondsLeft(r.WindowEnd, now) + }), + // What an empty list means here, in the list: "the budget is + // counting and nobody is inside a window" and "this budget is dead" + // are different answers, and `sources: []` alone cannot tell them. + howToRead = !live + ? "this budget has expired: the guard no longer consults it, and the windows below are what is left of it" + : total == 0 + ? "the budget is live and counting, and no source is inside a running window right now — which is not the same as nobody ever having asked" + : "the counters live in this process, so N edges allow N budgets; an over-budget source is answered 429 on this path only, and clearing one source restarts its window at zero rather than exempting it" + }); + }); + + // Drop one source's window on one budget: the control for "my office is + // caught by the login budget" that is not "take the budget off every source + // on the site". It is not an exemption and the answer says so — the window + // restarts at zero and the budget starts counting this source again from + // there. For "let them through whatever they do", the allowlist is the + // control, and it outranks every pillar. + group.MapDelete("/rate-rules/{id:long}/sources", async (long id, string? source, + OpenWafDbContext db, RateRuleTracker rateRules, EdgeStateStore state, + ConfigChangeWriter changes, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "source")) return Results.BadRequest(new { error = unknown }); + if (string.IsNullOrWhiteSpace(source)) + return Results.BadRequest(new { error = "source is required: name the source key whose window on this budget should be dropped" }); + var rule = await db.RateRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct); + if (rule is null) return Results.NotFound(new { error = $"no rate rule with id {id}" }); + + var asked = source.Trim(); + var clearedKey = asked; + var dropped = rateRules.ForgetRuleSource(id, asked); + if (!dropped && IsAnAddress(asked)) + { + // The list prints keys; an operator types an address. Trying the + // key this edge would file that address under is the difference + // between "nothing was cleared" and the right source being let out + // — and the answer names the key it actually dropped. + // The snapshot's policy, not a provider's cached copy: this is the + // key the guard counted under, and a stale prefix length would + // answer "nothing was cleared" for a source that is paused. + var derived = SourceKey.For(asked, state.GetOrRefresh().Policy); + if (!string.Equals(derived, asked, StringComparison.Ordinal)) + { + dropped = rateRules.ForgetRuleSource(id, derived); + if (dropped) clearedKey = derived; + } + } + if (dropped) + await changes.RecordAsync(ConfigChangeLog.SectionRateRules, ConfigChangeLog.ActionChanged, + id.ToString(), $"window dropped for {clearedKey} — the counter restarts at zero, this is not an exemption", ct: ct); + return Results.Ok(new + { + id, + sourceKey = clearedKey, + asked = asked, + cleared = dropped, + note = dropped + ? $"{clearedKey} starts its window on this budget from zero at its next request: this is a counter reset, not an exemption, and the budget still applies to it and to every other source" + : "this source has no running window on this budget, so nothing was cleared — which is not the same as it being exempt" + }); + }); + // 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 diff --git a/dotnet/OpenWaf.Tests.Integration/BudgetSourceListingTests.cs b/dotnet/OpenWaf.Tests.Integration/BudgetSourceListingTests.cs new file mode 100644 index 0000000..5ec3299 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/BudgetSourceListingTests.cs @@ -0,0 +1,315 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Who a path budget is pausing, and letting one of them out (OPEN-71). +/// +/// Since OPEN-68 the budget listing has carried three numbers per budget — +/// sources counted, windows running, over budget now — and no name. "3 over +/// budget" is the half an operator cannot act on, and the only lever for one of +/// those three was to take the budget off every source on the site. The +/// edge-wide budget never had this hole: /admin-api/rate names its sources. +/// +/// What these tests hold the surface to: the list is the same state the three +/// counters report; it spends nothing; clearing one source leaves the others +/// paused; an address typed instead of a key still finds the source it is filed +/// under; and an empty list says which kind of empty it is. +/// +public sealed class BudgetSourceListingTests +{ + private const string First = "203.0.113.141"; + private const string Second = "203.0.113.142"; + private const string Path = "/signin"; + + private static async Task AdminAsync( + EdgeFixture f, HttpMethod method, string url, object? body = null, + string token = EdgeFixture.AdminToken) + { + using var request = new HttpRequestMessage(method, url); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + if (body is not null) request.Content = JsonContent.Create(body); + return await f.Client.SendAsync(request); + } + + private static async Task JsonAsync( + EdgeFixture f, string url, string token = EdgeFixture.AdminToken) + { + using var r = await AdminAsync(f, HttpMethod.Get, url, token: token); + Assert.Equal(HttpStatusCode.OK, r.StatusCode); + return JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + private static async Task AskAsync(EdgeFixture f, string path, string ip) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + using var r = await f.Client.SendAsync(request); + return (int)r.StatusCode; + } + + /// A budget of two per window on one path, with the edge-wide budget + /// far above it so the rule is the only thing in play. + private static async Task SeedRuleAsync(EdgeFixture f, string pattern = Path, int limit = 2) + { + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern, limitPerWindow = limit, windowSeconds = 300 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules"); + using var doc = JsonDocument.Parse(await list.Content.ReadAsStringAsync()); + return doc.RootElement.EnumerateArray() + .First(r => r.GetProperty("pattern").GetString() == pattern) + .GetProperty("id").GetInt64(); + } + + private static async Task<(EdgeFixture Fixture, long RuleId)> StackAsync() + { + var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 600); + return (f, await SeedRuleAsync(f)); + } + + [Fact] + public async Task A_budget_can_be_asked_who_it_is_pausing() + { + var (f, id) = await StackAsync(); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + for (var i = 0; i < 2; i++) await AskAsync(f, Path, Second); + + var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + Assert.Equal(id, body.GetProperty("id").GetInt64()); + Assert.Equal(Path, body.GetProperty("pattern").GetString()); + Assert.Equal(2, body.GetProperty("limitPerWindow").GetInt32()); + Assert.Equal("this-process", body.GetProperty("scope").GetString()); + // The key rule travels with the list: the entries are keys, and without + // the rule a /64 or a /24 reads as an address that is not the one asked for. + Assert.Equal(32, body.GetProperty("keyRule").GetProperty("ipv4PrefixLength").GetInt32()); + + var rows = body.GetProperty("sources").EnumerateArray().ToList(); + Assert.Equal(2, rows.Count); + // Busiest first: the source nearest a refusal is the one being read about. + Assert.Equal(First, rows[0].GetProperty("sourceKey").GetString()); + Assert.Equal(3, rows[0].GetProperty("count").GetInt32()); + Assert.True(rows[0].GetProperty("overBudget").GetBoolean()); + Assert.True(rows[0].GetProperty("secondsLeft").GetInt32() > 0); + Assert.Equal(Second, rows[1].GetProperty("sourceKey").GetString()); + Assert.Equal(2, rows[1].GetProperty("count").GetInt32()); + Assert.False(rows[1].GetProperty("overBudget").GetBoolean()); + } + + [Fact] + public async Task The_list_and_the_three_counters_are_the_same_state() + { + var (f, id) = await StackAsync(); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + for (var i = 0; i < 2; i++) await AskAsync(f, Path, Second); + await AskAsync(f, Path, "203.0.113.143"); + + var listing = await JsonAsync(f, "/admin-api/rate-rules"); + var row = listing.EnumerateArray().First(r => r.GetProperty("id").GetInt64() == id); + var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + + // The numbers the operator already trusts, and the names behind them, from + // one state: a list that disagreed with the counter would be a second + // ledger, which is what this feature exists to avoid. + Assert.Equal(row.GetProperty("liveWindows").GetInt32(), body.GetProperty("total").GetInt32()); + Assert.Equal(row.GetProperty("overBudgetNow").GetInt32(), + body.GetProperty("sources").EnumerateArray() + .Count(r => r.GetProperty("overBudget").GetBoolean())); + } + + [Fact] + public async Task Letting_one_source_out_leaves_the_others_paused() + { + var (f, id) = await StackAsync(); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, Second); + Assert.Equal(429, await AskAsync(f, Path, First)); + Assert.Equal(429, await AskAsync(f, Path, Second)); + + using (var cleared = await AdminAsync(f, HttpMethod.Delete, + $"/admin-api/rate-rules/{id}/sources?source={First}")) + { + Assert.Equal(HttpStatusCode.OK, cleared.StatusCode); + using var doc = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync()); + Assert.True(doc.RootElement.GetProperty("cleared").GetBoolean()); + Assert.Equal(First, doc.RootElement.GetProperty("sourceKey").GetString()); + // Said in the answer, not only in the README: this is a counter reset, + // not an exemption, and the budget still applies to this source. + Assert.Contains("not an exemption", doc.RootElement.GetProperty("note").GetString()!); + } + + // 404 is the upstream's own answer for a path it does not serve: the point + // is that the edge stopped answering 429 for this source. + Assert.Equal(404, await AskAsync(f, Path, First)); + // The neighbour is still where it was: one source out is not the budget off. + Assert.Equal(429, await AskAsync(f, Path, Second)); + + // And the list says what the reset actually did: the cleared source is + // counting again from one, not exempt, while the neighbour is still over. + var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + var rows = body.GetProperty("sources").EnumerateArray().ToList(); + Assert.Equal(2, rows.Count); + Assert.Equal(2, body.GetProperty("total").GetInt32()); + var letOut = rows.Single(r => r.GetProperty("sourceKey").GetString() == First); + Assert.Equal(1, letOut.GetProperty("count").GetInt32()); + Assert.False(letOut.GetProperty("overBudget").GetBoolean()); + var still = rows.Single(r => r.GetProperty("sourceKey").GetString() == Second); + Assert.True(still.GetProperty("overBudget").GetBoolean()); + } + + [Fact] + public async Task An_address_typed_instead_of_a_key_still_finds_the_source_it_is_filed_under() + { + var (f, id) = await StackAsync(); + // Group the sources by /24: the budget now counts one key for the whole + // block, which is the whole point of the key rule. + using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { ipv4KeyPrefixLength = 24 })) { } + for (var i = 0; i < 3; i++) await AskAsync(f, Path, "203.0.113.150"); + + var listed = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + var key = listed.GetProperty("sources")[0].GetProperty("sourceKey").GetString(); + Assert.Equal("203.0.113.0/24", key); + + // The operator types the address they are looking at, not the key. + using (var cleared = await AdminAsync(f, HttpMethod.Delete, + $"/admin-api/rate-rules/{id}/sources?source=203.0.113.150")) + { + Assert.Equal(HttpStatusCode.OK, cleared.StatusCode); + using var doc = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync()); + Assert.True(doc.RootElement.GetProperty("cleared").GetBoolean()); + // And the answer names the key it actually dropped, so the operator + // knows what else shares it. + Assert.Equal("203.0.113.0/24", doc.RootElement.GetProperty("sourceKey").GetString()); + } + Assert.Equal(0, (await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources")) + .GetProperty("total").GetInt32()); + } + + [Fact] + public async Task An_empty_list_says_which_kind_of_empty_it_is() + { + var (f, live) = await StackAsync(); + var dead = await SeedRuleAsync(f, "/signin-late"); + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.RateRules.FirstAsync(r => r.Id == dead); + row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5); + await db.SaveChangesAsync(); + await f.Service().InvalidateAsync(); + } + + var counting = await JsonAsync(f, $"/admin-api/rate-rules/{live}/sources"); + Assert.Empty(counting.GetProperty("sources").EnumerateArray()); + Assert.True(counting.GetProperty("live").GetBoolean()); + // "counting, nobody inside a window" — not "nobody ever asked". + Assert.Contains("not the same as nobody ever having asked", + counting.GetProperty("howToRead").GetString()!); + + var expired = await JsonAsync(f, $"/admin-api/rate-rules/{dead}/sources"); + Assert.False(expired.GetProperty("live").GetBoolean()); + Assert.Contains("expired", expired.GetProperty("howToRead").GetString()!); + } + + [Fact] + public async Task Reading_the_list_spends_none_of_the_budget_it_reports() + { + var (f, id) = await StackAsync(); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + + var before = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + var beforeCount = before.GetProperty("sources")[0].GetProperty("count").GetInt32(); + for (var i = 0; i < 6; i++) + { + var again = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"); + Assert.Equal(beforeCount, again.GetProperty("sources")[0].GetProperty("count").GetInt32()); + } + // And the next real request is the fourth, not the seventh: the page that + // exists to show a pause would otherwise be the cause of one. + Assert.Equal(429, await AskAsync(f, Path, First)); + } + + [Fact] + public async Task An_unknown_budget_and_an_unnamed_parameter_are_refused_by_name() + { + var (f, id) = await StackAsync(); + + using (var missing = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules/999999/sources")) + { + Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode); + Assert.Contains("999999", await missing.Content.ReadAsStringAsync()); + } + using (var unknown = await AdminAsync(f, HttpMethod.Get, $"/admin-api/rate-rules/{id}/sources?source={First}")) + { + Assert.Equal(HttpStatusCode.BadRequest, unknown.StatusCode); + Assert.Contains("source", await unknown.Content.ReadAsStringAsync()); + } + using (var noSource = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}/sources")) + { + Assert.Equal(HttpStatusCode.BadRequest, noSource.StatusCode); + Assert.Contains("source is required", await noSource.Content.ReadAsStringAsync()); + } + using (var missingRule = await AdminAsync(f, HttpMethod.Delete, + "/admin-api/rate-rules/999999/sources?source=203.0.113.1")) + Assert.Equal(HttpStatusCode.NotFound, missingRule.StatusCode); + } + + [Fact] + public async Task The_read_only_token_reads_the_list_and_cannot_clear_it() + { + var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 600, + readOnlyToken: EdgeFixture.ReadOnlyToken); + var id = await SeedRuleAsync(f); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + + var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources", EdgeFixture.ReadOnlyToken); + Assert.Equal(3, body.GetProperty("sources")[0].GetProperty("count").GetInt32()); + + using (var cleared = await AdminAsync(f, HttpMethod.Delete, + $"/admin-api/rate-rules/{id}/sources?source={First}", token: EdgeFixture.ReadOnlyToken)) + // 403, not 401: the token is known and its level is the answer. A + // read-only token that got 401 would read as "wrong secret", which is + // a different problem for the operator to chase. + Assert.Equal(HttpStatusCode.Forbidden, cleared.StatusCode); + + // Still paused, and still saying so. + Assert.Equal(429, await AskAsync(f, Path, First)); + var after = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources", EdgeFixture.ReadOnlyToken); + Assert.Equal(1, after.GetProperty("total").GetInt32()); + } + + [Fact] + public async Task Clearing_a_source_leaves_a_record_of_itself() + { + var (f, id) = await StackAsync(); + for (var i = 0; i < 3; i++) await AskAsync(f, Path, First); + + using (await AdminAsync(f, HttpMethod.Delete, + $"/admin-api/rate-rules/{id}/sources?source={First}")) { } + // A second clear has nothing to clear and answers differently — and it + // writes no second record, because nothing changed. + using (var again = await AdminAsync(f, HttpMethod.Delete, + $"/admin-api/rate-rules/{id}/sources?source={First}")) + { + Assert.Equal(HttpStatusCode.OK, again.StatusCode); + using var doc = JsonDocument.Parse(await again.Content.ReadAsStringAsync()); + Assert.False(doc.RootElement.GetProperty("cleared").GetBoolean()); + Assert.Contains("no running window", doc.RootElement.GetProperty("note").GetString()!); + } + + var changes = await JsonAsync(f, "/admin-api/changes"); + var row = changes.EnumerateArray().First(c => c.GetProperty("target").GetString() == id.ToString()); + Assert.Equal("rate rule", row.GetProperty("section").GetString()); + Assert.Equal("changed", row.GetProperty("action").GetString()); + Assert.Contains("not an exemption", row.GetProperty("detail").GetString()!); + Assert.Equal(1, changes.EnumerateArray() + .Count(c => c.GetProperty("target").GetString() == id.ToString() + && c.GetProperty("action").GetString() == "changed")); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs b/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs index 454ef73..6b2c20e 100644 --- a/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs +++ b/dotnet/OpenWaf.Tests.Unit/RateRuleTrackerTests.cs @@ -221,6 +221,85 @@ public sealed class RateRuleTrackerTests Assert.Equal(T0, next.WindowStart); } + // Who a budget is pausing (OPEN-71). The listing has shown three numbers per + // budget and no name, so the operator could see "3 over budget" and had one + // lever for it: delete the budget for everyone. + [Fact] + public void One_budget_can_be_asked_which_sources_are_inside_it() + { + var tracker = new RateRuleTracker(); + var login = Rule(1, "/login*", 2); + var api = Rule(7, "/api/*", 5); + + tracker.Record(login, "203.0.113.1", T0); + tracker.Record(login, "203.0.113.1", T0.AddSeconds(1)); + tracker.Record(login, "203.0.113.1", T0.AddSeconds(2)); // 3 of 2: over + tracker.Record(login, "203.0.113.2", T0); // 1 of 2: inside + tracker.Record(login, "203.0.113.3", T0.AddSeconds(-600)); // window ran out + tracker.Record(api, "203.0.113.1", T0); // a different budget + + var rows = tracker.SourcesFor(1, 2, T0.AddSeconds(3), 10, 0); + // Busiest first, this budget only, live windows only, and the over-budget + // flag computed from the limit the caller passed — not from a copy. + Assert.Equal(2, rows.Count); + Assert.Equal("203.0.113.1", rows[0].SourceKey); + Assert.Equal(3, rows[0].Count); + Assert.True(rows[0].OverBudget); + Assert.Equal("203.0.113.2", rows[1].SourceKey); + Assert.False(rows[1].OverBudget); + Assert.Equal(2, tracker.LiveWindowCount(1, T0.AddSeconds(3))); + Assert.Equal(1, tracker.LiveWindowCount(7, T0.AddSeconds(3))); + } + + [Fact] + public void The_source_list_pages_and_keeps_one_order_across_the_pages() + { + var tracker = new RateRuleTracker(); + var rule = Rule(1, "/login*", 10); + for (var i = 0; i < 5; i++) + for (var n = 0; n <= i; n++) + tracker.Record(rule, $"203.0.113.{i}", T0.AddSeconds(n)); + + // Same count and same key order on every call, so a page boundary cannot + // show one source twice and hide another. + var first = tracker.SourcesFor(1, 10, T0.AddSeconds(10), 2, 0).Select(r => r.SourceKey).ToList(); + var second = tracker.SourcesFor(1, 10, T0.AddSeconds(10), 2, 2).Select(r => r.SourceKey).ToList(); + Assert.Equal(["203.0.113.4", "203.0.113.3"], first); + Assert.Equal(["203.0.113.2", "203.0.113.1"], second); + Assert.Equal(5, tracker.LiveWindowCount(1, T0.AddSeconds(10))); + Assert.Empty(tracker.SourcesFor(1, 10, T0.AddSeconds(10), 2, 5)); + } + + [Fact] + public void Dropping_one_source_lets_it_out_without_touching_the_others() + { + var tracker = new RateRuleTracker(); + var login = Rule(1, "/login*", 1); + var api = Rule(7, "/api/*", 1); + + tracker.Record(login, "office", T0); + tracker.Record(login, "office", T0.AddSeconds(1)); // over + tracker.Record(login, "attacker", T0); + tracker.Record(login, "attacker", T0.AddSeconds(1)); // over + tracker.Record(api, "office", T0); + + Assert.True(tracker.ForgetRuleSource(1, "office")); + // Only this budget, only this source: the other source is still over it, + // and the same source is still counted on the other budget. + Assert.Equal(1, tracker.LiveWindowCount(1, T0.AddSeconds(2))); + Assert.Equal(["attacker"], tracker.SourcesFor(1, 1, T0.AddSeconds(2), 10, 0) + .Select(r => r.SourceKey)); + Assert.Equal(1, tracker.LiveWindowCount(7, T0.AddSeconds(2))); + // A second drop has nothing to drop, and says so rather than answering + // the same way as the first. + Assert.False(tracker.ForgetRuleSource(1, "office")); + Assert.False(tracker.ForgetRuleSource(1, "")); + // And the source is not exempt: its next request starts a window at one. + var again = tracker.Record(login, "office", T0.AddSeconds(3)); + Assert.Equal(1, again.Count); + Assert.False(again.OverBudget); + } + [Fact] public void An_unidentifiable_source_is_not_counted() { diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index f4f44a6..b94d072 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1788,6 +1788,43 @@ check 'the scene cleans itself' 0 \ admin "$EDGE/admin-api/blocks?live=false" \ | python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$DOS_IP"'","'"$DOS_NET"'")]))')" + +# Who a path budget is pausing (OPEN-71), on the shipped image: the listing has +# named three numbers per budget and no source, so the only lever for one paused +# source was to take the budget off every source on the site. +echo '- the shipped budget says who it is pausing' +BUD_IP=198.51.100.161 +BUD_IP2=198.51.100.162 +admin -X PUT -H 'Content-Type: application/json' --data-binary "$DRY_ON_JSON" \ + "$EDGE/admin-api/policy" >/dev/null +code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":300,"note":"who scene"}' \ + "$EDGE/admin-api/rate-rules" >/dev/null +BUD_RULE_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/budgeted*"][0])')" +for _ in 1 2 3 4; do code -H "X-Forwarded-For: $BUD_IP" "$EDGE/budgeted" >/dev/null; done +for _ in 1 2 3 4; do code -H "X-Forwarded-For: $BUD_IP2" "$EDGE/budgeted" >/dev/null; done +check 'the shipped budget names both sources and says both are over' yes \ + "$(admin "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources" | python3 -c 'import sys,json;d=json.load(sys.stdin);r=d["sources"];print("yes" if d["total"]==2 and len(r)==2 and all(x["overBudget"] for x in r) and d["scope"]=="this-process" else "no")')" +check 'the shipped names and the shipped counters are the same state' yes \ + "$(admin "$EDGE/admin-api/rate-rules" -o /tmp/cbud_row.json; \ + admin "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources" -o /tmp/cbud_src.json; \ + python3 -c "import json;row=[x for x in json.load(open('/tmp/cbud_row.json')) if x['id']==$BUD_RULE_ID][0];d=json.load(open('/tmp/cbud_src.json'));print('yes' if row['liveWindows']==d['total'] and row['overBudgetNow']==sum(1 for x in d['sources'] if x['overBudget']) else 'no')")" +check 'the shipped edge lets one source out and calls it a reset, not an exemption' yes \ + "$(admin -X DELETE "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources?source=$BUD_IP" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["cleared"] and "not an exemption" in d["note"] else "no")')" +check 'the let-out source is served again, the neighbour is still paused' '404 429' \ + "$(code -H "X-Forwarded-For: $BUD_IP" "$EDGE/budgeted") \ +$(code -H "X-Forwarded-For: $BUD_IP2" "$EDGE/budgeted")" +check 'the shipped read-only token reads the list and cannot clear it' '200 403' \ + "$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources") \ +$(code -X DELETE -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" \ + "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources?source=$BUD_IP2")" +check 'the scene cleans itself' 0 \ + "$(admin -X DELETE "$EDGE/admin-api/rate-rules/$BUD_RULE_ID" >/dev/null; \ + admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \ + "$EDGE/admin-api/policy" >/dev/null; \ + admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" + 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 48d1f75..02b9c3a 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -397,6 +397,18 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); check('the summary counts ranges apart from address blocks', summaryPills.some((p) => /^ranges 1$/.test(p)), JSON.stringify(summaryPills)); + // The gate's own probes are refusals — the upstream has no /probe — so by now + // the streak pillar has banned the probe address on its own, and an engine ban + // outlives the retry loop below by the whole ban duration. This assertion is + // about the range row, so that one ban is cleared by name first: clearing every + // engine ban would take the netblock offers down with it, and the next scene + // reads those. + const adminDelete = async (path) => { + const r = await fetch(`${EDGE}${path}`, { method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } }); + await r.body.cancel(); + }; + await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(RANGE_INSIDE)}`); + await page.click(`#blocks tbody button[data-act="delblock"][data-k="${RANGE_NET}"]`); await page.waitForFunction((net) => ![...document.querySelectorAll('#blocks tbody tr')] .some((tr) => tr.children[0].textContent.startsWith(net)), @@ -460,10 +472,6 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); // Clean up: the range, and the engine bans that produced it, so the scenes // after this one run on the stack they expect. - const adminDelete = async (path) => { - const r = await fetch(`${EDGE}${path}`, { method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } }); - await r.body.cancel(); - }; await adminDelete(`/admin-api/blocks?source=operator&key=${encodeURIComponent(NETBLOCK)}`); await adminDelete('/admin-api/blocks?source=engine'); let cleanedWire = await probe(NET_FRESH); @@ -557,6 +565,37 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); !!countedRow && Number(countedRow[3]) >= 1 && Number(countedRow[4]) >= 1 && Number(countedRow[5]) >= 1, JSON.stringify(countedRow || 'no row')); + // Who the budget is pausing, and letting one source out of it (OPEN-71). The + // table has always said "1 over budget"; the operator reading it had one lever + // — remove the budget for every source on the site. + 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="whobudget"]'); + if (b) b.click(); + }, `${PATH_BUDGET_PATH}*`); + await page.waitForFunction(() => /budget \d+ /.test(document.getElementById('budgetsources').textContent), + null, { timeout: 15000 }).catch(() => {}); + const who = (await page.textContent('#budgetsources')).replace(/\s+/g, ' '); + check('the page names the source a path budget is pausing, with its count against the limit', + /3 of 2 OVER: answered 429 on this path/.test(who) && /this-process/.test(who), who.slice(0, 300)); + + await page.evaluate(() => { + const b = document.querySelector('#budgetsources button[data-act="letout"]'); + if (b) b.click(); + }); + await page.waitForFunction(() => /window dropped for/.test(document.getElementById('status').textContent), + null, { timeout: 15000 }).catch(() => {}); + const letOut = await page.textContent('#status'); + check('one button lets one source out and says it is a counter reset, not an exemption', + /window dropped for/.test(letOut) && /not an exemption/.test(letOut), letOut); + check('the source that was let out reaches the upstream again on that path', + (await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH)) === 404, + `probe from ${PATH_BUDGET_IP} on ${PATH_BUDGET_PATH} after being let out`); + // Same reason as above: the probes this scene drew are refusals, and the streak + // pillar has now banned this address too. The check below is about the budget + // row, so the engine's own ban on this one address is cleared by name first. + await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(PATH_BUDGET_IP)}`); + 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"]'); diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 492080f..90712bd 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -843,6 +843,68 @@ check 'asking it six times wrote nothing: the operator list still holds those tw "$(for _ in 1 2 3 4 5 6; do dossier "$DOS_IP" >/dev/null; dossier "$DOS_INSIDE" >/dev/null; done; \ curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \ | python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')" + +# Who a path budget is pausing (OPEN-71). The listing has carried three numbers +# per budget since OPEN-68 and no name, so "2 over budget" was the half an +# operator could not act on: the only lever for one of those two was to take the +# budget off every source on the site. +echo '- a budget says who it is pausing, and one source can be let out' +BUD_IP=192.0.2.141 +BUD_IP2=192.0.2.142 +BUD_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":300}' +BUD_RULE_JSON='{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":300,"note":"who scene"}' +echo 'budgeted' > /tmp/openwaf-upstream/budgeted.txt +curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$BUD_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null +check 'a budget is written for one path' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$BUD_RULE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")" +BUD_RULE_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([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/budgeted*"][0])')" +check 'two sources cross it' '429 429' \ + "$(for _ in 1 2 3; do code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)" >/dev/null; done; \ + for _ in 1 2 3; do code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)" >/dev/null; done; \ + code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)") \ +$(code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)")" +check 'the budget names both sources, busiest first, with what each has spent' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);r=d["sources"];print("yes" if d["total"]==2 and len(r)==2 and all(x["overBudget"] for x in r) and r[0]["count"]>=4 and d["scope"]=="this-process" and d["keyRule"]["ipv4PrefixLength"]==32 else "no")')" +# The invariant that keeps this from being a second ledger: the names come from +# the same state as the three numbers the operator already reads. +check 'the names and the three counters are the same state' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \ + -o /tmp/bud_row.json; \ + curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources" \ + -o /tmp/bud_src.json; \ + python3 -c "import json;row=[x for x in json.load(open('/tmp/bud_row.json')) if x['id']==$BUD_RULE_ID][0];d=json.load(open('/tmp/bud_src.json'));print('yes' if row['liveWindows']==d['total'] and row['overBudgetNow']==sum(1 for x in d['sources'] if x['overBudget']) and row['trackedSources']>=d['total'] else 'no')")" +check 'one source is let out, and the answer says it is a reset and not an exemption' yes \ + "$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources?source=$BUD_IP" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["cleared"] and d["sourceKey"]=="'"$BUD_IP"'" and "not an exemption" in d["note"] else "no")')" +check 'the let-out source is served again on that path, the neighbour is still paused' '200 429' \ + "$(code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)") \ +$(code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)")" +check 'and the list now shows the let-out source counting from one, not exempt' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources" \ + | python3 -c "import sys,json;d=json.load(sys.stdin);m=[x for x in d['sources'] if x['sourceKey']=='$BUD_IP'];print('yes' if len(m)==1 and m[0]['count']==1 and not m[0]['overBudget'] else 'no')")" +check 'an unknown budget is a 404 and a missing source is a 400' '404 400' \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/999999/sources") \ +$(code -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources")" +check 'the clearing left a record of itself' 1 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \ + | python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['section']=='rate rule' and c['action']=='changed' and c['target']=='$BUD_RULE_ID']))")" +check 'the scene cleans itself' 0 \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID" >/dev/null; \ + curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"rateMode":"Off"}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null; \ + 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/budgeted.txt + check 'the scene cleans itself' 0 \ "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.121" >/dev/null; \