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.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// The volume half of the dry run (OPEN-69). The preview used to answer every /// pillar and stay silent about the one whose number the operator is choosing — /// "would this source be rate-limited" was a question the surface that exists to /// answer such questions could not ask. /// /// The property these tests exist to hold is the one that makes the section worth /// shipping: it reads the counters and never spends them. A preview that answered /// by counting its own question would refuse the next real request because /// somebody pressed a button. /// public sealed class VolumeDryRunTests { private const string Source = "203.0.113.140"; private static async Task DecideAsync(EdgeFixture f, string query) { using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/decide?{query}"); request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); using var r = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, r.StatusCode); return JsonDocument.Parse(await r.Content.ReadAsStringAsync()); } private static async Task GetAsync(EdgeFixture f, string path, string ip = Source) { 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) { using var request = new HttpRequestMessage(method, url); request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); if (body is not null) request.Content = JsonContent.Create(body); return await f.Client.SendAsync(request); } private static void OriginAnswersEverything(EdgeFixture f) => f.Upstream.StatusFor = _ => StatusCodes.Status200OK; [Fact] public async Task The_preview_answers_the_volume_pillar_it_used_to_leave_silent() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120); OriginAnswersEverything(f); using (await GetAsync(f, "/catalog")) { } // Inside the budget: the preview says so, and says the pillar would be // reached at all. This is the reading an operator wants before tightening // a number — "two of two, nothing crossed yet". using var before = await DecideAsync(f, $"ip={Source}&path=/catalog"); var early = before.RootElement.GetProperty("volume"); Assert.Equal("Enforce", early.GetProperty("mode").GetString()); Assert.Equal("this-process", early.GetProperty("scope").GetString()); Assert.Equal("would_be_counted", early.GetProperty("verdict").GetString()); Assert.True(early.GetProperty("reached").GetBoolean()); Assert.Equal(1, early.GetProperty("edgeBudget").GetProperty("count").GetInt32()); Assert.False(early.GetProperty("edgeBudget").GetProperty("overBudget").GetBoolean()); // The pillar row that used to be a silence now says where the answer is. var rateRow = before.RootElement.GetProperty("pillars").EnumerateArray() .First(p => p.GetProperty("pillar").GetString() == "rate"); Assert.Equal("not_evaluated", rateRow.GetProperty("outcome").GetString()); Assert.Contains("volume", rateRow.GetProperty("note").GetString()!); using (await GetAsync(f, "/catalog")) { } using (var over = await GetAsync(f, "/catalog")) Assert.Equal((HttpStatusCode)429, over.StatusCode); using var body = await DecideAsync(f, $"ip={Source}&path=/catalog"); var volume = body.RootElement.GetProperty("volume"); Assert.Equal("refused_now", volume.GetProperty("verdict").GetString()); var edge = volume.GetProperty("edgeBudget"); Assert.Equal(3, edge.GetProperty("count").GetInt32()); Assert.Equal(2, edge.GetProperty("limitPerWindow").GetInt32()); Assert.Equal(120, edge.GetProperty("windowSeconds").GetDouble()); Assert.True(edge.GetProperty("overBudget").GetBoolean()); // The answer says how long the pause runs, because "over budget" without // an end is a sentence an operator cannot act on. Assert.True(edge.GetProperty("secondsLeft").GetInt32() >= 1); // The crossing also wrote the engine ban the edge-wide budget has always // written, so this request is now answered before the volume pillar is // reached — and the note says that, instead of going on talking about a // budget this request would never touch. Assert.False(volume.GetProperty("reached").GetBoolean()); Assert.Contains("an earlier pillar answers this request", volume.GetProperty("note").GetString()!); // The crossing also wrote the engine ban the edge-wide budget has always // written, so this request is now answered by an earlier pillar — and the // answer says which, rather than letting the volume section speak as if it // would be consulted. } [Fact] public async Task With_the_pillar_off_the_preview_says_nothing_is_counted() { await using var f = new EdgeFixture(); OriginAnswersEverything(f); for (var i = 0; i < 4; i++) using (await GetAsync(f, "/catalog")) { } using var body = await DecideAsync(f, $"ip={Source}&path=/catalog"); var volume = body.RootElement.GetProperty("volume"); Assert.Equal("not_counted", volume.GetProperty("verdict").GetString()); Assert.Equal(JsonValueKind.Null, volume.GetProperty("edgeBudget").ValueKind); Assert.Equal(0, volume.GetProperty("pathBudgets").GetArrayLength()); Assert.Contains("nothing is counted", volume.GetProperty("note").GetString()!); } [Fact] public async Task An_observe_crossing_is_reported_without_promising_a_refusal() { await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 2, rateWindowSeconds: 120); OriginAnswersEverything(f); for (var i = 0; i < 4; i++) using (var probe = await GetAsync(f, "/catalog")) Assert.Equal(HttpStatusCode.OK, probe.StatusCode); using var body = await DecideAsync(f, $"ip={Source}&path=/catalog"); var volume = body.RootElement.GetProperty("volume"); Assert.Equal("over_budget_not_enforced", volume.GetProperty("verdict").GetString()); Assert.True(volume.GetProperty("edgeBudget").GetProperty("overBudget").GetBoolean()); Assert.Contains("Observe mode enforces nothing", volume.GetProperty("note").GetString()!); } [Fact] public async Task A_dry_run_does_not_spend_the_budget_it_is_asking_about() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 5, rateWindowSeconds: 120); OriginAnswersEverything(f); using (await GetAsync(f, "/catalog")) { } using (await GetAsync(f, "/catalog")) { } async Task Counted() { using var listing = await AdminAsync(f, HttpMethod.Get, $"/admin-api/rate?source={Source}"); using var doc = JsonDocument.Parse(await listing.Content.ReadAsStringAsync()); return doc.RootElement.GetProperty("sources")[0].GetProperty("count").GetInt32(); } Assert.Equal(2, await Counted()); for (var i = 0; i < 6; i++) using (var preview = await DecideAsync(f, $"ip={Source}&path=/catalog")) Assert.Equal(2, preview.RootElement.GetProperty("volume").GetProperty("edgeBudget").GetProperty("count").GetInt32()); // Six previews left the counter exactly where it was, and the next real // request is the third of the window rather than the ninth. Assert.Equal(2, await Counted()); using (await GetAsync(f, "/catalog")) { } Assert.Equal(3, await Counted()); using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.Equal(0, await db.Alerts.AsNoTracking().CountAsync(a => a.Kind == "rate_breach")); } [Fact] public async Task The_preview_lists_only_the_path_budgets_that_match_the_asked_path() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 120); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 120 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (await GetAsync(f, "/login")) { } using (await GetAsync(f, "/login")) { } using (var over = await GetAsync(f, "/login")) Assert.Equal((HttpStatusCode)429, over.StatusCode); using (var onPath = await DecideAsync(f, $"ip={Source}&path=/login")) { var budgets = onPath.RootElement.GetProperty("volume").GetProperty("pathBudgets"); var seen = budgets.EnumerateArray().Single(); Assert.Equal("/login*", seen.GetProperty("pattern").GetString()); Assert.True(seen.GetProperty("counted").GetBoolean()); Assert.Equal(3, seen.GetProperty("count").GetInt32()); Assert.True(seen.GetProperty("overBudget").GetBoolean()); Assert.True(seen.GetProperty("secondsLeft").GetInt32() >= 1); Assert.Contains("/login*", onPath.RootElement.GetProperty("volume").GetProperty("note").GetString()!); } // The same source, a path the budget does not name: the pause is about one // part of the site, and the preview has to say so or it describes a ban. using (var offPath = await DecideAsync(f, $"ip={Source}&path=/catalog")) { var volume = offPath.RootElement.GetProperty("volume"); Assert.Equal(0, volume.GetProperty("pathBudgets").GetArrayLength()); Assert.Equal("would_be_counted", volume.GetProperty("verdict").GetString()); } } [Fact] public async Task A_budget_in_force_for_the_path_with_nothing_counted_yet_is_not_reported_as_a_zero() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 120); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 120 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using var body = await DecideAsync(f, $"ip=203.0.113.199&path=/login"); var seen = body.RootElement.GetProperty("volume").GetProperty("pathBudgets").EnumerateArray().Single(); Assert.False(seen.GetProperty("counted").GetBoolean()); Assert.Equal(JsonValueKind.Null, seen.GetProperty("count").ValueKind); Assert.False(seen.GetProperty("overBudget").GetBoolean()); } [Fact] public async Task A_request_an_earlier_pillar_answers_never_reaches_the_counter() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120); OriginAnswersEverything(f); using (var rule = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", new { pattern = "/secret*", action = "block", note = "preview test" })) Assert.Equal(HttpStatusCode.NoContent, rule.StatusCode); using var body = await DecideAsync(f, $"ip={Source}&path=/secret"); Assert.True(body.RootElement.GetProperty("blocked").GetBoolean()); var volume = body.RootElement.GetProperty("volume"); Assert.False(volume.GetProperty("reached").GetBoolean()); Assert.Contains("an earlier pillar answers this request", volume.GetProperty("note").GetString()!); } [Fact] public async Task A_question_about_the_path_alone_says_a_budget_is_a_claim_about_a_source() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 120); using var body = await DecideAsync(f, "path=/catalog"); var volume = body.RootElement.GetProperty("volume"); Assert.Equal("no_source", volume.GetProperty("verdict").GetString()); Assert.Equal(JsonValueKind.Null, body.RootElement.GetProperty("sourceKey").ValueKind); } }