using System.Net; using System.Net.Http.Json; using Microsoft.AspNetCore.Http; using System.Text; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// A request budget written for one path instead of for the whole edge (OPEN-68). /// /// The edge-wide budget forces one number on every path, and for a login page /// that number is always wrong: high enough for an office behind one NAT, and /// useless against a credential-stuffing run. These tests hold the claim the /// feature makes — the pause is for that path and for nothing else, and it is /// not a ban. /// public sealed class RateRuleTests { private const string Visitor = "203.0.113.140"; private static async Task GetAsync(EdgeFixture f, string path, string ip = Visitor) { 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 async Task BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync(); private static void OriginAnswersEverything(EdgeFixture f) => f.Upstream.StatusFor = _ => StatusCodes.Status200OK; [Fact] public async Task A_path_budget_refuses_that_path_and_leaves_the_rest_of_the_site_open() { // The edge-wide budget is set far above the path budget on purpose: the // 429 below has to be the path rule's answer, not the site's. await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60, note = "credential stuffing" })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (var first = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, first.StatusCode); using (var second = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, second.StatusCode); using (var over = await GetAsync(f, "/login")) { Assert.Equal((HttpStatusCode)429, over.StatusCode); var body = await BodyAsync(over); Assert.Contains("rate_limited", body); // The reason names the rule, its count, its limit and the pattern it // was written for, so an operator reading a log line can tell which // budget fired without opening the console. Assert.Contains("rate_rule_", body); Assert.Contains("_3_of_2_for_/login*", body); Assert.True(over.Headers.TryGetValues("Retry-After", out var values)); Assert.True(int.Parse(values!.First()) >= 1); } // The path the budget names but does not match still flows, and so does // every other path. This is the whole point of the feature: the pause is // about one part of the site. using (var other = await GetAsync(f, "/index.html")) Assert.Equal(HttpStatusCode.OK, other.StatusCode); lock (f.Upstream.Paths) { Assert.Equal(2, f.Upstream.Paths.Count(p => p == "/login")); Assert.Contains("/index.html", f.Upstream.Paths); } } [Fact] public async Task Crossing_a_path_budget_writes_no_ban_so_the_visitor_keeps_the_rest_of_the_site() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/reset", limitPerWindow = 1, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); for (var i = 0; i < 4; i++) { using var probe = await GetAsync(f, "/reset"); Assert.True(probe.StatusCode is HttpStatusCode.OK or HttpStatusCode.TooManyRequests); } using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); // The edge-wide budget answers a rate breach with a ban, because // there the claim is about the whole site. A path budget makes a // narrower claim, so it writes nothing that outlives the window. var written = await db.Blocks.AsNoTracking().ToListAsync(); Assert.Empty(written); } } [Fact] public async Task An_observe_budget_refuses_nothing_and_says_what_it_would_have_blocked() { await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); for (var i = 0; i < 5; i++) { using var probe = await GetAsync(f, "/login"); Assert.Equal(HttpStatusCode.OK, probe.StatusCode); } using var scope = f.Factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var alerts = await db.Alerts.AsNoTracking().Where(a => a.Kind == "rate_breach").ToListAsync(); // One alert for the crossing, and it names the pattern: an operator who // set the number too low has to be able to tell which budget is wrong. Assert.Single(alerts); Assert.Equal(3, alerts[0].Count); Assert.Contains("path budget of 2", alerts[0].Detail); Assert.Contains("/login*", alerts[0].Detail); Assert.Contains("mode=Observe, nothing was blocked", alerts[0].Detail); } [Fact] public async Task With_the_volume_pillar_off_no_path_budget_is_counted() { // The documented seam: the path budgets hang off the same switch as the // edge-wide one, so "off" means off for both rather than a half-counting // edge whose listings say one thing and whose counters another. await using var f = new EdgeFixture(); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); for (var i = 0; i < 6; i++) { using var probe = await GetAsync(f, "/login"); Assert.Equal(HttpStatusCode.OK, probe.StatusCode); } 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 A_budget_that_expires_stops_enforcing_without_being_deleted() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60, expiresInMinutes = 1 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (var first = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, first.StatusCode); using (var second = await GetAsync(f, "/login")) Assert.Equal((HttpStatusCode)429, second.StatusCode); long id; using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) { Assert.Equal(HttpStatusCode.OK, list.StatusCode); using var doc = JsonDocument.Parse(await BodyAsync(list)); id = doc.RootElement[0].GetProperty("id").GetInt64(); Assert.True(doc.RootElement[0].GetProperty("live").GetBoolean()); } using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var row = await db.RateRules.FirstAsync(r => r.Id == id); row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); await db.SaveChangesAsync(); } // A direct row edit is not something the operator can do, so nothing // invalidated the guard's snapshot on the way here. This is the same // refresh any admin mutation triggers, and it is what makes "the next // request" the honest answer rather than "after the TTL". await f.Service().InvalidateAsync(); using (var after = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, after.StatusCode); using (var all = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules?live=false")) { using var doc = JsonDocument.Parse(await BodyAsync(all)); Assert.Equal(id, doc.RootElement[0].GetProperty("id").GetInt64()); Assert.False(doc.RootElement[0].GetProperty("live").GetBoolean()); } } [Fact] public async Task Removing_a_budget_stops_enforcing_on_the_next_request() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (var first = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, first.StatusCode); using (var second = await GetAsync(f, "/login")) Assert.Equal((HttpStatusCode)429, second.StatusCode); long id; using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) using (var body = JsonDocument.Parse(await BodyAsync(list))) id = body.RootElement[0].GetProperty("id").GetInt64(); using (var removed = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}")) Assert.Equal(HttpStatusCode.NoContent, removed.StatusCode); // A fresh source, and the same one: the counters go with the row, so a // source that was paused a moment ago is not still paused by a budget // that no longer exists. using (var again = await GetAsync(f, "/login")) Assert.Equal(HttpStatusCode.OK, again.StatusCode); using (var missing = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}")) Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode); } [Fact] public async Task The_surface_refuses_a_budget_it_could_not_enforce() { await using var f = new EdgeFixture(); using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "login*", limitPerWindow = 5 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("must start with /", await BodyAsync(bad)); } using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 0 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("limitPerWindow must be 1..100000", await BodyAsync(bad)); } using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", windowSeconds = 99999 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("windowSeconds must be 1..3600", await BodyAsync(bad)); } using (var bad = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", expiresInMinutes = 0 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("expiresInMinutes", await BodyAsync(bad)); } using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules")) { Assert.Equal(HttpStatusCode.OK, list.StatusCode); Assert.Equal("0", list.Headers.GetValues("X-Total-Count").First()); } } [Fact] public async Task Two_live_budgets_for_one_path_are_refused_rather_than_resolved_by_accident() { await using var f = new EdgeFixture(); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 5 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (var clash = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 50 })) { Assert.Equal(HttpStatusCode.Conflict, clash.StatusCode); Assert.Contains("already sets a budget for /login*", await BodyAsync(clash)); } // An expired budget is not live, so it does not hold the pattern open. using (var scope = f.Factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); foreach (var row in await db.RateRules.ToListAsync()) { row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); await db.SaveChangesAsync(); } } using (var again = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 50 })) Assert.Equal(HttpStatusCode.NoContent, again.StatusCode); } [Fact] public async Task The_state_answer_says_whether_the_budgets_are_being_read_at_all() { await using var f = new EdgeFixture(); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 2, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state"); Assert.Equal(HttpStatusCode.OK, state.StatusCode); using var doc = JsonDocument.Parse(await BodyAsync(state)); Assert.Equal(1, doc.RootElement.GetProperty("rateRules").GetInt32()); Assert.True(doc.RootElement.GetProperty("rateRulesAvailable").GetBoolean()); Assert.Equal(JsonValueKind.Null, doc.RootElement.GetProperty("rateRulesError").ValueKind); } [Fact] public async Task The_listing_reports_what_a_budget_is_counting_right_now() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); OriginAnswersEverything(f); using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 1, windowSeconds = 60 })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); using (await GetAsync(f, "/login")) { } using (await GetAsync(f, "/login")) { } using (await GetAsync(f, "/login", "203.0.113.141")) { } using (await GetAsync(f, "/index.html")) { } using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules"); using var doc = JsonDocument.Parse(await BodyAsync(list)); var rule = doc.RootElement[0]; // Two sources have a window for this rule; one of them is over it now. // The path the budget does not name is not counted at all, which is the // difference between this and the edge-wide budget. This is the pair of // numbers that tells an operator whether a budget is a defence or their // own traffic — and in observe mode it is the only pair that does. Assert.Equal(2, rule.GetProperty("trackedSources").GetInt32()); Assert.Equal(2, rule.GetProperty("liveWindows").GetInt32()); Assert.Equal(1, rule.GetProperty("overBudgetNow").GetInt32()); Assert.Equal(1, rule.GetProperty("limitPerWindow").GetInt32()); Assert.Equal(60, rule.GetProperty("windowSeconds").GetInt32()); } [Fact] public async Task A_budget_travels_to_another_edge_in_one_call() { // The document carries the policy too, so the source edge is one with the // volume pillar on: an import that switched the target off would import a // row and no defence, and the test would be measuring the wrong thing. await using var source = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); using (var created = await AdminAsync(source, HttpMethod.Post, "/admin-api/rate-rules", new { pattern = "/login*", limitPerWindow = 4, windowSeconds = 30, note = "staging" })) Assert.Equal(HttpStatusCode.NoContent, created.StatusCode); JsonElement document; using (var exportResponse = await source.Client.GetAsync( $"/admin-api/export?token={EdgeFixture.AdminToken}")) { Assert.Equal(HttpStatusCode.OK, exportResponse.StatusCode); using var export = JsonDocument.Parse(await BodyAsync(exportResponse)); document = export.RootElement.Clone(); Assert.Equal(1, document.GetProperty("counts").GetProperty("rateRules").GetInt32()); Assert.Equal("/login*", document.GetProperty("rateRules")[0].GetProperty("pattern").GetString()); Assert.Equal(4, document.GetProperty("rateRules")[0].GetProperty("limitPerWindow").GetInt32()); Assert.Equal(30, document.GetProperty("rateRules")[0].GetProperty("windowSeconds").GetInt32()); } // The receiving edge has its own volume switch, and a path budget hangs // off it like the edge-wide one does: importing a budget into an edge // with the pillar off imports a row, not a defence. await using var target = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000); using (var importResponse = await target.Client.PostAsync( $"/admin-api/import?token={EdgeFixture.AdminToken}", new StringContent(document.GetRawText(), Encoding.UTF8, "application/json"))) { Assert.Equal(HttpStatusCode.OK, importResponse.StatusCode); using var imported = JsonDocument.Parse(await BodyAsync(importResponse)); Assert.Equal(1, imported.RootElement.GetProperty("rateRules").GetProperty("added").GetInt32()); } using (var list = await AdminAsync(target, HttpMethod.Get, "/admin-api/rate-rules")) using (var body = JsonDocument.Parse(await BodyAsync(list))) { Assert.Equal(1, body.RootElement.GetArrayLength()); Assert.Equal("/login*", body.RootElement[0].GetProperty("pattern").GetString()); Assert.Equal(4, body.RootElement[0].GetProperty("limitPerWindow").GetInt32()); } // And the imported budget enforces, not merely lists. OriginAnswersEverything(target); using (var first = await GetAsync(target, "/login")) Assert.Equal(HttpStatusCode.OK, first.StatusCode); using (var second = await GetAsync(target, "/login")) Assert.Equal(HttpStatusCode.OK, second.StatusCode); using (var third = await GetAsync(target, "/login")) Assert.Equal(HttpStatusCode.OK, third.StatusCode); using (var fourth = await GetAsync(target, "/login")) Assert.Equal(HttpStatusCode.OK, fourth.StatusCode); using (var fifth = await GetAsync(target, "/login")) Assert.Equal((HttpStatusCode)429, fifth.StatusCode); } }