Files
Pavlo Ratushnyi ddddfc864b recovered-partial: the blast-radius preview exists on disk with nobody's record on it
Recovered-partial, UNVERIFIED. These changes were in the working tree at session
start with no checkpoint record on any item (OPEN-75 carries no execution plan,
work result or handoff note), so they are preserved rather than built on.

Attribution: they are the OPEN-75 surface — GET /admin-api/impact, the console
panel that calls it, the write-path refusal of abbreviated v4 spellings, and the
smoke / compose / console scenes for it. The README section and endpoint-list
entry the item's definition of done asks for are not here.

Gate evidence taken against this state, not claimed for it:
  build (warnings-as-errors)  clean
  unit                        378/378
  integration                 403/405 — AlertPushQueueTests.Attempts_run_out_and_
                              the_surface_says_who_was_never_told and
                              PillarFailureVisibilityTests.The_snapshot_age_is_
                              measured_against_the_ttl_it_is_supposed_to_respect
                              fail here AND fail identically at 6f92d37 with
                              these changes absent, in a separate worktree, so
                              they are not this work's failures; their failure
                              site moves between runs (assertion vs fixture
                              StartServer), which is what an environment-sensitive
                              test looks like.
2026-10-05 18:20:42 +02:00

316 lines
15 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// What would this ban touch? (OPEN-75): the blast radius of a range or address
/// before the operator writes it.
///
/// Both failures the surface exists to catch are silent. A /24 written over an
/// office block refuses people who were never the target, and a range written
/// inside an existing exemption refuses nobody at all — the operator sees 204 and
/// moves on. The dry run answers one named request and the horizon answers what
/// stops being enforced soon; neither answers the question asked before the write.
///
/// What these tests hold the surface to: the preview runs the real engine over a
/// snapshot with the proposed entry added, so the split between newly refused,
/// already refused and still passing is the wire's split and not a second
/// implementation of it; an exemption outranks the ban and the answer says so;
/// a write that changes nothing is named as one; a bare address is previewed
/// under the key this edge files it under, which with a group prefix is wider
/// than the address typed; the match is normalised by the write path's own code;
/// and asking writes nothing.
/// </summary>
public sealed class BanImpactTests
{
private const string Net = "203.0.113.32/29"; // .32 – .39
private const string A = "203.0.113.33";
private const string B = "203.0.113.34";
private const string Exempt = "203.0.113.35";
private const string Outside = "203.0.113.50";
private static async Task<HttpResponseMessage> AdminAsync(
EdgeFixture f, HttpMethod method, string url, object? body = null,
string? token = EdgeFixture.AdminToken)
{
using var request = new HttpRequestMessage(method, url);
if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await f.Client.SendAsync(request);
}
private static async Task<(HttpStatusCode Status, JsonElement Body)> ImpactAsync(
EdgeFixture f, string query, string? token = EdgeFixture.AdminToken)
{
using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/impact?{query}", token: token);
var text = await r.Content.ReadAsStringAsync();
var body = string.IsNullOrWhiteSpace(text)
? default
: JsonDocument.Parse(text).RootElement.Clone();
return (r.StatusCode, body);
}
private static async Task AskAsync(EdgeFixture f, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/anything");
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
using var r = await f.Client.SendAsync(request);
_ = (int)r.StatusCode;
}
/// <summary>Traffic first, so the sources the preview probes are sources this
/// edge really is watching rather than rows the test invented.</summary>
private static async Task SeedTrafficAsync(EdgeFixture f, params string[] ips)
{
foreach (var ip in ips) await AskAsync(f, ip);
await f.FlushObservationsAsync();
}
private static List<JsonElement> Sources(JsonElement body)
=> body.GetProperty("sources").EnumerateArray().ToList();
private static JsonElement RowFor(JsonElement body, string key)
=> Assert.Single(Sources(body), r => r.GetProperty("source").GetString() == key);
[Fact]
public async Task The_preview_names_the_sources_inside_the_range_it_would_newly_refuse()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A, B, Outside);
var (status, body) = await ImpactAsync(f, $"match={Net}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(Net, body.GetProperty("match").GetString());
Assert.Equal("range", body.GetProperty("kind").GetString());
Assert.Equal("snapshot+database", body.GetProperty("scope").GetString());
Assert.True(body.GetProperty("wouldRefuse").GetBoolean());
Assert.False(body.GetProperty("changesNothing").GetBoolean());
Assert.False(body.GetProperty("wrote").GetBoolean());
// The two watched sources inside the range flip; the one outside is not
// probed at all, and the range's own network address always is — so it is
// in the count too, and an answer that left it out would be a preview of
// a range the edge cannot answer about.
Assert.Equal(3, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32());
Assert.Equal(0, body.GetProperty("counts").GetProperty("alreadyRefused").GetInt32());
Assert.DoesNotContain(Outside, body.ToString());
foreach (var key in new[] { A, B, "203.0.113.32" })
{
var row = RowFor(body, key);
Assert.Equal("pass", row.GetProperty("before").GetString());
Assert.Equal("block_operator", row.GetProperty("after").GetString());
Assert.Equal(Net, row.GetProperty("afterBy").GetString());
Assert.Equal("newly refused", row.GetProperty("change").GetString());
}
Assert.Contains("would be refused by this write", body.GetProperty("note").GetString()!);
}
[Fact]
public async Task A_source_already_refused_by_something_else_is_not_counted_as_a_change()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A, B);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = A, reason = "already banned" })) { }
var (_, body) = await ImpactAsync(f, $"match={Net}");
var row = RowFor(body, A);
Assert.Equal("block_operator", row.GetProperty("before").GetString());
Assert.Equal(A, row.GetProperty("beforeBy").GetString());
Assert.Equal("already refused", row.GetProperty("change").GetString());
Assert.Equal(2, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32());
Assert.Equal(1, body.GetProperty("counts").GetProperty("alreadyRefused").GetInt32());
}
[Fact]
public async Task An_exemption_inside_the_range_keeps_passing_and_the_answer_says_why()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A, Exempt);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
new { match = Exempt, note = "the office" })) { }
var (_, body) = await ImpactAsync(f, $"match={Net}");
var row = RowFor(body, Exempt);
Assert.Equal("pass_allowlisted", row.GetProperty("before").GetString());
Assert.Equal("pass_allowlisted", row.GetProperty("after").GetString());
Assert.Equal("an allow entry", row.GetProperty("afterBy").GetString());
Assert.Equal("still passes", row.GetProperty("change").GetString());
// The exemption is named as sitting inside the match, so the operator
// sees the part of the range the ban will not reach.
var inside = body.GetProperty("exemptionsInside").EnumerateArray().ToList();
Assert.Equal(Exempt, Assert.Single(inside).GetProperty("match").GetString());
Assert.Equal("the office", inside[0].GetProperty("note").GetString());
Assert.Empty(body.GetProperty("outrankedBy").EnumerateArray());
}
[Fact]
public async Task A_range_written_under_an_exemption_that_covers_it_refuses_nobody()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A);
// The exemption is broader than the ban about to be written: the pillar
// order answers with the exemption and the ban never speaks.
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
new { match = Net, note = "the whole block" })) { }
var (_, body) = await ImpactAsync(f, $"match={Net}");
Assert.Equal(0, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32());
Assert.True(body.GetProperty("changesNothing").GetBoolean());
var outranking = body.GetProperty("outrankedBy").EnumerateArray().ToList();
Assert.Equal(Net, Assert.Single(outranking).GetProperty("match").GetString());
Assert.Equal("the whole block", outranking[0].GetProperty("note").GetString());
Assert.Equal("still passes", RowFor(body, A).GetProperty("change").GetString());
Assert.Contains("outrankedBy", body.GetProperty("note").GetString()!);
}
[Fact]
public async Task A_write_that_changes_nothing_is_named_as_one_and_says_what_already_covers_it()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A);
// A broader range is already live, so the /29 about to be written is
// decoration.
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = "203.0.113.32/28", reason = "the whole netblock" })) { }
var (_, body) = await ImpactAsync(f, $"match={Net}");
Assert.True(body.GetProperty("changesNothing").GetBoolean());
Assert.Equal(0, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32());
var covered = body.GetProperty("alreadyCoveredBy");
Assert.Equal("block_operator", covered.GetProperty("verdict").GetString());
Assert.Equal("203.0.113.32/28", covered.GetProperty("by").GetString());
Assert.Equal("already refused", RowFor(body, A).GetProperty("change").GetString());
}
[Fact]
public async Task The_match_is_normalised_by_the_write_paths_own_code()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A);
// 203.0.113.37/29 and 203.0.113.32/29 are one row; the preview answers
// about the spelling the edge would keep.
var (_, body) = await ImpactAsync(f, "match=203.0.113.37/29");
Assert.Equal(Net, body.GetProperty("match").GetString());
var (bad, badBody) = await ImpactAsync(f, "match=203.0.113.32/40");
Assert.Equal(HttpStatusCode.BadRequest, bad);
Assert.Contains("prefix must be 0..32", badBody.GetProperty("error").GetString()!);
// A /0 is refused on meaning by the write path, and the preview refuses it
// in the same words rather than answering about every address there is.
var (zero, zeroBody) = await ImpactAsync(f, "match=203.0.113.0/0");
Assert.Equal(HttpStatusCode.BadRequest, zero);
Assert.Contains("shutdown, not a ban", zeroBody.GetProperty("error").GetString()!);
// The abbreviated form is refused in the write's words, not answered
// about: the parser behind the write path reads "203.0.113" as
// 203.0.0.113, and a preview of that row would be a preview of a ban on a
// live address nobody meant.
var (typo, typoBody) = await ImpactAsync(f, "match=203.0.113");
Assert.Equal(HttpStatusCode.BadRequest, typo);
Assert.Contains("not an IP address", typoBody.GetProperty("error").GetString()!);
}
[Fact]
public async Task A_bare_address_is_previewed_under_the_key_this_edge_files_it_under()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
new { ipv4KeyPrefixLength = 29 })) { }
await SeedTrafficAsync(f, A, "203.0.113.41");
// With a /29 key the edge files .33 as the group, so the preview of one
// address answers about the group the write would ban — and about no other
// group: .41 is watched too, and is not inside this one.
var (_, body) = await ImpactAsync(f, $"match={A}");
Assert.Equal("address", body.GetProperty("kind").GetString());
Assert.Equal("203.0.113.32/29", body.GetProperty("filedUnder").GetString());
Assert.Equal(1, body.GetProperty("probed").GetInt32());
Assert.Equal(1, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32());
var row = RowFor(body, "203.0.113.32/29");
Assert.Equal("newly refused", row.GetProperty("change").GetString());
Assert.DoesNotContain("203.0.113.40/29", body.ToString());
}
[Fact]
public async Task The_limit_bounds_the_sources_probed_and_says_it_left_some_out()
{
await using var f = new EdgeFixture();
await SeedTrafficAsync(f, A, B, Exempt, "203.0.113.36", "203.0.113.37");
var (_, body) = await ImpactAsync(f, $"match={Net}&limit=2");
Assert.Equal(2, body.GetProperty("probed").GetInt32());
Assert.Equal(2, Sources(body).Count);
Assert.True(body.GetProperty("truncated").GetBoolean());
}
[Fact]
public async Task A_question_it_cannot_answer_is_refused_by_name()
{
await using var f = new EdgeFixture();
var cases = new[]
{
("", "match is required"),
("match=" + Net + "&path=anything", "path must start with /"),
("match=" + Net + "&limit=0", "limit must be 1..200"),
("match=" + Net + "&limit=201", "limit must be 1..200"),
("match=" + Net + "&source=engine", "unknown query parameter 'source'"),
};
foreach (var (query, expected) in cases)
{
var (status, body) = await ImpactAsync(f, query);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains(expected, body.GetProperty("error").GetString()!);
}
}
[Fact]
public async Task Asking_is_a_read_the_read_only_token_can_make_and_that_changes_no_answer_on_the_wire()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
await SeedTrafficAsync(f, A, B);
static async Task<int> RowsAsync(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
return await db.Blocks.CountAsync() + await db.NetworkBans.CountAsync()
+ await db.ConfigChanges.CountAsync();
}
var before = await RowsAsync(f);
var (status, _) = await ImpactAsync(f, $"match={Net}", token: EdgeFixture.ReadOnlyToken);
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(before, await RowsAsync(f));
// The preview promised block_operator for these sources; the wire still
// answers pass, because the preview wrote nothing to the snapshot either.
using var request = new HttpRequestMessage(HttpMethod.Get, "/anything");
request.Headers.TryAddWithoutValidation("X-Forwarded-For", A);
using var live = await f.Client.SendAsync(request);
Assert.NotEqual(HttpStatusCode.Forbidden, live.StatusCode);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Net })) { }
using var after = new HttpRequestMessage(HttpMethod.Get, "/anything");
after.Headers.TryAddWithoutValidation("X-Forwarded-For", A);
using var refused = await f.Client.SendAsync(after);
// The write path's own answer: an operator block goes out with the
// configured status, 301 by default. The point of the assertion is only
// that the row the preview promised is the row the write put in effect.
Assert.Equal(HttpStatusCode.MovedPermanently, refused.StatusCode);
var (anon, _) = await ImpactAsync(f, $"match={Net}", token: null);
Assert.Equal(HttpStatusCode.Unauthorized, anon);
}
}