using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; namespace OpenWaf.Tests.Integration; /// /// The operator's config as one document (OPEN-61). /// /// Every row in it could already be written one at a time, so the interesting /// question is not "can it be stored" but "does the second edge behave like the /// first afterwards". That is what these tests ask: a real edge writes a block, /// an exemption, a path rule and a country decision; a second edge with an empty /// database imports what the first exported; and the assertions are made on the /// wire of the second edge, not in its tables. /// /// The rulings under test are the ones the feature could quietly get wrong: /// engine bans do not travel, import is additive and idempotent, expiry is an /// instant, and a document this build cannot read writes nothing. /// public sealed class ConfigTransferTests { private const string Blocked = "203.0.113.141"; private const string Exempt = "203.0.113.142"; private const string Bystander = "203.0.113.143"; private const string EngineBanned = "203.0.113.144"; private static async Task GetAsync(EdgeFixture f, string path, string ip) { 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 ExportAsync(EdgeFixture f) { using var response = await f.Client.GetAsync($"/admin-api/export?token={EdgeFixture.AdminToken}"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); return await response.Content.ReadAsStringAsync(); } private static async Task<(HttpStatusCode Status, JsonElement Body)> ImportAsync(EdgeFixture f, string document) { using var content = new StringContent(document, Encoding.UTF8, "application/json"); using var response = await f.Client.PostAsync($"/admin-api/import?token={EdgeFixture.AdminToken}", content); return (response.StatusCode, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone()); } /// An edge with a hand-written config, and one engine ban it earned /// by serving refusals — the thing that must not travel. private static async Task<(EdgeFixture Fixture, string Document)> WriteConfigAndExportAsync() { var f = new EdgeFixture(); using (var b = await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", new { ip = Blocked, reason = "incident: written by hand" })) Assert.Equal(HttpStatusCode.NoContent, b.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 r = await f.Client.PostAsJsonAsync($"/admin-api/rules?token={EdgeFixture.AdminToken}", new { pattern = "/wp-admin*", action = "block", note = "cms" })) Assert.Equal(HttpStatusCode.NoContent, r.StatusCode); using (var c = await f.Client.PutAsync( $"/admin-api/countries/de?allowed=false&token={EdgeFixture.AdminToken}", null)) Assert.Equal(HttpStatusCode.NoContent, c.StatusCode); // Three upstream refusals at the default threshold: an engine ban, earned // by this edge's own traffic. for (var i = 0; i < 3; i++) using (var probe = await GetAsync(f, "/anything", EngineBanned)) Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); return (f, await ExportAsync(f)); } [Fact] public async Task An_exported_document_replays_the_operators_decisions_on_another_edge() { var (source, document) = await WriteConfigAndExportAsync(); await using (source) { var exported = JsonDocument.Parse(document).RootElement; Assert.Equal(1, exported.GetProperty("counts").GetProperty("blocks").GetInt32()); Assert.Equal(1, exported.GetProperty("counts").GetProperty("rules").GetInt32()); Assert.Equal(1, exported.GetProperty("counts").GetProperty("countries").GetInt32()); // The sentence the AC asks for: the ban this edge earned stays here, // and the export says how many it left out. Assert.True(exported.GetProperty("engineBlocksLeftBehind").GetInt32() >= 1, document); Assert.DoesNotContain(EngineBanned, exported.GetProperty("blocks").EnumerateArray().Select(b => b.GetProperty("ip").GetString())); await using var target = new EdgeFixture(); var (status, report) = await ImportAsync(target, document); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("allow").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("rules").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("countries").GetProperty("added").GetInt32()); Assert.True(report.GetProperty("policy").GetProperty("applied").GetBoolean(), report.ToString()); // The claim is on the wire, not in the tables. using (var blocked = await GetAsync(target, "/anything", Blocked)) Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); using (var exempt = await GetAsync(target, "/anything", Exempt)) Assert.Equal(HttpStatusCode.NotFound, exempt.StatusCode); using (var rule = await GetAsync(target, "/wp-admin", Bystander)) Assert.Equal(HttpStatusCode.Forbidden, rule.StatusCode); using (var bystander = await GetAsync(target, "/anything", Bystander)) Assert.Equal(HttpStatusCode.NotFound, bystander.StatusCode); // The engine ban did not come with it. using (var engine = await target.Client.GetAsync( $"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) Assert.Empty(JsonDocument.Parse(await engine.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); using (var countries = await target.Client.GetAsync( $"/admin-api/countries?token={EdgeFixture.AdminToken}")) { var rows = JsonDocument.Parse(await countries.Content.ReadAsStringAsync()) .RootElement.EnumerateArray().ToList(); var de = rows.FirstOrDefault(r => r.GetProperty("code").GetString() == "DE"); Assert.Equal(JsonValueKind.Object, de.ValueKind); Assert.False(de.GetProperty("isAllowed").GetBoolean()); } } } [Fact] public async Task Importing_the_same_document_twice_lands_each_row_once() { var (source, document) = await WriteConfigAndExportAsync(); await using (source) { await using var target = new EdgeFixture(); var (first, _) = await ImportAsync(target, document); Assert.Equal(HttpStatusCode.OK, first); var (second, report) = await ImportAsync(target, document); Assert.Equal(HttpStatusCode.OK, second); Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("blocks").GetProperty("alreadyThere").GetInt32()); Assert.Equal(0, report.GetProperty("rules").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("rules").GetProperty("alreadyThere").GetInt32()); Assert.Equal(0, report.GetProperty("countries").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("countries").GetProperty("alreadyThere").GetInt32()); using (var blocks = await target.Client.GetAsync( $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) Assert.Single(JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); } } [Fact] public async Task A_row_past_its_expiry_is_skipped_and_counted_rather_than_imported_live() { await using var target = new EdgeFixture(); var document = JsonSerializer.Serialize(new { version = 1, blocks = new[] { new { ip = Blocked, reason = "already over", expiresAt = DateTimeOffset.UtcNow.AddMinutes(-30) }, new { ip = Exempt, reason = "still running", expiresAt = DateTimeOffset.UtcNow.AddMinutes(30) } } }); var (status, report) = await ImportAsync(target, document); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("blocks").GetProperty("skippedExpired").GetInt32()); using (var expired = await GetAsync(target, "/anything", Blocked)) Assert.Equal(HttpStatusCode.NotFound, expired.StatusCode); using (var live = await GetAsync(target, "/anything", Exempt)) Assert.Equal(HttpStatusCode.MovedPermanently, live.StatusCode); // And the expiry that did travel is an instant, not a fresh duration: // the row says when it stops, within the minute the document named. using (var blocks = await target.Client.GetAsync( $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) { var rows = JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray().ToList(); var mine = rows.Single(r => r.GetProperty("sourceKey").GetString() == Exempt); Assert.InRange(mine.GetProperty("expiresAt").GetDateTimeOffset(), DateTimeOffset.UtcNow.AddMinutes(28), DateTimeOffset.UtcNow.AddMinutes(32)); } } [Fact] public async Task A_bad_item_is_named_by_section_and_position_and_the_rest_still_lands() { await using var target = new EdgeFixture(); var document = JsonSerializer.Serialize(new { version = 1, blocks = new object[] { new { ip = Blocked, reason = "good" }, new { ip = "not-an-ip", reason = "bad" } }, rules = new object[] { new { pattern = "no-slash", action = "block" } } }); var (status, report) = await ImportAsync(target, document); Assert.Equal(HttpStatusCode.OK, status); Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); Assert.Equal(1, report.GetProperty("blocks").GetProperty("rejected").GetInt32()); Assert.Equal(1, report.GetProperty("rules").GetProperty("rejected").GetInt32()); var bad = report.GetProperty("rejected").EnumerateArray().ToList(); Assert.Contains(bad, r => r.GetProperty("section").GetString() == "blocks" && r.GetProperty("index").GetInt32() == 1 && r.GetProperty("error").GetString()!.Contains("not an IP address")); Assert.Contains(bad, r => r.GetProperty("section").GetString() == "rules"); using (var blocked = await GetAsync(target, "/anything", Blocked)) Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); } [Fact] public async Task A_document_this_build_cannot_read_is_refused_by_name_and_writes_nothing() { await using var target = new EdgeFixture(); var future = JsonSerializer.Serialize(new { version = 999, blocks = new[] { new { ip = Blocked, reason = "would have landed" } } }); var (versionStatus, versionBody) = await ImportAsync(target, future); Assert.Equal(HttpStatusCode.BadRequest, versionStatus); Assert.Contains("999", versionBody.ToString()); var (jsonStatus, jsonBody) = await ImportAsync(target, "{\"version\": 1, \"blocks\": ["); Assert.Equal(HttpStatusCode.BadRequest, jsonStatus); Assert.Contains("not valid JSON", jsonBody.ToString()); using (var blocks = await target.Client.GetAsync( $"/admin-api/blocks?live=false&token={EdgeFixture.AdminToken}")) Assert.Empty(JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); } [Fact] public async Task An_out_of_range_policy_in_a_document_is_refused_by_the_same_bounds_as_a_typed_request() { var (source, document) = await WriteConfigAndExportAsync(); await using (source) { // The same document, with one policy field the API would refuse from // a keyboard: streakThreshold=0. var broken = document.Replace("\"streakThreshold\":10", "\"streakThreshold\":0") .Replace("\"streakThreshold\":3", "\"streakThreshold\":0"); await using var target = new EdgeFixture(); var before = await target.Client.GetAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}"); var beforeThreshold = JsonDocument.Parse(await before.Content.ReadAsStringAsync()) .RootElement.GetProperty("streakThreshold").GetInt32(); var (status, report) = await ImportAsync(target, broken); Assert.Equal(HttpStatusCode.OK, status); Assert.False(report.GetProperty("policy").GetProperty("applied").GetBoolean(), report.ToString()); Assert.Contains("streakThreshold", report.GetProperty("policy").GetProperty("error").GetString()); // The rows are not held hostage to a bad policy section: the report // says which half happened. Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); var after = await target.Client.GetAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}"); Assert.Equal(beforeThreshold, JsonDocument.Parse(await after.Content.ReadAsStringAsync()) .RootElement.GetProperty("streakThreshold").GetInt32()); } } }