using System.Net; using System.Net.Http.Json; using Microsoft.AspNetCore.Http; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Tests.Integration; /// /// The volume pillar, end to end (OPEN-56). /// /// Every other defence in this edge reads something that already happened: the /// status the application answered, the country the address sits in, a list a /// human wrote. A source that asks for a cheap path over and over produces no /// refusal, so no streak ever matures and the application serves every request. /// These tests run the upstream answering 200 on purpose — the whole claim is /// about the traffic that the origin is happy to serve. /// public sealed class RatePolicyTests { private const string Visitor = "203.0.113.161"; 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(); /// An origin that answers, so nothing in this file can be credited /// to the streak pillar. private static void OriginAnswersEverything(EdgeFixture f) => f.Upstream.StatusFor = _ => StatusCodes.Status200OK; [Fact] public async Task Over_the_budget_the_edge_answers_429_and_the_origin_never_sees_the_surplus() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 3); OriginAnswersEverything(f); for (var i = 0; i < 3; i++) { using var ok = await GetAsync(f, "/catalog"); Assert.Equal(HttpStatusCode.OK, ok.StatusCode); } using (var over = await GetAsync(f, "/catalog")) { Assert.Equal((HttpStatusCode)429, over.StatusCode); var body = await BodyAsync(over); Assert.Contains("rate_limited", body); // The answer says when the pause ends, in the header the verb means. Assert.True(over.Headers.TryGetValues("Retry-After", out var values)); Assert.True(int.Parse(values!.First()) >= 1); Assert.Contains("rate_4_of_3", body); } // The crossing also wrote an engine ban, and the ban is the part that // outlives the window: from here the answer is the ban's own 403, not a // "slow down" that expires with the window. Both refusals keep the // origin out of it, which is the claim under test. using (var over = await GetAsync(f, "/other")) { Assert.Equal(HttpStatusCode.Forbidden, over.StatusCode); Assert.Contains("blocked_by_policy", await BodyAsync(over)); } lock (f.Upstream.Paths) { Assert.Equal(3, f.Upstream.Paths.Count(p => p == "/catalog")); Assert.DoesNotContain("/other", f.Upstream.Paths); } } [Fact] public async Task A_different_source_gets_its_own_budget() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2); OriginAnswersEverything(f); for (var i = 0; i < 2; i++) (await GetAsync(f, "/catalog", "203.0.113.161")).Dispose(); using (var over = await GetAsync(f, "/catalog", "203.0.113.161")) Assert.Equal((HttpStatusCode)429, over.StatusCode); using (var neighbour = await GetAsync(f, "/catalog", "203.0.113.162")) Assert.Equal(HttpStatusCode.OK, neighbour.StatusCode); } [Fact] public async Task A_breach_also_writes_an_engine_ban_the_operator_can_see_and_clear() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2); OriginAnswersEverything(f); for (var i = 0; i < 3; i++) (await GetAsync(f, "/catalog")).Dispose(); using (var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine")) { var rows = JsonDocument.Parse(await BodyAsync(blocks)).RootElement; Assert.Equal(1, rows.GetArrayLength()); var row = rows[0]; Assert.Equal(Visitor, row.GetProperty("sourceKey").GetString()); // The reason says volume, not refusals: an operator reading why a // source is locked out is reading the explanation. Assert.Contains("rate policy", row.GetProperty("reason").GetString()); Assert.Contains("budget of 2", row.GetProperty("reason").GetString()); Assert.NotNull(row.GetProperty("expiresAt").GetString()); } // The ban is the part that outlives the window: the next request is // refused by the engine-ban pillar, with the ban's own answer. using (var later = await GetAsync(f, "/catalog")) { Assert.Equal(HttpStatusCode.Forbidden, later.StatusCode); Assert.Contains("blocked_by_policy", await BodyAsync(later)); } } [Fact] public async Task Observe_mode_counts_and_says_so_once_without_refusing_anything() { await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 2); OriginAnswersEverything(f); for (var i = 0; i < 5; i++) { using var probe = await GetAsync(f, "/catalog"); Assert.Equal(HttpStatusCode.OK, probe.StatusCode); } lock (f.Upstream.Paths) Assert.Equal(5, f.Upstream.Paths.Count(p => p == "/catalog")); 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, not one per request: a flood is exactly // the traffic that turns a per-request write into the attack. Assert.Single(alerts); Assert.Equal(3, alerts[0].Count); Assert.Contains("budget of 2", alerts[0].Detail); Assert.Contains("mode=Observe, nothing was blocked", alerts[0].Detail); // And nothing was banned in observe mode. using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine"); Assert.Equal(0, JsonDocument.Parse(await BodyAsync(blocks)).RootElement.GetArrayLength()); } [Fact] public async Task Off_is_the_default_and_nothing_is_counted() { await using var f = new EdgeFixture(); OriginAnswersEverything(f); for (var i = 0; i < 6; i++) (await GetAsync(f, "/catalog")).Dispose(); using (var state = await AdminAsync(f, HttpMethod.Get, "/admin-api/state")) { var root = JsonDocument.Parse(await BodyAsync(state)).RootElement; Assert.Equal("Off", root.GetProperty("rateMode").GetString()); Assert.Equal(0, root.GetProperty("rateTrackedSources").GetInt32()); } using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate"); var rows = JsonDocument.Parse(await BodyAsync(list)).RootElement; Assert.Equal("Off", rows.GetProperty("mode").GetString()); Assert.Equal(0, rows.GetProperty("trackedSources").GetInt32()); } [Fact] public async Task The_allowlist_and_the_admin_surface_are_outside_the_budget() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1); OriginAnswersEverything(f); using (var allow = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", new { match = Visitor, note = "the office" })) Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); for (var i = 0; i < 5; i++) { using var probe = await GetAsync(f, "/catalog"); Assert.Equal(HttpStatusCode.OK, probe.StatusCode); } // The recovery hatch stays open at any budget: the page that raises the // limit is served from the same edge that is refusing everyone else. for (var i = 0; i < 5; i++) { using var admin = await AdminAsync(f, HttpMethod.Get, "/admin-api/state"); Assert.Equal(HttpStatusCode.OK, admin.StatusCode); } // A source that is not allowlisted still hits the budget. using (var stranger = await GetAsync(f, "/catalog", "203.0.113.163")) Assert.Equal(HttpStatusCode.OK, stranger.StatusCode); using (var stranger2 = await GetAsync(f, "/catalog", "203.0.113.163")) Assert.Equal((HttpStatusCode)429, stranger2.StatusCode); } [Fact] public async Task A_request_the_guard_already_refused_is_not_counted_again() { await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2); OriginAnswersEverything(f); using (var rule = await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", new { pattern = "/probe*", action = "block" })) Assert.Equal(HttpStatusCode.NoContent, rule.StatusCode); for (var i = 0; i < 4; i++) { using var probe = await GetAsync(f, "/probe.php"); Assert.Equal(HttpStatusCode.Forbidden, probe.StatusCode); } // The rule refused them, so the budget never saw them: the same source // still has its whole budget for the paths the rule does not name. using (var page = await GetAsync(f, "/catalog")) Assert.Equal(HttpStatusCode.OK, page.StatusCode); using (var page2 = await GetAsync(f, "/catalog")) Assert.Equal(HttpStatusCode.OK, page2.StatusCode); using (var page3 = await GetAsync(f, "/catalog")) Assert.Equal((HttpStatusCode)429, page3.StatusCode); } [Fact] public async Task The_window_restarts_and_the_source_flows_again() { // A ban as short as the window, so this test asks about the window and // not about the ban the breach also wrote. await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1, rateWindowSeconds: 1, banDuration: "00:00:01"); OriginAnswersEverything(f); using (var first = await GetAsync(f, "/catalog")) Assert.Equal(HttpStatusCode.OK, first.StatusCode); using (var over = await GetAsync(f, "/catalog")) Assert.Equal((HttpStatusCode)429, over.StatusCode); await Task.Delay(TimeSpan.FromSeconds(1.4)); using (var after = await GetAsync(f, "/catalog")) Assert.Equal(HttpStatusCode.OK, after.StatusCode); } [Fact] public async Task A_rate_value_outside_its_range_is_refused_by_name_and_changes_nothing() { await using var f = new EdgeFixture(); using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { rateLimitPerWindow = 0 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("rateLimitPerWindow must be 1..100000", await BodyAsync(bad)); } using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { rateWindowSeconds = 0 })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("rateWindowSeconds must be 1..3600", await BodyAsync(bad)); } using (var bad = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { rateMode = "sometimes" })) { Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); Assert.Contains("rateMode must be one of Off|Observe|Enforce", await BodyAsync(bad)); } using (var policy = await AdminAsync(f, HttpMethod.Get, "/admin-api/policy")) { var root = JsonDocument.Parse(await BodyAsync(policy)).RootElement; Assert.Equal("Off", root.GetProperty("rateMode").GetString()); Assert.Equal(100, root.GetProperty("rateLimitPerWindow").GetInt32()); Assert.Equal(60, root.GetProperty("rateWindowSeconds").GetDouble()); } } [Fact] public async Task A_written_budget_is_live_on_the_wire_without_a_restart() { await using var f = new EdgeFixture(); OriginAnswersEverything(f); using (var put = await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { rateMode = "enforce", rateLimitPerWindow = 2, rateWindowSeconds = 60 })) { Assert.Equal(HttpStatusCode.OK, put.StatusCode); var root = JsonDocument.Parse(await BodyAsync(put)).RootElement; Assert.Equal("Enforce", root.GetProperty("rateMode").GetString()); Assert.Equal(2, root.GetProperty("rateLimitPerWindow").GetInt32()); } for (var i = 0; i < 2; i++) (await GetAsync(f, "/catalog")).Dispose(); using var over = await GetAsync(f, "/catalog"); Assert.Equal((HttpStatusCode)429, over.StatusCode); } [Fact] public async Task The_listing_says_what_the_limiter_is_counting_right_now() { await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 10); OriginAnswersEverything(f); for (var i = 0; i < 4; i++) (await GetAsync(f, "/catalog", "203.0.113.161")).Dispose(); for (var i = 0; i < 2; i++) (await GetAsync(f, "/catalog", "203.0.113.164")).Dispose(); using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate")) { var root = JsonDocument.Parse(await BodyAsync(list)).RootElement; Assert.Equal("Observe", root.GetProperty("mode").GetString()); Assert.Equal(10, root.GetProperty("limitPerWindow").GetInt32()); Assert.Equal(60, root.GetProperty("windowSeconds").GetDouble()); Assert.Equal(2, root.GetProperty("trackedSources").GetInt32()); Assert.Equal(2, root.GetProperty("liveWindows").GetInt32()); var rows = root.GetProperty("sources"); Assert.Equal(2, rows.GetArrayLength()); // Biggest first: the operator is looking for the source that is // about to cross, not for an alphabetical roll call. Assert.Equal(4, rows[0].GetProperty("count").GetInt32()); Assert.False(rows[0].GetProperty("overBudget").GetBoolean()); Assert.NotNull(rows[0].GetProperty("windowEnd").GetString()); } using (var filtered = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate?source=203.0.113.164")) { var root = JsonDocument.Parse(await BodyAsync(filtered)).RootElement; Assert.Equal(1, root.GetProperty("liveWindows").GetInt32()); Assert.Equal(2, root.GetProperty("trackedSources").GetInt32()); Assert.Equal(1, root.GetProperty("sources").GetArrayLength()); } using var emptyFilter = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate?source="); Assert.Equal(HttpStatusCode.BadRequest, emptyFilter.StatusCode); } }