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; /// /// 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. /// 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 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 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 ChangeCountAsync(EdgeFixture f) { using var scope = f.Factory.Services.CreateScope(); return await scope.ServiceProvider.GetRequiredService().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(); 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(); 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().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(); var policy = f.Service().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().PruneAsync(CancellationToken.None); Assert.Equal(f.Service().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)); } }