Files
Pavlo Ratushnyi 6a65cbf344 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.
2026-10-05 09:14:09 +02:00

170 lines
7.7 KiB
C#

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);