using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Security; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// An operator can ban a range, not only an address (OPEN-66). /// /// The edge already understood networks in three places — the allowlist matches /// by CIDR, the volume budget groups sources by prefix, an IPv6 streak is keyed /// on a /64 — and refused them in the one control an operator reaches for during /// an incident: POST /admin-api/blocks answered "not an IP address" for a /// /24. So a scanner rotating inside one netblock cost one write and one row per /// address, and the export of an edge's decisions could not carry the range to /// another edge. /// /// What these tests hold the feature to, in order: a range is a block and is /// enforced by containment; one range is one row however it is spelled; the /// operator's list stays one list for reading, for deleting by name and for /// clearing by provenance; a range that covers every address is refused on /// meaning rather than on form; and the range travels. /// public sealed class NetworkBanTests { private const string Range = "203.0.113.16/28"; // .16 – .31 private const string Inside = "203.0.113.21"; private const string AlsoInside = "203.0.113.30"; private const string Outside = "203.0.113.32"; private const string Address = "203.0.113.44"; private static async Task GetAsync(EdgeFixture f, string path, string ip) { using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); return await f.Client.SendAsync(request); } private static async Task<(HttpStatusCode Status, string Body)> BlockAsync(EdgeFixture f, object body) { using var response = await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", body); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } private static async Task> RowsAsync(EdgeFixture f) { using var response = await f.Client.GetAsync( $"/admin-api/blocks?live=false&token={EdgeFixture.AdminToken}"); var body = await response.Content.ReadAsStringAsync(); Assert.True(response.StatusCode == HttpStatusCode.OK, $" {(int)response.StatusCode}: {body}"); return JsonDocument.Parse(body) .RootElement.EnumerateArray().ToList(); } [Fact] public async Task A_CIDR_is_a_block_and_the_listing_says_which_shape_it_is() { await using var f = new EdgeFixture(); var (status, _) = await BlockAsync(f, new { ip = Range, reason = "netblock scanning /wp-login" }); Assert.Equal(HttpStatusCode.NoContent, status); // Enforced on containment, not on the address the operator typed: two // different sources inside the range are both refused, and the neighbour // one address past its end is served. using (var first = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, first.StatusCode); using (var second = await GetAsync(f, "/anything", AlsoInside)) Assert.Equal(HttpStatusCode.MovedPermanently, second.StatusCode); using (var outside = await GetAsync(f, "/anything", Outside)) Assert.Equal(HttpStatusCode.NotFound, outside.StatusCode); var rows = await RowsAsync(f); var row = Assert.Single(rows, r => r.GetProperty("sourceKey").GetString() == Range); Assert.Equal("range", row.GetProperty("kind").GetString()); Assert.Equal("operator", row.GetProperty("source").GetString()); Assert.True(row.GetProperty("live").GetBoolean()); Assert.Contains("netblock", row.GetProperty("reason").GetString()); // The address rows still say what they are; the marker is not a column // that only one shape of the list can answer. var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); Assert.Equal(HttpStatusCode.NoContent, addressStatus); var addressRow = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Address); Assert.Equal("address", addressRow.GetProperty("kind").GetString()); } [Fact] public async Task One_range_is_one_row_however_it_is_spelled() { await using var f = new EdgeFixture(); var (first, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "written sloppily" }); Assert.Equal(HttpStatusCode.NoContent, first); var (second, _) = await BlockAsync(f, new { ip = Range, reason = "the same network" }); Assert.Equal(HttpStatusCode.NoContent, second); // Masked to the network address, and the second write found the first // row rather than standing beside it. var rows = await RowsAsync(f); Assert.Equal(1, rows.Count(r => r.GetProperty("kind").GetString() == "range")); var row = rows.Single(r => r.GetProperty("kind").GetString() == "range"); Assert.Equal(Range, row.GetProperty("sourceKey").GetString()); Assert.Equal("the same network", row.GetProperty("reason").GetString()); } [Fact] public async Task A_prefix_that_names_one_address_is_that_address_and_not_a_second_row() { await using var f = new EdgeFixture(); var (status, _) = await BlockAsync(f, new { ip = "203.0.113.44/32", reason = "one host, written as a range" }); Assert.Equal(HttpStatusCode.NoContent, status); var row = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Address); Assert.Equal("address", row.GetProperty("kind").GetString()); using (var blocked = await GetAsync(f, "/anything", Address)) Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); } [Fact] public async Task A_range_over_every_address_is_refused_and_says_why() { await using var f = new EdgeFixture(); foreach (var (written, expected) in new[] { ("0.0.0.0/0", "every address"), ("::/0", "every address") }) { var (status, body) = await BlockAsync(f, new { ip = written, reason = "shutdown dressed as a ban" }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains(expected, body); } // A refusal is a refusal: nothing was written, and the edge still serves. Assert.Empty(await RowsAsync(f)); using (var served = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); } [Fact] public async Task A_malformed_range_is_refused_by_name() { await using var f = new EdgeFixture(); foreach (var written in new[] { "203.0.113.0/33", "203.0.113.0/-1", "203.0.113.0/abc", "not-an-ip/24" }) { var (status, body) = await BlockAsync(f, new { ip = written, reason = "typo" }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains(written, body); } Assert.Empty(await RowsAsync(f)); } [Fact] public async Task An_allow_entry_inside_a_banned_range_still_exempts() { await using var f = new EdgeFixture(); var (blocked, _) = await BlockAsync(f, new { ip = Range, reason = "the whole netblock" }); Assert.Equal(HttpStatusCode.NoContent, blocked); using (var inside = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); using (var allow = await f.Client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", new { match = Inside, note = "the one customer in that block" })) Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); // The exemption outranks the range exactly as it outranks an address // block, and the rest of the range stays banned. using (var exempt = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, exempt.StatusCode); using (var neighbour = await GetAsync(f, "/anything", AlsoInside)) Assert.Equal(HttpStatusCode.MovedPermanently, neighbour.StatusCode); } [Fact] public async Task A_range_is_removed_by_name_and_the_count_says_what_was_removed() { await using var f = new EdgeFixture(); var (status, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "typed sloppily" }); Assert.Equal(HttpStatusCode.NoContent, status); using (var inside = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); // Deleting it by the spelling the operator typed finds the row the edge // stored, which is the masked one. using var deleted = await f.Client.DeleteAsync( $"/admin-api/blocks?key=203.0.113.21/28&token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.OK, deleted.StatusCode); Assert.Equal(1, JsonDocument.Parse(await deleted.Content.ReadAsStringAsync()) .RootElement.GetProperty("deleted").GetInt32()); using (var served = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); } [Fact] public async Task Clearing_the_operator_list_clears_the_ranges_and_clearing_the_engine_never_does() { await using var f = new EdgeFixture(); var (rangeStatus, _) = await BlockAsync(f, new { ip = Range, reason = "netblock" }); Assert.Equal(HttpStatusCode.NoContent, rangeStatus); var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); Assert.Equal(HttpStatusCode.NoContent, addressStatus); // The provenance the engine owns cannot reach a range: the engine did not // write one, and a clear that reports the engine's list empty while a /24 // is still refusing visitors would be a lie about what is in force. using (var engineClear = await f.Client.DeleteAsync( $"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) { Assert.Equal(HttpStatusCode.OK, engineClear.StatusCode); Assert.Equal(0, JsonDocument.Parse(await engineClear.Content.ReadAsStringAsync()) .RootElement.GetProperty("deleted").GetInt32()); } using (var stillBanned = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, stillBanned.StatusCode); // The operator's list is one list, so the clear that names it removes // both shapes of it. using (var operatorClear = await f.Client.DeleteAsync( $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) { Assert.Equal(HttpStatusCode.OK, operatorClear.StatusCode); Assert.Equal(2, JsonDocument.Parse(await operatorClear.Content.ReadAsStringAsync()) .RootElement.GetProperty("deleted").GetInt32()); } using (var served = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); using (var addressServed = await GetAsync(f, "/anything", Address)) Assert.Equal(HttpStatusCode.NotFound, addressServed.StatusCode); Assert.Empty(await RowsAsync(f)); } [Fact] public async Task A_range_past_its_expiry_enforces_nothing_and_shows_itself_as_dead() { await using var f = new EdgeFixture(); var (status, _) = await BlockAsync(f, new { ip = Range, reason = "overnight", expiresInMinutes = 60 }); Assert.Equal(HttpStatusCode.NoContent, status); using (var inside = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); // Move the clock by moving the row, the way the expiry and retention // tests do: the hour passes for this range and for nothing else. using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var row = await db.NetworkBans.SingleAsync(b => b.Match == Range); row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); await db.SaveChangesAsync(); } await f.Service().InvalidateAsync(CancellationToken.None); using (var served = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); // The dead row stays in the table that shows it, marked dead, and is out // of the live view — the same honesty rule as an address block. var dead = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Range); Assert.False(dead.GetProperty("live").GetBoolean()); Assert.NotEqual(JsonValueKind.Null, dead.GetProperty("expiresAt").ValueKind); using var liveListing = await f.Client.GetAsync( $"/admin-api/blocks?live=true&token={EdgeFixture.AdminToken}"); var liveRows = JsonDocument.Parse(await liveListing.Content.ReadAsStringAsync()) .RootElement.EnumerateArray().Select(r => r.GetProperty("sourceKey").GetString()).ToList(); Assert.DoesNotContain(Range, liveRows); } [Fact] public async Task The_state_counts_ranges_apart_from_address_blocks() { await using var f = new EdgeFixture(); var (rangeStatus, _) = await BlockAsync(f, new { ip = Range, reason = "netblock" }); Assert.Equal(HttpStatusCode.NoContent, rangeStatus); var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); Assert.Equal(HttpStatusCode.NoContent, addressStatus); using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}"); var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; Assert.Equal(1, state.GetProperty("operatorRanges").GetInt32()); Assert.Equal(1, state.GetProperty("operatorBlocks").GetInt32()); Assert.True(state.GetProperty("operatorRangesAvailable").GetBoolean()); } [Fact] public async Task A_range_travels_in_the_document_and_is_enforced_on_the_edge_that_imports_it() { await using var source = new EdgeFixture(); var (status, _) = await BlockAsync(source, new { ip = Range, reason = "written here", expiresInMinutes = 60 * 24 }); Assert.Equal(HttpStatusCode.NoContent, status); using var exportResponse = await source.Client.GetAsync($"/admin-api/export?token={EdgeFixture.AdminToken}"); var document = await exportResponse.Content.ReadAsStringAsync(); var exported = JsonDocument.Parse(document).RootElement; Assert.Equal(1, exported.GetProperty("counts").GetProperty("blocks").GetInt32()); Assert.Contains(Range, exported.GetProperty("blocks").EnumerateArray() .Select(b => b.GetProperty("ip").GetString())); await using var target = new EdgeFixture(); using (var before = await GetAsync(target, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, before.StatusCode); using (var content = new StringContent(document, Encoding.UTF8, "application/json")) using (var import = await target.Client.PostAsync( $"/admin-api/import?token={EdgeFixture.AdminToken}", content)) { Assert.Equal(HttpStatusCode.OK, import.StatusCode); var report = JsonDocument.Parse(await import.Content.ReadAsStringAsync()).RootElement; Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); } // The receiving edge enforces it on the wire, not only in its table, and // the expiry travelled as an instant rather than as a duration. using (var inside = await GetAsync(target, "/anything", Inside)) Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); using (var outside = await GetAsync(target, "/anything", Outside)) Assert.Equal(HttpStatusCode.NotFound, outside.StatusCode); var imported = (await RowsAsync(target)).Single(r => r.GetProperty("sourceKey").GetString() == Range); Assert.Equal("range", imported.GetProperty("kind").GetString()); Assert.NotEqual(JsonValueKind.Null, imported.GetProperty("expiresAt").ValueKind); // The same document twice lands once. using (var content = new StringContent(document, Encoding.UTF8, "application/json")) using (var again = await target.Client.PostAsync( $"/admin-api/import?token={EdgeFixture.AdminToken}", content)) { var report = JsonDocument.Parse(await again.Content.ReadAsStringAsync()).RootElement; Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("blocks").GetProperty("alreadyThere").GetInt32()); } } [Fact] public async Task A_document_carrying_a_range_over_everything_is_refused_row_by_row() { await using var f = new EdgeFixture(); var document = """ {"version":1,"blocks":[{"ip":"0.0.0.0/0","reason":"shutdown"}], "allow":[],"rules":[],"countries":[]} """; using var content = new StringContent(document, Encoding.UTF8, "application/json"); using var import = await f.Client.PostAsync($"/admin-api/import?token={EdgeFixture.AdminToken}", content); Assert.Equal(HttpStatusCode.OK, import.StatusCode); var report = JsonDocument.Parse(await import.Content.ReadAsStringAsync()).RootElement; Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("blocks").GetProperty("rejected").GetInt32()); Assert.Contains("every address", report.GetProperty("rejected").ToString()); Assert.Empty(await RowsAsync(f)); using (var served = await GetAsync(f, "/anything", Inside)) Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); } [Fact] public async Task A_range_lands_in_the_change_log_under_the_name_the_row_is_stored_under() { await using var f = new EdgeFixture(); var (status, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "typed sloppily" }); Assert.Equal(HttpStatusCode.NoContent, status); using var response = await f.Client.GetAsync( $"/admin-api/changes?section=block&token={EdgeFixture.AdminToken}"); var body = await response.Content.ReadAsStringAsync(); // The record names the row, not the typo: one network, one spelling, in // the table and in the log beside it. Assert.Contains(Range, body); Assert.DoesNotContain("203.0.113.21/28", body); } [Fact] public async Task The_read_only_token_cannot_write_a_range() { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); using var response = await f.Client.PostAsJsonAsync( $"/admin-api/blocks?token={EdgeFixture.ReadOnlyToken}", new { ip = Range, reason = "dashboard" }); Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.Empty(await RowsAsync(f)); } [Fact] public async Task An_address_missing_an_octet_is_refused_and_writes_no_row() { // The parser behind the write path accepts the legacy short forms and // fills the missing octets in for you: "203.0.113" parses as 203.0.0.113. // On a read that is a wrong answer about an address that does not exist; // here it is a row — a ban on a live address nobody meant, filed under a // spelling the operator will not find in the listing. The read surfaces // refuse the string; the write path refuses it too, and says so. await using var f = new EdgeFixture(); var (status, body) = await BlockAsync(f, new { ip = "203.0.113" }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains("not an IP address", body); var (rangeStatus, rangeBody) = await BlockAsync(f, new { ip = "203.0.113/24" }); Assert.Equal(HttpStatusCode.BadRequest, rangeStatus); Assert.Contains("not an IP address", rangeBody); Assert.Empty(await RowsAsync(f)); } }