A scanner rotating through a rented /29 used to cost one row and one write per address: POST /admin-api/blocks answered "not an IP address" for a CIDR while the allowlist control beside it accepted one, and the config export could not carry the operator's answer either. A CIDR now has its own table and is enforced by containment. The rulings: - One list, two shapes. GET /admin-api/blocks merges address rows and range rows and says which is which with `kind`; DELETE ?key= takes the CIDR as it was typed; ?source=engine still cannot reach an operator's range, while ?source=operator clears both operator shapes. - Containment is checked on the raw peer address, the same field the allowlist is matched on, after the exact operator block and before the engine's own ban. The verdict stays block_operator, so nothing downstream had to learn a new reason; the decision trace names the range that answered, and an allow entry still outranks a range. - What is written is normalised before it is stored: 203.0.113.37/28 is stored as 203.0.113.32/28, a /32 or /128 is stored as the bare address it already was, and the full-width prefix is refused on meaning rather than on form — "0.0.0.0/0" covers every address there is, including the one this was written from; that is a shutdown, not a ban on a source. - A request pays for the number of distinct prefix lengths, not for the number of ranges: the index buckets by prefix and asks a set for the request address masked to it, most specific first, and an expired row does not stop the search for a broader live one. - Export carries ranges in the blocks section and import lands them idempotently, so an edge's decisions survive the move. /state counts them apart from address blocks, and the console prints the shape beside the row. What the run caught: - BlockRow read Range?.Field ?? Entry!.Field. The two rows are mutually exclusive, so a range with no expiry, reason or redirect — the common case — dereferenced the row that is not there and GET /admin-api/blocks answered 500. - NetworkBanIndex filed a row under "a.b.c.d/24" while the lookup compared a masked address with no prefix, so no range ever matched: ten unit tests red before the bucket key was fixed to the network address alone. - smoke and compose both wrote their JSON bodies with escaped quotes straight inside a command substitution, which truncates the body and answers 400 — the hazard this file's own header warns about. The payloads are variables now. - Scene ordering in smoke: the range scene clears the engine's list wholesale, which took the expired scanner row a later scene asserts on. It runs after those scenes now, and says why in the file. - Test-side, worth keeping: 203.0.113.37/28 is not the network 203.0.113.16/28 names, so an assertion that writes one and expects the other is testing the mask, not the match. build 0 warnings / 0 errors, unit 334/334, integration 312/312 in 31 s, console 105 assertions 0 failed, smoke passed 137 failed 0, compose 285 passed 0 failed against the built image at 262 MB. Refs OPEN-66.
300 lines
12 KiB
C#
300 lines
12 KiB
C#
using System.Net.Sockets;
|
|
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Tests.Unit;
|
|
|
|
/// <summary>
|
|
/// The range half of the operator's block list (OPEN-66), as pure functions:
|
|
/// what the operator typed becomes which row, and which row answers for an
|
|
/// address. The integration tests ask the same questions over a wire; these ask
|
|
/// the ones that must hold whatever the wire is doing — the normalisation that
|
|
/// keeps one claim to one row, the index that keeps the per-request cost off the
|
|
/// table size, and the position of a range in the ordered decision.
|
|
/// </summary>
|
|
public sealed class NetworkBanTests
|
|
{
|
|
private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero);
|
|
|
|
private static NetworkBan Ban(string match, DateTimeOffset? expires = null, string? redirect = null) => new()
|
|
{
|
|
Match = match,
|
|
CreatedAt = Now.AddHours(-2),
|
|
ExpiresAt = expires,
|
|
RedirectTo = redirect,
|
|
Reason = "operator: netblock scanning"
|
|
};
|
|
|
|
private static string Normalized(string written)
|
|
{
|
|
Assert.True(NetworkBans.TryNormalize(written, out var normalized, out _), written);
|
|
return normalized;
|
|
}
|
|
|
|
// ---- what the operator typed, and the one spelling it becomes ----
|
|
|
|
[Fact]
|
|
public void An_address_stays_an_address()
|
|
{
|
|
Assert.Equal("203.0.113.7", Normalized("203.0.113.7"));
|
|
Assert.Equal("2001:db8::7", Normalized(" 2001:db8::7 "));
|
|
}
|
|
|
|
[Fact]
|
|
public void A_network_is_masked_to_its_own_address()
|
|
{
|
|
// The spelling the operator typed is not the spelling the row is stored
|
|
// under, and that is the point: 198.51.100.37/28 and 198.51.100.32/28 are
|
|
// one claim, and two rows for it are two rows to notice and remove.
|
|
Assert.Equal("203.0.113.32/28", Normalized("203.0.113.37/28"));
|
|
Assert.Equal("198.51.100.0/24", Normalized("198.51.100.200/24"));
|
|
Assert.Equal("2001:db8::/64", Normalized("2001:db8:0:0:1:2:3:4/64"));
|
|
}
|
|
|
|
[Fact]
|
|
public void A_prefix_that_names_one_address_is_that_address()
|
|
{
|
|
Assert.Equal("203.0.113.7", Normalized("203.0.113.7/32"));
|
|
Assert.Equal("2001:db8::7", Normalized("2001:db8::7/128"));
|
|
}
|
|
|
|
[Fact]
|
|
public void An_ipv4_in_mapped_form_is_the_v4_it_is()
|
|
{
|
|
Assert.Equal("203.0.113.0/24", Normalized("::ffff:203.0.113.0/24"));
|
|
}
|
|
|
|
[Fact]
|
|
public void A_range_over_every_address_is_refused_on_meaning_not_on_form()
|
|
{
|
|
foreach (var written in new[] { "0.0.0.0/0", "::/0" })
|
|
{
|
|
Assert.False(NetworkBans.TryNormalize(written, out _, out var error));
|
|
Assert.Contains("every address", error);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void A_prefix_that_cannot_be_a_prefix_is_refused_by_name()
|
|
{
|
|
foreach (var (written, expected) in new[]
|
|
{
|
|
("203.0.113.0/33", "0..32"),
|
|
("203.0.113.0/-1", "0..32"),
|
|
("2001:db8::/129", "0..128"),
|
|
("203.0.113.0/abc", "whole number of bits"),
|
|
("not-an-ip/24", "not an IP address")
|
|
})
|
|
{
|
|
Assert.False(NetworkBans.TryNormalize(written, out _, out var error), written);
|
|
Assert.Contains(expected, error);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void The_range_test_is_syntactic_so_it_can_decide_the_table_before_the_parse()
|
|
{
|
|
Assert.True(NetworkBans.IsRangeSyntax("203.0.113.0/24"));
|
|
Assert.False(NetworkBans.IsRangeSyntax("203.0.113.1"));
|
|
Assert.False(NetworkBans.IsRangeSyntax(null));
|
|
}
|
|
|
|
// ---- the index: cost bounded by prefix lengths, not by rows ----
|
|
|
|
[Fact]
|
|
public void A_range_answers_for_every_address_inside_it_and_for_none_outside()
|
|
{
|
|
var index = new NetworkBanIndex([Ban("203.0.113.16/28")]);
|
|
|
|
Assert.True(index.TryMatch("203.0.113.16", Now, out var first));
|
|
Assert.Equal("203.0.113.16/28", first.Match);
|
|
Assert.True(index.TryMatch("203.0.113.31", Now, out _));
|
|
Assert.False(index.TryMatch("203.0.113.15", Now, out _));
|
|
Assert.False(index.TryMatch("203.0.113.32", Now, out _));
|
|
Assert.False(index.TryMatch(null, Now, out _));
|
|
Assert.False(index.TryMatch("not-an-address", Now, out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void The_most_specific_range_is_the_one_that_answers()
|
|
{
|
|
var index = new NetworkBanIndex([Ban("203.0.113.0/24"), Ban("203.0.113.16/28")]);
|
|
|
|
Assert.True(index.TryMatch("203.0.113.21", Now, out var winner));
|
|
Assert.Equal("203.0.113.16/28", winner.Match);
|
|
// Outside the narrow one, the broad one still speaks.
|
|
Assert.True(index.TryMatch("203.0.113.99", Now, out var broad));
|
|
Assert.Equal("203.0.113.0/24", broad.Match);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_expired_range_answers_nothing_and_does_not_hide_a_live_one()
|
|
{
|
|
var index = new NetworkBanIndex([
|
|
Ban("203.0.113.16/28", Now.AddMinutes(-1)),
|
|
Ban("203.0.113.0/24")
|
|
]);
|
|
|
|
Assert.True(index.TryMatch("203.0.113.21", Now, out var winner));
|
|
Assert.Equal("203.0.113.0/24", winner.Match);
|
|
|
|
var dead = new NetworkBanIndex([Ban("203.0.113.16/28", Now.AddMinutes(-1))]);
|
|
Assert.False(dead.TryMatch("203.0.113.21", Now, out _));
|
|
Assert.Equal(1, dead.Count);
|
|
}
|
|
|
|
[Fact]
|
|
public void A_v6_range_covers_v6_and_a_v4_address_is_never_inside_it()
|
|
{
|
|
var index = new NetworkBanIndex([Ban("2001:db8:1234::/48")]);
|
|
|
|
Assert.True(index.TryMatch("2001:db8:1234:5600::1", Now, out _));
|
|
Assert.False(index.TryMatch("2001:db8:1235::1", Now, out _));
|
|
Assert.False(index.TryMatch("203.0.113.21", Now, out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void A_v4_address_written_in_mapped_form_is_inside_the_v4_range()
|
|
{
|
|
var index = new NetworkBanIndex([Ban("203.0.113.16/28")]);
|
|
Assert.True(index.TryMatch("::ffff:203.0.113.21", Now, out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void The_index_counts_rows_and_a_match_that_came_from_nowhere_is_skipped()
|
|
{
|
|
var index = new NetworkBanIndex([Ban("203.0.113.0/24"), Ban("garbage")]);
|
|
Assert.Equal(1, index.Count);
|
|
Assert.True(index.Covers("203.0.113.9", Now));
|
|
Assert.False(NetworkBanIndex.Empty.TryMatch("203.0.113.9", Now, out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void The_family_and_prefix_of_a_stored_match_are_the_ones_the_index_buckets_on()
|
|
{
|
|
Assert.Equal(AddressFamily.InterNetwork, NetworkBans.FamilyOf("203.0.113.0/24"));
|
|
Assert.Equal(AddressFamily.InterNetworkV6, NetworkBans.FamilyOf("2001:db8::/48"));
|
|
Assert.Equal(24, NetworkBans.PrefixOf("203.0.113.0/24"));
|
|
Assert.Equal(-1, NetworkBans.PrefixOf("203.0.113.1"));
|
|
}
|
|
|
|
// ---- the position of a range in the ordered decision ----
|
|
|
|
private static EdgeSnapshot Snapshot(
|
|
EdgePolicy policy,
|
|
NetworkBanIndex? ranges = null,
|
|
IReadOnlyDictionary<string, BlockEntry>? manual = null,
|
|
IReadOnlyDictionary<string, BlockEntry>? bans = null,
|
|
IReadOnlyList<AllowEntry>? allow = null) => new()
|
|
{
|
|
GeneratedAt = Now,
|
|
Policy = policy,
|
|
OperatorRanges = ranges ?? NetworkBanIndex.Empty,
|
|
OperatorBlocks = manual ?? new Dictionary<string, BlockEntry>(),
|
|
EngineBans = bans ?? new Dictionary<string, BlockEntry>(),
|
|
AllowEntries = allow ?? []
|
|
};
|
|
|
|
[Fact]
|
|
public void A_range_refuses_a_source_inside_it_and_leaves_its_neighbour_alone()
|
|
{
|
|
var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28")]));
|
|
|
|
var inside = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
Assert.Equal(EdgeVerdict.BlockOperator, inside.Verdict);
|
|
Assert.Equal("203.0.113.16/28", inside.Range);
|
|
Assert.Equal("operator: netblock scanning", inside.Reason);
|
|
|
|
Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.32", "/x", Now).Verdict);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_allow_entry_inside_a_banned_range_is_still_an_exemption()
|
|
{
|
|
var snapshot = Snapshot(
|
|
EdgePolicy.Default,
|
|
new NetworkBanIndex([Ban("203.0.113.16/28")]),
|
|
allow: [new AllowEntry { Match = "203.0.113.21", Note = "the one customer in that block" }]);
|
|
|
|
var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
Assert.Equal(EdgeVerdict.PassAllowlisted, decision.Verdict);
|
|
Assert.Equal("the one customer in that block", decision.Reason);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_operator_range_outranks_the_ban_this_edge_earned()
|
|
{
|
|
var engineBan = new BlockEntry
|
|
{
|
|
SourceKey = "203.0.113.21",
|
|
Source = BlockSource.Engine,
|
|
CreatedAt = Now.AddMinutes(-5),
|
|
ExpiresAt = Now.AddMinutes(55),
|
|
Reason = "10 consecutive refusals"
|
|
};
|
|
var snapshot = Snapshot(
|
|
new EdgePolicy { Mode = EnforcementMode.Enforce },
|
|
new NetworkBanIndex([Ban("203.0.113.16/28")]),
|
|
bans: new Dictionary<string, BlockEntry> { ["203.0.113.21"] = engineBan });
|
|
|
|
var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict);
|
|
Assert.Equal("203.0.113.16/28", decision.Range);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_address_block_the_operator_wrote_wins_over_the_range_covering_it()
|
|
{
|
|
var manual = new BlockEntry
|
|
{
|
|
SourceKey = "203.0.113.21",
|
|
Source = BlockSource.Operator,
|
|
CreatedAt = Now.AddHours(-1),
|
|
Reason = "blocked by name first"
|
|
};
|
|
var snapshot = Snapshot(
|
|
EdgePolicy.Default,
|
|
new NetworkBanIndex([Ban("203.0.113.16/28")]),
|
|
manual: new Dictionary<string, BlockEntry> { ["203.0.113.21"] = manual });
|
|
|
|
var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict);
|
|
// The row that answered is the address row: no range on the decision, and
|
|
// the reason is the one written against the address.
|
|
Assert.Null(decision.Range);
|
|
Assert.Equal("blocked by name first", decision.Reason);
|
|
}
|
|
|
|
[Fact]
|
|
public void A_range_with_a_redirect_sends_the_blocked_visitor_there()
|
|
{
|
|
var snapshot = Snapshot(
|
|
EdgePolicy.Default,
|
|
new NetworkBanIndex([Ban("203.0.113.16/28", redirect: "https://honeypot.example.org/")]));
|
|
|
|
var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
Assert.Equal(301, decision.StatusCode);
|
|
Assert.Equal("https://honeypot.example.org/", decision.Location);
|
|
}
|
|
|
|
[Fact]
|
|
public void A_range_past_its_expiry_enforces_nothing()
|
|
{
|
|
var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28", Now.AddMinutes(-1))]));
|
|
Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now).Verdict);
|
|
}
|
|
|
|
[Fact]
|
|
public void The_trace_names_the_range_that_answered()
|
|
{
|
|
var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28")]));
|
|
var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now);
|
|
|
|
var trace = DecisionTrace.For(snapshot, decision, Now, hasAddress: true, hasCountry: false, "203.0.113.21");
|
|
var answered = trace.Single(t => t.Outcome == PillarOutcome.Answered);
|
|
Assert.Equal("operatorBlock", answered.Pillar);
|
|
Assert.Contains("203.0.113.16/28", answered.Note);
|
|
}
|
|
}
|