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; /// /// One source through time (OPEN-73): every decision this edge made about one /// address, in the order it made them. /// /// The records were never the problem. The block, the ban the edge wrote itself, /// the exemption, the range that covers the address, the alerts raised about it, /// the operator's change records and the row counting its refusals are all dated /// and all in this database — in six tables. An operator rebuilding the story by /// hand gets whichever listing they opened last, and the order — which is the /// answer — comes from memory. /// /// What these tests hold the surface to: the join reaches every store that can /// name the source or cover its address; a range is in the story because it /// covers the address, not because a row names it; expired rows stay and say so; /// the order is oldest-first whatever order the rows were written in; an empty /// story names what was searched; and asking writes nothing. /// public sealed class SourceHistoryTests { private const string Range = "203.0.113.64/29"; // .64 – .71 private const string Inside = "203.0.113.69"; private const string Source = "203.0.113.88"; private const string Nobody = "203.0.113.199"; private static async Task 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)> HistoryAsync( EdgeFixture f, string query, string? token = EdgeFixture.AdminToken) { using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/history?{query}", token: token); var text = await r.Content.ReadAsStringAsync(); // A refusal carries no body: an empty answer is an answer, and parsing it // would fail the test for the wrong reason. var body = string.IsNullOrWhiteSpace(text) ? default : JsonDocument.Parse(text).RootElement.Clone(); return (r.StatusCode, body); } private static async Task AskAsync(EdgeFixture f, string path, string ip) { using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); using var r = await f.Client.SendAsync(request); return (int)r.StatusCode; } /// Rows written straight to storage, because the API only accepts an /// expiry or a creation time relative to now and the test needs the order. private static async Task SeedAsync(EdgeFixture f, object row) { using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Add(row); await db.SaveChangesAsync(); await f.Service().InvalidateAsync(); } private static List Events(JsonElement body) => body.GetProperty("events").EnumerateArray().ToList(); private static bool HasKind(List events, string kind) => events.Any(e => e.GetProperty("kind").GetString() == kind); [Fact] public async Task The_story_joins_every_record_that_names_or_covers_the_address() { await using var f = new EdgeFixture(); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range, reason = "netblock scanning the site" })) { } using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Inside, reason = "the office behind it" })) { } await SeedAsync(f, new AllowEntry { Match = Inside, Note = "ticket 441", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-20) }); await AskAsync(f, "/anything", Inside); // The observation row is written off the response, on the writer's own // timer — the same reason every other surface that reads it flushes first. await f.FlushObservationsAsync(); var (status, body) = await HistoryAsync(f, $"ip={Inside}"); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(Inside, body.GetProperty("ip").GetString()); Assert.Equal(Inside, body.GetProperty("sourceKey").GetString()); Assert.Equal("database", body.GetProperty("scope").GetString()); var events = Events(body); Assert.True(events.Count >= 5, body.ToString()); foreach (var kind in new[] { "operator block", "range ban", "allow entry", "config change", "seen" }) Assert.True(HasKind(events, kind), $"no {kind} event in {body.GetProperty("count").GetInt32()} events"); // The range is in this address's story although no row names the address. var range = events.Single(e => e.GetProperty("kind").GetString() == "range ban"); Assert.Equal(Range, range.GetProperty("match").GetString()); Assert.True(range.GetProperty("inForce").GetBoolean()); Assert.Contains("covers this address", range.GetProperty("what").GetString()!); Assert.Contains("netblock scanning", range.GetProperty("detail").GetString()!); // A change to that range is a change to this source's conditions, so the // change record belongs in this address's story even though the operator // typed a CIDR and not this address. var changes = events.Where(e => e.GetProperty("kind").GetString() == "config change").ToList(); Assert.Contains(changes, e => e.GetProperty("match").GetString() == Range); Assert.Contains(changes, e => e.GetProperty("match").GetString() == Inside); Assert.True(body.GetProperty("searched").GetProperty("change").GetInt32() >= 2); } [Fact] public async Task An_alert_and_a_ban_the_edge_wrote_itself_are_both_in_the_source_story() { await using var f = new EdgeFixture(threshold: 3); f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway; for (var i = 0; i < 4; i++) await AskAsync(f, "/boom", Source); f.Upstream.StatusFor = _ => StatusCodes.Status404NotFound; for (var i = 0; i < 3; i++) await AskAsync(f, "/wp-login.php", Source); await f.FlushObservationsAsync(); var (_, body) = await HistoryAsync(f, $"ip={Source}"); var events = Events(body); var ban = Assert.Single(events, e => e.GetProperty("kind").GetString() == "engine ban"); Assert.Equal(Source, ban.GetProperty("match").GetString()); Assert.True(ban.GetProperty("inForce").GetBoolean()); Assert.Contains("banned the source itself", ban.GetProperty("what").GetString()!); Assert.Contains("last 404 /wp-login.php", ban.GetProperty("detail").GetString()!); Assert.True(HasKind(events, "alert"), body.ToString()); var alert = events.First(e => e.GetProperty("kind").GetString() == "alert"); Assert.Equal("server_error_streak", alert.GetProperty("what").GetString()!.Split(' ')[1]); // An alert is an event, not a state: "is it in force" is not a question it // answers, and false would say it had been switched off. Assert.True(alert.TryGetProperty("inForce", out var force) ? force.ValueKind == JsonValueKind.Null : true); Assert.True(HasKind(events, "seen"), body.ToString()); } [Fact] public async Task A_range_that_only_covers_the_address_is_still_part_of_its_history() { await using var f = new EdgeFixture(); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range, reason = "rotating scanner" })) { } var (_, body) = await HistoryAsync(f, $"ip={Inside}"); var range = Assert.Single(Events(body), e => e.GetProperty("kind").GetString() == "range ban"); Assert.Equal(Range, range.GetProperty("match").GetString()); Assert.Equal(1, body.GetProperty("searched").GetProperty("range").GetInt32()); // An address outside the range is not told it is inside it. var (_, other) = await HistoryAsync(f, "ip=203.0.113.72"); Assert.Equal(0, other.GetProperty("searched").GetProperty("range").GetInt32()); } [Fact] public async Task An_expired_row_stays_in_the_story_and_says_it_stopped_being_in_force() { await using var f = new EdgeFixture(); await SeedAsync(f, new AllowEntry { Match = Inside, Note = "the window the ticket gave", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-60), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5) }); var (_, body) = await HistoryAsync(f, $"ip={Inside}"); var allow = Assert.Single(Events(body), e => e.GetProperty("kind").GetString() == "allow entry"); Assert.False(allow.GetProperty("inForce").GetBoolean()); Assert.NotEqual(JsonValueKind.Null, allow.GetProperty("expiresAt").ValueKind); Assert.Contains("the window the ticket gave", allow.GetProperty("detail").GetString()!); // The store was searched and the row was found: an expired row is not the // same answer as nothing having ever been written. Assert.Equal(1, body.GetProperty("searched").GetProperty("allow").GetInt32()); Assert.Equal(1, body.GetProperty("count").GetInt32()); } [Fact] public async Task The_order_is_oldest_first_whatever_order_the_rows_were_written_in() { await using var f = new EdgeFixture(); var now = DateTimeOffset.UtcNow; // Written newest-first on purpose: the order of the writes is not the // order of the story, and reading it backwards turns "the exemption, then // the ban" into "the ban, then the exemption". await SeedAsync(f, new BlockEntry { SourceKey = Source, Source = BlockSource.Operator, Reason = "ban, an hour later", CreatedAt = now.AddMinutes(-30) }); await SeedAsync(f, new AllowEntry { Match = Source, Note = "exemption first", CreatedAt = now.AddMinutes(-90) }); var (_, body) = await HistoryAsync(f, $"ip={Source}"); var events = Events(body); Assert.Equal(2, events.Count); Assert.Equal("allow entry", events[0].GetProperty("kind").GetString()); Assert.Equal("operator block", events[1].GetProperty("kind").GetString()); var stamps = events.Select(e => DateTimeOffset.Parse(e.GetProperty("at").GetString()!)).ToList(); Assert.True(stamps[0] < stamps[1], string.Join(" then ", stamps)); } [Fact] public async Task An_address_with_nothing_recorded_is_answered_in_words_with_what_was_searched() { await using var f = new EdgeFixture(); var (status, body) = await HistoryAsync(f, $"ip={Nobody}"); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(0, body.GetProperty("count").GetInt32()); Assert.Empty(Events(body)); foreach (var key in new[] { "block", "range", "allow", "alert", "change", "observation" }) Assert.Equal(0, body.GetProperty("searched").GetProperty(key).GetInt32()); Assert.Contains("nothing recorded", body.GetProperty("note").GetString()!); } [Fact] public async Task A_window_or_a_limit_it_cannot_answer_with_is_refused_by_name() { await using var f = new EdgeFixture(); foreach (var query in new[] { "ip=203.0.113.88&within=0", "ip=203.0.113.88&within=129601", "ip=203.0.113.88&limit=0", "ip=203.0.113.88&limit=2001", "ip=203.0.113.88&nonsense=1", "within=60", "ip=203.0.113" }) { var (status, body) = await HistoryAsync(f, query); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.False(string.IsNullOrWhiteSpace(body.GetProperty("error").GetString())); } } [Fact] public async Task Reading_a_story_writes_nothing_and_the_read_only_token_may_ask_it() { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Source, reason = "incident" })) { } Assert.Equal(HttpStatusCode.OK, (await HistoryAsync(f, $"ip={Source}")).Status); // A story is a read: the token that can look but not change may ask it, // and the answer is the same one the write token gets. var (readOnly, readOnlyBody) = await HistoryAsync(f, $"ip={Source}", token: EdgeFixture.ReadOnlyToken); Assert.Equal(HttpStatusCode.OK, readOnly); Assert.Equal(1, readOnlyBody.GetProperty("searched").GetProperty("block").GetInt32()); var before = await CountAsync(f); for (var i = 0; i < 6; i++) await HistoryAsync(f, $"ip={Source}"); Assert.Equal(before, await CountAsync(f)); var (noToken, _) = await HistoryAsync(f, $"ip={Source}", token: null); Assert.Equal(HttpStatusCode.Unauthorized, noToken); } private static async Task CountAsync(EdgeFixture f) { using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return $"{await db.Blocks.CountAsync()} {await db.Alerts.CountAsync()} " + $"{await db.AllowEntries.CountAsync()} {await db.ConfigChanges.CountAsync()} " + $"{await db.Observations.CountAsync()}"; } }