an operator can ask what the edge would answer, before it answers anyone

OPEN-59. Every other admin surface answers what the edge already did, so the only test for a path rule, an exemption or a country rule is a real visitor getting the real refusal. GET /admin-api/decide?ip=&path=&country= runs the same DecisionEngine over the same snapshot the wire reads — there is no second decision to drift — and narrates the order.

The trace is the product: a verdict says what would happen, the pillar list says which pillar to change, and it keeps four silences apart (did_not_match, not_reached, not_enforced_in_this_mode, not_evaluated). In Observe mode the engine line says whether a live ban for that source exists, because 'nothing was known about this address' and 'something was known and the mode chose not to act' are the two answers operators read as one. What a preview cannot honestly answer — the live rate counter and a streak that depends on responses the upstream has not produced — is named in the body rather than left out.

Three things the run caught. IPAddress.TryParse accepts abbreviated IPv4, so '203.0.113' parses as 203.0.113.0 and a missing octet was answered 'pass' for an address the operator did not mean; the guard now requires a full dotted quad. The preview read state.Current while the guard calls GetOrRefresh(), so it could answer from a snapshot the wire had already replaced — the whole claim of the feature is that the two agree. And a Pass carries no source key, so the Observe note claimed 'no live ban' for a source that had one; the key is now computed for the question rather than read off the answer.

