Files
Pavlo Ratushnyi 575ef88afe 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.
2026-10-05 01:36:29 +02:00

295 lines
14 KiB
C#

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