using System.Net; using System.Net.Http.Json; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Domain.Security; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// One address, one answer (OPEN-70). /// /// Every operator surface here is a table with a filter on it, so investigating /// one source meant opening six calls and holding the join in one's head. The /// join is where the mistakes live: a v6 address looked up in full when the ban /// is keyed on the /64, an expired exemption read as a live one, a CIDR ban an /// equality lookup never finds, a per-process streak read as the deployment's. /// /// What these tests hold the surface to, in order: containment rather than /// equality for ranges and exemptions; the key rather than the address for bans /// and budgets; an expired row named as expired rather than as absent; the scope /// of every part named in the answer; a question it cannot answer refused by /// name; the read-only token able to ask it; and nothing spent by asking it. /// public sealed class SourceDossierTests { private const string Range = "203.0.113.16/28"; // .16 – .31 private const string Inside = "203.0.113.21"; private const string Outside = "203.0.113.32"; private const string Source = "203.0.113.77"; private static async Task DossierAsync( EdgeFixture f, string query, string? token = EdgeFixture.AdminToken) { using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/source?{query}"); if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); using var r = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, r.StatusCode); return JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone(); } private static async Task<(HttpStatusCode Status, string Error)> AskAsync(EdgeFixture f, string query) { using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/source?{query}"); request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); using var r = await f.Client.SendAsync(request); return (r.StatusCode, await r.Content.ReadAsStringAsync()); } 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 AdminAsync( EdgeFixture f, HttpMethod method, string url, object? body = null, string token = EdgeFixture.AdminToken) { using var request = new HttpRequestMessage(method, url); request.Headers.TryAddWithoutValidation("X-Admin-Token", token); if (body is not null) request.Content = JsonContent.Create(body); return await f.Client.SendAsync(request); } /// Three refusals in a row from one address: the engine's own ban, /// the streak that produced it and the durable row that remembers it. private static async Task BanByTheEngineAsync(EdgeFixture f, string ip) { for (var i = 0; i < 3; i++) using (var r = await GetAsync(f, "/wp-login.php", ip)) Assert.Equal(HttpStatusCode.NotFound, r.StatusCode); await f.FlushObservationsAsync(); } [Fact] public async Task One_call_answers_what_this_edge_knows_about_one_address() { await using var f = new EdgeFixture(); await BanByTheEngineAsync(f, Source); var body = await DossierAsync(f, $"ip={Source}"); Assert.Equal(Source, body.GetProperty("ip").GetString()); Assert.Equal(Source, body.GetProperty("sourceKey").GetString()); // The key rule travels with the key: without it, a v6 sourceKey looks // like a typo of the address the operator typed. Assert.Equal(32, body.GetProperty("keyRule").GetProperty("ipv4PrefixLength").GetInt32()); Assert.Equal(64, body.GetProperty("keyRule").GetProperty("ipv6PrefixLength").GetInt32()); Assert.Equal("block_engine", body.GetProperty("verdict").GetString()); Assert.Contains("banned", body.GetProperty("answer").GetString()!); var ban = body.GetProperty("engineBan"); Assert.True(ban.GetProperty("live").GetBoolean()); Assert.True(ban.GetProperty("applies").GetBoolean()); Assert.Equal("database", ban.GetProperty("scope").GetString()); Assert.False(string.IsNullOrEmpty(ban.GetProperty("reason").GetString())); Assert.Equal("/wp-login.php", ban.GetProperty("lastPath").GetString()); // The two stores of the same source's history, named apart: the standing // counter is this process's, the maximum is the database's. var streak = body.GetProperty("streak"); Assert.Equal("this-process", streak.GetProperty("scope").GetString()); Assert.Equal(3, streak.GetProperty("consecutiveRefusals").GetInt32()); Assert.Equal(3, streak.GetProperty("threshold").GetInt32()); Assert.Equal(3, streak.GetProperty("maxConsecutiveEver").GetInt32()); Assert.Equal("database", streak.GetProperty("durableScope").GetString()); Assert.Equal("this-process", body.GetProperty("volume").GetProperty("scope").GetString()); Assert.Empty(body.GetProperty("netblockOffers").EnumerateArray()); // No path was asked for, so the path-dependent pillars are named as // unasked rather than answered as clear. Assert.True(body.GetProperty("wouldAnswer").ValueKind == JsonValueKind.Null); Assert.Contains("path", body.GetProperty("answerScope").GetString()!); } [Fact] public async Task A_range_ban_answers_for_every_address_it_covers_and_says_where_it_came_from() { await using var f = new EdgeFixture(); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range, reason = "netblock scanning" })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); var covered = await DossierAsync(f, $"ip={Inside}"); Assert.Equal("block_operator", covered.GetProperty("verdict").GetString()); var ban = covered.GetProperty("operatorBlock"); // The distinction the operator has to be able to see: this address is not // on the list, a network that contains it is. Assert.True(ban.GetProperty("cameFromRange").GetBoolean()); Assert.Equal(Range, ban.GetProperty("match").GetString()); Assert.Equal("netblock scanning", ban.GetProperty("reason").GetString()); Assert.Contains(Range, covered.GetProperty("answer").GetString()!); // The neighbour one address past the end is not answered by that row, and // "nothing" is said as none rather than as an empty object. var neighbour = await DossierAsync(f, $"ip={Outside}"); Assert.Equal("none", neighbour.GetProperty("verdict").GetString()); Assert.True(neighbour.GetProperty("operatorBlock").ValueKind == JsonValueKind.Null); } [Fact] public async Task An_exemption_inside_a_banned_range_is_an_exemption() { await using var f = new EdgeFixture(); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range })) { } using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", new { match = Inside, note = "the office" })) { } var body = await DossierAsync(f, $"ip={Inside}"); Assert.Equal("pass_allowlisted", body.GetProperty("verdict").GetString()); Assert.Equal("the office", body.GetProperty("allow").GetProperty("note").GetString()); Assert.True(body.GetProperty("allow").GetProperty("live").GetBoolean()); // The dossier and the wire agree: the same containment rule, asked once. using (var served = await GetAsync(f, "/anything", Inside)) Assert.NotEqual(HttpStatusCode.MovedPermanently, served.StatusCode); } [Fact] public async Task An_expired_row_is_named_as_expired_rather_than_as_absent() { await using var f = new EdgeFixture(); using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); db.AllowEntries.Add(new AllowEntry { Match = Source, Note = "was exempt", CreatedAt = DateTimeOffset.UtcNow.AddDays(-3), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1) }); db.Blocks.Add(new BlockEntry { SourceKey = Source, Source = BlockSource.Operator, CreatedAt = DateTimeOffset.UtcNow.AddDays(-3), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1), Reason = "an incident that ended" }); await db.SaveChangesAsync(); await f.Service().InvalidateAsync(); } var body = await DossierAsync(f, $"ip={Source}"); // Both rows exist and neither answers: an operator deciding whether to // re-ban needs to know the row was there, and "null" would say it never was. Assert.False(body.GetProperty("allow").GetProperty("live").GetBoolean()); Assert.Equal("was exempt", body.GetProperty("allow").GetProperty("note").GetString()); Assert.False(body.GetProperty("operatorBlock").GetProperty("live").GetBoolean()); Assert.Equal("an incident that ended", body.GetProperty("operatorBlock").GetProperty("reason").GetString()); // Nothing live refuses this source, so the answer is none — not a verdict // borrowed from the dead rows. Assert.Equal("none", body.GetProperty("verdict").GetString()); } [Fact] public async Task A_live_engine_ban_in_observe_mode_is_reported_and_said_not_to_apply() { // The shape this actually takes: the ban was written while the edge // enforced, and the operator switched the mode afterwards. A ban that is // standing and enforcing nothing is the reading an operator has to be able // to see, because the mode going back to Enforce puts it back on the wire. await using var f = new EdgeFixture(); await BanByTheEngineAsync(f, Source); using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { mode = "Observe" })) { } var body = await DossierAsync(f, $"ip={Source}"); var ban = body.GetProperty("engineBan"); Assert.True(ban.GetProperty("live").GetBoolean()); Assert.False(ban.GetProperty("applies").GetBoolean()); Assert.Equal("Observe", ban.GetProperty("enforcementMode").GetString()); Assert.Equal("none", body.GetProperty("verdict").GetString()); Assert.Contains("enforces nothing", body.GetProperty("answer").GetString()!); } [Fact] public async Task An_ipv6_source_is_answered_on_its_key_and_not_on_its_address() { await using var f = new EdgeFixture(); // One /64, two addresses: the allocation is one source, which is the only // way a v6 streak rule means anything. await BanByTheEngineAsync(f, "2001:db8:1:2::10"); var body = await DossierAsync(f, "ip=2001:db8:1:2::11"); Assert.Equal("2001:db8:1:2::/64", body.GetProperty("sourceKey").GetString()); // Looked up by the address the operator typed, this dossier would have // answered "nothing known" about a source this edge has already banned. Assert.Equal("block_engine", body.GetProperty("verdict").GetString()); Assert.Equal("2001:db8:1:2::/64", body.GetProperty("engineBan").GetProperty("sourceKey").GetString()); Assert.Equal(3, body.GetProperty("streak").GetProperty("consecutiveRefusals").GetInt32()); } [Fact] public async Task A_path_budget_this_source_is_inside_appears_without_a_path_being_asked() { // A path budget counts only while the volume pillar counts at all, so the // edge-wide limit is set far above the rule's: the rule is what is being // asked about here, not the site-wide number. await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 100, rateWindowSeconds: 300); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 5, windowSeconds = 120, note = "stuffing" })) { } using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/other*", limitPerWindow = 5 })) { } for (var i = 0; i < 2; i++) using (await GetAsync(f, "/login", Source)) { } var budgets = (await DossierAsync(f, $"ip={Source}")) .GetProperty("volume").GetProperty("pathBudgets"); // Only the budget this source is actually inside, with the pattern it was // written under — an id alone is a number an operator cannot read. var row = Assert.Single(budgets.EnumerateArray()); Assert.Equal("/login*", row.GetProperty("pattern").GetString()); Assert.Equal(2, row.GetProperty("count").GetInt32()); Assert.Equal(5, row.GetProperty("limitPerWindow").GetInt32()); Assert.Equal(120, row.GetProperty("windowSeconds").GetInt32()); Assert.False(row.GetProperty("overBudget").GetBoolean()); Assert.True(row.GetProperty("secondsLeft").GetInt32() > 0); } [Fact] public async Task Asking_the_dossier_spends_none_of_the_budget_it_reports() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 300); using (await GetAsync(f, "/catalog", Source)) { } for (var i = 0; i < 4; i++) { var body = await DossierAsync(f, $"ip={Source}"); // The same number every time: the dossier reads the counters and does // not move them. Assert.Equal(1, body.GetProperty("volume").GetProperty("edgeBudget").GetProperty("count").GetInt32()); } using (await GetAsync(f, "/catalog", Source)) { } using (var refused = await GetAsync(f, "/catalog", Source)) Assert.Equal((HttpStatusCode)429, refused.StatusCode); // The refusal is the third real request, not the fourth look at a page. } [Fact] public async Task With_a_path_the_dossier_and_the_dry_run_answer_the_same_verdict() { await using var f = new EdgeFixture(); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range })) { } var dossier = await DossierAsync(f, $"ip={Inside}&path=/anything"); Assert.Equal("/anything", dossier.GetProperty("askedPath").GetString()); var would = dossier.GetProperty("wouldAnswer"); Assert.Equal("block_operator", would.GetProperty("verdict").GetString()); Assert.True(would.GetProperty("blocked").GetBoolean()); Assert.Equal(301, would.GetProperty("status").GetInt32()); Assert.Equal(Range, would.GetProperty("range").GetString()); // The volume pillar is answered, not left silent, and it says it spent // nothing: an earlier pillar answers, so the counter is never reached. Assert.Equal("not_counted", would.GetProperty("volume").GetProperty("verdict").GetString()); using var preview = await AdminAsync(f, HttpMethod.Get, $"/admin-api/decide?ip={Inside}&path=/anything"); using var doc = JsonDocument.Parse(await preview.Content.ReadAsStringAsync()); Assert.Equal( would.GetProperty("verdict").GetString(), doc.RootElement.GetProperty("verdict").GetString()); } [Fact] public async Task A_question_this_surface_cannot_answer_is_refused_by_name() { await using var f = new EdgeFixture(); var missing = await AskAsync(f, ""); Assert.Equal(HttpStatusCode.BadRequest, missing.Status); Assert.Contains("ip is required", missing.Error); var blank = await AskAsync(f, "ip="); Assert.Equal(HttpStatusCode.BadRequest, blank.Status); // A typo in the address must not answer "nothing known about this source". var typo = await AskAsync(f, "ip=203.0.113"); Assert.Equal(HttpStatusCode.BadRequest, typo.Status); Assert.Contains("must be an address", typo.Error); var badPath = await AskAsync(f, $"ip={Source}&path=anything"); Assert.Equal(HttpStatusCode.BadRequest, badPath.Status); Assert.Contains("path must start with /", badPath.Error); var unknown = await AskAsync(f, $"ip={Source}&addres={Source}"); Assert.Equal(HttpStatusCode.BadRequest, unknown.Status); Assert.Contains("addres", unknown.Error); } [Fact] public async Task The_read_only_token_reads_a_dossier_and_changes_nothing() { await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Source, reason = "written by the operator" })) { } var body = await DossierAsync(f, $"ip={Source}", EdgeFixture.ReadOnlyToken); Assert.Equal("block_operator", body.GetProperty("verdict").GetString()); // The list is what it was, and the change log holds only the operator's // own write — a read that left a record would be a write wearing a mask. using (var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?live=false", token: EdgeFixture.ReadOnlyToken)) { Assert.Equal(HttpStatusCode.OK, blocks.StatusCode); using var doc = JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()); Assert.Single(doc.RootElement.EnumerateArray()); } using (var changes = await AdminAsync(f, HttpMethod.Get, "/admin-api/changes", token: EdgeFixture.ReadOnlyToken)) { Assert.Equal(HttpStatusCode.OK, changes.StatusCode); using var doc = JsonDocument.Parse(await changes.Content.ReadAsStringAsync()); Assert.Single(doc.RootElement.EnumerateArray()); } // No token at all is not the read-only level: the surface stays shut. using (var anonymous = await f.Client.GetAsync($"/admin-api/source?ip={Source}")) Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); } }