The budget listing has carried three numbers per budget since OPEN-68 — sources
counted, windows running, over budget now — and no name. "3 over budget" is the
half an operator cannot act on, and the only lever for one of those three was
`DELETE /admin-api/rate-rules/{id}`: take the budget off every source on the site
to release one office behind one NAT. The edge-wide budget never had this hole,
because /admin-api/rate names its sources.
* GET /admin-api/rate-rules/{id}/sources — who this budget is inside right now:
sourceKey, count against the limit, when the window ends and how many seconds
are left, overBudget. Busiest first, live windows only, paged with
X-Total-Count / X-Truncated like every other listing. `total` is the same
number the listing's `liveWindows` reports and the over-budget count matches
`overBudgetNow`: the names come from the same state as the three counters,
not from a second ledger.
* DELETE /admin-api/rate-rules/{id}/sources?source=<key> — drop one source's
window on one budget. Not an exemption, and the answer says so: the window
restarts at zero and the budget counts this source again from there, while
every other source stays paused. An operator who types an address gets the
key this edge files it under, and the answer names the key it dropped,
because the others sharing it are still paused. A second clear answers
`cleared: false` and writes no second record; the first is in the change log
under `rate rule / changed`.
* Console: a `who` button per budget row, and a `let out` button per source.
Rulings kept: the entries are source keys with the prefix rule printed beside
them (a /24 in the list is the point, not a bug); the limit is passed in from the
rule row rather than copied into the counter, so one number is enforced once;
reading spends nothing, so the page that exists to show a pause cannot cause one;
an empty list says which kind of empty it is — "counting, nobody inside a window"
and "this budget has expired" are different answers; and the read-only token gets
a 403 on the clear, not a 401, because the token is known and its level is the
answer.
What the run caught, on this tree: two console scenes failed with `answered 403`
because the gate's own probes are refusals and the streak pillar had banned the
probe addresses — a correct edge, and a scene that cannot retry past a one-hour
ban. Both now clear that one ban by name, leaving the engine bans the netblock
scene reads standing. The first run of the feature also caught the clear
reporting `cleared: false` after actually dropping the window: the derived-key
branch dropped the state and never set the flag.
build 0 warnings / 0 errors, unit 377/377, integration 365/365 in 31 s,
console 129 assertions / 0 failed, smoke passed 202 / failed 0, compose 317
passed / 0 failed against the built image at 262 MB.
Refs OPEN-71.
316 lines
16 KiB
C#
316 lines
16 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// Who a path budget is pausing, and letting one of them out (OPEN-71).
|
|
///
|
|
/// Since OPEN-68 the budget listing has carried three numbers per budget —
|
|
/// sources counted, windows running, over budget now — and no name. "3 over
|
|
/// budget" is the half an operator cannot act on, and the only lever for one of
|
|
/// those three was to take the budget off every source on the site. The
|
|
/// edge-wide budget never had this hole: /admin-api/rate names its sources.
|
|
///
|
|
/// What these tests hold the surface to: the list is the same state the three
|
|
/// counters report; it spends nothing; clearing one source leaves the others
|
|
/// paused; an address typed instead of a key still finds the source it is filed
|
|
/// under; and an empty list says which kind of empty it is.
|
|
/// </summary>
|
|
public sealed class BudgetSourceListingTests
|
|
{
|
|
private const string First = "203.0.113.141";
|
|
private const string Second = "203.0.113.142";
|
|
private const string Path = "/signin";
|
|
|
|
private static async Task<HttpResponseMessage> AdminAsync(
|
|
EdgeFixture f, HttpMethod method, string url, object? body = null,
|
|
string token = EdgeFixture.AdminToken)
|
|
{
|
|
using var request = new HttpRequestMessage(method, url);
|
|
if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
|
|
if (body is not null) request.Content = JsonContent.Create(body);
|
|
return await f.Client.SendAsync(request);
|
|
}
|
|
|
|
private static async Task<JsonElement> JsonAsync(
|
|
EdgeFixture f, string url, string token = EdgeFixture.AdminToken)
|
|
{
|
|
using var r = await AdminAsync(f, HttpMethod.Get, url, token: token);
|
|
Assert.Equal(HttpStatusCode.OK, r.StatusCode);
|
|
return JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|
|
|
|
private static async Task<int> AskAsync(EdgeFixture f, string path, string ip)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
|
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
|
|
using var r = await f.Client.SendAsync(request);
|
|
return (int)r.StatusCode;
|
|
}
|
|
|
|
/// <summary>A budget of two per window on one path, with the edge-wide budget
|
|
/// far above it so the rule is the only thing in play.</summary>
|
|
private static async Task<long> SeedRuleAsync(EdgeFixture f, string pattern = Path, int limit = 2)
|
|
{
|
|
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
|
|
new { pattern, limitPerWindow = limit, windowSeconds = 300 }))
|
|
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
|
|
using var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules");
|
|
using var doc = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
|
|
return doc.RootElement.EnumerateArray()
|
|
.First(r => r.GetProperty("pattern").GetString() == pattern)
|
|
.GetProperty("id").GetInt64();
|
|
}
|
|
|
|
private static async Task<(EdgeFixture Fixture, long RuleId)> StackAsync()
|
|
{
|
|
var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 600);
|
|
return (f, await SeedRuleAsync(f));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_budget_can_be_asked_who_it_is_pausing()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
for (var i = 0; i < 2; i++) await AskAsync(f, Path, Second);
|
|
|
|
var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
Assert.Equal(id, body.GetProperty("id").GetInt64());
|
|
Assert.Equal(Path, body.GetProperty("pattern").GetString());
|
|
Assert.Equal(2, body.GetProperty("limitPerWindow").GetInt32());
|
|
Assert.Equal("this-process", body.GetProperty("scope").GetString());
|
|
// The key rule travels with the list: the entries are keys, and without
|
|
// the rule a /64 or a /24 reads as an address that is not the one asked for.
|
|
Assert.Equal(32, body.GetProperty("keyRule").GetProperty("ipv4PrefixLength").GetInt32());
|
|
|
|
var rows = body.GetProperty("sources").EnumerateArray().ToList();
|
|
Assert.Equal(2, rows.Count);
|
|
// Busiest first: the source nearest a refusal is the one being read about.
|
|
Assert.Equal(First, rows[0].GetProperty("sourceKey").GetString());
|
|
Assert.Equal(3, rows[0].GetProperty("count").GetInt32());
|
|
Assert.True(rows[0].GetProperty("overBudget").GetBoolean());
|
|
Assert.True(rows[0].GetProperty("secondsLeft").GetInt32() > 0);
|
|
Assert.Equal(Second, rows[1].GetProperty("sourceKey").GetString());
|
|
Assert.Equal(2, rows[1].GetProperty("count").GetInt32());
|
|
Assert.False(rows[1].GetProperty("overBudget").GetBoolean());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_list_and_the_three_counters_are_the_same_state()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
for (var i = 0; i < 2; i++) await AskAsync(f, Path, Second);
|
|
await AskAsync(f, Path, "203.0.113.143");
|
|
|
|
var listing = await JsonAsync(f, "/admin-api/rate-rules");
|
|
var row = listing.EnumerateArray().First(r => r.GetProperty("id").GetInt64() == id);
|
|
var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
|
|
// The numbers the operator already trusts, and the names behind them, from
|
|
// one state: a list that disagreed with the counter would be a second
|
|
// ledger, which is what this feature exists to avoid.
|
|
Assert.Equal(row.GetProperty("liveWindows").GetInt32(), body.GetProperty("total").GetInt32());
|
|
Assert.Equal(row.GetProperty("overBudgetNow").GetInt32(),
|
|
body.GetProperty("sources").EnumerateArray()
|
|
.Count(r => r.GetProperty("overBudget").GetBoolean()));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Letting_one_source_out_leaves_the_others_paused()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, Second);
|
|
Assert.Equal(429, await AskAsync(f, Path, First));
|
|
Assert.Equal(429, await AskAsync(f, Path, Second));
|
|
|
|
using (var cleared = await AdminAsync(f, HttpMethod.Delete,
|
|
$"/admin-api/rate-rules/{id}/sources?source={First}"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
|
|
using var doc = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync());
|
|
Assert.True(doc.RootElement.GetProperty("cleared").GetBoolean());
|
|
Assert.Equal(First, doc.RootElement.GetProperty("sourceKey").GetString());
|
|
// Said in the answer, not only in the README: this is a counter reset,
|
|
// not an exemption, and the budget still applies to this source.
|
|
Assert.Contains("not an exemption", doc.RootElement.GetProperty("note").GetString()!);
|
|
}
|
|
|
|
// 404 is the upstream's own answer for a path it does not serve: the point
|
|
// is that the edge stopped answering 429 for this source.
|
|
Assert.Equal(404, await AskAsync(f, Path, First));
|
|
// The neighbour is still where it was: one source out is not the budget off.
|
|
Assert.Equal(429, await AskAsync(f, Path, Second));
|
|
|
|
// And the list says what the reset actually did: the cleared source is
|
|
// counting again from one, not exempt, while the neighbour is still over.
|
|
var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
var rows = body.GetProperty("sources").EnumerateArray().ToList();
|
|
Assert.Equal(2, rows.Count);
|
|
Assert.Equal(2, body.GetProperty("total").GetInt32());
|
|
var letOut = rows.Single(r => r.GetProperty("sourceKey").GetString() == First);
|
|
Assert.Equal(1, letOut.GetProperty("count").GetInt32());
|
|
Assert.False(letOut.GetProperty("overBudget").GetBoolean());
|
|
var still = rows.Single(r => r.GetProperty("sourceKey").GetString() == Second);
|
|
Assert.True(still.GetProperty("overBudget").GetBoolean());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_address_typed_instead_of_a_key_still_finds_the_source_it_is_filed_under()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
// Group the sources by /24: the budget now counts one key for the whole
|
|
// block, which is the whole point of the key rule.
|
|
using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { ipv4KeyPrefixLength = 24 })) { }
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, "203.0.113.150");
|
|
|
|
var listed = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
var key = listed.GetProperty("sources")[0].GetProperty("sourceKey").GetString();
|
|
Assert.Equal("203.0.113.0/24", key);
|
|
|
|
// The operator types the address they are looking at, not the key.
|
|
using (var cleared = await AdminAsync(f, HttpMethod.Delete,
|
|
$"/admin-api/rate-rules/{id}/sources?source=203.0.113.150"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
|
|
using var doc = JsonDocument.Parse(await cleared.Content.ReadAsStringAsync());
|
|
Assert.True(doc.RootElement.GetProperty("cleared").GetBoolean());
|
|
// And the answer names the key it actually dropped, so the operator
|
|
// knows what else shares it.
|
|
Assert.Equal("203.0.113.0/24", doc.RootElement.GetProperty("sourceKey").GetString());
|
|
}
|
|
Assert.Equal(0, (await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources"))
|
|
.GetProperty("total").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_empty_list_says_which_kind_of_empty_it_is()
|
|
{
|
|
var (f, live) = await StackAsync();
|
|
var dead = await SeedRuleAsync(f, "/signin-late");
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var row = await db.RateRules.FirstAsync(r => r.Id == dead);
|
|
row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5);
|
|
await db.SaveChangesAsync();
|
|
await f.Service<EdgeStateStore>().InvalidateAsync();
|
|
}
|
|
|
|
var counting = await JsonAsync(f, $"/admin-api/rate-rules/{live}/sources");
|
|
Assert.Empty(counting.GetProperty("sources").EnumerateArray());
|
|
Assert.True(counting.GetProperty("live").GetBoolean());
|
|
// "counting, nobody inside a window" — not "nobody ever asked".
|
|
Assert.Contains("not the same as nobody ever having asked",
|
|
counting.GetProperty("howToRead").GetString()!);
|
|
|
|
var expired = await JsonAsync(f, $"/admin-api/rate-rules/{dead}/sources");
|
|
Assert.False(expired.GetProperty("live").GetBoolean());
|
|
Assert.Contains("expired", expired.GetProperty("howToRead").GetString()!);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Reading_the_list_spends_none_of_the_budget_it_reports()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
|
|
var before = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
var beforeCount = before.GetProperty("sources")[0].GetProperty("count").GetInt32();
|
|
for (var i = 0; i < 6; i++)
|
|
{
|
|
var again = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources");
|
|
Assert.Equal(beforeCount, again.GetProperty("sources")[0].GetProperty("count").GetInt32());
|
|
}
|
|
// And the next real request is the fourth, not the seventh: the page that
|
|
// exists to show a pause would otherwise be the cause of one.
|
|
Assert.Equal(429, await AskAsync(f, Path, First));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_unknown_budget_and_an_unnamed_parameter_are_refused_by_name()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
|
|
using (var missing = await AdminAsync(f, HttpMethod.Get, "/admin-api/rate-rules/999999/sources"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
|
|
Assert.Contains("999999", await missing.Content.ReadAsStringAsync());
|
|
}
|
|
using (var unknown = await AdminAsync(f, HttpMethod.Get, $"/admin-api/rate-rules/{id}/sources?source={First}"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.BadRequest, unknown.StatusCode);
|
|
Assert.Contains("source", await unknown.Content.ReadAsStringAsync());
|
|
}
|
|
using (var noSource = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/rate-rules/{id}/sources"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.BadRequest, noSource.StatusCode);
|
|
Assert.Contains("source is required", await noSource.Content.ReadAsStringAsync());
|
|
}
|
|
using (var missingRule = await AdminAsync(f, HttpMethod.Delete,
|
|
"/admin-api/rate-rules/999999/sources?source=203.0.113.1"))
|
|
Assert.Equal(HttpStatusCode.NotFound, missingRule.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_read_only_token_reads_the_list_and_cannot_clear_it()
|
|
{
|
|
var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 1000, rateWindowSeconds: 600,
|
|
readOnlyToken: EdgeFixture.ReadOnlyToken);
|
|
var id = await SeedRuleAsync(f);
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
|
|
var body = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources", EdgeFixture.ReadOnlyToken);
|
|
Assert.Equal(3, body.GetProperty("sources")[0].GetProperty("count").GetInt32());
|
|
|
|
using (var cleared = await AdminAsync(f, HttpMethod.Delete,
|
|
$"/admin-api/rate-rules/{id}/sources?source={First}", token: EdgeFixture.ReadOnlyToken))
|
|
// 403, not 401: the token is known and its level is the answer. A
|
|
// read-only token that got 401 would read as "wrong secret", which is
|
|
// a different problem for the operator to chase.
|
|
Assert.Equal(HttpStatusCode.Forbidden, cleared.StatusCode);
|
|
|
|
// Still paused, and still saying so.
|
|
Assert.Equal(429, await AskAsync(f, Path, First));
|
|
var after = await JsonAsync(f, $"/admin-api/rate-rules/{id}/sources", EdgeFixture.ReadOnlyToken);
|
|
Assert.Equal(1, after.GetProperty("total").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Clearing_a_source_leaves_a_record_of_itself()
|
|
{
|
|
var (f, id) = await StackAsync();
|
|
for (var i = 0; i < 3; i++) await AskAsync(f, Path, First);
|
|
|
|
using (await AdminAsync(f, HttpMethod.Delete,
|
|
$"/admin-api/rate-rules/{id}/sources?source={First}")) { }
|
|
// A second clear has nothing to clear and answers differently — and it
|
|
// writes no second record, because nothing changed.
|
|
using (var again = await AdminAsync(f, HttpMethod.Delete,
|
|
$"/admin-api/rate-rules/{id}/sources?source={First}"))
|
|
{
|
|
Assert.Equal(HttpStatusCode.OK, again.StatusCode);
|
|
using var doc = JsonDocument.Parse(await again.Content.ReadAsStringAsync());
|
|
Assert.False(doc.RootElement.GetProperty("cleared").GetBoolean());
|
|
Assert.Contains("no running window", doc.RootElement.GetProperty("note").GetString()!);
|
|
}
|
|
|
|
var changes = await JsonAsync(f, "/admin-api/changes");
|
|
var row = changes.EnumerateArray().First(c => c.GetProperty("target").GetString() == id.ToString());
|
|
Assert.Equal("rate rule", row.GetProperty("section").GetString());
|
|
Assert.Equal("changed", row.GetProperty("action").GetString());
|
|
Assert.Contains("not an exemption", row.GetProperty("detail").GetString()!);
|
|
Assert.Equal(1, changes.EnumerateArray()
|
|
.Count(c => c.GetProperty("target").GetString() == id.ToString()
|
|
&& c.GetProperty("action").GetString() == "changed"));
|
|
}
|
|
}
|