Gates on this tree: build 0 warnings / 0 errors, unit 256/256, integration 245/245, smoke 65/0, compose 229/0 against the built image (261 MB), console 90/0.
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 01:36:29 +02:00
parent 892cec172f
commit 575ef88afe
9 changed files with 877 additions and 19 deletions
+53 -6
View File
@@ -389,6 +389,8 @@ GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=fals
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
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
```
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
@@ -756,6 +758,51 @@ absolute http(s) URL or a 400, and the decision point ignores a target it cannot
send and answers the block's own default instead, for a row that arrived by a
restored backup or a hand edit.
### Asking what the edge would answer, before it answers anyone
`GET /admin-api/decide?ip=&path=&country=` runs the same `DecisionEngine` over
the same snapshot the wire reads and answers the question every other admin
surface cannot: what would happen to this request. Writing a path rule, an
exemption or a country rule currently has one test — a real visitor getting the
real refusal — and `Observe` mode is no help, because it switches the engine off
for everything rather than answering one named request.
```
GET /admin-api/decide?ip=203.0.113.7&path=/wp-admin
{ "verdict": "block_rule", "blocked": true, "status": 403,
"rule": { "id": 12, "pattern": "/wp-admin*", "action": "block", "note": "scan" },
"pillars": [
{ "pillar": "alwaysPass", "outcome": "did_not_match" },
{ "pillar": "allowlist", "outcome": "did_not_match" },
{ "pillar": "requestRule", "outcome": "answered", "note": "a request rule blocked this path (rule_12)" },
{ "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" } ] }
```
The `pillars` list is the point. A verdict says what would happen; the trace says
**which pillar to change**, and it keeps the three silences apart — `did_not_match`
(asked, said no), `not_reached` (never asked, because an earlier pillar spoke),
`not_enforced_in_this_mode` (this configuration does not run it) and
`not_evaluated` (this question could not ask it). In `Observe` mode the engine line
goes further and says whether a live ban for that source exists, because "nothing
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
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.
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
`203.0.113.0`, which is exactly the typo that would otherwise be answered `pass`.
### The numbers leave the edge in Prometheus format
`GET /metrics` answers the counters `/admin-api/state` shows a human, in the
@@ -993,9 +1040,9 @@ 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
schema upgrade on it: build 0 warnings / 0 errors, unit **250/250**, integration
**236/236 in 32 s**, console **90 assertions, 0 failed**, smoke **passed 60,
failed 0**, and compose **223 passed, 0 failed** against the built image at
schema upgrade on it: build 0 warnings / 0 errors, unit **256/256**, integration
**245/245 in 19 s**, console **90 assertions, 0 failed**, smoke **passed 65,
failed 0**, and compose **229 passed, 0 failed** against the built image at
261 MB. 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
@@ -1236,10 +1283,10 @@ dotnet/
OpenWaf.Domain/ pure decision core: source key, streak, ordered decision, refusal page
OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo, in-place schema upgrade
OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode
OpenWaf.Tests.Unit/ 250 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters
OpenWaf.Tests.Integration/ 236 tests driving the real pipeline against a fake upstream
OpenWaf.Tests.Unit/ 256 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters
OpenWaf.Tests.Integration/ 245 tests driving the real pipeline against a fake upstream
scripts/smoke.sh 52 assertions against a running edge + a real upstream
scripts/compose-smoke.sh 223 assertions against the built image (compose + nginx)
scripts/compose-smoke.sh 229 assertions against the built image (compose + nginx)
scripts/console-check.cjs 90 assertions against the page, in a real Chromium
scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2)
.github/workflows/ci.yml runs the gates on every push
@@ -0,0 +1,197 @@
using OpenWaf.Domain.Policy;
namespace OpenWaf.Domain.Engine;
/// <summary>What one pillar of the ordered decision did, in the answer an
/// operator reads. The distinction between the last three is the whole point of
/// the type: "this pillar did not match" and "this pillar was never asked" are
/// different facts, and an operator deciding whether to add a rule needs to know
/// which one they are looking at.</summary>
public enum PillarOutcome
{
Answered,
DidNotMatch,
NotReached,
/// <summary>The pillar exists but this configuration does not run it —
/// an engine ban in Observe mode, a geo policy switched off.</summary>
NotEnforcedInThisMode,
/// <summary>The pillar could not be asked at all: no address was given, or
/// the answer depends on state this call must not touch.</summary>
NotEvaluated
}
/// <summary>One line of the trace.</summary>
public sealed record PillarTrace(string Pillar, PillarOutcome Outcome, string? Note = null);
/// <summary>The outcome in the spelling the surface uses: lower-case and
/// underscored, the way the verdicts are spelled in the log and in the metrics,
/// so one word means one thing wherever an operator meets it.</summary>
public static class PillarOutcomes
{
public static string Label(PillarOutcome outcome) => outcome switch
{
PillarOutcome.Answered => "answered",
PillarOutcome.DidNotMatch => "did_not_match",
PillarOutcome.NotReached => "not_reached",
PillarOutcome.NotEnforcedInThisMode => "not_enforced_in_this_mode",
PillarOutcome.NotEvaluated => "not_evaluated",
_ => outcome.ToString().ToLowerInvariant()
};
}
/// <summary>
/// The ordered decision, narrated (OPEN-59).
///
/// <see cref="DecisionEngine.Decide"/> returns one value, which is what the
/// response path needs and nothing like what an operator needs. The order of the
/// pillars is a documented property of the design — an allowlist outranks a
/// block, a path rule outranks a source list, an always-pass prefix outranks
/// everything — and the only way to show it is to say, pillar by pillar, what
/// each one got asked and what it said.
///
/// This is a pure function over the same snapshot and the same decision, so it
/// cannot disagree with the wire: it does not re-run any matching. It reads the
/// verdict and the order, and it is allowed exactly one extra question — whether
/// a live engine ban exists for a source the mode refused to enforce — because
/// that is the difference between "nothing was known about this address" and
/// "something was known and this mode chose not to act on it".
/// </summary>
public static class DecisionTrace
{
/// <summary>The pillars in the order the decision runs them. The rate pillar
/// is last because the guard runs it last, after everything that may already
/// have answered.</summary>
public static readonly string[] Pillars =
["alwaysPass", "allowlist", "requestRule", "operatorBlock", "engineBan", "geo", "rate"];
public static IReadOnlyList<PillarTrace> For(
EdgeSnapshot snapshot, EdgeDecision decision, DateTimeOffset now,
bool hasAddress, bool hasCountry, string? sourceKey = null)
{
var answered = decision.Verdict switch
{
EdgeVerdict.PassBypassed => "alwaysPass",
EdgeVerdict.PassAllowlisted => "allowlist",
EdgeVerdict.BlockRule or EdgeVerdict.PassRuleObserved => "requestRule",
EdgeVerdict.BlockOperator => "operatorBlock",
EdgeVerdict.BlockEngine => "engineBan",
EdgeVerdict.GeoReject => "geo",
EdgeVerdict.BlockRate => "rate",
_ => null
};
var order = Pillars;
var answeredAt = answered is null ? order.Length : Array.IndexOf(order, answered);
var rows = new List<PillarTrace>(order.Length);
for (var i = 0; i < order.Length; i++)
{
var name = order[i];
if (i == answeredAt)
{
rows.Add(new PillarTrace(name, PillarOutcome.Answered, NoteFor(decision)));
continue;
}
// Before the pillar that answered: it was asked and it said no —
// unless this configuration or this question meant it was never
// asked at all, which is a different answer and the operator has to
// be able to tell them apart.
if (i < answeredAt && WasAsked(name, snapshot.Policy, hasAddress, hasCountry))
{
rows.Add(new PillarTrace(name, PillarOutcome.DidNotMatch));
continue;
}
var outcome = Unasked(name, snapshot.Policy, hasAddress, hasCountry);
// A silent line carries its reason. "engineBan: not_evaluated" without
// "because no address was given" is the same half-answer the bare
// verdict was.
rows.Add(new PillarTrace(name, outcome,
outcome == PillarOutcome.NotReached
? null
: NoteForUnasked(name, snapshot, sourceKey, hasAddress, hasCountry, now)));
}
return rows;
}
/// <summary>Whether this pillar was given the question at all. Each false is
/// a property of the design, not of this request: the source pillars need an
/// address because they are claims about a source; the engine pillar is
/// skipped entirely outside Enforce mode; the geo pillar needs a country,
/// which it may not have even when the pillar is on.</summary>
private static bool WasAsked(string name, EdgePolicy policy, bool hasAddress, bool hasCountry) => name switch
{
"operatorBlock" => hasAddress,
"engineBan" => hasAddress && policy.Mode == EnforcementMode.Enforce,
"geo" => policy.Geo != GeoMode.Off && hasCountry,
"rate" => false,
_ => true
};
/// <summary>Why a pillar did not speak, when it did not answer.</summary>
private static PillarOutcome Unasked(string name, EdgePolicy policy, bool hasAddress, bool hasCountry)
=> name switch
{
"operatorBlock" when !hasAddress => PillarOutcome.NotEvaluated,
"engineBan" when !hasAddress => PillarOutcome.NotEvaluated,
"engineBan" when policy.Mode != EnforcementMode.Enforce => PillarOutcome.NotEnforcedInThisMode,
"geo" when policy.Geo == GeoMode.Off => PillarOutcome.NotEnforcedInThisMode,
"geo" when !hasCountry => PillarOutcome.NotEvaluated,
// A preview never spends the live counter, whatever the mode.
"rate" => PillarOutcome.NotEvaluated,
_ => PillarOutcome.NotReached
};
/// <summary>The note that goes on the answering line. Short on purpose — the
/// full evidence (rule pattern, block reason, expiry) is in the response
/// beside the trace, not repeated inside it.</summary>
private static string? NoteFor(EdgeDecision decision) => decision.Verdict switch
{
EdgeVerdict.PassAllowlisted => string.IsNullOrWhiteSpace(decision.Reason)
? "an allow entry matched this address"
: $"an allow entry matched this address: {decision.Reason}",
EdgeVerdict.BlockRule => $"a request rule blocked this path ({decision.Reason})",
EdgeVerdict.PassRuleObserved => $"a request rule matched and is set to observe ({decision.Reason})",
EdgeVerdict.BlockOperator => "the operator's own list",
EdgeVerdict.BlockEngine => "a ban this edge wrote from the responses this source produced",
EdgeVerdict.GeoReject => decision.Reason,
EdgeVerdict.BlockRate => "over the request budget",
EdgeVerdict.PassBypassed => "the path is an always-pass prefix",
_ => null
};
/// <summary>The note a silent line carries. This is the one place the trace
/// asks a second question of the snapshot: in Observe mode an engine ban
/// exists and does not act, and an operator has to be able to tell that apart
/// from there being nothing to act on.</summary>
public static string? NoteForUnasked(
string name, EdgeSnapshot snapshot, string? sourceKey, bool hasAddress, bool hasCountry, DateTimeOffset now)
{
var policy = snapshot.Policy;
switch (name)
{
case "engineBan" when !hasAddress:
case "operatorBlock" when !hasAddress:
case "geo" when policy.Geo != GeoMode.Off && !hasCountry:
return name == "geo"
? "the geo pillar is on and no country is known for this address"
: "no address was given, and this pillar is a claim about a source";
case "engineBan" when policy.Mode != EnforcementMode.Enforce:
var live = sourceKey is not null && snapshot.EngineBans.TryGetValue(sourceKey, out var ban)
&& ban.IsLive(now);
return live
? "a live engine ban exists for this source and Observe mode does not enforce it"
: "Observe mode does not enforce engine bans";
case "geo" when policy.Geo == GeoMode.Off:
return "the geo pillar is off";
case "rate":
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";
default:
return null;
}
}
}
@@ -28,3 +28,24 @@ public enum EdgeVerdict
/// refuse a request, and it deserves a name in the log for that.</summary>
BlockRate = 8
}
/// <summary>The verdict in the spelling every surface uses — the log, the metrics
/// label, and the decision preview (OPEN-59). One mapping, because the same word
/// has to mean the same thing in an alert rule and in a grepped line, and
/// <c>ToString()</c> on the enum answers "blockrule", which is neither.</summary>
public static class EdgeVerdictLabel
{
public static string For(EdgeVerdict verdict) => verdict switch
{
EdgeVerdict.Pass => "pass",
EdgeVerdict.PassAllowlisted => "pass_allowlisted",
EdgeVerdict.PassBypassed => "pass_bypassed",
EdgeVerdict.PassRuleObserved => "pass_rule_observed",
EdgeVerdict.BlockOperator => "block_operator",
EdgeVerdict.BlockEngine => "block_engine",
EdgeVerdict.BlockRule => "block_rule",
EdgeVerdict.GeoReject => "geo_reject",
EdgeVerdict.BlockRate => "block_rate",
_ => "unknown"
};
}
+139
View File
@@ -573,6 +573,130 @@ internal static class AdminEndpoints
});
});
// OPEN-59: the dry run. Every other surface here answers what the edge
// already did; an operator about to write a rule, an exemption or a
// country rule has no way to ask what a request WOULD get, so the only
// test is a real request from a real address and a mistake is a real
// refusal of a real visitor. This runs the same DecisionEngine over the
// same snapshot the wire reads — there is no second decision to drift —
// and narrates the order, because "blocked" without "which pillar said
// so and which never got asked" is the half an operator cannot act on.
//
// It changes nothing: no counter, no streak, no rate window, no alert.
// The two pillars a preview cannot honestly answer — the live budget and
// the streak that depends on responses the upstream has not produced —
// 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) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "path", "country"))
return Results.BadRequest(new { error = unknown });
if (ip is not null && string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new { error = "ip must not be blank; omit the parameter to ask about the path alone" });
// A typo in the address must not answer "pass". The guard would have
// had a real address; this call has whatever was typed, and the only
// honest response to a non-address is a refusal naming it.
if (ip is not null && !IsAnAddress(ip.Trim()))
return Results.BadRequest(new { error = $"ip must be an address; got \"{ip}\"" });
var askedPath = string.IsNullOrWhiteSpace(path) ? "/" : path!.Trim();
if (!askedPath.StartsWith('/'))
return Results.BadRequest(new { error = $"path must start with /; got \"{askedPath}\"" });
var now = DateTimeOffset.UtcNow;
// The same call the guard makes, not the raw field: a preview that
// read a stale snapshot would answer a request the wire is no longer
// answering, and the whole claim of the feature is that the two
// agree.
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
var hasAddress = !string.IsNullOrWhiteSpace(ip);
// The country is part of the question. Given, it is used as given;
// otherwise the geo pillar is asked the same way the guard asks it,
// and the answer says which of the two happened — a preview that
// silently skipped the lookup would answer a different request.
string? askedCountry = null;
var countrySource = "none";
if (!string.IsNullOrWhiteSpace(country))
{
askedCountry = country.Trim().ToUpperInvariant();
countrySource = "given";
}
else if (policy.Geo != GeoMode.Off && hasAddress)
{
askedCountry = geo.Lookup(ip);
if (askedCountry is not null) countrySource = "geo-database";
}
var decision = DecisionEngine.Decide(snapshot, hasAddress ? ip!.Trim() : null, askedPath, now, askedCountry);
// The key this edge would use for the address — computed here rather
// than read off the decision, because a Pass carries no source key and
// the trace still has to be able to say whether a live ban exists for
// this source.
var askedKey = hasAddress ? SourceKey.For(ip!.Trim(), policy) : null;
var rows = DecisionTrace.For(
snapshot, decision, now, hasAddress, askedCountry is not null, askedKey);
RequestRule? matchedRule = null;
if (decision.Reason is { Length: > 5 } reason && reason.StartsWith("rule_", StringComparison.Ordinal)
&& long.TryParse(reason[5..], out var ruleId))
matchedRule = snapshot.RequestRules.FirstOrDefault(r => r.Id == ruleId);
return Results.Ok(new
{
// The question, echoed exactly, so the answer cannot be read as
// being about something else.
path = askedPath,
ip = hasAddress ? ip!.Trim() : null,
sourceKey = string.IsNullOrEmpty(askedKey) ? null : askedKey,
country = askedCountry,
countrySource,
// The answer, in the words the wire uses: the same verdict value
// the log prints and the status the visitor gets.
verdict = EdgeVerdictLabel.For(decision.Verdict),
blocked = decision.IsBlocked,
status = decision.StatusCode,
location = decision.Location,
reason = decision.Reason,
expiresAt = decision.ExpiresAt,
// The evidence behind the verdict, not just its name. An id
// without the pattern is a number; a reason without the expiry is
// a sentence with no end.
rule = matchedRule is null ? null : new
{
id = matchedRule.Id,
pattern = matchedRule.Pattern,
action = matchedRule.Action.ToString().ToLowerInvariant(),
note = matchedRule.Note,
expiresAt = matchedRule.ExpiresAt
},
// 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.
pillars = rows.Select(t => new
{
pillar = t.Pillar,
outcome = PillarOutcomes.Label(t.Outcome),
note = t.Note
}),
notEvaluated = rows
.Where(t => t.Outcome is PillarOutcome.NotEvaluated or PillarOutcome.NotEnforcedInThisMode)
.Select(t => t.Pillar),
// Which state this was computed against. A preview is a claim
// about the snapshot, not a guarantee about the next request: a
// block written a second ago lands when the snapshot refreshes.
mode = policy.Mode.ToString(),
geoMode = policy.Geo.ToString(),
rateMode = policy.Rate.ToString(),
snapshotAgeSeconds = Math.Round((now - snapshot.GeneratedAt).TotalSeconds, 1),
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
snapshotStale = state.IsStale
});
});
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, HttpContext ctx) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
@@ -781,6 +905,21 @@ internal static class AdminEndpoints
/// implemented. A refusal that lists the truth for the endpoint is only true
/// if the guard knows the truth for the endpoint.
/// </summary>
/// <summary>Is this string an address, or a typo shaped like one?
///
/// <see cref="System.Net.IPAddress.TryParse"/> alone is not enough: it accepts
/// abbreviated IPv4, so "203.0.113" parses as 203.0.113.0. On a preview that
/// is the exact failure this guard exists to catch — an operator missing one
/// octet gets "pass" for an address that is not the one they meant, and the
/// whole value of the surface is that its answer is about a named request.
/// </summary>
private static bool IsAnAddress(string value)
{
if (!System.Net.IPAddress.TryParse(value, out var parsed)) return false;
if (parsed.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) return true;
return value.Split('.').Length == 4;
}
private static bool TryKnownQuery(HttpContext ctx, out string? error, params string[] allowed)
{
// `token` is not a handler parameter — the admin auth layer reads it out
@@ -37,19 +37,7 @@ public sealed class EdgeCounterLedger
/// <summary>The label the exposition gives this verdict. Lower-case,
/// snake_case, and spelled the way the log spells it, so the same word
/// appears in the alert and in the line an operator greps for.</summary>
public static string LabelFor(EdgeVerdict verdict) => verdict switch
{
EdgeVerdict.Pass => "pass",
EdgeVerdict.PassAllowlisted => "pass_allowlisted",
EdgeVerdict.PassBypassed => "pass_bypassed",
EdgeVerdict.PassRuleObserved => "pass_rule_observed",
EdgeVerdict.BlockOperator => "block_operator",
EdgeVerdict.BlockEngine => "block_engine",
EdgeVerdict.BlockRule => "block_rule",
EdgeVerdict.GeoReject => "geo_reject",
EdgeVerdict.BlockRate => "block_rate",
_ => "unknown"
};
public static string LabelFor(EdgeVerdict verdict) => EdgeVerdictLabel.For(verdict);
/// <summary>Every verdict the edge can answer with, in label form. The
/// exposition emits all of them, including the zeros: a counter that is
@@ -0,0 +1,294 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// Asking the edge what it would answer, before it answers anyone (OPEN-59).
///
/// The feature exists because the only way to test a rule today is to let a real
/// visitor be refused by it. So these tests hold the two properties that make a
/// preview worth having rather than merely convenient:
///
/// It must be the <b>same decision</b>. A preview implemented a second time
/// drifts from the wire, and an operator acts on the drift. The tests compare the
/// preview against the status the same source actually gets.
///
/// It must <b>change nothing</b>. A dry run that spends a request budget, matures
/// a streak or writes an alert is a real request wearing a label, and the
/// operator's test of a rule would itself be traffic the defence counts.
/// </summary>
public sealed class DecisionPreviewTests
{
private const string Source = "203.0.113.140";
private static async Task<(HttpStatusCode Status, JsonElement Body)> DecideAsync(
EdgeFixture f, string query, string? ip = Source)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/decide?{query}");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
if (ip is not null) request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
using var r = await f.Client.SendAsync(request);
return (r.StatusCode, JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement);
}
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 async Task WaitForBanAsync(EdgeFixture f)
{
for (var i = 0; i < 40; i++)
{
using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine");
if ((await blocks.Content.ReadAsStringAsync()).Contains(Source)) return;
await Task.Delay(250);
}
}
private static async Task BanAsync(EdgeFixture f)
{
for (var i = 0; i < 3; i++)
{
using var probe = new HttpRequestMessage(HttpMethod.Get, "/wp-admin");
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Source);
using var r = await f.Client.SendAsync(probe);
}
await WaitForBanAsync(f);
}
private static string Outcome(JsonElement pillars, string pillar)
=> pillars.GetProperty(pillar).GetProperty("outcome").GetString()!;
/// <summary>The trace is keyed by pillar name so an assertion says which
/// pillar it means, rather than depending on the position of an array
/// element — the order is the thing under test, and an assertion that reads
/// it by index would pass when the order changed.</summary>
private static JsonElement ByName(JsonElement pillars)
{
var map = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
foreach (var row in pillars.EnumerateArray()) map[row.GetProperty("pillar").GetString()!] = row;
return JsonSerializer.SerializeToElement(map);
}
[Fact]
public async Task A_path_rule_is_answered_before_the_source_pillars_are_ever_asked()
{
await using var f = new EdgeFixture();
using (var rule = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules",
new { pattern = "/preview-check*", action = "block", note = "written for this test" }))
{
Assert.True(rule.IsSuccessStatusCode, await rule.Content.ReadAsStringAsync());
}
var (status, body) = await DecideAsync(f, "path=/preview-check&ip=203.0.113.140");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal("block_rule", body.GetProperty("verdict").GetString());
Assert.True(body.GetProperty("blocked").GetBoolean());
Assert.Equal(403, body.GetProperty("status").GetInt32());
Assert.Equal("/preview-check*", body.GetProperty("rule").GetProperty("pattern").GetString());
Assert.Equal("written for this test", body.GetProperty("rule").GetProperty("note").GetString());
var pillars = ByName(body.GetProperty("pillars"));
Assert.Equal("did_not_match", Outcome(pillars, "alwaysPass"));
Assert.Equal("did_not_match", Outcome(pillars, "allowlist"));
Assert.Equal("answered", Outcome(pillars, "requestRule"));
// The part a verdict alone cannot say: these pillars were never asked,
// so adding a block for this address would not change this answer.
Assert.Equal("not_reached", Outcome(pillars, "operatorBlock"));
Assert.Equal("not_reached", Outcome(pillars, "engineBan"));
Assert.Equal("not_evaluated", Outcome(pillars, "rate"));
// The two pillars a preview cannot honestly answer are named, not absent.
Assert.Contains("rate", body.GetProperty("notEvaluated").EnumerateArray().Select(e => e.GetString()));
Assert.Contains("preview", pillars.GetProperty("rate").GetProperty("note").GetString());
}
[Fact]
public async Task The_preview_and_the_wire_give_the_same_answer_for_the_same_source()
{
await using var f = new EdgeFixture();
await BanAsync(f);
var (status, body) = await DecideAsync(f, $"path=/anything&ip={Source}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal("block_engine", body.GetProperty("verdict").GetString());
Assert.Equal(403, body.GetProperty("status").GetInt32());
Assert.False(body.GetProperty("expiresAt").ValueKind is JsonValueKind.Null);
Assert.Equal(Source, body.GetProperty("sourceKey").GetString());
using var real = new HttpRequestMessage(HttpMethod.Get, "/anything");
real.Headers.TryAddWithoutValidation("X-Forwarded-For", Source);
using var realResponse = await f.Client.SendAsync(real);
Assert.Equal((int)body.GetProperty("status").GetInt32(), (int)realResponse.StatusCode);
}
[Fact]
public async Task Observe_mode_says_a_live_ban_exists_and_that_the_mode_does_not_act_on_it()
{
await using var f = new EdgeFixture();
await BanAsync(f);
using (var observe = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { mode = "Observe" }))
{
Assert.True(observe.IsSuccessStatusCode, await observe.Content.ReadAsStringAsync());
}
for (var i = 0; i < 20; i++)
{
var (_, probe) = await DecideAsync(f, $"path=/anything&ip={Source}");
if (probe.GetProperty("verdict").GetString() == "pass") break;
await Task.Delay(250);
}
var (_, body) = await DecideAsync(f, $"path=/anything&ip={Source}");
Assert.Equal("pass", body.GetProperty("verdict").GetString());
Assert.False(body.GetProperty("blocked").GetBoolean());
var pillars = ByName(body.GetProperty("pillars"));
var engine = pillars.GetProperty("engineBan");
Assert.Equal("not_enforced_in_this_mode", engine.GetProperty("outcome").GetString());
// The distinction the operator needs: not "nothing was known about this
// address", but "something was known and this mode chose not to act".
Assert.Contains("a live engine ban exists", engine.GetProperty("note").GetString());
}
[Fact]
public async Task An_allow_entry_outranks_a_live_operator_block_and_says_which_entry_spoke()
{
await using var f = new EdgeFixture();
using (var block = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "blocked first" }))
{
Assert.True(block.IsSuccessStatusCode, await block.Content.ReadAsStringAsync());
}
using (var allow = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
new { match = $"{Source}/32", note = "the office" }))
{
Assert.True(allow.IsSuccessStatusCode, await allow.Content.ReadAsStringAsync());
}
var (_, body) = await DecideAsync(f, $"path=/anything&ip={Source}");
Assert.Equal("pass_allowlisted", body.GetProperty("verdict").GetString());
var pillars = ByName(body.GetProperty("pillars"));
Assert.Equal("answered", Outcome(pillars, "allowlist"));
Assert.Contains("the office", pillars.GetProperty("allowlist").GetProperty("note").GetString());
// The block is still there and still live; it simply never got asked.
Assert.Equal("not_reached", Outcome(pillars, "operatorBlock"));
}
[Fact]
public async Task A_given_country_is_used_as_given_and_a_denied_one_is_refused_with_451()
{
await using var f = new EdgeFixture(geo: "DenyList");
using (var deny = await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/DE?allowed=false"))
{
Assert.True(deny.IsSuccessStatusCode, await deny.Content.ReadAsStringAsync());
}
var (_, denied) = await DecideAsync(f, $"path=/anything&ip={Source}&country=DE");
Assert.Equal("geo_reject", denied.GetProperty("verdict").GetString());
Assert.Equal(451, denied.GetProperty("status").GetInt32());
Assert.Equal("given", denied.GetProperty("countrySource").GetString());
Assert.Equal("DE", denied.GetProperty("country").GetString());
var (_, allowed) = await DecideAsync(f, $"path=/anything&ip={Source}&country=FR");
Assert.Equal("pass", allowed.GetProperty("verdict").GetString());
}
[Fact]
public async Task A_preview_changes_nothing_the_defence_counts()
{
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 600);
// The guard's own count of this preview request is pass_bypassed and is
// deliberately excluded: the assertion is that the preview did not touch
// the traffic counters, and the admin request carrying it is traffic the
// edge answered like any other.
static long Guarded(OpenWaf.Edge.Observability.EdgeCounterLedger ledger)
{
var counts = ledger.Snapshot();
long total = 0;
for (var i = 0; i < counts.Length; i++)
if (i != (int)OpenWaf.Domain.Engine.EdgeVerdict.PassBypassed) total += counts[i];
return total;
}
string Counters()
{
var metrics = f.Service<OpenWaf.Edge.Observability.EdgeCounterLedger>();
var rates = f.Service<OpenWaf.Domain.Engine.RateTracker>();
var streaks = f.Service<OpenWaf.Domain.Engine.IStreakTracker>();
return $"{Guarded(metrics)}|{rates.TrackedCount}|{streaks.TrackedCount}";
}
// One request through the wire first, so the counters are non-zero and a
// "nothing changed" assertion cannot be satisfied by nothing having
// happened at all.
using (var probe = new HttpRequestMessage(HttpMethod.Get, "/anything"))
{
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Source);
using var r = await f.Client.SendAsync(probe);
}
var before = Counters();
for (var i = 0; i < 5; i++) _ = await DecideAsync(f, $"path=/anything&ip={Source}");
Assert.Equal(before, Counters());
// And the budget the preview declined to spend is still whole: two more
// real requests are still inside a budget of two, which is the number the
// preview would have broken had it counted.
using var second = new HttpRequestMessage(HttpMethod.Get, "/anything");
second.Headers.TryAddWithoutValidation("X-Forwarded-For", Source);
using var secondResponse = await f.Client.SendAsync(second);
// 404 is the upstream's own answer, and reaching it is the point: the
// budget of two still has room, which is what the preview declined to
// spend. A 429 here would mean the previews counted.
Assert.NotEqual(HttpStatusCode.TooManyRequests, secondResponse.StatusCode);
}
[Fact]
public async Task A_typo_in_the_address_is_refused_rather_than_answered_with_pass()
{
await using var f = new EdgeFixture();
var (status, body) = await DecideAsync(f, "path=/anything&ip=203.0.113");
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("must be an address", body.GetProperty("error").GetString());
Assert.Contains("203.0.113", body.GetProperty("error").GetString());
}
[Fact]
public async Task A_parameter_this_surface_never_read_is_refused_before_it_is_ignored()
{
await using var f = new EdgeFixture();
var (status, body) = await DecideAsync(f, "path=/anything&source=engine");
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("source", body.GetProperty("error").GetString());
}
[Fact]
public async Task Asking_about_a_path_alone_names_the_source_pillars_as_never_asked()
{
await using var f = new EdgeFixture();
var (_, body) = await DecideAsync(f, "path=/anything", ip: null);
Assert.Equal("pass", body.GetProperty("verdict").GetString());
Assert.True(body.GetProperty("sourceKey").ValueKind is JsonValueKind.Null);
var pillars = ByName(body.GetProperty("pillars"));
foreach (var pillar in new[] { "operatorBlock", "engineBan" })
{
Assert.Equal("not_evaluated", Outcome(pillars, pillar));
Assert.Contains("no address was given", pillars.GetProperty(pillar).GetProperty("note").GetString());
}
// The geo pillar gets the more specific truth: it is off in this
// configuration, which is a different fact from "no address was given".
Assert.Equal("not_enforced_in_this_mode", Outcome(pillars, "geo"));
Assert.Contains("the geo pillar is off", pillars.GetProperty("geo").GetProperty("note").GetString());
// And the path pillars were asked, because they need no address.
Assert.Equal("did_not_match", Outcome(pillars, "requestRule"));
}
}
@@ -0,0 +1,132 @@
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The narrated order (OPEN-59). The decision itself is covered by
/// <see cref="DecisionEngineTests"/>; what is covered here is the answer an
/// operator is given about that decision, and the two ways it can lie: calling a
/// pillar that was never asked a pillar that said no, and calling a pillar this
/// configuration does not run a pillar that was asked and agreed.
/// </summary>
public sealed class DecisionTraceTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 5, 12, 0, 0, TimeSpan.Zero);
private static EdgeSnapshot Snapshot(
EdgePolicy? policy = null,
Dictionary<string, BlockEntry>? bans = null) => new()
{
GeneratedAt = Now,
Policy = policy ?? EdgePolicy.Default,
EngineBans = bans ?? new Dictionary<string, BlockEntry>(StringComparer.Ordinal)
};
private static string OutcomeOf(IReadOnlyList<PillarTrace> rows, string pillar)
=> PillarOutcomes.Label(rows.First(r => r.Pillar == pillar).Outcome);
private static string? NoteOf(IReadOnlyList<PillarTrace> rows, string pillar)
=> rows.First(r => r.Pillar == pillar).Note;
[Fact]
public void A_pass_with_no_address_names_the_source_pillars_as_never_asked()
{
var rows = DecisionTrace.For(Snapshot(), EdgeDecision.Pass, Now, hasAddress: false, hasCountry: false);
Assert.Equal(DecisionTrace.Pillars.Length, rows.Count);
foreach (var pillar in new[] { "alwaysPass", "allowlist", "requestRule" })
Assert.Equal("did_not_match", OutcomeOf(rows, pillar));
foreach (var pillar in new[] { "operatorBlock", "engineBan" })
{
Assert.Equal("not_evaluated", OutcomeOf(rows, pillar));
Assert.Contains("no address was given", NoteOf(rows, pillar)!);
}
// The geo pillar gets the more specific truth in this configuration: it is
// off, which is a different fact from the missing address.
Assert.Equal("not_enforced_in_this_mode", OutcomeOf(rows, "geo"));
Assert.Equal("not_evaluated", OutcomeOf(rows, "rate"));
}
[Fact]
public void A_pillar_after_the_answering_one_was_not_reached_rather_than_answered_no()
{
var decision = new EdgeDecision(EdgeVerdict.BlockRule, 403, Reason: "rule_7", RulePattern: "/x*");
var rows = DecisionTrace.For(
Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }), decision, Now, hasAddress: true, hasCountry: false);
Assert.Equal("did_not_match", OutcomeOf(rows, "alwaysPass"));
Assert.Equal("did_not_match", OutcomeOf(rows, "allowlist"));
Assert.Equal("answered", OutcomeOf(rows, "requestRule"));
Assert.Contains("rule_7", NoteOf(rows, "requestRule")!);
Assert.Equal("not_reached", OutcomeOf(rows, "operatorBlock"));
Assert.Equal("not_reached", OutcomeOf(rows, "engineBan"));
}
[Fact]
public void Observe_mode_is_reported_as_a_pillar_this_configuration_does_not_run()
{
var observe = new EdgePolicy { Mode = EnforcementMode.Observe };
var rows = DecisionTrace.For(Snapshot(observe), EdgeDecision.Pass, Now, hasAddress: true, hasCountry: false);
Assert.Equal("not_enforced_in_this_mode", OutcomeOf(rows, "engineBan"));
// And in Enforce mode the same pillar was asked and said no, which is the
// difference an operator acts on.
var enforce = DecisionTrace.For(
Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }),
EdgeDecision.Pass, Now, hasAddress: true, hasCountry: false);
Assert.Equal("did_not_match", OutcomeOf(enforce, "engineBan"));
Assert.Null(NoteOf(enforce, "engineBan"));
}
[Fact]
public void A_live_ban_the_mode_refused_to_enforce_is_named_as_existing()
{
var observe = new EdgePolicy { Mode = EnforcementMode.Observe };
var snapshot = Snapshot(observe, new Dictionary<string, BlockEntry>(StringComparer.Ordinal)
{
["203.0.113.9"] = new()
{
SourceKey = "203.0.113.9",
Source = BlockSource.Engine,
ExpiresAt = Now.AddMinutes(30),
Reason = "3 consecutive refusals"
}
});
var note = DecisionTrace.NoteForUnasked("engineBan", snapshot, "203.0.113.9", true, false, Now);
Assert.Contains("a live engine ban exists", note);
// The same line for a source nothing is known about says exactly that,
// because "nothing was known" and "known and not acted on" are the two
// answers an operator keeps confusing.
var quiet = DecisionTrace.NoteForUnasked("engineBan", snapshot, "198.51.100.1", true, false, Now);
Assert.Contains("Observe mode does not enforce engine bans", quiet);
Assert.DoesNotContain("exists", quiet);
}
[Fact]
public void A_geo_policy_that_is_on_but_has_no_country_is_not_the_same_as_one_that_is_off()
{
var on = new EdgePolicy { Geo = GeoMode.DenyList };
var rows = DecisionTrace.For(Snapshot(on), EdgeDecision.Pass, Now, hasAddress: true, hasCountry: false);
Assert.Equal("not_evaluated", OutcomeOf(rows, "geo"));
Assert.Contains("no country is known", NoteOf(rows, "geo")!);
var off = DecisionTrace.For(Snapshot(), EdgeDecision.Pass, Now, hasAddress: true, hasCountry: true);
Assert.Equal("not_enforced_in_this_mode", OutcomeOf(off, "geo"));
Assert.Contains("the geo pillar is off", NoteOf(off, "geo")!);
}
[Fact]
public void Every_verdict_has_its_own_spelling_because_blockrule_is_not_a_word_any_surface_prints()
{
var labels = Enum.GetValues<EdgeVerdict>().Select(EdgeVerdictLabel.For).ToArray();
Assert.Equal(Enum.GetValues<EdgeVerdict>().Length, labels.Distinct().Count());
Assert.Contains("block_rule", labels);
Assert.Contains("pass_rule_observed", labels);
Assert.DoesNotContain("blockrule", labels);
Assert.All(labels, l => Assert.Equal(l, l.ToLowerInvariant()));
}
}
+22
View File
@@ -1393,6 +1393,28 @@ check 'the body names no address from the scene above' 'yes' \
check 'and no per-source label exists anywhere in it' 'yes' \
"$(printf '%s\n' "$OPEN58_BODY" | grep -Eq '(^|,)(ip|path|user_agent)=' && echo no || echo yes)"
echo "- asking the shipped edge what it would answer (OPEN-59)"
# The same dry run against the image an operator would actually deploy. The scene
# above already wrote and removed a rule, so this writes one it can ask about and
# removes it again, leaving the volume as it found it.
OPEN59_IP="203.0.113.$(( 100 + RANDOM % 40 ))"
OPEN59_WRITE=$(admin -X POST -H 'Content-Type: application/json' \
-d '{"pattern":"/preview-only*","action":"block","note":"compose: asked, not sent"}' \
-w '\nCODE%{http_code}' "$EDGE/admin-api/rules")
check 'a rule can be written to be asked about' '204' "$(printf '%s' "$OPEN59_WRITE" | sed -n 's/.*CODE//p')"
OPEN59_DECIDE=$(admin "$EDGE/admin-api/decide?ip=$OPEN59_IP&path=/preview-only")
check 'the preview answers with the verdict the wire would give' block_rule \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')"
check 'and names the pillar that spoke' requestRule \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next(r["pillar"] for r in p if r["outcome"]=="answered"))')"
check 'and echoes the rule it matched, pattern and all' '/preview-only*' \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["rule"]["pattern"])')"
check 'and refuses an address that is not an address rather than answering pass' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/decide?ip=203.0.113&path=/preview-only")"
OPEN59_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/preview-only*'" id)
check 'and the rule is removable again, so the volume is left clean' '204' \
"$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/rules/$OPEN59_RULE")"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+18
View File
@@ -152,6 +152,24 @@ check 'the body names no address, no path and no operator note' yes \
check 'a source the edge is refusing can still be watched' 200 \
"$(code -H "X-Admin-Token: $TOKEN" -H "X-Forwarded-For: $SCANNER" "http://127.0.0.1:$EDGE_PORT/metrics")"
echo '- asking the edge what it would answer (OPEN-59)'
# The dry run. The assertion that matters is not the verdict — the scene above
# already proved the ban is enforced — it is that the preview answers about the
# named address and says which pillar spoke, including the ones that never got
# asked.
DECIDE=$(curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$SCANNER&path=/anything")
check 'the preview answers with the verdict the wire gives' block_engine \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')"
check 'and names the pillar that spoke' engineBan \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next(r["pillar"] for r in p if r["outcome"]=="answered"))')"
check 'and says the geo pillar was never asked in this configuration' not_enforced_in_this_mode \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next(r["outcome"] for r in p if r["pillar"]=="geo"))')"
check 'a typo in the address is refused rather than answered with pass' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=203.0.113&path=/anything")"
check 'a parameter this surface never read is refused before it is ignored' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$SCANNER&path=/anything&source=engine")"
echo '- operator list'
check 'add an operator block' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \