An operator running several edges types every rule several times: blocks, allowlist, request rules, country rules and the policy overrides have their own endpoints one row at a time, and nothing moved them as a set. A new deployment starts empty, and a change that turns out wrong has nothing to be restored from. This is the multi-instance finding one level up from the shared streak store: SharedStreaks shares the counters, nothing shared the decisions.
GET /admin-api/export answers one document — version, exportedAt, edgeId, per-section counts, the policy section, and blocks / allowlist / rules / country rules. Only live rows; rules keep their evaluation order; and the document names how many engine bans it left behind, because "0 blocks" and "0 operator blocks, 7 engine bans left behind" are different sentences. A ban the engine earned is a claim about this edge's own traffic, so enforcing it where that traffic was never seen is a decision nobody made.
POST /admin-api/import is additive and idempotent: it never deletes a row the document does not mention — a transfer that silently clears a fleet's exemptions is worse than one that duplicates a block — a live row for the same source is reported as already there rather than rewritten, and expiry travels as an instant, so a block that expires in ten minutes where it came from expires in ten minutes here. Per-section counts (added / alreadyThere / skippedExpired / rejected) and a rejected[] list named by section and index; an unknown version, an oversize body or a malformed document writes nothing at all; a storage failure answers 503 with the report, because "it failed" and "it added 41 of 60" must not collapse into one sentence.
What the run caught, in order: (1) a unit assert used "203.0.113" as the invalid address and passed for the wrong reason — IPAddress.TryParse accepts it as 203.0.113.0, so the assert now names 203.0.113.999. (2) Two smoke asserts were wrong rather than the product: a helper printed a Python boolean where the gate compares text, and a blocks delete was asserted as 204 when the endpoint answers 200 with {"deleted":n}. (3) The metrics-as-a-number test could pass its wait on a cache refreshed between an enqueue and its first attempt — pending > 0 was true a moment before attempts > 0 could be — so the wait now requires both numbers. (4) A real defect, not a test one: the alert notifier left the rows it had claimed claimed when the process stopped, so the next process waited out the five-minute reclaim window to deliver an alert that was already owed. It now releases what it holds on the way out, and the reclaim window is back to being what it is for — a process that was killed and cannot say anything.
Gates on this tree: build 0 warnings / 0 errors, unit 285/285, integration 257/257 in 23s, smoke 82 passed / 0 failed (14 new), image 262 MB, compose-smoke 243 passed / 0 failed with 0 containers left behind (11 new, against the shipped image).
Refs OPEN-61.
276 lines
14 KiB
C#
276 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<HttpResponseMessage> 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<string> 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());
|
|
}
|
|
|
|
/// <summary>An edge with a hand-written config, and one engine ban it earned
|
|
/// by serving refusals — the thing that must not travel.</summary>
|
|
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());
|
|
}
|
|
}
|
|
}
|