using System.Net.Sockets; using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Security; namespace OpenWaf.Tests.Unit; /// /// 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. /// 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 An_abbreviated_v4_is_refused_because_it_is_not_an_address_anyone_typed() { // IPAddress.TryParse accepts the legacy short forms and fills the missing // octets in: "203.0.113" parses as 203.0.0.113, and "10.1" as 10.0.0.1. // On this path a parse that guesses writes a row, so an operator missing // one octet bans a live address that was never the target and then reads // the listing looking for the spelling they typed. The read surfaces // (/decide, /history, /find) already refuse these strings; the write path // has to refuse the same ones or the two disagree about whether the // address exists at all. foreach (var written in new[] { "203.0.113", "203.0.113/24", "10.1", "10.1/16", "203" }) { Assert.False(NetworkBans.TryNormalize(written, out _, out var error), written); Assert.Contains("not an IP address", error); } // The whole spelling still passes, mapped v6 included — the rule is about // a v4 address written in fewer than four parts, not about v6. Assert.Equal("203.0.113.0/24", Normalized("::ffff:203.0.113.0/24")); Assert.Equal("203.0.113.7", Normalized("203.0.113.7")); } [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? manual = null, IReadOnlyDictionary? bans = null, IReadOnlyList? allow = null) => new() { GeneratedAt = Now, Policy = policy, OperatorRanges = ranges ?? NetworkBanIndex.Empty, OperatorBlocks = manual ?? new Dictionary(), EngineBans = bans ?? new Dictionary(), 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 { ["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 { ["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); } }