using System.Net; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Security; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// A capped listing is only honest if the response says it is capped. The block /// listing already carried X-Total-Count and X-Truncated; the two the console /// reads most did not, and every listing clamped its limit instead of refusing /// one nobody meant. All three were measured on the shipped image (openwaf:ci) /// with 1103 sources recorded: /// GET /admin-api/observations?limit=100000 → 200, 1000 rows, no total, no /// truncation flag — 103 recorded sources were unreachable, and the /// response read like the whole answer /// GET /admin-api/observations?limit=0 and ?limit=-1 → 200, one row /// GET /admin-api/streaks?limit=1000 → 200, 2 streaks, trackedSources 3, /// X-Truncated: true — nothing had been cut; the third source's streak had /// been ended by a clean answer and the listing leaves those out on purpose /// public sealed class ListingCompletenessTests { private static string? Header(HttpResponseMessage r, string name) => r.Headers.TryGetValues(name, out var a) ? string.Join(",", a) : r.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b) : null; private static async Task<(HttpStatusCode Status, JsonElement Body, string? Total, string? Truncated, string Text)> GetAsync( EdgeFixture f, string url) { using var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); using var response = await f.Client.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); var body = response.StatusCode == HttpStatusCode.OK && text.Length > 0 ? JsonDocument.Parse(text).RootElement : default; return (response.StatusCode, body, Header(response, "X-Total-Count"), Header(response, "X-Truncated"), text); } private static string[] KeysOf(JsonElement body) => body.EnumerateArray().Select(e => e.GetProperty("sourceKey").GetString()!).ToArray(); [Fact] public async Task The_observation_listing_says_how_many_there_are_and_the_offset_reaches_the_rest() { await using var f = new EdgeFixture(threshold: 9); var sources = new[] { "203.0.113.201", "203.0.113.202", "203.0.113.203", "203.0.113.204", "203.0.113.205" }; foreach (var ip in sources) await f.SendAsync(f.Client, "/nope", ip); await f.FlushObservationsAsync(); var first = await GetAsync(f, "/admin-api/observations?limit=2"); Assert.Equal(HttpStatusCode.OK, first.Status); Assert.Equal("5", first.Total); Assert.Equal("true", first.Truncated); Assert.Equal(2, KeysOf(first.Body).Length); var second = await GetAsync(f, "/admin-api/observations?limit=2&offset=2"); Assert.Equal("5", second.Total); Assert.Equal("true", second.Truncated); Assert.Empty(KeysOf(first.Body).Intersect(KeysOf(second.Body))); var whole = await GetAsync(f, "/admin-api/observations?limit=1000"); Assert.Equal("false", whole.Truncated); Assert.Equal(5, KeysOf(whole.Body).Length); // Paging is not decorative here: it is the only way to reach a row the // cap would otherwise hide, so every recorded source has to be reachable. var seen = new List(); for (var offset = 0; offset < 5; offset++) { var page = await GetAsync(f, $"/admin-api/observations?limit=1&offset={offset}"); Assert.Equal("5", page.Total); seen.AddRange(KeysOf(page.Body)); } Assert.Equal(sources.Length, seen.Distinct().Count()); } [Fact] public async Task The_alert_listing_says_the_same_about_itself() { await using var f = new EdgeFixture(); var now = DateTimeOffset.UtcNow; using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); for (var i = 1; i <= 4; i++) db.Alerts.Add(new EdgeAlert { SourceKey = $"203.0.113.21{i}", Kind = "server_error_streak", Count = i, CreatedAt = now.AddMinutes(-i), Detail = "seeded for the listing" }); await db.SaveChangesAsync(); } var page = await GetAsync(f, "/admin-api/alerts?limit=3"); Assert.Equal(HttpStatusCode.OK, page.Status); Assert.Equal("4", page.Total); Assert.Equal("true", page.Truncated); Assert.Equal(3, page.Body.GetArrayLength()); var rest = await GetAsync(f, "/admin-api/alerts?limit=3&offset=3"); Assert.Equal("false", rest.Truncated); Assert.Equal(1, rest.Body.GetArrayLength()); } [Theory] [InlineData("/admin-api/observations?limit=0", "1..1000")] [InlineData("/admin-api/observations?limit=-1", "1..1000")] [InlineData("/admin-api/observations?limit=1001", "1..1000")] [InlineData("/admin-api/alerts?limit=0", "1..1000")] [InlineData("/admin-api/alerts?limit=1001", "1..1000")] [InlineData("/admin-api/blocks?limit=0", "1..2000")] [InlineData("/admin-api/blocks?limit=2001", "1..2000")] [InlineData("/admin-api/streaks?limit=0", "1..1000")] [InlineData("/admin-api/streaks?limit=1001", "1..1000")] public async Task A_limit_nobody_meant_is_refused_by_name_instead_of_becoming_one_row(string url, string range) { await using var f = new EdgeFixture(); await f.SendAsync(f.Client, "/nope", "203.0.113.221"); await f.FlushObservationsAsync(); var (status, _, _, _, text) = await GetAsync(f, url); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains($"limit must be {range}", text); } [Theory] [InlineData("/admin-api/observations?offset=-1")] [InlineData("/admin-api/alerts?offset=-1")] [InlineData("/admin-api/blocks?offset=-1")] [InlineData("/admin-api/streaks?offset=-1")] public async Task An_offset_before_the_first_row_is_refused(string url) { await using var f = new EdgeFixture(); var (status, _, _, _, text) = await GetAsync(f, url); Assert.Equal(HttpStatusCode.BadRequest, status); Assert.Contains("offset must be 0 or more", text); } [Fact] public async Task The_streak_listing_is_not_called_truncated_by_sources_whose_streak_a_clean_answer_ended() { await using var f = new EdgeFixture(threshold: 5); f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404; for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, "/probe", "203.0.113.231"); await f.SendAsync(f.Client, "/probe", "203.0.113.232"); await f.SendAsync(f.Client, "/probe", "203.0.113.233"); await f.SendAsync(f.Client, "/ok", "203.0.113.233"); var all = await GetAsync(f, "/admin-api/streaks?limit=1000"); Assert.Equal(HttpStatusCode.OK, all.Status); Assert.Equal("false", all.Truncated); Assert.Equal(3, all.Body.GetProperty("trackedSources").GetInt32()); Assert.Equal(2, all.Body.GetProperty("standingStreaks").GetInt32()); Assert.Equal(2, all.Body.GetProperty("streaks").GetArrayLength()); // And when something really is cut, the header says so and the offset // reaches the row that was cut. var one = await GetAsync(f, "/admin-api/streaks?limit=1"); Assert.Equal("true", one.Truncated); Assert.Equal(1, one.Body.GetProperty("streaks").GetArrayLength()); Assert.Equal("203.0.113.231", one.Body.GetProperty("streaks")[0].GetProperty("sourceKey").GetString()); var next = await GetAsync(f, "/admin-api/streaks?limit=1&offset=1"); Assert.Equal("false", next.Truncated); Assert.Equal("203.0.113.232", next.Body.GetProperty("streaks")[0].GetProperty("sourceKey").GetString()); } }