Files
openwaf/dotnet/OpenWaf.Tests.Integration/ConfigChangeRecordTests.cs
T
Pavlo Ratushnyi 3959f1fe6b a change to the operator's config leaves a record of itself
Every operator write already changes a row; what was missing is the answer an operator actually asks at 03:00 - when did this rule get here, who cleared that ban, did a document bring this edge's config. Since the transfer landed, an edge can be different from yesterday with nothing on it saying how.

config_changes carries one row per deliberate change: the instant, the section (block, allow, rule, country, policy, config), the action (added, removed, changed, imported), the target the operator typed, their own sentence where one was given, and the surface the change came through. GET /admin-api/changes answers it newest first, capped and paged like every other listing, filterable by section and since, readable by the read-only token because it is a read. A policy record says what moved ("mode Enforce->Off, streakThreshold 3->4") rather than only that something did. /admin-api/state counts the rows and the write failures.

The rulings, because each is a decision and not a detail:

 * Engine bans are not in the log. A ban the engine earned is not a decision somebody made, and the block row already carries its evidence - consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic.
 * An import is one record per section, not one per row: "3 added, 1 already there, 0 past expiry, 0 rejected". A 2 000-row document would otherwise bury a table whose whole use is being readable.
 * The record names the surface, never a person. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record.
 * A record that cannot be written never undoes the change it describes. Enforcement is the product, so the change stands and the failure is counted - changeWriteFailures, changesNotWritten, changeLastError - because "the config changed and the record of it did not land" has to be a sentence an operator can read rather than one that silently never happened.
 * Bounded twice, both keys the operator's: ChangeRetentionDays (30) and ChangeLogMaxRows (5000, oldest dropped first). The age window alone would let a scripted churn grow the table without limit; the cap alone would drop last month's incident record the week someone did a lot of editing.

What the run caught, in order: (1) Two gate assertions were wrong rather than the product - a policy record was asserted in a scene where no policy write had happened yet, and "one imported record per section" was asserted against a stack that had already imported twice, so the assertion now reads the newest imported record instead of counting them. (2) DELETE /admin-api/countries/{code} answers 204, and the new assertion expected 200. (3) A shell trap in the new scene: a $VAR inside a single-quoted python -c is not interpolated, so the first version would have handed python a literal "$CHANGES_BEFORE" instead of a number.

Gates on this tree: build 0 warnings / 0 errors, unit 313/313, integration 298/298 in 23s, smoke 127 passed / 0 failed (14 new), image 262 MB, compose-smoke 278 passed / 0 failed with 0 containers left behind (11 new, against the shipped image), console 90 assertions / 0 failed.

Refs OPEN-64.
2026-10-05 05:58:42 +02:00

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, "&section=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, "&section=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, "&section=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, 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));
}
}