the dry run says what the volume pillar would answer for that source
`GET /admin-api/decide` answers what would happen to a named request and which pillar said so, and it stayed silent about the one pillar whose number the operator is choosing. The count is kept in the guard rather than read off a snapshot, so the preview printed `rate: not_evaluated` and left "would this source be rate-limited" as the one question the surface exists to answer could not ask. The rulings this had to make, and the answer each one got: * Reading, never spending, is the invariant. The section is built from peek reads of both trackers, so N dry runs leave `count` exactly where it was and write no alert. A preview that answered by counting its own question would refuse the next real request because somebody pressed a button — the tool for finding an over-tight budget would itself be the cause of it. * Four silences stay apart: `not_counted` (the pillar is off, so there is no budget to cross), `no_source` (no address was asked, and a budget is a claim about a source), `refused_now`, `would_be_counted`. A fifth, `over_budget_not_enforced`, exists because "over budget" and "would be refused" are two answers separated by the mode, and collapsing them is how an observe budget becomes a surprise the day someone switches it on. * `reached: false` says an earlier pillar answers the request, so the guard would never consult the counter for it. The volume section still reports the counters — they are true — but the note stops talking about a budget this request would never touch. * A budget in force for the path with nothing counted for this source yet prints `counted: false`, not `count: 0`. "0 of 2" and "nothing yet" are answers an operator acts on differently. * The path budgets are matched by the same `PathPattern.Matches`, in the same order, as the guard: a preview that matched differently would be a preview of a different edge. * The counters are this process's (`scope: "this-process"`), said in the answer rather than left for the operator to remember. * The `rate` pillar row keeps `not_evaluated` — the engine really did not evaluate it — and its note now points at the section that did, instead of ending as a silence. What the runs caught, in order: * The first version answered `refused_now` for an Observe crossing. The counters were right and the sentence was wrong: observe enforces nothing. The mode is now part of the verdict. * An integration expectation asserted the note of the `rate` pillar row after a crossing, and read the engine ban the crossing itself had written instead — the request was no longer reaching the volume pillar. The assertion moved to the preview taken before the crossing, and the ban case now asserts the honest note. * Rewording that note broke an older preview test that keyed on the word "preview" in it; the wording keeps the word, and the older test is the one that caught the rewording. * The smoke scene compared a listing's over-budget count against a request count, which would have passed for the wrong reason; it now asserts the pair (tracked, over) before and after six previews. Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit 371/371, integration 345/345 in 43 s, console 122 assertions 0 failed, smoke passed 182 failed 0, compose 304 passed 0 failed against the built image at 262 MB, 0 containers left behind. Refs OPEN-69.
This commit is contained in:
@@ -417,7 +417,8 @@ GET /admin-api/countries/summary sources and refusals per country, from the a
|
||||
GET /admin-api/geo which database is loaded and how old it is
|
||||
GET /admin-api/state snapshot age, tracked sources, counts, push state
|
||||
GET /admin-api/decide?ip=&path=&country= what the edge WOULD answer that request,
|
||||
and which pillar said so
|
||||
which pillar said so, and what the volume
|
||||
counters say about that source right now
|
||||
```
|
||||
|
||||
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
|
||||
@@ -825,7 +826,15 @@ GET /admin-api/decide?ip=203.0.113.7&path=/wp-admin
|
||||
{ "pillar": "operatorBlock","outcome": "not_reached" },
|
||||
{ "pillar": "engineBan", "outcome": "not_reached" },
|
||||
{ "pillar": "geo", "outcome": "not_enforced_in_this_mode", "note": "the geo pillar is off" },
|
||||
{ "pillar": "rate", "outcome": "not_evaluated", "note": "a preview does not consume the live counter" } ] }
|
||||
{ "pillar": "rate", "outcome": "not_evaluated", "note": "answered by the `volume` section of this preview, which reads the counters without spending them" } ],
|
||||
"volume": { "mode": "Enforce", "scope": "this-process", "verdict": "refused_now", "reached": true,
|
||||
"edgeBudget": { "count": 4, "limitPerWindow": 2, "windowSeconds": 60,
|
||||
"windowStartsAt": "…", "windowEndsAt": "…", "secondsLeft": 37,
|
||||
"overBudget": true },
|
||||
"pathBudgets": [ { "id": 1, "pattern": "/wp-admin*", "limitPerWindow": 20,
|
||||
"windowSeconds": 60, "counted": true, "count": 6,
|
||||
"overBudget": false, "windowEndsAt": "…", "secondsLeft": 51 } ],
|
||||
"note": "the edge-wide budget is already crossed for this source: in Enforce mode this request is answered 429 for the rest of that window, and a path budget pauses only the path it names" } }
|
||||
```
|
||||
|
||||
The `pillars` list is the point. A verdict says what would happen; the trace says
|
||||
@@ -837,14 +846,35 @@ goes further and says whether a live ban for that source exists, because "nothin
|
||||
was known about this address" and "something was known and the mode chose not to
|
||||
act" are the two answers operators keep reading as one.
|
||||
|
||||
What it cannot answer is stated in the body rather than left out: the **rate
|
||||
pillar** is a live counter this call must not spend, and the **streak** depends on
|
||||
responses the upstream has not produced yet. A bare `pass` without those two
|
||||
What it cannot answer is stated in the body rather than left out: the **streak**
|
||||
depends on responses the upstream has not produced yet. A bare `pass` without it
|
||||
would be a wrong answer, not an incomplete one. It changes nothing — no counter,
|
||||
no streak, no budget, no alert — and the answer is labelled with the snapshot it
|
||||
was computed from (`snapshotAgeSeconds`, `snapshotTtlSeconds`, `snapshotStale`),
|
||||
because a block written a second ago lands when the snapshot refreshes.
|
||||
|
||||
The volume half of that gap is closed (OPEN-69). The `volume` section answers what
|
||||
the counters of this process say about that source right now: the mode, the
|
||||
edge-wide window (`count`, `limitPerWindow`, `windowSeconds`, when it ends and how
|
||||
many seconds are left), and one row per live path budget whose pattern matches the
|
||||
asked path — in the order the guard evaluates them, by the same matcher. The
|
||||
`verdict` keeps the four answers apart: `not_counted` (the pillar is off, so there
|
||||
is no budget to cross), `no_source` (no address was asked, and a budget is a claim
|
||||
about a source), `refused_now` (a counter this request falls inside is already past
|
||||
its budget), `would_be_counted`. `reached: false` says an earlier pillar answers
|
||||
the request, so the guard would never consult the counter for it and nothing would
|
||||
be spent. A budget that is in force for this path but has counted nothing for this
|
||||
source yet prints `counted: false` rather than `count: 0` — "0 of 2" and "nothing
|
||||
yet" are answers an operator acts on differently.
|
||||
|
||||
Reading rather than spending is the invariant: the section is built from peek
|
||||
reads, so N dry runs leave `count` exactly where it was and write no alert. A
|
||||
preview that answered by counting its own question would refuse the next real
|
||||
request because somebody pressed a button, and the tool for finding an over-tight
|
||||
budget would itself be the cause of it. The counters are this process's
|
||||
(`scope: "this-process"`), and the answer says so rather than letting a preview on
|
||||
one edge speak for another.
|
||||
|
||||
Input is refused, not guessed: an unknown query parameter is a 400 (the same
|
||||
guard every admin endpoint runs), and an `ip` that is not a full address is a 400
|
||||
naming the value. `IPAddress.TryParse` alone would accept `203.0.113` as
|
||||
@@ -1159,7 +1189,12 @@ sources counted, windows running, over budget now — with the last one marked,
|
||||
a form that writes one with a pattern, two numbers, a note and an optional expiry.
|
||||
The line under the table distinguishes a database with no rate-rule table from an
|
||||
operator who wrote no budgets, which is the difference between a migration to
|
||||
apply and a decision not to make. The line under it
|
||||
apply and a decision not to make. The page also asks the dry run
|
||||
directly (OPEN-69): an address and a path, and the answer prints the verdict, the
|
||||
path rule that spoke if one did, the edge-wide window with the seconds left in it,
|
||||
and one line per path budget whose pattern matches the asked path. The volume line
|
||||
is the part that makes the button safe to press on a live site — it is read off the
|
||||
counters, and the gate asserts that asking leaves those counters where they were. The line under it
|
||||
says which of the two answers an empty table is — "off, nothing is being
|
||||
counted" or "counting, nobody is over budget yet" — and says plainly that the
|
||||
counting is this process's. That bar is the honest limit of the word
|
||||
@@ -1355,9 +1390,9 @@ have not, so the two sets of numbers are labelled separately rather than merged
|
||||
into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable
|
||||
alert-push queue, the config transfer, the second token, the startup refusals, the change
|
||||
log and that log on the console, the operator's ranges, the netblock watch and
|
||||
the per-path request budgets:
|
||||
build 0 warnings / 0 errors, unit **361/361**, integration **337/337 in 30 s**,
|
||||
console **120 assertions, 0 failed**, smoke **passed 169, failed 0**, and compose **300 passed,
|
||||
the per-path request budgets and the volume answer of the dry run:
|
||||
build 0 warnings / 0 errors, unit **371/371**, integration **345/345 in 43 s**,
|
||||
console **122 assertions, 0 failed**, smoke **passed 182, failed 0**, and compose **304 passed,
|
||||
0 failed** against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being
|
||||
started from the repository root, where there is no `appsettings.json`, so it
|
||||
loaded no `ReverseProxy` section, logged "Request reached the end of the
|
||||
|
||||
@@ -189,9 +189,14 @@ public static class DecisionTrace
|
||||
case "geo" when policy.Geo == GeoMode.Off:
|
||||
return "the geo pillar is off";
|
||||
case "rate":
|
||||
// The pillar is not in the engine — a count is kept while requests
|
||||
// arrive — but since OPEN-69 it is no longer unasked: the `volume`
|
||||
// section of the same answer reads the counters without spending
|
||||
// them, and the note says where to look rather than leaving the
|
||||
// row as a silence.
|
||||
return policy.Rate == RateMode.Off
|
||||
? "the volume pillar is off, and a preview never spends the budget anyway"
|
||||
: "a preview does not consume the live counter";
|
||||
? "the volume pillar is off: nothing is counted, and this preview's `volume` section says so"
|
||||
: "answered by the `volume` section of this preview, which reads the counters without spending them";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -108,6 +108,31 @@ public sealed class RateRuleTracker
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the counters already say about one source for one rule,
|
||||
/// without moving them. The dry run (OPEN-69) has to be able to ask "is this
|
||||
/// source over its path budget right now" — and a preview that answered by
|
||||
/// counting the question itself would spend the budget it is asking about, so
|
||||
/// the next real request would be refused because someone pressed a button.
|
||||
/// Null means there is no running window for this pair: not "zero requests",
|
||||
/// which is a different answer and the one an operator acts on differently.</summary>
|
||||
public RuleRateObservation? Peek(RateRule rule, string sourceKey, DateTimeOffset now)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sourceKey)) return null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_states.TryGetValue((rule.Id, sourceKey), out var state)) return null;
|
||||
var end = state.WindowStart + state.WindowLength;
|
||||
if (now >= end) return null;
|
||||
return new RuleRateObservation(
|
||||
state.Count,
|
||||
rule.LimitPerWindow > 0 && state.Count > rule.LimitPerWindow,
|
||||
state.WindowStart, end,
|
||||
// A peek has no crossing: the crossing is an event on a counted
|
||||
// request, and this call counts nothing.
|
||||
BreachStarted: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How many sources this rule is holding a window for, live or not —
|
||||
/// the number that says whether the rule is counting anything at all.</summary>
|
||||
public int TrackedCount(long ruleId)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
using OpenWaf.Domain.Policy;
|
||||
using OpenWaf.Domain.Security;
|
||||
|
||||
namespace OpenWaf.Domain.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// What the volume pillar would answer for one named request, read off the
|
||||
/// counters without moving them (OPEN-69).
|
||||
///
|
||||
/// The preview endpoint used to answer every pillar and stay silent about this
|
||||
/// one, because the count lives in the guard rather than in the snapshot. The
|
||||
/// silence was not neutral: the volume pillar is the pillar operators most often
|
||||
/// read as a ban, and the number they are choosing is exactly the number the
|
||||
/// preview could not comment on.
|
||||
///
|
||||
/// The one invariant the whole type exists to keep: <b>asking does not spend</b>.
|
||||
/// A preview that answered by counting its own question would refuse the next real
|
||||
/// request because somebody pressed a button, and the tool that was supposed to
|
||||
/// prevent an over-tight budget would itself be the cause.
|
||||
/// </summary>
|
||||
public static class VolumePreview
|
||||
{
|
||||
/// <summary>The volume pillar is off: nothing is counted anywhere on this
|
||||
/// edge, so there is no budget to be over.</summary>
|
||||
public const string VerdictNotCounted = "not_counted";
|
||||
|
||||
/// <summary>No address was given, and a budget is a claim about a source.</summary>
|
||||
public const string VerdictNoSource = "no_source";
|
||||
|
||||
/// <summary>A counter for this source is already past a budget the request
|
||||
/// falls inside, so in Enforce mode this request is the one that gets 429.</summary>
|
||||
public const string VerdictRefusedNow = "refused_now";
|
||||
|
||||
/// <summary>A counter is past its budget and the mode is Observe: the crossing
|
||||
/// is real and alerting, and this request would still be served. Reading
|
||||
/// "over budget" as "would be refused" is how an observe budget turns into a
|
||||
/// surprise outage the moment the mode is switched.</summary>
|
||||
public const string VerdictOverBudgetNotEnforced = "over_budget_not_enforced";
|
||||
|
||||
/// <summary>The request would be counted and allowed: the budget is standing
|
||||
/// between this source and a refusal, and the counters say how far away.</summary>
|
||||
public const string VerdictWouldBeCounted = "would_be_counted";
|
||||
|
||||
public static VolumeAnswer For(
|
||||
EdgePolicy policy, EdgeSnapshot snapshot, string path, string? sourceKey,
|
||||
RateTracker rates, RateRuleTracker rateRules, DateTimeOffset now, bool reached)
|
||||
{
|
||||
var counting = policy.Rate != RateMode.Off && !string.IsNullOrEmpty(sourceKey);
|
||||
|
||||
EdgeBudgetPreview? edge = null;
|
||||
var overEdge = false;
|
||||
if (counting)
|
||||
{
|
||||
// The same read the operator's rate listing makes, aimed at one
|
||||
// source: it reports the running window and nothing else, because a
|
||||
// window that has already run out is about to restart at zero and
|
||||
// "0 of 20" from a dead window is a different answer from "0 of 20".
|
||||
var live = rates.LiveRates(now, policy, 1, 0, sourceKey, out _);
|
||||
if (live.Count > 0)
|
||||
{
|
||||
var w = live[0];
|
||||
overEdge = w.OverBudget;
|
||||
edge = new EdgeBudgetPreview(
|
||||
w.Count, policy.RateLimitPerWindow, Math.Round(policy.RateWindow.TotalSeconds, 1),
|
||||
w.WindowStart, w.WindowEnd, SecondsLeft(w.WindowEnd, now), w.OverBudget);
|
||||
}
|
||||
}
|
||||
|
||||
var budgets = new List<PathBudgetPreview>();
|
||||
var overPath = false;
|
||||
if (counting)
|
||||
{
|
||||
// The same matcher the guard uses, in the same order: a preview that
|
||||
// matched paths differently from the enforcement would be a preview of
|
||||
// a different edge.
|
||||
foreach (var rule in snapshot.RateRules)
|
||||
{
|
||||
if (!rule.IsLive(now) || !PathPattern.Matches(rule.Pattern, path)) continue;
|
||||
var seen = rateRules.Peek(rule, sourceKey!, now);
|
||||
if (seen is null)
|
||||
{
|
||||
budgets.Add(new PathBudgetPreview(rule.Id, rule.Pattern, rule.LimitPerWindow,
|
||||
rule.WindowSeconds, false, null, false, null, null));
|
||||
continue;
|
||||
}
|
||||
if (seen.OverBudget) overPath = true;
|
||||
budgets.Add(new PathBudgetPreview(rule.Id, rule.Pattern, rule.LimitPerWindow,
|
||||
rule.WindowSeconds, true, seen.Count, seen.OverBudget, seen.WindowEnd,
|
||||
SecondsLeft(seen.WindowEnd, now)));
|
||||
}
|
||||
}
|
||||
|
||||
var crossed = overEdge || overPath;
|
||||
var verdict = policy.Rate == RateMode.Off
|
||||
? VerdictNotCounted
|
||||
: string.IsNullOrEmpty(sourceKey)
|
||||
? VerdictNoSource
|
||||
: !crossed
|
||||
? VerdictWouldBeCounted
|
||||
: policy.Rate == RateMode.Enforce
|
||||
? VerdictRefusedNow
|
||||
: VerdictOverBudgetNotEnforced;
|
||||
|
||||
return new VolumeAnswer(
|
||||
policy.Rate.ToString(), "this-process", verdict, reached, edge, budgets,
|
||||
NoteFor(verdict, reached, overEdge, budgets));
|
||||
}
|
||||
|
||||
/// <summary>The sentence that keeps the three silences apart: the pillar is
|
||||
/// off, the request never reaches the pillar, and the pillar is reached with
|
||||
/// nothing counted yet.</summary>
|
||||
private static string NoteFor(string verdict, bool reached, bool overEdge, IReadOnlyList<PathBudgetPreview> budgets)
|
||||
{
|
||||
if (verdict == VerdictNotCounted)
|
||||
return "the volume pillar is off: nothing is counted on this edge, so no budget can be crossed";
|
||||
if (verdict == VerdictNoSource)
|
||||
return "no address was given, and a budget is a claim about a source";
|
||||
if (!reached)
|
||||
return "an earlier pillar answers this request, so the volume pillar would not be reached and nothing would be counted for it";
|
||||
var which = overEdge
|
||||
? "the edge-wide budget"
|
||||
: budgets.FirstOrDefault(b => b.OverBudget) is { } over
|
||||
? $"the path budget for {over.Pattern}"
|
||||
: null;
|
||||
if (which is null)
|
||||
return "the counters live in this process, so N edges allow N budgets; a path budget pauses only the path it names and writes no ban";
|
||||
return verdict == VerdictOverBudgetNotEnforced
|
||||
? $"{which} is already crossed for this source, and Observe mode enforces nothing: the request is served and one alert per source per window is raised"
|
||||
: $"{which} is already crossed for this source: this request is answered 429 for the rest of that window, and a path budget pauses only the path it names";
|
||||
}
|
||||
|
||||
private static int SecondsLeft(DateTimeOffset windowEnd, DateTimeOffset now)
|
||||
=> Math.Max(0, (int)Math.Ceiling((windowEnd - now).TotalSeconds));
|
||||
}
|
||||
|
||||
/// <summary>The edge-wide window this source is inside, or null when it has none
|
||||
/// running — which is not the same as a window at zero.</summary>
|
||||
public sealed record EdgeBudgetPreview(
|
||||
int Count,
|
||||
int LimitPerWindow,
|
||||
double WindowSeconds,
|
||||
DateTimeOffset WindowStartsAt,
|
||||
DateTimeOffset WindowEndsAt,
|
||||
int SecondsLeft,
|
||||
bool OverBudget);
|
||||
|
||||
/// <summary>One live path budget whose pattern matches the asked path.
|
||||
/// <c>counted=false</c> means the rule is in force for this path but this source
|
||||
/// has no window on it yet — the difference between "0 of 2" and "nothing yet".</summary>
|
||||
public sealed record PathBudgetPreview(
|
||||
long Id,
|
||||
string Pattern,
|
||||
int LimitPerWindow,
|
||||
int WindowSeconds,
|
||||
bool Counted,
|
||||
int? Count,
|
||||
bool OverBudget,
|
||||
DateTimeOffset? WindowEndsAt,
|
||||
int? SecondsLeft);
|
||||
|
||||
/// <summary>The volume answer of a dry run.</summary>
|
||||
public sealed record VolumeAnswer(
|
||||
string Mode,
|
||||
string Scope,
|
||||
string Verdict,
|
||||
bool Reached,
|
||||
EdgeBudgetPreview? EdgeBudget,
|
||||
IReadOnlyList<PathBudgetPreview> PathBudgets,
|
||||
string Note);
|
||||
@@ -146,6 +146,14 @@ internal static class AdminConsole
|
||||
<div id="raterulenote" class="muted"></div>
|
||||
<div class="scroll"><table id="raterules"><thead><tr><th>pattern</th><th class="num">requests</th><th class="num">window s</th><th class="num">sources counted</th><th class="num">windows running</th><th class="num">over budget now</th><th>note</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Ask what the edge would answer</h2>
|
||||
<div class="bar">
|
||||
<input id="askIp" placeholder="address" autocomplete="off" size="18">
|
||||
<input id="askPath" placeholder="path, e.g. /wp-login.php" autocomplete="off" size="26">
|
||||
<button id="askDecide">ask</button>
|
||||
</div>
|
||||
<div id="askanswer" class="muted"></div>
|
||||
|
||||
<h2>Sources the edge is watching</h2>
|
||||
<div class="bar">
|
||||
<input id="srcfilter" placeholder="filter observations and streaks by source key" autocomplete="off" size="28">
|
||||
@@ -800,6 +808,50 @@ el('addRateRule').onclick = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
el('askDecide').onclick = async () => {
|
||||
// The dry run asked from the page. It is a read: the edge says so in the body,
|
||||
// and the volume half of the answer (OPEN-69) is read off the counters without
|
||||
// spending them — which is the whole reason this button is safe to press while
|
||||
// the site is live.
|
||||
const ip = el('askIp').value.trim();
|
||||
const path = el('askPath').value.trim() || '/';
|
||||
if (!ip) { note('an address first — a verdict is a claim about a source', true); return; }
|
||||
const r = await apiRaw('/admin-api/decide?ip=' + encodeURIComponent(ip) + '&path=' + encodeURIComponent(path));
|
||||
if (failed(r)) return;
|
||||
const d = r.body;
|
||||
const v = d.volume || {};
|
||||
const lines = [];
|
||||
lines.push('would answer: ' + (d.verdict || '?') + (d.blocked ? ' (' + d.status + ')' : '')
|
||||
+ (d.reason ? ' — ' + d.reason : ''));
|
||||
const rule = d.rule;
|
||||
if (rule) lines.push('path rule ' + rule.id + ' ' + rule.pattern + ' (' + rule.action + ')');
|
||||
const edge = v.edgeBudget;
|
||||
lines.push('volume: ' + (v.mode || '?') + ' · ' + (v.verdict || '?') + ' · ' + (v.scope || '?')
|
||||
+ (edge ? ' · edge budget ' + edge.count + ' of ' + edge.limitPerWindow
|
||||
+ ' per ' + edge.windowSeconds + ' s, ' + edge.secondsLeft + ' s left'
|
||||
+ (edge.overBudget ? ' — OVER' : '') : ' · edge budget: no running window'));
|
||||
const budgets = v.pathBudgets || [];
|
||||
if (budgets.length) {
|
||||
lines.push('path budgets for this path: ' + budgets.map((b) => b.pattern + ' '
|
||||
+ (b.counted ? b.count + ' of ' + b.limitPerWindow + ' per ' + b.windowSeconds + ' s'
|
||||
: 'in force, nothing counted for this source yet')
|
||||
+ (b.overBudget ? ' — OVER (pauses this path only, not a ban)' : '')).join(' · '));
|
||||
} else {
|
||||
lines.push('path budgets for this path: none — the edge-wide budget is the only one');
|
||||
}
|
||||
lines.push(v.note || '');
|
||||
// textContent, not innerHTML: the address and the path came from the operator's
|
||||
// keyboard, and an answer page that renders them as markup is an XSS in the one
|
||||
// place the operator goes to look at an attack.
|
||||
const box = el('askanswer');
|
||||
box.textContent = '';
|
||||
for (const line of lines) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = line;
|
||||
box.appendChild(div);
|
||||
}
|
||||
};
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -729,7 +729,8 @@ internal static partial class AdminEndpoints
|
||||
// are named in the body rather than left out, because a bare "pass"
|
||||
// without them is a wrong answer, not an incomplete one.
|
||||
group.MapGet("/decide", (string? ip, string? path, string? country,
|
||||
EdgeStateStore state, IGeoIpLookup geo, HttpContext ctx) =>
|
||||
EdgeStateStore state, IGeoIpLookup geo, RateTracker rates, RateRuleTracker rateRules,
|
||||
HttpContext ctx) =>
|
||||
{
|
||||
if (!TryKnownQuery(ctx, out var unknown, "ip", "path", "country"))
|
||||
return Results.BadRequest(new { error = unknown });
|
||||
@@ -814,6 +815,19 @@ internal static partial class AdminEndpoints
|
||||
note = matchedRule.Note,
|
||||
expiresAt = matchedRule.ExpiresAt
|
||||
},
|
||||
// The volume pillar (OPEN-69). It is not in DecisionEngine — a
|
||||
// count has to be kept while requests arrive, not read off a
|
||||
// snapshot — so the preview answered every other pillar and stayed
|
||||
// silent about this one, which is the pillar operators most often
|
||||
// read as a ban. What this section says is what the counters of
|
||||
// this process say right now, read without spending them: a preview
|
||||
// that answered by counting its own question would refuse the next
|
||||
// real request because somebody pressed a button.
|
||||
volume = VolumePreview.For(policy, snapshot, askedPath, askedKey, rates, rateRules, now,
|
||||
// The guard runs the volume pillar only for a request no other pillar has
|
||||
// answered, so the preview says the same: a refusal from an earlier pillar
|
||||
// never reaches the counter and never spends it.
|
||||
decision.Verdict == EdgeVerdict.Pass),
|
||||
// The order, pillar by pillar, with the reason each one after the
|
||||
// answering pillar did not speak. This is the part that makes the
|
||||
// answer actionable: it says which pillar to change.
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OpenWaf.Infrastructure.Persistence;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// The volume half of the dry run (OPEN-69). The preview used to answer every
|
||||
/// pillar and stay silent about the one whose number the operator is choosing —
|
||||
/// "would this source be rate-limited" was a question the surface that exists to
|
||||
/// answer such questions could not ask.
|
||||
///
|
||||
/// The property these tests exist to hold is the one that makes the section worth
|
||||
/// shipping: it reads the counters and never spends them. A preview that answered
|
||||
/// by counting its own question would refuse the next real request because
|
||||
/// somebody pressed a button.
|
||||
/// </summary>
|
||||
public sealed class VolumeDryRunTests
|
||||
{
|
||||
private const string Source = "203.0.113.140";
|
||||
|
||||
private static async Task<JsonDocument> DecideAsync(EdgeFixture f, string query)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/decide?{query}");
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
using var r = await f.Client.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.OK, r.StatusCode);
|
||||
return JsonDocument.Parse(await r.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip = Source)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
|
||||
return await f.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> AdminAsync(
|
||||
EdgeFixture f, HttpMethod method, string url, object? body = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url);
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
if (body is not null) request.Content = JsonContent.Create(body);
|
||||
return await f.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static void OriginAnswersEverything(EdgeFixture f) =>
|
||||
f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
||||
|
||||
[Fact]
|
||||
public async Task The_preview_answers_the_volume_pillar_it_used_to_leave_silent()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (await GetAsync(f, "/catalog")) { }
|
||||
|
||||
// Inside the budget: the preview says so, and says the pillar would be
|
||||
// reached at all. This is the reading an operator wants before tightening
|
||||
// a number — "two of two, nothing crossed yet".
|
||||
using var before = await DecideAsync(f, $"ip={Source}&path=/catalog");
|
||||
var early = before.RootElement.GetProperty("volume");
|
||||
Assert.Equal("Enforce", early.GetProperty("mode").GetString());
|
||||
Assert.Equal("this-process", early.GetProperty("scope").GetString());
|
||||
Assert.Equal("would_be_counted", early.GetProperty("verdict").GetString());
|
||||
Assert.True(early.GetProperty("reached").GetBoolean());
|
||||
Assert.Equal(1, early.GetProperty("edgeBudget").GetProperty("count").GetInt32());
|
||||
Assert.False(early.GetProperty("edgeBudget").GetProperty("overBudget").GetBoolean());
|
||||
|
||||
// The pillar row that used to be a silence now says where the answer is.
|
||||
var rateRow = before.RootElement.GetProperty("pillars").EnumerateArray()
|
||||
.First(p => p.GetProperty("pillar").GetString() == "rate");
|
||||
Assert.Equal("not_evaluated", rateRow.GetProperty("outcome").GetString());
|
||||
Assert.Contains("volume", rateRow.GetProperty("note").GetString()!);
|
||||
|
||||
using (await GetAsync(f, "/catalog")) { }
|
||||
using (var over = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
|
||||
using var body = await DecideAsync(f, $"ip={Source}&path=/catalog");
|
||||
var volume = body.RootElement.GetProperty("volume");
|
||||
Assert.Equal("refused_now", volume.GetProperty("verdict").GetString());
|
||||
|
||||
var edge = volume.GetProperty("edgeBudget");
|
||||
Assert.Equal(3, edge.GetProperty("count").GetInt32());
|
||||
Assert.Equal(2, edge.GetProperty("limitPerWindow").GetInt32());
|
||||
Assert.Equal(120, edge.GetProperty("windowSeconds").GetDouble());
|
||||
Assert.True(edge.GetProperty("overBudget").GetBoolean());
|
||||
// The answer says how long the pause runs, because "over budget" without
|
||||
// an end is a sentence an operator cannot act on.
|
||||
Assert.True(edge.GetProperty("secondsLeft").GetInt32() >= 1);
|
||||
// The crossing also wrote the engine ban the edge-wide budget has always
|
||||
// written, so this request is now answered before the volume pillar is
|
||||
// reached — and the note says that, instead of going on talking about a
|
||||
// budget this request would never touch.
|
||||
Assert.False(volume.GetProperty("reached").GetBoolean());
|
||||
Assert.Contains("an earlier pillar answers this request", volume.GetProperty("note").GetString()!);
|
||||
|
||||
// The crossing also wrote the engine ban the edge-wide budget has always
|
||||
// written, so this request is now answered by an earlier pillar — and the
|
||||
// answer says which, rather than letting the volume section speak as if it
|
||||
// would be consulted.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task With_the_pillar_off_the_preview_says_nothing_is_counted()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
OriginAnswersEverything(f);
|
||||
for (var i = 0; i < 4; i++) using (await GetAsync(f, "/catalog")) { }
|
||||
|
||||
using var body = await DecideAsync(f, $"ip={Source}&path=/catalog");
|
||||
var volume = body.RootElement.GetProperty("volume");
|
||||
Assert.Equal("not_counted", volume.GetProperty("verdict").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, volume.GetProperty("edgeBudget").ValueKind);
|
||||
Assert.Equal(0, volume.GetProperty("pathBudgets").GetArrayLength());
|
||||
Assert.Contains("nothing is counted", volume.GetProperty("note").GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_observe_crossing_is_reported_without_promising_a_refusal()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 2, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
for (var i = 0; i < 4; i++)
|
||||
using (var probe = await GetAsync(f, "/catalog"))
|
||||
Assert.Equal(HttpStatusCode.OK, probe.StatusCode);
|
||||
|
||||
using var body = await DecideAsync(f, $"ip={Source}&path=/catalog");
|
||||
var volume = body.RootElement.GetProperty("volume");
|
||||
Assert.Equal("over_budget_not_enforced", volume.GetProperty("verdict").GetString());
|
||||
Assert.True(volume.GetProperty("edgeBudget").GetProperty("overBudget").GetBoolean());
|
||||
Assert.Contains("Observe mode enforces nothing", volume.GetProperty("note").GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_dry_run_does_not_spend_the_budget_it_is_asking_about()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 5, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
|
||||
using (await GetAsync(f, "/catalog")) { }
|
||||
using (await GetAsync(f, "/catalog")) { }
|
||||
|
||||
async Task<int> Counted()
|
||||
{
|
||||
using var listing = await AdminAsync(f, HttpMethod.Get, $"/admin-api/rate?source={Source}");
|
||||
using var doc = JsonDocument.Parse(await listing.Content.ReadAsStringAsync());
|
||||
return doc.RootElement.GetProperty("sources")[0].GetProperty("count").GetInt32();
|
||||
}
|
||||
|
||||
Assert.Equal(2, await Counted());
|
||||
|
||||
for (var i = 0; i < 6; i++)
|
||||
using (var preview = await DecideAsync(f, $"ip={Source}&path=/catalog"))
|
||||
Assert.Equal(2, preview.RootElement.GetProperty("volume").GetProperty("edgeBudget").GetProperty("count").GetInt32());
|
||||
|
||||
// Six previews left the counter exactly where it was, and the next real
|
||||
// request is the third of the window rather than the ninth.
|
||||
Assert.Equal(2, await Counted());
|
||||
using (await GetAsync(f, "/catalog")) { }
|
||||
Assert.Equal(3, await Counted());
|
||||
|
||||
using var scope = f.Factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||
Assert.Equal(0, await db.Alerts.AsNoTracking().CountAsync(a => a.Kind == "rate_breach"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_preview_lists_only_the_path_budgets_that_match_the_asked_path()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
|
||||
new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 120 }))
|
||||
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
||||
|
||||
using (await GetAsync(f, "/login")) { }
|
||||
using (await GetAsync(f, "/login")) { }
|
||||
using (var over = await GetAsync(f, "/login"))
|
||||
Assert.Equal((HttpStatusCode)429, over.StatusCode);
|
||||
|
||||
using (var onPath = await DecideAsync(f, $"ip={Source}&path=/login"))
|
||||
{
|
||||
var budgets = onPath.RootElement.GetProperty("volume").GetProperty("pathBudgets");
|
||||
var seen = budgets.EnumerateArray().Single();
|
||||
Assert.Equal("/login*", seen.GetProperty("pattern").GetString());
|
||||
Assert.True(seen.GetProperty("counted").GetBoolean());
|
||||
Assert.Equal(3, seen.GetProperty("count").GetInt32());
|
||||
Assert.True(seen.GetProperty("overBudget").GetBoolean());
|
||||
Assert.True(seen.GetProperty("secondsLeft").GetInt32() >= 1);
|
||||
Assert.Contains("/login*", onPath.RootElement.GetProperty("volume").GetProperty("note").GetString()!);
|
||||
}
|
||||
|
||||
// The same source, a path the budget does not name: the pause is about one
|
||||
// part of the site, and the preview has to say so or it describes a ban.
|
||||
using (var offPath = await DecideAsync(f, $"ip={Source}&path=/catalog"))
|
||||
{
|
||||
var volume = offPath.RootElement.GetProperty("volume");
|
||||
Assert.Equal(0, volume.GetProperty("pathBudgets").GetArrayLength());
|
||||
Assert.Equal("would_be_counted", volume.GetProperty("verdict").GetString());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_budget_in_force_for_the_path_with_nothing_counted_yet_is_not_reported_as_a_zero()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
|
||||
new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 120 }))
|
||||
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
||||
|
||||
using var body = await DecideAsync(f, $"ip=203.0.113.199&path=/login");
|
||||
var seen = body.RootElement.GetProperty("volume").GetProperty("pathBudgets").EnumerateArray().Single();
|
||||
Assert.False(seen.GetProperty("counted").GetBoolean());
|
||||
Assert.Equal(JsonValueKind.Null, seen.GetProperty("count").ValueKind);
|
||||
Assert.False(seen.GetProperty("overBudget").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_request_an_earlier_pillar_answers_never_reaches_the_counter()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120);
|
||||
OriginAnswersEverything(f);
|
||||
using (var rule = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
|
||||
new { pattern = "/secret*", action = "block", note = "preview test" }))
|
||||
Assert.Equal(HttpStatusCode.NoContent, rule.StatusCode);
|
||||
|
||||
using var body = await DecideAsync(f, $"ip={Source}&path=/secret");
|
||||
Assert.True(body.RootElement.GetProperty("blocked").GetBoolean());
|
||||
var volume = body.RootElement.GetProperty("volume");
|
||||
Assert.False(volume.GetProperty("reached").GetBoolean());
|
||||
Assert.Contains("an earlier pillar answers this request", volume.GetProperty("note").GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_question_about_the_path_alone_says_a_budget_is_a_claim_about_a_source()
|
||||
{
|
||||
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120);
|
||||
using var body = await DecideAsync(f, "path=/catalog");
|
||||
var volume = body.RootElement.GetProperty("volume");
|
||||
Assert.Equal("no_source", volume.GetProperty("verdict").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, body.RootElement.GetProperty("sourceKey").ValueKind);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using OpenWaf.Domain.Engine;
|
||||
using OpenWaf.Domain.Policy;
|
||||
using OpenWaf.Domain.Security;
|
||||
|
||||
namespace OpenWaf.Tests.Unit;
|
||||
|
||||
/// <summary>
|
||||
/// The volume half of the dry run (OPEN-69). The preview used to answer every
|
||||
/// pillar and stay silent about the one whose number the operator is choosing, so
|
||||
/// these tests hold the two things that make the section worth having: it answers
|
||||
/// with the four different silences kept apart, and it never spends what it reads.
|
||||
/// </summary>
|
||||
public sealed class VolumePreviewTests
|
||||
{
|
||||
private static readonly DateTimeOffset T0 = new(2026, 10, 5, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static EdgePolicy Policy(RateMode mode = RateMode.Enforce, int limit = 2, int windowSeconds = 60) =>
|
||||
new() { Rate = mode, RateLimitPerWindow = limit, RateWindow = TimeSpan.FromSeconds(windowSeconds) };
|
||||
|
||||
private static EdgeSnapshot Snapshot(EdgePolicy policy, params RateRule[] rules) =>
|
||||
new() { Policy = policy, RateRules = rules, GeneratedAt = T0 };
|
||||
|
||||
private static RateRule Rule(long id, string pattern, int limit, int windowSeconds = 60) =>
|
||||
new() { Id = id, Pattern = pattern, LimitPerWindow = limit, WindowSeconds = windowSeconds };
|
||||
|
||||
[Fact]
|
||||
public void With_the_pillar_off_the_answer_is_not_counted_rather_than_zero_of_the_limit()
|
||||
{
|
||||
var rates = new RateTracker();
|
||||
var policy = Policy(RateMode.Off);
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, Rule(1, "/login*", 2)), "/login", "a",
|
||||
rates, new RateRuleTracker(), T0, true);
|
||||
|
||||
Assert.Equal(VolumePreview.VerdictNotCounted, answer.Verdict);
|
||||
Assert.Null(answer.EdgeBudget);
|
||||
Assert.Empty(answer.PathBudgets);
|
||||
Assert.Contains("nothing is counted", answer.Note);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_question_about_the_path_alone_says_a_budget_is_a_claim_about_a_source()
|
||||
{
|
||||
var policy = Policy();
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, Rule(1, "/login*", 2)), "/login", null,
|
||||
new RateTracker(), new RateRuleTracker(), T0, true);
|
||||
|
||||
Assert.Equal(VolumePreview.VerdictNoSource, answer.Verdict);
|
||||
Assert.Empty(answer.PathBudgets);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_edge_wide_budget_that_is_already_crossed_answers_refused_now_with_the_time_left()
|
||||
{
|
||||
var rates = new RateTracker();
|
||||
var policy = Policy(limit: 2);
|
||||
rates.Record("a", policy, T0);
|
||||
rates.Record("a", policy, T0.AddSeconds(1));
|
||||
rates.Record("a", policy, T0.AddSeconds(2));
|
||||
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy), "/index", "a",
|
||||
rates, new RateRuleTracker(), T0.AddSeconds(3), true);
|
||||
|
||||
Assert.Equal(VolumePreview.VerdictRefusedNow, answer.Verdict);
|
||||
Assert.NotNull(answer.EdgeBudget);
|
||||
Assert.Equal(3, answer.EdgeBudget!.Count);
|
||||
Assert.Equal(2, answer.EdgeBudget.LimitPerWindow);
|
||||
Assert.True(answer.EdgeBudget.OverBudget);
|
||||
Assert.Equal(57, answer.EdgeBudget.SecondsLeft);
|
||||
Assert.Contains("edge-wide budget", answer.Note);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_path_budget_names_the_path_it_was_written_for_in_the_answer()
|
||||
{
|
||||
var rules = new RateRuleTracker();
|
||||
var policy = Policy(limit: 1000);
|
||||
var rule = Rule(7, "/login*", 2);
|
||||
rules.Record(rule, "a", T0);
|
||||
rules.Record(rule, "a", T0.AddSeconds(1));
|
||||
rules.Record(rule, "a", T0.AddSeconds(2));
|
||||
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, rule), "/login", "a",
|
||||
new RateTracker(), rules, T0.AddSeconds(3), true);
|
||||
|
||||
Assert.Equal(VolumePreview.VerdictRefusedNow, answer.Verdict);
|
||||
// The edge-wide budget is not the one crossed, and the note says which is.
|
||||
Assert.Null(answer.EdgeBudget);
|
||||
var seen = Assert.Single(answer.PathBudgets);
|
||||
Assert.Equal(7, seen.Id);
|
||||
Assert.Equal("/login*", seen.Pattern);
|
||||
Assert.True(seen.Counted);
|
||||
Assert.Equal(3, seen.Count);
|
||||
Assert.True(seen.OverBudget);
|
||||
Assert.Contains("/login*", answer.Note);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_observe_budget_that_is_crossed_says_so_without_promising_a_refusal()
|
||||
{
|
||||
var rules = new RateRuleTracker();
|
||||
var policy = Policy(RateMode.Observe, limit: 1000);
|
||||
var rule = Rule(1, "/login*", 2);
|
||||
for (var i = 0; i < 3; i++) rules.Record(rule, "a", T0.AddSeconds(i));
|
||||
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, rule), "/login", "a",
|
||||
new RateTracker(), rules, T0.AddSeconds(3), true);
|
||||
|
||||
// "Over budget" and "would be refused" are two answers, and the mode is
|
||||
// what separates them. Collapsing them is how an observe budget becomes a
|
||||
// surprise the day someone switches it on.
|
||||
Assert.Equal(VolumePreview.VerdictOverBudgetNotEnforced, answer.Verdict);
|
||||
Assert.Contains("Observe mode enforces nothing", answer.Note);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_the_budgets_whose_pattern_matches_the_asked_path_are_answered()
|
||||
{
|
||||
var policy = Policy(limit: 1000);
|
||||
var answer = VolumePreview.For(policy,
|
||||
Snapshot(policy, Rule(1, "/login*", 2), Rule(2, "/api/*", 5)), "/login", "a",
|
||||
new RateTracker(), new RateRuleTracker(), T0, true);
|
||||
|
||||
var seen = Assert.Single(answer.PathBudgets);
|
||||
Assert.Equal("/login*", seen.Pattern);
|
||||
Assert.Equal(VolumePreview.VerdictWouldBeCounted, answer.Verdict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_budget_in_force_for_the_path_with_nothing_counted_yet_is_not_a_zero()
|
||||
{
|
||||
var policy = Policy(limit: 1000);
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, Rule(1, "/login*", 2)), "/login", "a",
|
||||
new RateTracker(), new RateRuleTracker(), T0, true);
|
||||
|
||||
var seen = Assert.Single(answer.PathBudgets);
|
||||
Assert.False(seen.Counted);
|
||||
Assert.Null(seen.Count);
|
||||
Assert.False(seen.OverBudget);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_request_an_earlier_pillar_answers_never_reaches_the_counter()
|
||||
{
|
||||
var rates = new RateTracker();
|
||||
var policy = Policy(limit: 2);
|
||||
rates.Record("a", policy, T0);
|
||||
rates.Record("a", policy, T0.AddSeconds(1));
|
||||
rates.Record("a", policy, T0.AddSeconds(2));
|
||||
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy), "/index", "a",
|
||||
rates, new RateRuleTracker(), T0.AddSeconds(3), reached: false);
|
||||
|
||||
Assert.False(answer.Reached);
|
||||
Assert.Contains("an earlier pillar answers this request", answer.Note);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Asking_the_preview_does_not_spend_the_budget_it_is_asking_about()
|
||||
{
|
||||
var rates = new RateTracker();
|
||||
var rules = new RateRuleTracker();
|
||||
var policy = Policy(limit: 2);
|
||||
var rule = Rule(1, "/login*", 2);
|
||||
rates.Record("a", policy, T0);
|
||||
rules.Record(rule, "a", T0);
|
||||
|
||||
var snapshot = Snapshot(policy, rule);
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var answer = VolumePreview.For(policy, snapshot, "/login", "a",
|
||||
rates, rules, T0.AddSeconds(1), true);
|
||||
Assert.Equal(1, answer.EdgeBudget!.Count);
|
||||
Assert.Equal(1, answer.PathBudgets[0].Count);
|
||||
}
|
||||
|
||||
// The next real request is the second of the window, not the sixth: a
|
||||
// preview that counted its own question would have refused it.
|
||||
Assert.Equal(2, rates.Record("a", policy, T0.AddSeconds(2)).Count);
|
||||
Assert.Equal(2, rules.Record(rule, "a", T0.AddSeconds(2)).Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_window_that_has_already_run_out_is_not_reported_as_a_running_budget()
|
||||
{
|
||||
var rates = new RateTracker();
|
||||
var rules = new RateRuleTracker();
|
||||
var policy = Policy(limit: 2, windowSeconds: 10);
|
||||
var rule = Rule(1, "/login*", 2, windowSeconds: 10);
|
||||
rates.Record("a", policy, T0);
|
||||
rules.Record(rule, "a", T0);
|
||||
|
||||
var answer = VolumePreview.For(policy, Snapshot(policy, rule), "/login", "a",
|
||||
rates, rules, T0.AddSeconds(30), true);
|
||||
|
||||
Assert.Null(answer.EdgeBudget);
|
||||
Assert.False(answer.PathBudgets[0].Counted);
|
||||
Assert.Equal(VolumePreview.VerdictWouldBeCounted, answer.Verdict);
|
||||
}
|
||||
}
|
||||
@@ -1727,6 +1727,33 @@ check 'removing the budget reopens the path, and the volume is left as it was' '
|
||||
"$EDGE/admin-api/policy" >/dev/null; \
|
||||
code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")"
|
||||
|
||||
# The dry run answers the volume pillar (OPEN-69), on the shipped image: the
|
||||
# preview used to answer every pillar and stay silent about the one whose number
|
||||
# the operator is choosing.
|
||||
echo '- the shipped dry run answers the volume pillar'
|
||||
DRY_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
|
||||
DRY_RULE_JSON='{"pattern":"/dryrun*","limitPerWindow":2,"windowSeconds":120}'
|
||||
DRY_IP=198.51.100.92
|
||||
admin -X PUT -H 'Content-Type: application/json' --data-binary "$DRY_ON_JSON" \
|
||||
"$EDGE/admin-api/policy" >/dev/null
|
||||
code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$DRY_RULE_JSON" "$EDGE/admin-api/rate-rules" >/dev/null
|
||||
check 'the shipped preview answers the volume pillar for a source with nothing counted' 'yes' \
|
||||
"$(admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" | python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["verdict"]=="would_be_counted" and v["edgeBudget"] is None and v["pathBudgets"][0]["counted"] is False else "no")')"
|
||||
for _ in 1 2 3; do code -H "X-Forwarded-For: $DRY_IP" "$EDGE/dryrun" >/dev/null; done
|
||||
check 'the shipped preview says this source is over that budget now' 'yes' \
|
||||
"$(admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" | python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];b=v["pathBudgets"][0];print("yes" if v["verdict"]=="refused_now" and b["count"]==3 and b["overBudget"] else "no")')"
|
||||
check 'six shipped previews leave the counters exactly where they were' '1 1' \
|
||||
"$(for _ in 1 2 3 4 5 6; do admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" >/dev/null; done; \
|
||||
admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])')"
|
||||
DRY_RULE_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
|
||||
check 'the scene cleans itself, so the volume is left as it was found' 'not_counted' \
|
||||
"$(admin -X DELETE "$EDGE/admin-api/rate-rules/$DRY_RULE_ID" >/dev/null; \
|
||||
admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \
|
||||
"$EDGE/admin-api/policy" >/dev/null; \
|
||||
admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)["volume"]["verdict"])')"
|
||||
|
||||
echo
|
||||
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
|
||||
@@ -529,6 +529,29 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||||
// first: otherwise the answer is the streak's 403 and the scene proves
|
||||
// nothing about the row it removed.
|
||||
await adminDelete('/admin-api/blocks?source=engine');
|
||||
|
||||
// The same question asked from the page (OPEN-69). The dry run answers the
|
||||
// volume pillar from the counters the checks above have already shown to be one
|
||||
// over budget — and asking it here is a read, so the counters still say the same
|
||||
// afterwards.
|
||||
await page.fill('#askIp', PATH_BUDGET_IP);
|
||||
await page.fill('#askPath', PATH_BUDGET_PATH);
|
||||
await page.click('#askDecide');
|
||||
await page.waitForFunction(() => /volume:/.test(document.getElementById('askanswer').textContent),
|
||||
null, { timeout: 15000 }).catch(() => {});
|
||||
const asked = (await page.textContent('#askanswer')).replace(/\s+/g, ' ');
|
||||
check('the page can ask what the edge would answer, and the volume pillar answers it',
|
||||
/volume: Enforce . refused_now/.test(asked) && /OVER/.test(asked), asked.slice(0, 240));
|
||||
const beforeRerender = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||||
await page.click('#refresh');
|
||||
await page.waitForFunction((pat) => {
|
||||
const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat);
|
||||
return !!tr && Number(tr.children[5].textContent) >= 1;
|
||||
}, `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {});
|
||||
const afterRerender = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||||
check('asking the dry run from the page did not move the counters',
|
||||
!!beforeRerender && !!afterRerender && beforeRerender.join('|') === afterRerender.join('|'),
|
||||
`${JSON.stringify(beforeRerender)} then ${JSON.stringify(afterRerender)}`);
|
||||
const countedRow = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||||
check('the page says who the budget counted and who is over it now',
|
||||
!!countedRow && Number(countedRow[3]) >= 1 && Number(countedRow[4]) >= 1 && Number(countedRow[5]) >= 1,
|
||||
|
||||
@@ -737,6 +737,68 @@ rm -f /tmp/openwaf-upstream/login.txt
|
||||
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
|
||||
|
||||
# The dry run answers the volume pillar (OPEN-69). The preview used to answer
|
||||
# every pillar and stay silent about the one whose number the operator is choosing;
|
||||
# the claim worth testing on the wire is that it answers it without spending it.
|
||||
echo '- the dry run answers the volume pillar'
|
||||
echo 'dry run' > /tmp/openwaf-upstream/dryrun.txt
|
||||
DRY_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
|
||||
DRY_RULE_JSON='{"pattern":"/dryrun*","limitPerWindow":2,"windowSeconds":120}'
|
||||
DRY_IP=192.0.2.88
|
||||
decide() { curl -s -H "X-Admin-Token: $TOKEN" \
|
||||
"http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$1&path=$2"; }
|
||||
check 'the volume switch is on for this scene' Enforce \
|
||||
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$DRY_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
|
||||
check 'a source with no running window is answered as nothing counted, not as zero of the limit' yes \
|
||||
"$(decide "$DRY_IP" /dryrun.txt \
|
||||
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["verdict"]=="would_be_counted" and v["edgeBudget"] is None and v["pathBudgets"]==[] else "no")')"
|
||||
check 'a written path budget appears in the preview for its path' 204 \
|
||||
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$DRY_RULE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
|
||||
check 'and it says so before it has counted anything for this source' yes \
|
||||
"$(decide "$DRY_IP" /dryrun.txt \
|
||||
| python3 -c 'import sys,json;b=json.load(sys.stdin)["volume"]["pathBudgets"][0];print("yes" if b["pattern"]=="/dryrun*" and not b["counted"] and b["count"] is None else "no")')"
|
||||
check 'the first two requests on that path are proxied' '200 200' \
|
||||
"$(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)") $(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)")"
|
||||
check 'the third crosses the budget' 429 \
|
||||
"$(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)")"
|
||||
check 'the preview now says this source is over that budget' yes \
|
||||
"$(decide "$DRY_IP" /dryrun.txt \
|
||||
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];b=v["pathBudgets"][0];print("yes" if v["verdict"]=="refused_now" and b["count"]==3 and b["overBudget"] and b["secondsLeft"]>=1 else "no")')"
|
||||
check 'a path the budget does not name is answered without it' yes \
|
||||
"$(decide "$DRY_IP" /wp-admin \
|
||||
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["pathBudgets"]==[] and v["verdict"]=="would_be_counted" else "no")')"
|
||||
# The counters of the listing are the same counters the preview reads, so the pair
|
||||
# is compared before and after: a preview that answered by counting its own
|
||||
# question would move them, and the next real request would be refused because
|
||||
# somebody pressed a button.
|
||||
BUDGET_COUNTERS='import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])'
|
||||
check 'the listing says one source is over that budget' '1 1' \
|
||||
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
|
||||
| python3 -c "$BUDGET_COUNTERS")"
|
||||
check 'six previews leave those counters exactly where they were' '1 1' \
|
||||
"$(for _ in 1 2 3 4 5 6; do decide "$DRY_IP" /dryrun.txt >/dev/null; done; \
|
||||
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
|
||||
| python3 -c "$BUDGET_COUNTERS")"
|
||||
check 'the pillar row that used to be a silence names the volume section' yes \
|
||||
"$(decide "$DRY_IP" /dryrun.txt \
|
||||
| python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if any("volume" in (p.get("note") or "") for p in d["pillars"] if p["pillar"]=="rate") else "no")')"
|
||||
check 'with the pillar off the preview says nothing is counted' yes \
|
||||
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
|
||||
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null; \
|
||||
decide "$DRY_IP" /dryrun.txt \
|
||||
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["verdict"]=="not_counted" and v["edgeBudget"] is None else "no")')"
|
||||
DRY_RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
|
||||
check 'the scene cleans itself, so the rest of the gate runs on the stack it expects' 0 \
|
||||
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
|
||||
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$DRY_RULE_ID" >/dev/null; \
|
||||
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
|
||||
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
|
||||
rm -f /tmp/openwaf-upstream/dryrun.txt
|
||||
|
||||
echo '- admin surface'
|
||||
check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
|
||||
check 'the policy is readable' Enforce \
|
||||
|
||||
Reference in New Issue
Block a user