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; /// /// The edge notices a netblock behind its bans and offers it as a range (OPEN-67). /// /// OPEN-66 made a range enforceable. This is the half that decides an operator /// should write one: a scanner farm inside one /24 is twenty engine bans and /// twenty operator decisions, and nothing in the edge connected them. /// /// The rulings these tests hold: /// * the evidence is the edge's own live engine bans — an operator's row and an /// expired ban are not evidence about a netblock; /// * an offer is an offer: nothing here changes what the edge answers a visitor; /// * the operator's decision closes the offer, and the surface says so; /// * the thresholds are configuration, refused outside their bounds by name; /// * reading the list is not news, so it raises no alert, and the same block is /// not alerted about twice in a row. /// public sealed class NetblockWatchTests { private const string Block = "203.0.113.0/24"; private const string Inside = "203.0.113.1"; /// Seed N live engine bans inside one /24, the way the engine writes /// them: keyed on the source, expiring in an hour. private static async Task SeedEngineBansAsync(EdgeFixture f, params string[] keys) { var now = DateTimeOffset.UtcNow; using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var i = 0; foreach (var key in keys) { db.Blocks.Add(new BlockEntry { SourceKey = key, Source = BlockSource.Engine, CreatedAt = now.AddMinutes(-20 + i), ExpiresAt = now.AddHours(1), Reason = "12 consecutive refusals 400-499 in 5 min" }); i++; } await db.SaveChangesAsync(); } private static async Task NetblocksAsync(EdgeFixture f) { using var response = await f.Client.GetAsync($"/admin-api/netblocks?token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); } private static async Task<(HttpStatusCode Status, JsonElement Body)> PolicyAsync(EdgeFixture f, object body) { using var response = await f.Client.PutAsJsonAsync( $"/admin-api/policy?token={EdgeFixture.AdminToken}", body); return (response.StatusCode, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone()); } [Fact] public async Task The_edge_offers_the_block_its_own_bans_point_at() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14", "198.51.100.9"); var body = await NetblocksAsync(f); Assert.Equal(5, body.GetProperty("threshold").GetInt32()); Assert.Equal(24, body.GetProperty("prefixV4").GetInt32()); Assert.Equal("this-edge", body.GetProperty("scope").GetString()); // The rules the numbers were produced with travel with them: a candidate // count without its threshold is a number an operator cannot read. var candidate = Assert.Single(body.GetProperty("netblocks").EnumerateArray()); Assert.Equal(Block, candidate.GetProperty("match").GetString()); // Five of the six bans, because the sixth is in another block: the offer // is one block, not "the edge has been busy". Assert.Equal(5, candidate.GetProperty("bans").GetInt32()); Assert.False(candidate.GetProperty("alreadyBanned").GetBoolean()); Assert.Equal(3, candidate.GetProperty("sample").GetArrayLength()); Assert.Contains("203.0.113.10", candidate.GetProperty("sample").ToString()); Assert.True(candidate.GetProperty("firstBanAt").GetDateTime() < candidate.GetProperty("lastBanAt").GetDateTime()); } [Fact] public async Task An_expired_ban_and_an_operators_row_are_not_evidence_about_a_netblock() { await using var f = new EdgeFixture(); var now = DateTimeOffset.UtcNow; using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); foreach (var key in new[] { "203.0.113.10", "203.0.113.11", "203.0.113.12" }) db.Blocks.Add(new BlockEntry { SourceKey = key, Source = BlockSource.Engine, ExpiresAt = now.AddHours(1) }); // Ages out on its own: the edge stopped honouring it, so it says // nothing about a block that is still worth banning. db.Blocks.Add(new BlockEntry { SourceKey = "203.0.113.13", Source = BlockSource.Engine, ExpiresAt = now.AddMinutes(-5) }); // The operator's own row is a decision already taken, not a pattern // the watch should offer back. db.Blocks.Add(new BlockEntry { SourceKey = "203.0.113.14", Source = BlockSource.Operator }); await db.SaveChangesAsync(); } Assert.Empty((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); } [Fact] public async Task An_offer_changes_nothing_on_the_wire() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); // The block is offered; the visitor inside it is still served. A watch // that started enforcing on its own would be a ban nobody authorised. using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); request.Headers.TryAddWithoutValidation("X-Forwarded-For", Inside); using var response = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); using var preview = await f.Client.GetAsync( $"/admin-api/decide?ip={Inside}&token={EdgeFixture.AdminToken}"); var verdict = JsonDocument.Parse(await preview.Content.ReadAsStringAsync()).RootElement; Assert.Equal("pass", verdict.GetProperty("verdict").GetString()); } [Fact] public async Task Banning_the_offered_range_closes_the_offer() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); using (var block = await f.Client.PostAsJsonAsync( $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Block, reason = "the netblock the edge noticed" })) Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); Assert.True(candidate.GetProperty("alreadyBanned").GetBoolean()); // And the range is in force, which is the point of taking the offer. using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); request.Headers.TryAddWithoutValidation("X-Forwarded-For", Inside); using var response = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.MovedPermanently, response.StatusCode); } [Fact] public async Task The_threshold_is_a_key_and_zero_is_the_watch_off() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12"); var (status, body) = await PolicyAsync(f, new { netblockCandidateBans = 3 }); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(3, body.GetProperty("netblockCandidateBans").GetInt32()); Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); (status, body) = await PolicyAsync(f, new { netblockCandidateBans = 0 }); Assert.Equal(HttpStatusCode.OK, status); var off = await NetblocksAsync(f); Assert.Equal(0, off.GetProperty("threshold").GetInt32()); Assert.Empty(off.GetProperty("netblocks").EnumerateArray()); Assert.Contains("off", off.GetProperty("note").GetString()); } [Fact] public async Task A_netblock_key_outside_its_bounds_is_refused_by_name() { await using var f = new EdgeFixture(); var (status, body) = await PolicyAsync(f, new { netblockPrefixV4 = 33 }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains("netblockPrefixV4", body.GetProperty("error").GetString()); Assert.Contains("8..31", body.GetProperty("error").GetString()); (status, body) = await PolicyAsync(f, new { netblockCandidateBans = -1 }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains("netblockCandidateBans", body.GetProperty("error").GetString()); (status, body) = await PolicyAsync(f, new { netblockPrefixV6 = 7 }); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains("netblockPrefixV6", body.GetProperty("error").GetString()); // Nothing moved: a refused write leaves the policy the edge is running on // exactly where it was. var current = await PolicyAsync(f, new { }); Assert.Equal(24, current.Body.GetProperty("netblockPrefixV4").GetInt32()); Assert.Equal(5, current.Body.GetProperty("netblockCandidateBans").GetInt32()); } [Fact] public async Task A_wider_block_is_a_different_offer() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "198.51.100.12", "192.0.2.13", "203.0.114.14"); var (status, _) = await PolicyAsync(f, new { netblockPrefixV4 = 16, netblockCandidateBans = 3 }); Assert.Equal(HttpStatusCode.OK, status); var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); Assert.Equal("203.0.0.0/16", candidate.GetProperty("match").GetString()); Assert.Equal(3, candidate.GetProperty("bans").GetInt32()); } [Fact] public async Task The_watch_raises_one_alert_per_block_rather_than_one_per_scan() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); await f.Service().ScanAndAlertAsync(CancellationToken.None); await f.Service().ScanAndAlertAsync(CancellationToken.None); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var alerts = await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync(); var alert = Assert.Single(alerts); Assert.Equal(Block, alert.SourceKey); Assert.Equal(5, alert.Count); Assert.Contains("203.0.113.0/24", alert.Detail); // The sentence the alert owes: nothing was banned, and the operator holds // the call that would change that. Assert.Contains("Nothing was banned", alert.Detail); } [Fact] public async Task Reading_the_list_is_not_news_and_raises_no_alert() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); await NetblocksAsync(f); await NetblocksAsync(f); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.Empty(await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync()); } [Fact] public async Task A_block_the_operator_already_wrote_is_not_shouted_at_again() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); using (var block = await f.Client.PostAsJsonAsync( $"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Block })) Assert.Equal(HttpStatusCode.NoContent, block.StatusCode); await f.Service().ScanAndAlertAsync(CancellationToken.None); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.Empty(await db.Alerts.Where(a => a.Kind == NetblockWatcher.AlertKind).ToListAsync()); } [Fact] public async Task The_state_says_whether_the_watch_ran_and_what_it_saw() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "203.0.113.10", "203.0.113.11", "203.0.113.12", "203.0.113.13", "203.0.113.14"); await f.Service().ScanAndAlertAsync(CancellationToken.None); using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}"); var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; Assert.Equal(5, state.GetProperty("netblockCandidateBans").GetInt32()); Assert.Equal(24, state.GetProperty("netblockPrefixV4").GetInt32()); Assert.Equal(48, state.GetProperty("netblockPrefixV6").GetInt32()); Assert.Equal(1, state.GetProperty("netblockCandidates").GetInt32()); Assert.True(state.GetProperty("netblockLastScanAt").GetDateTime() > DateTimeOffset.UnixEpoch); Assert.True(state.GetProperty("netblockScanError").ValueKind == JsonValueKind.Null); } [Fact] public async Task v6_bans_are_offered_one_allocation_up_from_the_key_they_are_stored_under() { await using var f = new EdgeFixture(); await SeedEngineBansAsync(f, "2001:db8:1:1::/64", "2001:db8:1:2::/64", "2001:db8:1:3::/64", "2001:db8:1:4::/64", "2001:db8:1:5::/64"); var candidate = Assert.Single((await NetblocksAsync(f)).GetProperty("netblocks").EnumerateArray()); Assert.Equal("2001:db8:1::/48", candidate.GetProperty("match").GetString()); Assert.Equal(5, candidate.GetProperty("bans").GetInt32()); } [Fact] public async Task A_change_to_a_netblock_key_is_recorded_like_any_other_policy_change() { await using var f = new EdgeFixture(); await PolicyAsync(f, new { netblockCandidateBans = 2 }); using var response = await f.Client.GetAsync( $"/admin-api/changes?section=policy&token={EdgeFixture.AdminToken}"); var rows = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; Assert.Contains("netblockCandidateBans 5->2", rows.ToString()); } [Fact] public async Task The_netblock_knobs_travel_with_the_operators_config() { await using var source = new EdgeFixture(); await PolicyAsync(source, new { netblockCandidateBans = 2, netblockPrefixV4 = 20 }); using var export = await source.Client.GetAsync( $"/admin-api/export?token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.OK, export.StatusCode); var document = await export.Content.ReadAsStringAsync(); Assert.Contains("netblockCandidateBans", document); Assert.Contains("netblockPrefixV4", document); await using var target = new EdgeFixture(); using var import = await target.Client.PostAsync( $"/admin-api/import?token={EdgeFixture.AdminToken}", new StringContent(document, Encoding.UTF8, "application/json")); Assert.Equal(HttpStatusCode.OK, import.StatusCode); var policy = await PolicyAsync(target, new { }); Assert.Equal(2, policy.Body.GetProperty("netblockCandidateBans").GetInt32()); Assert.Equal(20, policy.Body.GetProperty("netblockPrefixV4").GetInt32()); } }