The edge-wide budget is one number for the whole site, and for a login path that number is always wrong: a hundred requests a minute does not stop a credential-stuffing run that makes twenty attempts a minute — twenty looks like a person — while five a minute locks an honest office behind one NAT out of every page they own. The only way to make both statements true is to price the paths differently. The rulings this had to make, and the answer each one got: * A rate rule is not a path rule. A path rule refuses a request because of what it asked for; a budget refuses it because of how often that source asked. The pattern language is shared because the thing being described — this path and what hangs off it — is the same. * Crossing a budget writes no engine ban. The claim is about one path, so a ban would refuse the rest of the site as punishment for a login-page rate. The answer is 429 with Retry-After for the rest of that source's window, and the reason names the rule, its count, its limit and the pattern it was written for. * The counters are a separate tracker, not a scope inside RateTracker. The edge-wide counter reads its limit and window from the policy; a rule carries its own. One map whose parameters change per entry is a map whose eviction and idle rules stop meaning anything. * The budgets hang off rateMode rather than getting a switch of their own: Enforce refuses, Observe counts and raises one rate_breach alert per source per window naming the pattern, Off counts nothing at all. A half-counting edge is the state an operator cannot reason about. * A second live budget for one pattern is a 409 — two live numbers for one path mean the stricter one wins by accident rather than by the operator's choice. * The bounds are the policy's own (1..100000 requests, 1..3600 seconds), so one vocabulary of numbers covers both budgets and a document cannot bring in a budget the API would have refused. * The listing answers with three counters — sources counted, windows running, over budget now — because "nobody has blown this" and "nobody can" look identical on paper and are different decisions. What the runs caught, in order: * The smoke scene first ran on 198.51.100.0/24, which an earlier scene of the same gate allowlists. An allowlisted source never reaches the counter, so the scene would have printed a row of 200s while measuring nothing. It runs on TEST-NET-1 now. * The console scene drew three 404s of its own and the streak pillar banned the address, so the reopen assertion read the streak's 403 instead of the absence of the budget. The engine list is cleared before that probe and the comment says which pillar the clearing belongs to. * The compose assertion compared a JSON boolean against the word "yes". * The change-log vocabulary test still listed six sections; there are seven now. * A unit expectation counted requests where the tracker holds windows: one (rule, source) pair is one window, and the count inside it is what the budget is measured against. Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit 361/361, integration 337/337 in 30 s, console 120 assertions 0 failed, smoke passed 169 failed 0, compose 300 passed 0 failed against the built image at 262 MB, 0 containers left behind. Refs OPEN-68.
295 lines
14 KiB
C#
295 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Domain.Security;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The record of a deliberate change to the operator's config (OPEN-64).
|
|
///
|
|
/// Every operator write already changes a row; what was missing is the answer to
|
|
/// "when did this get here, and did a document bring it". These tests ask the
|
|
/// surface, not the table, because the surface is what an operator reads at 03:00
|
|
/// — and they ask the rulings, not the plumbing: an import is recorded per
|
|
/// section rather than per row, a record that cannot be written never undoes the
|
|
/// change it describes, and the log says which surface acted without claiming to
|
|
/// know which human.
|
|
/// </summary>
|
|
public sealed class ConfigChangeRecordTests
|
|
{
|
|
private const string Blocked = "203.0.113.171";
|
|
private const string Exempt = "203.0.113.172";
|
|
private const string RulePath = "/wp-login*";
|
|
|
|
private static async Task<JsonElement> ChangesAsync(EdgeFixture f, string query = "")
|
|
{
|
|
using var response = await f.Client.GetAsync(
|
|
$"/admin-api/changes?token={EdgeFixture.AdminToken}{query}");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|
|
|
|
private static async Task<JsonElement> StateAsync(EdgeFixture f)
|
|
{
|
|
using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}");
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|
|
|
|
private static async Task<int> ChangeCountAsync(EdgeFixture f)
|
|
{
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
return await scope.ServiceProvider.GetRequiredService<OpenWafDbContext>().ConfigChanges.CountAsync();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_operator_block_lands_a_record_that_names_the_ip_and_the_reason()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}",
|
|
new { ip = Blocked, reason = "incident: confirmed scraper" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
|
|
var rows = await ChangesAsync(f);
|
|
Assert.Equal(1, rows.GetArrayLength());
|
|
var row = rows[0];
|
|
Assert.Equal("block", row.GetProperty("section").GetString());
|
|
Assert.Equal("added", row.GetProperty("action").GetString());
|
|
Assert.Equal(Blocked, row.GetProperty("target").GetString());
|
|
Assert.Equal("incident: confirmed scraper", row.GetProperty("detail").GetString());
|
|
// The surface, not a person: the edge has one admin token, and a record
|
|
// that named a human it cannot identify would be a false record.
|
|
Assert.Equal("operator", row.GetProperty("actor").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_removal_is_recorded_as_a_removal()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
using (var removed = await f.Client.DeleteAsync(
|
|
$"/admin-api/blocks?source=operator&key={Blocked}&token={EdgeFixture.AdminToken}"))
|
|
Assert.Equal(HttpStatusCode.OK, removed.StatusCode);
|
|
|
|
var rows = await ChangesAsync(f, "§ion=block");
|
|
Assert.Equal(2, rows.GetArrayLength());
|
|
// Newest first: the removal is the first row the operator sees.
|
|
Assert.Equal("removed", rows[0].GetProperty("action").GetString());
|
|
Assert.Equal("added", rows[1].GetProperty("action").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_policy_write_records_what_moved_not_only_that_something_did()
|
|
{
|
|
await using var f = new EdgeFixture(mode: "Enforce");
|
|
using (var write = await f.Client.PutAsJsonAsync(
|
|
$"/admin-api/policy?token={EdgeFixture.AdminToken}", new { mode = "Off" }))
|
|
Assert.Equal(HttpStatusCode.OK, write.StatusCode);
|
|
|
|
var rows = await ChangesAsync(f, "§ion=policy");
|
|
Assert.Equal(1, rows.GetArrayLength());
|
|
var detail = rows[0].GetProperty("detail").GetString();
|
|
Assert.Contains("mode Enforce->Off", detail);
|
|
Assert.Equal("changed", rows[0].GetProperty("action").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_rule_an_exemption_and_a_country_decision_are_all_recorded()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using (var r = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/rules?token={EdgeFixture.AdminToken}",
|
|
new { pattern = RulePath, action = "block", note = "cms" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, r.StatusCode);
|
|
using (var a = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/allow?token={EdgeFixture.AdminToken}",
|
|
new { match = Exempt, note = "office" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, a.StatusCode);
|
|
using (var c = await f.Client.PutAsync(
|
|
$"/admin-api/countries/de?allowed=false&token={EdgeFixture.AdminToken}", null))
|
|
Assert.Equal(HttpStatusCode.NoContent, c.StatusCode);
|
|
|
|
var rows = await ChangesAsync(f);
|
|
var sections = rows.EnumerateArray().Select(x => x.GetProperty("section").GetString()).ToList();
|
|
Assert.Contains("rule", sections);
|
|
Assert.Contains("allow", sections);
|
|
Assert.Contains("country", sections);
|
|
var rule = rows.EnumerateArray().First(x => x.GetProperty("section").GetString() == "rule");
|
|
Assert.Equal(RulePath, rule.GetProperty("target").GetString());
|
|
Assert.Contains("cms", rule.GetProperty("detail").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_import_is_recorded_per_section_and_not_per_row()
|
|
{
|
|
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
|
|
var document = JsonSerializer.Serialize(new
|
|
{
|
|
version = 1,
|
|
blocks = new object[]
|
|
{
|
|
new { ip = "203.0.113.173" }, new { ip = "203.0.113.174" }, new { ip = "203.0.113.175" }
|
|
}
|
|
});
|
|
using var content = new StringContent(document, Encoding.UTF8, "application/json");
|
|
using var imported = await f.Client.PostAsync(
|
|
$"/admin-api/import?token={EdgeFixture.AdminToken}", content);
|
|
Assert.Equal(HttpStatusCode.OK, imported.StatusCode);
|
|
|
|
var rows = await ChangesAsync(f, "§ion=block");
|
|
// Three rows arrived; one record says so. A 2 000-row document must not
|
|
// bury the table whose whole use is being readable.
|
|
Assert.Equal(1, rows.GetArrayLength());
|
|
Assert.Equal("imported", rows[0].GetProperty("action").GetString());
|
|
Assert.Equal("import", rows[0].GetProperty("actor").GetString());
|
|
Assert.Contains("3 added", rows[0].GetProperty("detail").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_read_only_token_can_read_the_log_because_it_is_a_read()
|
|
{
|
|
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/changes");
|
|
using var response = await f.Client.SendAsync(request);
|
|
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
|
|
|
var asReadOnly = await ChangesAsync(f);
|
|
Assert.Equal(1, asReadOnly.GetArrayLength());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_unknown_section_is_answered_by_the_vocabulary_not_by_an_empty_list()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using var response = await f.Client.GetAsync(
|
|
$"/admin-api/changes?section=traffic&token={EdgeFixture.AdminToken}");
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
Assert.Contains("block, allow, rule, rate rule, country, policy, config", body);
|
|
Assert.Contains("traffic", body);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_log_is_capped_and_says_when_it_is_truncated()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
for (var i = 0; i < 5; i++)
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = $"203.0.113.{180 + i}" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
|
|
using var response = await f.Client.GetAsync(
|
|
$"/admin-api/changes?limit=2&token={EdgeFixture.AdminToken}");
|
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.Equal("5", response.Headers.TryGetValues("X-Total-Count", out var total) ? total.Single() : "");
|
|
Assert.Equal("true", response.Headers.TryGetValues("X-Truncated", out var trunc) ? trunc.Single() : "");
|
|
using var page = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
|
Assert.Equal(2, page.RootElement.GetArrayLength());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_record_that_cannot_be_written_never_undoes_the_change_and_is_counted()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
await db.Database.ExecuteSqlRawAsync(
|
|
"""CREATE TRIGGER "gate_changes_insert" BEFORE INSERT ON "config_changes" BEGIN SELECT RAISE(ABORT, 'gate: durable write blocked'); END""");
|
|
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}",
|
|
new { ip = Blocked, reason = "the record will not land" }))
|
|
{
|
|
// Enforcement is the product. A change refused because its audit row
|
|
// would not fit is a change the operator believes they have.
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
}
|
|
|
|
Assert.Equal(0, await ChangeCountAsync(f));
|
|
var state = await StateAsync(f);
|
|
Assert.Equal(0, state.GetProperty("configChanges").GetInt32());
|
|
Assert.True(state.GetProperty("changeWriteFailures").GetInt32() >= 1);
|
|
Assert.Equal(1, state.GetProperty("changesNotWritten").GetInt32());
|
|
Assert.Contains("gate: durable write blocked", state.GetProperty("changeLastError").GetString());
|
|
|
|
// And the block is really in effect, which is the whole reason the
|
|
// request was allowed to succeed.
|
|
using var probe = new HttpRequestMessage(HttpMethod.Get, "/anything");
|
|
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Blocked);
|
|
using var probeResponse = await f.Client.SendAsync(probe);
|
|
Assert.Equal(HttpStatusCode.MovedPermanently, probeResponse.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_change_log_is_bounded_by_age_and_by_rows()
|
|
{
|
|
await using var f = new EdgeFixture(observationRetentionDays: 7);
|
|
for (var i = 0; i < 4; i++)
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = $"203.0.113.{190 + i}" }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
Assert.Equal(4, await ChangeCountAsync(f));
|
|
|
|
// The age window: a record older than the window goes.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
foreach (var row in await db.ConfigChanges.OrderBy(c => c.Id).Take(2).ToListAsync())
|
|
row.At = DateTimeOffset.UtcNow.AddDays(-40);
|
|
await db.SaveChangesAsync();
|
|
}
|
|
await f.Service<RetentionWorker>().PruneAsync(CancellationToken.None);
|
|
Assert.Equal(2, await ChangeCountAsync(f));
|
|
|
|
// The row cap, which the age window cannot provide: an operator scripting
|
|
// a thousand edits inside a week would otherwise grow a table whose whole
|
|
// use is being readable. The oldest go first.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
var policy = f.Service<EdgePolicyProvider>().Current;
|
|
for (var i = 0; i < policy.ChangeLogMaxRows + 3; i++)
|
|
db.ConfigChanges.Add(new ConfigChange
|
|
{
|
|
At = DateTimeOffset.UtcNow, Section = "block", Action = "added",
|
|
Target = $"203.0.113.{i % 200}", Actor = ConfigChangeLog.ActorOperator
|
|
});
|
|
await db.SaveChangesAsync();
|
|
}
|
|
await f.Service<RetentionWorker>().PruneAsync(CancellationToken.None);
|
|
Assert.Equal(f.Service<EdgePolicyProvider>().Current.ChangeLogMaxRows, await ChangeCountAsync(f));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_state_counts_the_records_the_edge_holds()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
Assert.Equal(0, (await StateAsync(f)).GetProperty("configChanges").GetInt32());
|
|
using (var write = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked }))
|
|
Assert.Equal(HttpStatusCode.NoContent, write.StatusCode);
|
|
Assert.Equal(1, (await StateAsync(f)).GetProperty("configChanges").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_rejected_write_lands_no_record_because_it_landed_no_change()
|
|
{
|
|
await using var f = new EdgeFixture();
|
|
using var rejected = await f.Client.PostAsJsonAsync(
|
|
$"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = "not-an-address" });
|
|
Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode);
|
|
Assert.Equal(0, await ChangeCountAsync(f));
|
|
}
|
|
}
|