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.
301 lines
15 KiB
C#
301 lines
15 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// The delivery, not the alert (OPEN-60).
|
|
///
|
|
/// The alert table already had these tests. What is under test here is the
|
|
/// separate promise the webhook added — that somebody is told — and the way that
|
|
/// promise used to fail quietly: the queue of "not pushed yet" lived in one
|
|
/// process's memory, so an endpoint down for ten minutes swallowed every alert
|
|
/// raised in that window, and a restart swallowed everything still waiting. The
|
|
/// alert row was correct the whole time, which is what made it invisible.
|
|
///
|
|
/// So every test here asks the same question in a different way: an alert was
|
|
/// raised, the endpoint could not take it, and does the operator still hear about
|
|
/// it later?
|
|
/// </summary>
|
|
public sealed class AlertPushQueueTests
|
|
{
|
|
private const string Failing = "203.0.113.81";
|
|
|
|
private static async Task<JsonElement> StateAsync(EdgeFixture f)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
response.EnsureSuccessStatusCode();
|
|
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|
|
|
|
private static async Task<JsonElement> WaitForStateAsync(EdgeFixture f, Func<JsonElement, bool> ready)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (true)
|
|
{
|
|
var state = await StateAsync(f);
|
|
if (ready(state) || DateTime.UtcNow > deadline) return state;
|
|
await Task.Delay(150);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The queue has emptied and at least one delivery landed. Waiting on
|
|
/// "delivered >= 1" alone reads the queue between two rows: one scene can
|
|
/// raise more than one alert, and the second row is still owed the moment the
|
|
/// first lands — which is how this suite first failed, on a correct product.
|
|
/// </summary>
|
|
private static bool Settled(JsonElement s) =>
|
|
s.GetProperty("alertPushPending").GetInt32() == 0
|
|
&& s.GetProperty("alertPushDelivered").GetInt32() >= 1;
|
|
|
|
private static int PushesTo(FakeUpstream upstream, string marker)
|
|
{
|
|
lock (upstream.Bodies) return upstream.Bodies.Count(b => b.Contains(marker));
|
|
}
|
|
|
|
/// <summary>Six 502s from one source: the 5xx streak alert fires.</summary>
|
|
private static async Task BreakTheUpstreamAsync(EdgeFixture f)
|
|
{
|
|
for (var i = 0; i < 6; i++)
|
|
{
|
|
using var probe = new HttpRequestMessage(HttpMethod.Get, "/checkout");
|
|
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Failing);
|
|
using var r = await f.Client.SendAsync(probe);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task An_endpoint_that_refused_is_asked_again_once_it_heals()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
|
|
// Wait for an attempt to have happened, not merely for a row to exist: a
|
|
// row that has not been tried yet has no error to name, and an assertion
|
|
// written against it passes for the wrong reason.
|
|
var failing = await WaitForStateAsync(f,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
Assert.True(failing.GetProperty("alertWebhookFailures").GetInt32() >= 1, failing.ToString());
|
|
Assert.Equal(0, failing.GetProperty("alertPushDelivered").GetInt32());
|
|
Assert.Equal(0, failing.GetProperty("alertPushGivenUp").GetInt32());
|
|
// The queue says what it is waiting on, in words an operator can act on.
|
|
Assert.Contains("500", failing.GetProperty("alertPushLastError").GetString());
|
|
|
|
// The endpoint heals. Nothing new happens at the edge — no new alert, no
|
|
// operator action — and the delivery still goes out.
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status200OK
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
var healed = await WaitForStateAsync(f, Settled);
|
|
Assert.True(PushesTo(f.Upstream, "server_error_streak") >= 1, "the healed endpoint never got the alert");
|
|
Assert.Equal(0, healed.GetProperty("alertPushPending").GetInt32());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one()
|
|
{
|
|
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
|
|
|
|
// First process: the endpoint refuses, so the delivery is owed and stays
|
|
// owed after this process is gone.
|
|
string? owed = null;
|
|
await using (var first = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
|
|
maxPushAttempts: 20, pushRetrySeconds: 1))
|
|
{
|
|
first.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
await BreakTheUpstreamAsync(first);
|
|
var state = await WaitForStateAsync(first,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
Assert.True(state.GetProperty("alertPushPending").GetInt32() >= 1, state.ToString());
|
|
owed = state.GetProperty("alertPushOldestPendingAt").GetString();
|
|
}
|
|
|
|
Assert.NotNull(owed);
|
|
|
|
// Second process, same database, working endpoint. It raised nothing and
|
|
// nobody asked it to remember anything: the queue is rows, so the promise
|
|
// outlives the process that made it.
|
|
//
|
|
// The 25 s the wait allows is the assertion. A row the first process
|
|
// claimed and never finished would otherwise sit behind that claim until
|
|
// the reclaim window expires — five minutes — and this test would fail on
|
|
// a queue that is durable and merely waiting. The notifier releases what
|
|
// it holds on the way out; the window is for a process that was killed.
|
|
await using var second = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
second.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
var state2 = await WaitForStateAsync(second, Settled);
|
|
Assert.Equal(0, state2.GetProperty("alertPushPending").GetInt32());
|
|
var pushed = PushesTo(second.Upstream, "server_error_streak");
|
|
Assert.True(pushed >= 1, "the new process never delivered what the old one owed");
|
|
// The payload came with the row, not out of the old process's memory.
|
|
lock (second.Upstream.Bodies)
|
|
Assert.Contains(second.Upstream.Bodies, b => b.Contains(Failing));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Attempts_run_out_and_the_surface_says_who_was_never_told()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 2, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
|
|
var state = await WaitForStateAsync(f, s => s.GetProperty("alertPushGivenUp").GetInt32() >= 1);
|
|
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
|
|
Assert.True(state.GetProperty("alertPushGivenUp").GetInt32() >= 1, state.ToString());
|
|
|
|
// The distinction this item exists for: a failing counter alone cannot
|
|
// tell "still asking" from "stopped asking".
|
|
Assert.Contains("gave up after 2 attempts", state.GetProperty("alertPushLastError").GetString());
|
|
|
|
// And giving up on the delivery does not undo the alert.
|
|
using var scope = f.Factory.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.NotEmpty(await db.Alerts.AsNoTracking()
|
|
.Where(a => a.Kind == "server_error_streak" && a.SourceKey == Failing).ToListAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_delivery_owed_outlives_the_alert_row_it_was_copied_from()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
await WaitForStateAsync(f,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
|
|
// Retention prunes edge_alerts on the ban-retention window. A delivery
|
|
// still owed must not go with them, which is why the payload is copied
|
|
// onto the queue row rather than read back from the alert.
|
|
using (var scope = f.Factory.Services.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
Assert.True(await db.Alerts.ExecuteDeleteAsync() >= 1);
|
|
}
|
|
|
|
f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
var state = await WaitForStateAsync(f, Settled);
|
|
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
|
|
lock (f.Upstream.Bodies)
|
|
Assert.Contains(f.Upstream.Bodies, b => b.Contains("server_error_streak") && b.Contains(Failing));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Two_edges_on_one_database_do_not_tell_the_same_person_twice()
|
|
{
|
|
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
|
|
await using (var first = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
|
|
maxPushAttempts: 20, pushRetrySeconds: 1))
|
|
{
|
|
first.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
await BreakTheUpstreamAsync(first);
|
|
await WaitForStateAsync(first,
|
|
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
|
|
}
|
|
|
|
// Two processes, one database, one owed delivery each, two working
|
|
// endpoints. A duplicate page at 03:00 is not a harmless bug, so the row
|
|
// is claimed before it is sent and exactly one process sends it.
|
|
await using var a = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
await using var b = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
a.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
b.Upstream.StatusFor = _ => StatusCodes.Status200OK;
|
|
|
|
// Wait on the queue, not on the bodies: a body arrives a moment before the
|
|
// row that produced it is marked delivered, and an assertion written
|
|
// against the wire would read the database mid-write.
|
|
PushQueueCounts queueA = new(0, 0, 0, null, null, 0), queueB = new(0, 0, 0, null, null, 0);
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (DateTime.UtcNow < deadline)
|
|
{
|
|
queueA = await a.Service<AlertNotifier>().ReadCountsAsync();
|
|
queueB = await b.Service<AlertNotifier>().ReadCountsAsync();
|
|
if (queueA.Pending == 0 && queueA.Delivered >= 1) break;
|
|
await Task.Delay(250);
|
|
}
|
|
|
|
Assert.Equal(0, queueA.Pending);
|
|
Assert.True(queueA.Delivered >= 1, $"nothing was delivered — A: {queueA}, B: {queueB}");
|
|
Assert.Equal(0, queueA.GivenUp);
|
|
|
|
// The count that proves the claim works: every owed row was sent, and no
|
|
// row was sent twice. Two processes polling the same table on the same
|
|
// interval is exactly where a duplicate would appear.
|
|
var total = PushesTo(a.Upstream, Failing) + PushesTo(b.Upstream, Failing);
|
|
Assert.Equal(queueA.Delivered, total);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task The_queue_is_a_number_a_scraper_can_put_an_alert_rule_on()
|
|
{
|
|
await using var f = new EdgeFixture(
|
|
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
|
|
f.Upstream.StatusFor = p => p == "/hook"
|
|
? StatusCodes.Status500InternalServerError
|
|
: StatusCodes.Status502BadGateway;
|
|
|
|
await BreakTheUpstreamAsync(f);
|
|
await WaitForStateAsync(f, s => s.GetProperty("alertPushPending").GetInt32() >= 1);
|
|
|
|
// The gauge is cached, so it is at most five seconds behind the rows and
|
|
// the test has to wait for the cache rather than assume it.
|
|
string body = "";
|
|
var scrapeDeadline = DateTime.UtcNow.AddSeconds(15);
|
|
while (DateTime.UtcNow < scrapeDeadline)
|
|
{
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/metrics");
|
|
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
|
using var response = await f.Client.SendAsync(request);
|
|
body = await response.Content.ReadAsStringAsync();
|
|
// Both numbers, not just the first: a pass that refreshes the cache
|
|
// between an enqueue and its first attempt sees a row that is owed
|
|
// and not yet tried, so "pending > 0" alone can be true a moment
|
|
// before "attempts > 0" ever can.
|
|
if (System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_pending [1-9]")
|
|
&& System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_attempts_total [1-9]")) break;
|
|
await Task.Delay(250);
|
|
}
|
|
|
|
// A count of rows, not of one alert: a storm can owe more than one
|
|
// delivery, so the assertion is that the gauge is non-zero and the other
|
|
// two are still zero.
|
|
Assert.Matches(@"openwaf_alert_push_pending [1-9]", body);
|
|
Assert.Contains("openwaf_alert_push_delivered_total 0", body);
|
|
Assert.Contains("openwaf_alert_push_given_up_total 0", body);
|
|
Assert.Matches(@"openwaf_alert_push_attempts_total [1-9]", body);
|
|
Assert.Contains("openwaf_alert_push_oldest_pending_age_seconds", body);
|
|
}
|
|
}
|