diff --git a/README.md b/README.md index d73ae82..7962123 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,24 @@ the design, not a side effect of registration order: |---|--------|--------|----------| | 1 | always-pass prefixes — `/admin-api`, `/admin`, `/healthz`, `/readyz`, `/openapi` | pass | the recovery hatch for an operator who blocked themselves | | 2 | **allowlist** (address or CIDR, matched on the raw peer address) | pass | wins over everything, including a geo deny | -| 3 | **operator block** (`source=operator`) | 301 to `RedirectTo`, else a honey-pot list | never expires | -| 4 | **engine ban** (`source=engine`) | 403 + `Retry-After` + a reason | expires on its own | -| 5 | **geo policy** (deny list / allow list) | 451 + a note that says the inference is probabilistic | policy, not data | +| 3 | **request rule** (a path pattern an operator wrote; `observe` or `block`) | 403 naming the rule id, or a counted match with the request passed through | operator's list, may expire | +| 4 | **operator block** (`source=operator`) | 301 to `RedirectTo`, else a honey-pot list | never expires | +| 5 | **engine ban** (`source=engine`) | 403 + `Retry-After` + a reason | expires on its own | +| 6 | **geo policy** (deny list / allow list) | 451 + a note that says the inference is probabilistic | policy, not data | + +The request rule is the only pillar that looks at the request rather than at +what the upstream answered or who sent it. Before it, a known-bad request always +reached the origin and became a defence only if the origin's answer happened to +fall in the refusal range three times in a row. A rule is a glob over the path — +`*` and `?`, anchored at both ends, case-insensitive, `*` crossing `/` — not a +regular expression, because the operator writes the pattern and an anonymous +visitor writes the path. The first live rule that matches is the answer, in the +order the listing shows them. `observe` counts matches and lets the request +through (one alert per rule per 15 minutes, and the rules listing carries the +tally), which is how an operator finds out what a rule would have blocked before +it blocks anything; `block` refuses in `Observe` mode too, because the mode +switches off what the edge decides by itself, not what a human wrote down — the +same ruling that keeps an operator block live. A second middleware, `ResponseObservationMiddleware`, sits *inside* the guard: it awaits the upstream, classifies the status the application actually returned, @@ -278,7 +293,10 @@ GET /admin-api/allow?live[=false]&limit&offset POST {"match","note","expire GET /admin-api/policy PUT {"mode":"Enforce","streakThreshold":8,…} GET /admin-api/observations per-source streaks, durable — the maximum ever seen GET /admin-api/streaks the streak standing right now, in this process, with the threshold -GET /admin-api/alerts server_error_streak | candidate_ban +GET /admin-api/alerts server_error_streak | candidate_ban | rule_match +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/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 @@ -686,6 +704,9 @@ running ×1` — because a pill that only appears when something is wrong makes "no alerts" and "alerts are not being written" look identical from the operator's chair, and because the ban case has to read differently: those two bans are not merely unrecorded, they are not in force anywhere. +It lists the path rules in the order they are enforced, with the action, the +expiry and how many times an observe rule has matched — and writing one from the +page is the same call as writing it through the API. It shows the alerts the edge raises — `server_error_streak` (your upstream is failing, and the edge will not ban the visitor who saw it) and `candidate_ban` (the rule would have banned, but the mode is Observe). That table is the whole @@ -825,12 +846,14 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-04 with the -alert webhook on it: build 0 warnings / 0 errors, unit **151/151**, integration -**194/194 in 28 s**, console **79 assertions, 0 failed**, smoke **passed 29, +path rules on it: build 0 warnings / 0 errors, unit **195/195**, integration +**208/208 in 25 s**, console **85 assertions, 0 failed**, smoke **passed 36, failed 0**, and compose **209 passed, 0 failed** against the built image at -261 MB — re-run on this tree because the webhook is a second reader of the alert -table, and the shipped stack has to stay exactly as quiet with no endpoint -configured as it was before. Carried from the 2026-10-02 run and +261 MB — re-run on this tree because a new pillar changes what the shipped stack +enforces, and because the compose data volume outlives `compose down`: the run +after a schema change starts against a database that has every table except the +new one, which is the state the rules read is now written to survive and to say +out loud. Carried from the 2026-10-02 run and not re-measured since: image 261 MB, 0 containers left behind, enforcement lag 33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`, `/tmp/c26_int4.log`, `/tmp/c26_smoke.log`, `/tmp/c26_compose5.log`, @@ -840,7 +863,7 @@ collections — answered **157 passed, 16 failed**, every one of them `Timed out waiting for the entry point to build the IHost after 00:05:00` (`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` the same tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Re-measured 2026-10-04, -the default parallel scheduling answered **194/194 in 28 s**, and the same tree +the default parallel scheduling answered **208/208 in 25 s**, and the same tree run inside a filesystem-and-network sandbox failed **every** fixture with exactly that timeout — a test host that cannot bind a loopback socket hangs in this shape. Scheduling is one variable in that symptom; whether the test host can @@ -1004,6 +1027,20 @@ Stated, because a defence that hides its failure modes is not a defence. with its own outage story. Alerts raised while the process was down are never pushed at all. The table is what an operator reads; the push is what makes a 03:00 outage reach something that acts. +* **A database that predates a table does not gain it.** The default schema + step is `EnsureCreated`: it creates a missing database and changes nothing + about an existing one. The migration set is there for the `migrate` path and + now covers `source_streaks` and `request_rules`, but an upgrade that keeps its + database can arrive with every table except the new one. That is why the + snapshot refresh reads the rules in a statement of their own: a missing + `request_rules` costs the rules pillar and says so — `requestRulesAvailable` + and `requestRulesError` on `/admin-api/state`, a NOT READ line over the rules + table — instead of freezing the operator's block list, which is the failure + this file keeps warning about. +* **A path rule is matched on every request.** The scan is a linear walk over + the live rules, capped at 500 of them, and the pattern language is a glob + rather than a regex so no pattern can backtrack exponentially against a path + someone else chose. The cap is a request-path decision, not a UI one. * **Aggregates, not a request log.** `source_observations` keeps counters and the last-seen evidence per source, and ages out after `OpenWaf:Policy:ObservationRetentionDays` (default 7, 1–365). Raw IPs are not @@ -1016,9 +1053,9 @@ dotnet/ OpenWaf.Domain/ pure decision core: source key, streak, ordered decision OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode - OpenWaf.Tests.Unit/ 151 tests over the decision logic and the durability counters - OpenWaf.Tests.Integration/ 194 tests driving the real pipeline against a fake upstream -scripts/smoke.sh 29 assertions against a running edge + a real upstream + OpenWaf.Tests.Unit/ 195 tests over the decision logic and the durability counters + OpenWaf.Tests.Integration/ 208 tests driving the real pipeline against a fake upstream +scripts/smoke.sh 36 assertions against a running edge + a real upstream scripts/compose-smoke.sh 209 assertions against the built image (compose + nginx) scripts/console-check.cjs 75 assertions against the page, in a real Chromium scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2) diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs index 169d77b..4a93adc 100644 --- a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs +++ b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs @@ -11,12 +11,22 @@ namespace OpenWaf.Domain.Engine; /// still be able to reach the admin API and undo it; /// 2. allowlist — the exemption path, evaluated on the raw /// address so a CIDR means what the operator wrote; -/// 3. operator block — the human's list, which the toggle cannot +/// 3. request rules — the only pillar that looks at the request +/// itself; an operator's pattern, first live match wins, and an +/// observe-action match does not stop the rest of the order from running; +/// 4. operator block — the human's list, which the toggle cannot /// switch off; -/// 4. engine ban — enforced only in ; -/// 5. geo policy — last, so an allowlisted operator inside a +/// 5. engine ban — enforced only in ; +/// 6. geo policy — last, so an allowlisted operator inside a /// denied country gets one defined answer: through. /// +/// A request rule sits above the two source-level lists because it is the more +/// specific claim about this request: "this path is refused" is what the request +/// is being asked, while "this source is refused" is a claim about who is +/// asking. It sits below the allowlist because the allowlist is the one thing +/// that outranks every other pillar, and an exemption that a path pattern could +/// override is not an exemption. +/// /// Pure function over an . No I/O, no clock of its /// own — now is passed in, which is what makes the expiry and streak /// rules testable without waiting. @@ -34,19 +44,46 @@ public static class DecisionEngine if (IsAlwaysPass(path, policy)) return new EdgeDecision(EdgeVerdict.PassBypassed); - if (string.IsNullOrWhiteSpace(clientIp)) return EdgeDecision.Pass; - - foreach (var entry in snapshot.AllowEntries) + if (!string.IsNullOrWhiteSpace(clientIp)) { - if (!entry.IsLive(now)) continue; - if (NetworkMatch.Matches(clientIp, entry.Match)) + foreach (var entry in snapshot.AllowEntries) { - return new EdgeDecision(EdgeVerdict.PassAllowlisted, Reason: entry.Note); + if (!entry.IsLive(now)) continue; + if (NetworkMatch.Matches(clientIp, entry.Match)) + { + return new EdgeDecision(EdgeVerdict.PassAllowlisted, Reason: entry.Note); + } } } - var key = SourceKey.For(clientIp, policy); - if (key.Length == 0) return EdgeDecision.Pass; + var key = string.IsNullOrWhiteSpace(clientIp) ? string.Empty : SourceKey.For(clientIp, policy); + + // The request itself, which needs no address to judge. An observe match + // is remembered and the order continues: a rule that watches must not + // become an exemption for a source that is banned two steps down. + EdgeDecision? observed = null; + foreach (var rule in snapshot.RequestRules) + { + if (!rule.IsLive(now)) continue; + if (!Security.PathPattern.Matches(rule.Pattern, path)) continue; + if (rule.Action == Security.RequestRuleAction.Block) + { + return new EdgeDecision(EdgeVerdict.BlockRule, 403, + Reason: $"rule_{rule.Id}", SourceKey: key.Length == 0 ? null : key, + RulePattern: rule.Pattern); + } + // First live match wins, whatever its action — the listing an + // operator reads is the evaluation order, so a rule above another + // is the answer. A later block rule does not get to override an + // earlier observe rule; that would make the order on the page a + // decoration. + observed ??= new EdgeDecision(EdgeVerdict.PassRuleObserved, + Reason: $"rule_{rule.Id}", SourceKey: key.Length == 0 ? null : key, + RulePattern: rule.Pattern); + break; + } + + if (key.Length == 0) return observed ?? EdgeDecision.Pass; if (snapshot.OperatorBlocks.TryGetValue(key, out var manual) && manual.IsLive(now)) { @@ -77,7 +114,7 @@ public static class DecisionEngine } } - return EdgeDecision.Pass; + return observed ?? EdgeDecision.Pass; } /// Q6: a per-entry redirect overrides the kind's default. The diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs index fc8df55..de10922 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs @@ -9,9 +9,14 @@ public sealed record EdgeDecision( string? Location = null, string? Reason = null, string? SourceKey = null, - DateTimeOffset? ExpiresAt = null) + DateTimeOffset? ExpiresAt = null, + /// The pattern that matched, for a rule verdict. The rule id is in + /// Reason; the pattern is what an operator reads in the log and the alert, + /// because an id means nothing without the page in front of them. + string? RulePattern = null) { - public bool IsBlocked => Verdict is EdgeVerdict.BlockOperator or EdgeVerdict.BlockEngine or EdgeVerdict.GeoReject; + public bool IsBlocked => Verdict is EdgeVerdict.BlockOperator or EdgeVerdict.BlockEngine + or EdgeVerdict.GeoReject or EdgeVerdict.BlockRule; public static readonly EdgeDecision Pass = new(EdgeVerdict.Pass); } diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs index 57ea6f8..d81dff9 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs @@ -24,6 +24,12 @@ public sealed record EdgeSnapshot public IReadOnlyDictionary Countries { get; init; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + /// Operator-written request rules, in the order the operator wrote + /// them. The first live match wins, so the listing an operator reads is the + /// evaluation order — a list whose answer depended on insertion order + /// hidden inside a dictionary would be unreadable. + public IReadOnlyList RequestRules { get; init; } = []; + public static EdgeSnapshot Empty(EdgePolicy policy) => new() { GeneratedAt = DateTimeOffset.MinValue, Policy = policy }; } diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs index 85a6a29..aaa2158 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeVerdict.cs @@ -13,5 +13,13 @@ public enum EdgeVerdict PassBypassed = 2, BlockOperator = 3, BlockEngine = 4, - GeoReject = 5 + GeoReject = 5, + /// Refused by an operator-written request rule. Fires in Observe + /// mode too: the mode switches off what the edge decides by itself, not + /// what a human wrote down. + BlockRule = 6, + /// Passed. An observe-action request rule matched, and the guard + /// records it — the verdict exists so "nothing matched" and "a rule matched + /// and was told to watch" are different answers. + PassRuleObserved = 7 } diff --git a/dotnet/OpenWaf.Domain/Security/PathPattern.cs b/dotnet/OpenWaf.Domain/Security/PathPattern.cs new file mode 100644 index 0000000..a1c72eb --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/PathPattern.cs @@ -0,0 +1,100 @@ +namespace OpenWaf.Domain.Security; + +/// +/// The matcher behind . +/// +/// A glob, deliberately not a regular expression. The pattern is evaluated on +/// the request path, in the guard, on every request. A regex the operator can +/// type is a ReDoS an anonymous visitor can trigger — (a+)+$ against a +/// path of 40 a's is the textbook case, and the edge would spend the CPU, not +/// the operator. A glob with * and ? matched by the two-pointer +/// loop below is linear in the path length times the number of stars, and +/// there is no way to write a pattern in it that backtracks exponentially. +/// +/// Three semantics worth stating because they are where glob implementations +/// differ: +/// * anchored at both ends — /env matches /env and nothing else; +/// /.env* matches /.env, /.env.local; +/// * * crosses / — this matches request paths, not file names, +/// and /admin* blocking /admin/users is what an operator means +/// by writing it; +/// * case-insensitive — the same posture as the always-pass prefixes and the +/// country codes, and a scanner that cannot decide /.ENV from +/// /.env should not get through on the difference. +/// +/// The query string is not part of the path and is never matched. A rule about +/// a query would need its own matching rules and would be a different feature. +/// +public static class PathPattern +{ + /// The same budget the attacker-controlled path field already gets + /// (512) is generous here; 256 is four times what the longest real path + /// rule needs and keeps the listing readable. + public const int MaxLength = 256; + + /// How many rules one edge evaluates per request. The scan is a + /// linear loop over live rules; 500 of them is a few microseconds, and the + /// cap is what stops the listing becoming the thing that decides whether a + /// request is served. + public const int MaxRules = 500; + + public static bool IsValid(string? pattern) => ExplainRejection(pattern) is null; + + /// Null when the pattern is usable, otherwise the reason it is + /// not — said to the operator at the moment they type it, because a rule + /// that can never match is a rule that silently does nothing. + public static string? ExplainRejection(string? pattern) + { + if (string.IsNullOrWhiteSpace(pattern)) + return "pattern must not be empty"; + // Checked before the trim, on what was actually sent. A tab or a NUL is + // not a path byte, and a pattern that survives trimming is a pattern + // whose meaning changed on the way in — the operator wrote one thing + // and the edge would enforce another. + foreach (var c in pattern) + { + if (c < 0x20 || c == 0x7f) + return "pattern must not contain control characters"; + } + var trimmed = pattern.Trim(); + if (trimmed.Length > MaxLength) + return $"pattern must be at most {MaxLength} characters; got {trimmed.Length}"; + if (!trimmed.StartsWith('/')) + return "pattern must start with / — it is matched against the request path, which always does"; + // A pattern made only of wildcards matches every request, which is a + // different act from writing a rule: it is "take the site down". It is + // refused rather than accepted, because nobody means it by typing "*". + if (trimmed is "*" or "/*" or "/**" or "/?") + return "pattern must name something more specific than every request on the site"; + return null; + } + + public static bool Matches(string? pattern, string? path) + { + if (pattern is null || path is null) return false; + var p = pattern.Trim(); + // Two-pointer glob with one backtrack point per star: O(len(path) * + // stars), no exponential backtracking, no allocation. + int pi = 0, si = 0, star = -1, match = 0; + while (si < path.Length) + { + if (pi < p.Length && (p[pi] == '?' || char.ToUpperInvariant(p[pi]) == char.ToUpperInvariant(path[si]))) + { + pi++; si++; + } + else if (pi < p.Length && p[pi] == '*') + { + star = pi++; + match = si; + } + else if (star >= 0) + { + pi = star + 1; + si = ++match; + } + else return false; + } + while (pi < p.Length && p[pi] == '*') pi++; + return pi == p.Length; + } +} diff --git a/dotnet/OpenWaf.Domain/Security/RequestRule.cs b/dotnet/OpenWaf.Domain/Security/RequestRule.cs new file mode 100644 index 0000000..ece9ca6 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/RequestRule.cs @@ -0,0 +1,54 @@ +namespace OpenWaf.Domain.Security; + +/// What a matched request rule does. Said as two values because the +/// difference is the whole reason an operator can add a rule at all. +public enum RequestRuleAction +{ + /// Record the match as an alert and let the request through. This + /// is what makes a rule safe to write: an operator can see what it would + /// have blocked before it blocks anything. + Observe = 0, + + /// Refuse the request. Fires in Observe mode too — the mode + /// switches off what the edge decides by itself, not what a human wrote + /// down, which is the same ruling that keeps an operator block live in + /// Observe mode. + Block = 1 +} + +/// +/// A rule about the request itself: a path pattern the edge refuses (or +/// records) before the request reaches the application. +/// +/// Until this existed the edge only ever reacted to what the upstream +/// answered — a streak of 4xx/5xx from one source, a country, an operator's +/// list. It never looked at the request. That leaves the part of a WAF's job +/// nobody else in this design does: refusing a known-bad request before it +/// costs the origin anything, and refusing it without first waiting for the +/// origin to answer 404 three times. +/// +/// It is an operator-authored list, not a signature feed: the patterns are +/// written by a human who can read the access log, and every one of them is +/// visible, editable and removable on the same page that shows the bans. +/// +public sealed class RequestRule +{ + public long Id { get; init; } + + /// Glob over the request path — see . + /// Anchored, case-insensitive, * and ? only. + public string Pattern { get; set; } = string.Empty; + + public RequestRuleAction Action { get; set; } + + public string? Note { get; set; } + + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + + /// A rule that expires. A path rule written during an active scan + /// is usually wrong six weeks later, and nothing in the system will say + /// so; the expiry is the part that stops being true on its own. + public DateTimeOffset? ExpiresAt { get; set; } + + public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now; +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 513747d..5a9a650 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -103,6 +103,11 @@ internal static class AdminConsole + + + + +
—
@@ -115,6 +120,10 @@ internal static class AdminConsole
matchnoteexpires
+

Path rules

+
+
patternactionnotematchesexpires
+

Sources the edge is watching

@@ -236,12 +245,13 @@ function row(cells) { async function load() { if (!token) { note('no token', true); return; } try { - const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, alertsRes, geoRes] = await Promise.all([ + const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, pathRulesRes, alertsRes, geoRes] = await Promise.all([ apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'), apiRaw(withSrc('/admin-api/observations?limit=25')), apiRaw(withSrc('/admin-api/streaks')), apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'), - apiRaw('/admin-api/allow?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'), + apiRaw('/admin-api/allow?live=false&limit=500'), + apiRaw('/admin-api/rules?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'), apiRaw('/admin-api/geo') ]); // The core read decides whether there is anything to draw. When the admin @@ -257,7 +267,7 @@ async function load() { const obs = obsRes.body; const alerts = alertsRes.body; const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body, - allow = allowRes.body, geo = geoRes.body; + allow = allowRes.body, pathRules = pathRulesRes.body, geo = geoRes.body; // The listing is capped server-side. Saying so is the difference between a // console and a misleading one: the delete beside this table is not capped. el('blocknote').textContent = blocksRes.truncated @@ -370,6 +380,30 @@ async function load() { + (allowRes.truncated ? ' · showing ' + allow.length + ' of ' + allowRes.total + ' rows' : '') + (allowExpired ? ' · ' + allowExpired + ' EXPIRED: those rows no longer exempt anyone' : '') : 'nothing allowlisted'; + // Path rules are the one pillar about the request rather than the response, + // and the two actions mean different things to the person reading: observe + // answers "what would this have blocked", block refuses the request before + // the application sees it. The order on the page is the order the engine + // evaluates, so the first row that matches is the answer. + const expiredRules = (pathRules || []).filter((r) => r.live === false).length; + el('pathrules').tBodies[0].innerHTML = (pathRules || []).map((r) => row([ + { v: r.pattern }, + { h: r.action === 'block' ? '' + esc(r.action) + '' : esc(r.action) }, + { v: r.note }, + { v: r.matches, n: true }, + { 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 — the edge judges responses, not requests' }]); + el('rulenote').textContent = state.requestRulesAvailable === false + ? 'NOT READ — this database has no request-rule table (' + (state.requestRulesError || 'no reason given') + + '), so no path rule is in force. Apply the schema migration; every other pillar is enforcing.' + : (pathRules || []).length + ? 'the first rule that matches is the answer, in this order · observe counts what it would have blocked, block refuses before the application sees the request' + + (pathRulesRes.truncated ? ' · showing ' + pathRules.length + ' of ' + pathRulesRes.total + ' rules' : '') + + (expiredRules ? ' · ' + expiredRules + ' EXPIRED: those rules enforce nothing' : '') + : 'no path rules — the edge reacts to what the upstream answered, never to the request itself'; el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([ { h: srcBtn(o.sourceKey) }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, { v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') } @@ -550,6 +584,31 @@ el('addAllow').onclick = async () => { } }; +el('addRule').onclick = async () => { + const pattern = el('rulePattern').value.trim(); + if (!pattern) { note('a path pattern first, e.g. /.env*', true); return; } + // The same TTL field as the other two, with the same rule: empty means + // "never", and a 0 is refused rather than read as never. A path rule is the + // entry most likely to be right during a scan and wrong six weeks later, so + // the page nudges towards a number. + const rawTtl = el('ruleTtl').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; + } + if (await postJson('/admin-api/rules', { pattern, action: el('ruleAction').value, + note: el('ruleNote').value.trim() || 'written from the console', expiresInMinutes: ttl })) { + el('rulePattern').value = ''; el('ruleNote').value = ''; el('ruleTtl').value = ''; + done(el('ruleAction').value + ' rule 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. @@ -566,6 +625,9 @@ document.addEventListener('click', async (e) => { } else if (b.dataset.act === 'delallow') { const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); if (!failed(r)) done('allow entry removed'); + } 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 === '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 3adef88..af1d8d0 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -44,6 +44,22 @@ internal sealed record AllowDto( internal sealed record NewAllowRequest(string Match, string? Note, int? ExpiresInMinutes); +/// An operator-written request rule, with what it has matched since it +/// was last reported — an observe rule that reports nothing is indistinguishable +/// from one that matches nothing, and the whole point of observe is to answer +/// that question. +internal sealed record RuleDto( + long Id, + string Pattern, + string Action, + string? Note, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + bool Live, + int Matches); + +internal sealed record NewRuleRequest(string Pattern, string? Action, string? Note, int? ExpiresInMinutes); + internal sealed record PolicyDto( string Mode, int StreakThreshold, diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 4688518..5ffca5b 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Security; +using OpenWaf.Edge.Pipeline; using OpenWaf.Infrastructure.Geo; using OpenWaf.Infrastructure.Persistence; @@ -218,6 +219,90 @@ internal static class AdminEndpoints : Results.NotFound(new { error = $"no allow entry with id {id}" }); }); + // Request rules: the one pillar that looks at the request itself + // rather than at what the upstream answered or who sent it. Written by + // an operator, listed in the order the engine evaluates them, and + // capped — every request is checked against each live rule, so the + // listing size is a request-path cost and not only a page length. + group.MapGet("/rules", async (bool? live, int? limit, int? offset, + OpenWafDbContext db, RuleMatchLedger ledger, 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.RequestRules.AsNoTracking().Where(r => r.ExpiresAt == null || r.ExpiresAt > now) + : db.RequestRules.AsNoTracking(); + // Ordered by id, which is the order the engine evaluates them in. + // A listing sorted any other way would show the operator one order + // and enforce another. + var rows = await Query().OrderBy(r => r.Id).Skip(skip).Take(take).ToListAsync(ct); + var total = await Query().CountAsync(ct); + var matches = ledger.Snapshot(); + 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 => new RuleDto( + r.Id, r.Pattern, r.Action.ToString().ToLowerInvariant(), r.Note, r.CreatedAt, r.ExpiresAt, + r.ExpiresAt == null || r.ExpiresAt > now, + matches.TryGetValue(r.Id, out var m) ? m : 0)).ToList()); + }); + + group.MapPost("/rules", async (NewRuleRequest req, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + // A pattern that can never match is refused here rather than listed + // forever: a rule that silently does nothing is worse than a 400, + // because it reads like a defence that is in place. + var patternProblem = PathPattern.ExplainRejection(req.Pattern); + if (patternProblem is not null) return Results.BadRequest(new { error = patternProblem }); + 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 action = string.IsNullOrWhiteSpace(req.Action) ? "observe" : req.Action.Trim().ToLowerInvariant(); + if (action is not ("observe" or "block")) + return Results.BadRequest(new { error = $"action must be observe|block; got \"{req.Action}\"" }); + + var pattern = req.Pattern.Trim(); + var now = DateTimeOffset.UtcNow; + var clash = await db.RequestRules.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 = $"rule {clash} already covers {pattern} — the listing is the evaluation order, so a second live rule for one pattern can never fire" }); + + var live = await db.RequestRules.AsNoTracking() + .CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct); + if (live >= PathPattern.MaxRules) + return Results.BadRequest(new { error = $"at most {PathPattern.MaxRules} live rules; every request is checked against each of them" }); + + db.RequestRules.Add(new RequestRule + { + Pattern = pattern, + Action = action == "block" ? RequestRuleAction.Block : RequestRuleAction.Observe, + Note = req.Note, + ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null + }); + await db.SaveChangesAsync(ct); + await state.InvalidateAsync(ct); + return Results.NoContent(); + }); + + group.MapDelete("/rules/{id:long}", async (long id, OpenWafDbContext db, EdgeStateStore state, HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); + var n = await db.RequestRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct); + await state.InvalidateAsync(ct); + return n > 0 + ? Results.NoContent() + : Results.NotFound(new { error = $"no request rule with id {id}" }); + }); + // 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 @@ -572,6 +657,11 @@ internal static class AdminEndpoints // Which streak store this process registered, so the counts beside // it can be read as one edge's or the fleet's (OPEN-52). streakScope = policyProvider.Current.SharedStreaks ? "shared-database" : "this-process", + // Whether the rules pillar is reading anything at all. A database + // that predates the feature has every other table, and "no rules" + // and "the rules table is not there" have to be different answers. + requestRulesAvailable = state.RulesAvailable, + requestRulesError = state.RulesError, observationRetentionDays = (int)state.Current.Policy.ObservationRetention.TotalDays, banRetentionDays = (int)state.Current.Policy.BanRetention.TotalDays, mode = state.Current.Policy.Mode.ToString() diff --git a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs index 74895a3..881c2a6 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs @@ -20,8 +20,27 @@ public sealed class EdgeGuardMiddleware( RequestDelegate next, EdgeStateStore state, IGeoIpLookup geo, + RuleMatchLedger ledger, + AlertWriter alerts, ILogger log) { + /// An observe-action rule matched and the request is going + /// through. Count it, and alert at most once per rule per interval — the + /// same storm rule the 5xx alerts learned. + private async Task ObserveRuleMatchAsync(EdgeDecision decision, string path, CancellationToken ct) + { + if (decision.Reason is not { Length: > 5 } reason) return; + if (!long.TryParse(reason[5..], out var ruleId)) return; + + var report = ledger.RecordAndReport(ruleId, DateTimeOffset.UtcNow); + if (report is not (var matches, var since)) return; + + await alerts.RaiseAsync( + "rule_match", decision.SourceKey ?? "unknown", matches, null, path, + $"an observe rule matched {matches} {(matches == 1 ? "time" : "times")} " + + $"since {since:O}: {decision.RulePattern} (action=observe, nothing was blocked)", ct); + } + public async Task InvokeAsync(HttpContext ctx) { var snapshot = state.GetOrRefresh(); @@ -37,6 +56,8 @@ public sealed class EdgeGuardMiddleware( if (!decision.IsBlocked) { + if (decision.Verdict == EdgeVerdict.PassRuleObserved) + await ObserveRuleMatchAsync(decision, path, ctx.RequestAborted); await next(ctx); return; } @@ -68,6 +89,20 @@ public sealed class EdgeGuardMiddleware( "If it is wrong, an operator can clear it.")); break; + case EdgeVerdict.BlockRule: + // The response names the rule by id, not by pattern. The id is + // enough for an operator — the page shows both side by side — + // while the pattern in a 403 body tells an anonymous visitor + // exactly which payload to change. The pattern goes to the log + // and to the alert, which are the operator's channels. + await ctx.Response.WriteAsJsonAsync(new BlockedBody( + "blocked_by_rule", + decision.Reason, + null, + "This path matches a rule written for this site. If it is wrong, " + + "the operator who wrote it can remove it.")); + break; + case EdgeVerdict.GeoReject: await ctx.Response.WriteAsJsonAsync(new BlockedBody( "region_not_supported", diff --git a/dotnet/OpenWaf.Edge/Pipeline/RuleMatchLedger.cs b/dotnet/OpenWaf.Edge/Pipeline/RuleMatchLedger.cs new file mode 100644 index 0000000..d97e5b2 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Pipeline/RuleMatchLedger.cs @@ -0,0 +1,71 @@ +namespace OpenWaf.Edge.Pipeline; + +/// +/// Counts observe-action rule matches and decides when one is worth an alert. +/// +/// An observe rule exists to answer "what would this have blocked?" — but a +/// match per request is a log line, not an answer, and an alert per match is +/// the alert-storm failure this project already fixed once for 5xx streaks +/// ("a server-error storm alerts on the crossing and the doublings, not once +/// per request"). So the ledger counts every match and reports at most once +/// per rule per interval, carrying how many matched and since when. +/// +/// In-process on purpose. The count is a question about this edge's traffic; +/// the rule itself is shared through the database, the tally is not. +/// +public sealed class RuleMatchLedger +{ + /// How often one observe rule may raise an alert. 15 minutes is + /// short enough that an operator adding a rule sees the first answer inside + /// a coffee, and long enough that a scan lasting an hour is one alert. + public const int ReportIntervalMinutes = 15; + + private sealed class Entry + { + public int Matches; + public int Total; + public DateTimeOffset WindowStart = DateTimeOffset.UtcNow; + public DateTimeOffset LastReport = DateTimeOffset.MinValue; + } + + private readonly Dictionary _entries = new(); + private readonly object _gate = new(); + + /// Records one match. Returns the window to report — how many + /// matched and since when — when this rule is due an alert, otherwise null. + /// The first match of a rule reports immediately: an operator who has just + /// written a rule wants to know it matches something, not in a quarter. + public (int Matches, DateTimeOffset Since)? RecordAndReport(long ruleId, DateTimeOffset now) + { + lock (_gate) + { + if (!_entries.TryGetValue(ruleId, out var entry)) + _entries[ruleId] = entry = new Entry { WindowStart = now }; + + entry.Matches++; + entry.Total++; + + if (now - entry.LastReport < TimeSpan.FromMinutes(ReportIntervalMinutes)) return null; + + var report = (entry.Matches, entry.WindowStart); + entry.Matches = 0; + entry.WindowStart = now; + entry.LastReport = now; + return report; + } + } + + /// Every match this process has seen for the rule, reported or + /// not. The listing shows this rather than the window count: an operator + /// reading "watching" wants to know whether the pattern names anything at + /// all, and "0 since the last report" would answer that with a lie. + public IReadOnlyDictionary Snapshot() + { + lock (_gate) + { + var copy = new Dictionary(); + foreach (var (id, e) in _entries) copy[id] = e.Total; + return copy; + } + } +} diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 7b48d8e..0f94eca 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -62,6 +62,7 @@ builder.Services.AddSingleton(sp => new EdgeStateStore( RefreshTtl = EdgeStateStore.ParseRefreshTtl(builder.Configuration["OpenWaf:State:RefreshTtlSeconds"]) }); 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.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index eaada64..71d8411 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -65,6 +65,16 @@ public sealed class EdgeStateStore private int _refreshFailures; private string? _lastRefreshError; + /// Whether the last refresh could read the request-rule table. + /// False means the edge is enforcing everything except the rules, and says + /// so — see . + public bool RulesAvailable { get; private set; } = true; + + /// Why the rules could not be read, for the operator surface. + public string? RulesError => Volatile.Read(ref _rulesError); + + private string? _rulesError; + /// /// Reads the configured TTL. The TTL is the bound on how stale the block /// list may be, which makes it a security setting: an unparseable or @@ -119,6 +129,32 @@ public sealed class EdgeStateStore var blocks = await db.Blocks.AsNoTracking().ToListAsync(ct); var allow = await db.AllowEntries.AsNoTracking().ToListAsync(ct); var countries = await db.CountryRules.AsNoTracking().ToListAsync(ct); + // The rules read stands alone, on purpose. `request_rules` is the + // newest table in the schema, and a database created before the + // feature has every other table — so reading it in the same block + // as the rest would let one missing table stop a ban written a + // minute ago from ever being enforced, which is exactly the failure + // this file warns about two paragraphs down. When it fails, the + // snapshot is still the operator's list and the surface says the + // rules pillar is reading nothing. + IReadOnlyList rules; + try + { + // Ordered by id: the listing an operator reads and the order the + // engine evaluates are the same thing, so "which rule wins" has + // one answer that is visible on the page. + rules = await db.RequestRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(ct); + RulesAvailable = true; + Volatile.Write(ref _rulesError, null); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + rules = []; + RulesAvailable = false; + Volatile.Write(ref _rulesError, ex.Message); + _log.LogWarning(ex, + "EdgeStateStore: the request-rule table could not be read; enforcing the rest of the list without it."); + } var operatorBlocks = new Dictionary(StringComparer.Ordinal); var engineBans = new Dictionary(StringComparer.Ordinal); @@ -141,7 +177,8 @@ public sealed class EdgeStateStore OperatorBlocks = operatorBlocks, EngineBans = engineBans, AllowEntries = allow, - Countries = countryMap + Countries = countryMap, + RequestRules = rules }; } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261004171633_AddRequestRules.Designer.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261004171633_AddRequestRules.Designer.cs new file mode 100644 index 0000000..8911507 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261004171633_AddRequestRules.Designer.cs @@ -0,0 +1,362 @@ +// +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("20261004171633_AddRequestRules")] + partial class AddRequestRules + { + /// + 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.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.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.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/20261004171633_AddRequestRules.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261004171633_AddRequestRules.cs new file mode 100644 index 0000000..4f3b91b --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261004171633_AddRequestRules.cs @@ -0,0 +1,85 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + /// + public partial class AddRequestRules : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "request_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), + Action = 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_request_rules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "source_streaks", + columns: table => new + { + SourceKey = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + ConsecutiveRefusals = table.Column(type: "integer", nullable: false), + MaxConsecutiveRefusals = table.Column(type: "integer", nullable: false), + TotalRefusals = table.Column(type: "integer", nullable: false), + ConsecutiveServerErrors = table.Column(type: "integer", nullable: false), + MaxConsecutiveServerErrors = table.Column(type: "integer", nullable: false), + LastAlertedRefusals = table.Column(type: "integer", nullable: false), + LastAlertedServerErrors = table.Column(type: "integer", nullable: false), + LastRefusalAt = table.Column(type: "timestamp with time zone", nullable: true), + LastSeenAt = table.Column(type: "timestamp with time zone", nullable: false), + LastStatusCode = table.Column(type: "integer", nullable: true), + LastPath = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + LastUserAgent = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + LastCountryCode = table.Column(type: "character varying(2)", maxLength: 2, nullable: true), + LastCity = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + LastRegion = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_source_streaks", x => x.SourceKey); + }); + + migrationBuilder.CreateIndex( + name: "IX_request_rules_ExpiresAt", + table: "request_rules", + column: "ExpiresAt"); + + migrationBuilder.CreateIndex( + name: "IX_request_rules_Pattern", + table: "request_rules", + column: "Pattern"); + + migrationBuilder.CreateIndex( + name: "IX_source_streaks_LastSeenAt", + table: "source_streaks", + column: "LastSeenAt"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "request_rules"); + + migrationBuilder.DropTable( + name: "source_streaks"); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs index 168926a..d46c032 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs @@ -182,6 +182,41 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations b.ToTable("edge_alerts", (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") @@ -233,6 +268,73 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations 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") diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index 65e3657..8ed1fbb 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; /// -/// Seven tables, all small. The edge never queries them on the request path — +/// Eight 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. @@ -19,6 +19,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) public DbSet Alerts => Set(); public DbSet PolicySettings => Set(); public DbSet Streaks => Set(); + public DbSet RequestRules => Set(); protected override void OnModelCreating(ModelBuilder mb) { @@ -101,6 +102,21 @@ public sealed class OpenWafDbContext(DbContextOptions options) e.Property(a => a.Detail).HasMaxLength(1024).IsRequired(); }); + mb.Entity(e => + { + e.ToTable("request_rules"); + e.HasKey(r => r.Id); + // Not unique: an expired rule 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); + e.Property(r => r.Action).HasConversion(); + }); + mb.Entity(e => { e.ToTable("policy_settings"); diff --git a/dotnet/OpenWaf.Tests.Integration/RequestRuleTests.cs b/dotnet/OpenWaf.Tests.Integration/RequestRuleTests.cs new file mode 100644 index 0000000..2bf6729 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/RequestRuleTests.cs @@ -0,0 +1,307 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// The request rule, end to end: an operator writes a pattern over the API, the +/// guard refuses the path before the application ever sees the request, and the +/// observe action answers the question an operator actually has before turning +/// a rule on — what would this have blocked? +/// +/// Before this feature the edge only ever reacted to what the upstream answered. +/// A known-bad request still reached the origin and only became a defence if the +/// origin's answer happened to fall in the refusal range three times in a row. +/// +public sealed class RequestRuleTests +{ + 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(); + + [Fact] + public async Task A_block_rule_refuses_the_path_before_the_upstream_sees_the_request() + { + await using var f = new EdgeFixture(); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/.env*", action = "block", note = "probe sweep seen in the log" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var probe = await GetAsync(f, "/.env")) + { + Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); + var body = await BodyAsync(probe); + Assert.Contains("blocked_by_rule", body); + // The answer names the rule by id, never by pattern: the pattern in + // a 403 body tells the visitor which payload to change instead. + Assert.Contains("rule_", body); + Assert.DoesNotContain("/.env", body); + } + + using (var probe = await GetAsync(f, "/.env.local")) + Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); + + // The path the rule does not name still flows. + using (var probe = await GetAsync(f, "/index.html")) + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + + lock (f.Upstream.Paths) + { + Assert.DoesNotContain("/.env", f.Upstream.Paths); + Assert.DoesNotContain("/.env.local", f.Upstream.Paths); + Assert.Contains("/index.html", f.Upstream.Paths); + } + } + + [Fact] + public async Task An_observe_rule_lets_the_request_through_and_answers_what_it_would_have_blocked() + { + await using var f = new EdgeFixture(); + + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/xmlrpc.php", action = "observe" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + for (var i = 0; i < 3; i++) + { + using var probe = await GetAsync(f, "/xmlrpc.php"); + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + } + // A path the rule does not name is not counted. + using (var probe = await GetAsync(f, "/index.html")) { } + + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "rule_match").ToListAsync(); + + // One alert, raised by the first match — the same storm rule the 5xx + // alerts learned ("alert on the crossing and the doublings, not once per + // request"). The rest of the matches are counted, not re-alerted, and + // the listing below is where they are read. + Assert.Single(alerts); + Assert.Equal(1, alerts[0].Count); + Assert.Contains("/xmlrpc.php", alerts[0].Detail); + Assert.Contains("nothing was blocked", alerts[0].Detail); + + // And the listing carries the tally, so the page can say "watching, + // this many matches" rather than only "watching". + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules"); + var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement; + Assert.Equal(3, rows[0].GetProperty("matches").GetInt32()); + Assert.Equal("observe", rows[0].GetProperty("action").GetString()); + } + + [Fact] + public async Task The_listing_is_the_order_the_engine_enforces() + { + await using var f = new EdgeFixture(); + using (var a = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/api*", action = "observe", note = "first" })) + Assert.Equal(HttpStatusCode.NoContent, a.StatusCode); + using (var b = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/api/secret", action = "block", note = "second" })) + Assert.Equal(HttpStatusCode.NoContent, b.StatusCode); + + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules"); + var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement; + Assert.Equal(2, rows.GetArrayLength()); + Assert.Equal("/api*", rows[0].GetProperty("pattern").GetString()); + Assert.Equal("first", rows[0].GetProperty("note").GetString()); + Assert.True(rows[0].GetProperty("live").GetBoolean()); + Assert.Equal("/api/secret", rows[1].GetProperty("pattern").GetString()); + + // The first match wins, so the rule the page shows first is the answer — + // including when it is the gentler of the two actions. + using var probe = await GetAsync(f, "/api/secret"); + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + } + + [Theory] + [InlineData("wp-admin", "must start with /")] + [InlineData("/*", "more specific than every request")] + [InlineData("", "must not be empty")] + [InlineData(" ", "must not be empty")] + public async Task A_pattern_that_could_only_silently_do_nothing_is_refused_with_the_reason( + string pattern, string because) + { + await using var f = new EdgeFixture(); + using var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern, action = "block" }); + Assert.Equal(HttpStatusCode.BadRequest, created.StatusCode); + Assert.Contains(because, await BodyAsync(created)); + } + + [Fact] + public async Task An_unknown_action_is_refused_by_name_rather_than_defaulted() + { + await using var f = new EdgeFixture(); + using var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/.env", action = "blocked" }); + Assert.Equal(HttpStatusCode.BadRequest, created.StatusCode); + Assert.Contains("action must be observe|block", await BodyAsync(created)); + } + + [Fact] + public async Task A_second_live_rule_for_one_pattern_is_refused_and_names_the_rule_it_duplicates() + { + await using var f = new EdgeFixture(); + using (var first = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/.env*", action = "block" })) + Assert.Equal(HttpStatusCode.NoContent, first.StatusCode); + + using var second = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/.env*", action = "observe" }); + Assert.Equal(HttpStatusCode.Conflict, second.StatusCode); + var text = await BodyAsync(second); + Assert.Contains("already covers /.env*", text); + Assert.Contains("can never fire", text); + } + + [Fact] + public async Task Removing_a_rule_flows_the_path_again_and_says_which_row_was_not_there() + { + await using var f = new EdgeFixture(); + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/config*", action = "block" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var probe = await GetAsync(f, "/config.php")) + Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); + + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules"); + var id = JsonDocument.Parse(await BodyAsync(list)).RootElement[0].GetProperty("id").GetInt64(); + + using (var removed = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rules/{id}")) + Assert.Equal(HttpStatusCode.NoContent, removed.StatusCode); + + using (var probe = await GetAsync(f, "/config.php")) + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + + using (var again = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rules/{id}")) + { + Assert.Equal(HttpStatusCode.NotFound, again.StatusCode); + Assert.Contains($"no request rule with id {id}", await BodyAsync(again)); + } + } + + [Fact] + public async Task A_rule_stops_blocking_the_minute_its_expiry_passes() + { + await using var f = new EdgeFixture(); + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/backup*", action = "block", expiresInMinutes = 60 })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var probe = await GetAsync(f, "/backup.sql")) + Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); + + // Backdate the row rather than wait for a minute the test would rather + // not spend — the same shape the retention tests use. + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.RequestRules.FirstAsync(); + row.ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-5); + await db.SaveChangesAsync(); + } + await f.Service().InvalidateAsync(); + + using (var probe = await GetAsync(f, "/backup.sql")) + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + + using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules"); + Assert.Equal(0, JsonDocument.Parse(await BodyAsync(list)).RootElement.GetArrayLength()); + + using var all = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules?live=false"); + var rows = JsonDocument.Parse(await BodyAsync(all)).RootElement; + Assert.Equal(1, rows.GetArrayLength()); + Assert.False(rows[0].GetProperty("live").GetBoolean()); + } + + [Fact] + public async Task A_database_without_the_rule_table_enforces_everything_else_and_says_so() + { + // `request_rules` is the newest table in the schema, so a database + // created before this feature has every other one. If the rules read + // shared one statement block with the rest of the snapshot, that + // missing table would stop an operator block written a minute ago from + // ever being enforced. It does not, and the surface says which pillar is + // reading nothing. + await using var f = new EdgeFixture(); + + using (var blocked = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Visitor, reason = "the ban that must survive a missing table" })) + Assert.Equal(HttpStatusCode.NoContent, blocked.StatusCode); + + using (var scope = f.Factory.Services.CreateScope()) + await scope.ServiceProvider.GetRequiredService() + .Database.ExecuteSqlRawAsync("DROP TABLE request_rules"); + + await f.Service().InvalidateAsync(); + + // The operator block is still enforced — 301 to the policy's redirect + // target, which is what an operator block answers. The missing table + // costs the rules pillar, not the ban. + using (var probe = await GetAsync(f, "/anything")) + Assert.Equal(HttpStatusCode.MovedPermanently, probe.StatusCode); + + using var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state"); + var body = JsonDocument.Parse(await BodyAsync(state)).RootElement; + Assert.False(body.GetProperty("requestRulesAvailable").GetBoolean()); + Assert.Contains("request_rules", body.GetProperty("requestRulesError").GetString()); + Assert.Equal(0, body.GetProperty("snapshotRefreshFailures").GetInt32()); + } + + [Fact] + public async Task The_allowlist_still_outranks_a_rule_that_names_every_path() + { + await using var f = new EdgeFixture(); + using (var exempt = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", + new { match = Visitor, note = "the operator's own probe" })) + Assert.Equal(HttpStatusCode.NoContent, exempt.StatusCode); + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/.env*", action = "block" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using (var probe = await GetAsync(f, "/.env", Visitor)) + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + using (var probe = await GetAsync(f, "/.env", "203.0.113.141")) + Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); + } + + [Fact] + public async Task A_rule_answer_carries_the_completeness_headers_like_every_other_listing() + { + await using var f = new EdgeFixture(); + for (var i = 0; i < 3; i++) + using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = $"/p{i}*", action = "observe" })) + Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); + + using var page = await AdminAsync(f, HttpMethod.Get, "/admin-api/rules?limit=2"); + Assert.Equal("3", page.Headers.TryGetValues("X-Total-Count", out var v) ? string.Join(",", v) : null); + Assert.Equal("true", page.Headers.TryGetValues("X-Truncated", out var t) ? string.Join(",", t) : null); + Assert.Equal(2, JsonDocument.Parse(await BodyAsync(page)).RootElement.GetArrayLength()); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/PathPatternTests.cs b/dotnet/OpenWaf.Tests.Unit/PathPatternTests.cs new file mode 100644 index 0000000..9a4124a --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/PathPatternTests.cs @@ -0,0 +1,80 @@ +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// The pattern language behind a request rule. It is evaluated on the request +/// path of every request, so its semantics are security semantics: an operator +/// writes /.env* expecting /.env.local to be refused, and a +/// matcher that disagrees does not fail loudly — it serves the file. +/// +public sealed class PathPatternTests +{ + [Theory] + [InlineData("/.env", "/.env", true)] // anchored exact + [InlineData("/.env", "/.env.local", false)] // a prefix is not a match + [InlineData("/.env*", "/.env", true)] // * matches the empty run + [InlineData("/.env*", "/.env.local", true)] + [InlineData("/admin*", "/admin/users/1", true)] // * crosses / + [InlineData("/admin/*", "/admin/", true)] // * may match the empty run + [InlineData("/wp-login.php", "/wp-login.php", true)] + [InlineData("/?.html", "/a.html", true)] + [InlineData("/?.html", "/ab.html", false)] + [InlineData("/A*B", "/axxxB", true)] // case-insensitive + [InlineData("/a*b", "/A.X.B", true)] // * crosses . as it crosses / + [InlineData("/a-b", "/a.b", false)] // a literal dash is a dash + [InlineData("/*", "/anything/at/all", true)] + [InlineData("/x", "/x/", false)] + [InlineData("/x/", "/x", false)] + public void The_glob_means_what_the_operator_wrote(string pattern, string path, bool expected) + => Assert.Equal(expected, PathPattern.Matches(pattern, path)); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData(".env")] // cannot match a path, so it can only ever do nothing + [InlineData("*/wp-admin")] + [InlineData("*")] // every request on the site + [InlineData("/*")] + [InlineData("/**")] + [InlineData("/?")] + [InlineData("/.env\t")] // a control character is not a path byte + [InlineData("/.env\u007f")] + public void A_pattern_that_could_only_silently_do_nothing_is_refused(string? pattern) + => Assert.NotNull(PathPattern.ExplainRejection(pattern)); + + [Theory] + [InlineData("/.env*")] + [InlineData("/admin/*")] + [InlineData("/a?b")] + [InlineData("/search?q")] // a query string is not matched, but the path may hold it + [InlineData("/x y")] + public void A_pattern_that_can_name_a_real_path_is_accepted(string pattern) + => Assert.Null(PathPattern.ExplainRejection(pattern)); + + [Fact] + public void The_rejection_says_what_is_wrong_rather_than_only_that_something_is() + { + Assert.Contains("must start with /", PathPattern.ExplainRejection("wp-admin")); + Assert.Contains("more specific than every request", PathPattern.ExplainRejection("/*")); + Assert.Contains($"{PathPattern.MaxLength} characters", + PathPattern.ExplainRejection("/" + new string('a', PathPattern.MaxLength))); + } + + [Fact] + public void A_long_pattern_is_refused_because_it_is_matched_on_every_request() + => Assert.False(PathPattern.IsValid("/" + new string('a', PathPattern.MaxLength))); + + [Fact] + public void Matching_allocates_nothing_exotic_and_survives_a_path_of_repeated_a() + { + // The reason this is a glob and not a regex: (a+)+$ against 40 a's is + // the textbook exponential backtrack, and the pattern would be the + // operator's while the path is the visitor's. + var pattern = "/a*a*a*a*a*a*a*b"; + var path = "/" + new string('a', 400); + Assert.False(PathPattern.Matches(pattern, path)); + Assert.True(PathPattern.Matches(pattern, path + "b")); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/RequestRuleDecisionTests.cs b/dotnet/OpenWaf.Tests.Unit/RequestRuleDecisionTests.cs new file mode 100644 index 0000000..80a0f0f --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/RequestRuleDecisionTests.cs @@ -0,0 +1,157 @@ +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// Where the request-rule pillar sits in the order, and what it does not get to +/// change. The order is a documented property of this engine (OPEN-2), so a new +/// pillar is only safe once its precedence is pinned: a rule that outranked the +/// allowlist would break the operator's exemption, and an observe rule that +/// stopped the order would turn "watch this" into "let this through". +/// +public sealed class RequestRuleDecisionTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + + private static RequestRule Rule(long id, string pattern, RequestRuleAction action, + DateTimeOffset? expires = null) => new() + { + Id = id, Pattern = pattern, Action = action, ExpiresAt = expires, CreatedAt = Now.AddHours(-2) + }; + + private static EdgeSnapshot Snapshot( + EdgePolicy policy, + IReadOnlyList? rules = null, + IReadOnlyList? allow = null, + IReadOnlyDictionary? bans = null) => new() + { + GeneratedAt = Now, + Policy = policy, + RequestRules = rules ?? [], + AllowEntries = allow ?? [], + EngineBans = bans ?? new Dictionary() + }; + + [Fact] + public void A_block_rule_refuses_the_request_and_names_the_rule_that_did_it() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(7, "/.env*", RequestRuleAction.Block)]), + "203.0.113.9", "/.env.local", Now); + + Assert.Equal(EdgeVerdict.BlockRule, d.Verdict); + Assert.True(d.IsBlocked); + Assert.Equal(403, d.StatusCode); + Assert.Equal("rule_7", d.Reason); + Assert.Equal("/.env*", d.RulePattern); + } + + [Fact] + public void A_block_rule_fires_in_Observe_mode_because_the_mode_switches_off_the_edge_not_the_operator() + { + var d = DecisionEngine.Decide( + Snapshot(new EdgePolicy { Mode = EnforcementMode.Observe }, + [Rule(1, "/wp-login.php", RequestRuleAction.Block)]), + "203.0.113.9", "/wp-login.php", Now); + Assert.Equal(EdgeVerdict.BlockRule, d.Verdict); + } + + [Fact] + public void An_observe_rule_passes_and_says_that_it_matched() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(3, "/xmlrpc.php", RequestRuleAction.Observe)]), + "203.0.113.9", "/xmlrpc.php", Now); + + Assert.Equal(EdgeVerdict.PassRuleObserved, d.Verdict); + Assert.False(d.IsBlocked); + Assert.Equal("rule_3", d.Reason); + } + + [Fact] + public void An_observe_rule_is_not_an_exemption_for_a_source_the_engine_has_banned() + { + var ban = new BlockEntry + { + SourceKey = "203.0.113.9", Source = BlockSource.Engine, CreatedAt = Now.AddMinutes(-1), + ExpiresAt = Now.AddMinutes(30), Reason = "10 consecutive refusals" + }; + var d = DecisionEngine.Decide( + Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, + [Rule(3, "/xmlrpc.php", RequestRuleAction.Observe)], null, + new Dictionary { ["203.0.113.9"] = ban }), + "203.0.113.9", "/xmlrpc.php", Now); + + // The rule matched, and the ban still answers. Watching never lets + // anybody through. + Assert.Equal(EdgeVerdict.BlockEngine, d.Verdict); + } + + [Fact] + public void The_allowlist_outranks_a_block_rule_because_an_exemption_has_to_be_one() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, + [Rule(9, "/*", RequestRuleAction.Block)], + [new AllowEntry { Id = 1, Match = "203.0.113.0/24", Note = "office" }]), + "203.0.113.9", "/.env", Now); + Assert.Equal(EdgeVerdict.PassAllowlisted, d.Verdict); + } + + [Fact] + public void An_always_pass_prefix_outranks_a_block_rule_so_the_page_that_removes_rules_still_loads() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(9, "/admin-api/*", RequestRuleAction.Block)]), + "203.0.113.9", "/admin-api/rules", Now); + Assert.Equal(EdgeVerdict.PassBypassed, d.Verdict); + } + + [Fact] + public void An_expired_rule_matches_nothing() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(4, "/.env*", RequestRuleAction.Block, Now.AddMinutes(-1))]), + "203.0.113.9", "/.env", Now); + Assert.Equal(EdgeVerdict.Pass, d.Verdict); + } + + [Fact] + public void The_first_live_rule_in_the_listing_wins() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, + [ + Rule(1, "/api*", RequestRuleAction.Observe), + Rule(2, "/api/secret", RequestRuleAction.Block) + ]), + "203.0.113.9", "/api/secret", Now); + Assert.Equal(EdgeVerdict.PassRuleObserved, d.Verdict); + Assert.Equal("rule_1", d.Reason); + } + + [Fact] + public void A_rule_judges_the_request_even_when_the_address_cannot_be_resolved() + { + // The pillar is about the path, so an edge behind a misconfigured proxy + // still refuses /.env. What it cannot do is name the source. + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(11, "/.env*", RequestRuleAction.Block)]), + null, "/.env", Now); + + Assert.Equal(EdgeVerdict.BlockRule, d.Verdict); + Assert.Null(d.SourceKey); + } + + [Fact] + public void No_rule_matching_leaves_the_answer_exactly_as_it_was() + { + var d = DecisionEngine.Decide( + Snapshot(EdgePolicy.Default, [Rule(1, "/.env*", RequestRuleAction.Block)]), + "203.0.113.9", "/index.html", Now); + Assert.Equal(EdgeVerdict.Pass, d.Verdict); + Assert.Null(d.RulePattern); + } +} diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 0b90aa2..44c2c4b 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -80,6 +80,18 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); // The allow table can hold several rows at once, so a delete has to be aimed at // one of them: "click the first remove button" deletes whatever the server // happened to sort first, which is not the row this assertion is about. + const removeRule = async (pattern) => { + await page.evaluate((pat) => { + const tr = [...document.querySelectorAll('#pathrules tbody tr')] + .find((r) => r.children[0].textContent === pat); + const b = tr && tr.querySelector('button[data-act="delrule"]'); + if (b) b.click(); + }, pattern); + await page.waitForFunction( + (pat) => ![...document.querySelectorAll('#pathrules tbody tr')].some((r) => r.children[0].textContent === pat), + pattern, { timeout: 15000 }).catch(() => {}); + }; + const removeAllow = async (match) => { await page.evaluate((m) => { const tr = [...document.querySelectorAll('#allow tbody tr')] @@ -378,6 +390,97 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); await removeAllow(SEED_EXPIRED_CIDR); await removeAllow(WRITE_CIDR); + // A path rule is the one control that judges the request rather than the + // response the upstream gave, and it has two actions that mean opposite + // things. The gate writes one from the page, asks the edge for that path, and + // reads the answer back in both the table and the status code. + const RULE_PATH = '/gate-rule-probe'; + // Its own address, and the engine ban is cleared before the last probe. Every + // probe here is a 404 refusal, and the seed set the streak threshold to 3 — + // so the gate itself would otherwise ban its own probe address and the last + // assertion would read a `blocked_by_policy` as "the rule is still in force". + const RULE_IP = '203.0.113.188'; + const probePath = async (path, ip) => { + const r = await fetch(`${EDGE}${path}`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' }); + const text = await r.text(); + return { status: r.status, text }; + }; + const clearEngineBan = async (ip) => { + const r = await fetch(`${EDGE}/admin-api/blocks?source=engine&key=${encodeURIComponent(ip)}`, + { method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } }); + await r.body.cancel(); + }; + + await page.fill('#rulePattern', RULE_PATH + '*'); + // A : fill() waits for something that can be typed + // into and times out. selectOption is the selector's own verb. + await page.selectOption('#ruleAction', 'observe'); + await page.fill('#ruleNote', 'console gate: path rule'); + await page.fill('#ruleTtl', '60'); + await page.click('#addRule'); + await page.waitForFunction( + (pat) => [...document.querySelectorAll('#pathrules tbody tr')] + .some((r) => r.children[0].textContent === pat), + RULE_PATH + '*', { timeout: 15000 }).catch(() => {}); + const ruleRows = await cells('#pathrules tbody tr'); + check('the page can write a path rule and lists it with its action and expiry', + ruleRows.some((r) => r[0] === RULE_PATH + '*' && r[1] === 'observe' + && /console gate/.test(r[2] || '') && /\d{4}-\d{2}-\d{2}/.test(r[4] || '')), + JSON.stringify(ruleRows.map((r) => [r[0], r[1], r[4]]))); + + const observed = await probePath(RULE_PATH, RULE_IP); + await page.click('#refresh'); + await page.waitForFunction( + (pat) => { + const tr = [...document.querySelectorAll('#pathrules tbody tr')] + .find((r) => r.children[0].textContent === pat); + return !!tr && Number(tr.children[3].textContent) >= 1; + }, + RULE_PATH + '*', { timeout: 15000 }).catch(() => {}); + const countedRows = await cells('#pathrules tbody tr'); + check('an observe rule lets the request through and counts the match on the row', + observed.status === 404 + && countedRows.some((r) => r[0] === RULE_PATH + '*' && Number(r[3]) >= 1), + `${observed.status} ${JSON.stringify(countedRows.map((r) => [r[0], r[1], r[3]]))}`); + + const ruleNote = (await page.textContent('#rulenote')).replace(/\s+/g, ' ').trim(); + check('the line under the rules table says the order is the answer and what each action does', + /first rule that matches/.test(ruleNote) && /observe counts/.test(ruleNote), + JSON.stringify(ruleNote)); + + await removeRule(RULE_PATH + '*'); + await page.fill('#rulePattern', RULE_PATH + '*'); + await page.selectOption('#ruleAction', 'block'); + await page.fill('#ruleNote', 'console gate: blocking rule'); + await page.click('#addRule'); + await page.waitForFunction( + (pat) => [...document.querySelectorAll('#pathrules tbody tr')] + .some((r) => r.children[0].textContent === pat), + RULE_PATH + '*', { timeout: 15000 }).catch(() => {}); + const blocked = await probePath(RULE_PATH, RULE_IP); + check('a block rule refuses the path, and the answer names the rule not the pattern', + blocked.status === 403 && /blocked_by_rule/.test(blocked.text) && !blocked.text.includes(RULE_PATH), + `${blocked.status} ${JSON.stringify(blocked.text.slice(0, 160))}`); + const ruleActionRows = await cells('#pathrules tbody tr'); + check('a blocking rule is marked, not only printed', + ruleActionRows.some((r) => r[0] === RULE_PATH + '*' && r[1] === 'block'), + JSON.stringify(ruleActionRows.map((r) => [r[0], r[1]]))); + + await removeRule(RULE_PATH + '*'); + // Asked again, with waits. The row can leave the table a moment before the + // guard's snapshot is rebuilt — the delete commits, the listing stops showing + // it, and the snapshot refresh lands milliseconds later. That is the same + // staleness the TTL documents, so the gate waits for the state to agree rather + // than pretending the two reads are one. + let flowed = (await probePath(RULE_PATH, RULE_IP)).status; + for (let i = 0; i < 10 && flowed !== 404; i++) { + await clearEngineBan(RULE_IP); + await new Promise((r) => setTimeout(r, 500)); + flowed = (await probePath(RULE_PATH, RULE_IP)).status; + } + check('removing the rule from the page lets the path flow again', + flowed === 404, `after removal: ${flowed}`); + // The failure mode worth asserting on a write form is the quiet one: the // operator believes they blocked an address and did not. A typo in the field // must come back as the API's own error, not as a status line that says diff --git a/scripts/console-smoke.sh b/scripts/console-smoke.sh index 61d627d..cb74196 100755 --- a/scripts/console-smoke.sh +++ b/scripts/console-smoke.sh @@ -36,6 +36,12 @@ cleanup() { admin -X PUT -H 'Content-Type: application/json' \ -d '{"mode":"Enforce","geo":"Off","streakThreshold":10,"trustProxyHeaders":false}' "$EDGE/admin-api/policy" >/dev/null 2>&1 admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null 2>&1 + # The gate probes 404 paths, and the seed sets the streak threshold to 3, so + # the gate can ban its own probe address. An engine ban lives in the data + # volume and outlives `compose down`, and the next run's first assertion is + # "before the block, this address reaches the upstream" — which a leftover ban + # answers with 403 for the whole ban duration. + admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null 2>&1 # The page can write allow entries. The gate removes the one it added, but if # it failed before that step the entry would outlive the run inside the data # volume and quietly change the next run — so clear them here too. @@ -49,6 +55,12 @@ cleanup() { # the rule out, which matters because the row lives in the data volume and # outlives `compose down`. admin -X DELETE "$EDGE/admin-api/countries/US" >/dev/null 2>&1 + # The page can write path rules, and a rule outlives `compose down` in the + # data volume — where a leftover block rule would refuse a path for every run + # after this one. live=false so an expired rule is cleared too. + for id in $(admin "$EDGE/admin-api/rules?live=false&limit=2000" | tr ',' '\n' | sed -n 's/.*"id":\([0-9]*\).*/\1/p'); do + admin -X DELETE "$EDGE/admin-api/rules/$id" >/dev/null 2>&1 + done [ "${KEEP_UP:-0}" = 1 ] || docker compose down >/dev/null 2>&1 } trap cleanup EXIT diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 313e472..72baefe 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -117,6 +117,35 @@ check 'a page of one is a page of one' 1 \ "$(curl -s -H "X-Admin-Token: $TOKEN" \ "http://127.0.0.1:$EDGE_PORT/admin-api/allow?limit=1" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +# A path rule is the one pillar about the request rather than about what the +# upstream answered, so the smoke run asks the question the feature exists to +# answer: does a refused path reach the origin or not. +# Not $Bystander: the allowlist scene above exempted 198.51.100.0/24, and an +# exempt address is the one answer a path rule must not override. +RULE_IP=203.0.113.77 +RULE_JSON='{"pattern":"/gate-blocked*","action":"block","note":"smoke: the request itself"}' +BAD_RULE_JSON='{"pattern":"gate-blocked","action":"block"}' +echo '- a path rule refuses the request itself' +check 'add a blocking path rule' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$RULE_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rules")" +check 'the path is refused rather than proxied' 403 \ + "$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")" +check 'the refusal names the rule and not the pattern' yes \ + "$(curl -s -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)" | grep -q blocked_by_rule && echo yes || echo no)" +check 'a pattern that could never match is refused' 400 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$BAD_RULE_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rules")" +check 'the rules listing holds the rule' 1 \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')" +check 'the rule can be removed by id' 204 \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules/$RULE_ID")" +check 'and the path flows again once it is gone' 404 \ + "$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")" + echo '- expiry and clearing' sleep 7 check 'the engine ban lifted itself' 404 "$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")"