Every defence this edge had reads something that already happened: the status the application answered, the country the address sits in, a list a human wrote. A source asking for a cheap path two hundred times a minute produces no refusal, so no streak matures, no path rule names it, and the origin serves all two hundred. The only signal is the count, and a count has to be kept while the requests are arriving — which is why this pillar is the one piece of live state on the request path, and why it runs after the ordered decision instead of inside it. `rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds` (policy_settings, so no schema change). Off is the default: a limit nobody wrote is a defence nobody asked for, and a false positive here locks out a whole office behind one address. `observe` counts and raises one `rate_breach` alert per source per window. `enforce` answers the request that crosses with 429 + Retry-After — the surplus never reaches the origin — and writes an engine ban, so the stop outlives the window, is shared with the other edges and survives a restart; from then on the answer is the ban's own 403. One breach, one alert, one ban write per source per window: a flood is exactly the traffic that turns a per-request durable write into the thing that takes the database down. Exempt by construction rather than by a second copy of the precedence rules: the counter runs only on a plain Pass, so an always-pass prefix, an allowlisted address, a matched rule, a block or a geo refusal never reaches it. The budget counts exactly the requests that would have cost the origin. Costs, stated rather than hidden: the counter is per process, so N edges allow N times the budget (the same trade `SharedStreaks` made for the streak, at a round trip per request instead of per observed response); the window is fixed, not sliding, so the worst sustained rate is twice the limit across one boundary — a sliding counter needs one entry per request, which is a map that grows at attack rate. Two things the run caught rather than the design assumed: * The guard wrote the 429 and then called next() anyway, so YARP answered "the request cannot be forwarded, the response has already started". The pillar now says whether the request may go through. * `StreakTracker.Configure` was called by nobody outside its own tests, so `maxTrackedSources` bounded nothing in a running edge — the map grew to the built-in 10000 whatever the operator had asked for. Both maps are configured at warm-up and on a policy write now. And the smoke gate was not testing what its first line says. The edge was started from the repository root, where there is no appsettings.json, so it loaded no ReverseProxy section at all, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, and answered 404 for a path the upstream was serving with 200. Every assertion in the file expects a 404 or a refusal, so the gate kept passing on an edge that never proxied anything. Naming the content root fixes it; the streak scene also waits for the ban row to exist before asking the wire whether it is enforced, because the ban is written out of band after the response that proved it. Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219 in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209 passed 0 failed, image 261 MB. OPEN-56
359 lines
15 KiB
C#
359 lines
15 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public sealed class RatePolicyTests
|
|
{
|
|
private const string Visitor = "203.0.113.161";
|
|
|
|
private static async Task<HttpResponseMessage> 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<HttpResponseMessage> 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<string> BodyAsync(HttpResponseMessage r) => await r.Content.ReadAsStringAsync();
|
|
|
|
/// <summary>An origin that answers, so nothing in this file can be credited
|
|
/// to the streak pillar.</summary>
|
|
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<OpenWafDbContext>();
|
|
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);
|
|
}
|
|
}
|