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; /// /// 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? /// public sealed class AlertPushQueueTests { private const string Failing = "203.0.113.81"; private static async Task 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 WaitForStateAsync(EdgeFixture f, Func 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); } } /// /// 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. /// 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)); } /// Six 502s from one source: the 5xx streak alert fires. 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); // Settled means the QUEUE is empty, not merely that one row reached its // end. Six 502s at N=3 raise two alerts — the crossing at 3 and the // doubling at 6 — so two deliveries are owed, and the first one to give // up leaves the second still retrying for another backoff window. Waiting // on givenUp alone read that window as a product that had stopped asking // while still holding a row: measured on the Gitea Actions runner (run // 2361, head 223b8d6) this assertion read pending=1 there, and the same // race is what the Settled helper two screens up already exists for. var state = await WaitForStateAsync(f, s => s.GetProperty("alertPushGivenUp").GetInt32() >= 1 && s.GetProperty("alertPushPending").GetInt32() == 0); 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(); 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(); 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().ReadCountsAsync(); queueB = await b.Service().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); } }