using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
///
/// The alerting pillar used to end at a table. The rows are correct — the
/// server-error streak fires, the dry-run candidate is recorded — and then they
/// wait for an operator to open a page. That is the posture this project already
/// removed for blocking ("blocking is usually manual: a human notices abuse and
/// adds an IP. That never fires at 3am"), applied one level up: an alert nobody
/// is told about never fires at 3am either.
///
/// What these tests pin down is the shape of the fix, not only that it works:
/// * the push happens, and carries the alert rather than a ping;
/// * the database row stays the record of truth — a refused push does not
/// undo an alert, and no push at all does not hide one;
/// * a push that is failing is counted and surfaced, because a webhook that
/// has been down for a week is otherwise indistinguishable from a quiet
/// night, which is exactly the blindness the durability counters exist for.
///
public sealed class AlertWebhookTests
{
private const string Failing = "203.0.113.81";
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 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();
}
/// The push runs on a background worker, off the request path —
/// that is the point of it, so a test cannot assume it has already happened
/// when the response came back. Poll, then assert on what was actually
/// there rather than throwing, so a failure prints the state.
private static async Task WaitForStateAsync(EdgeFixture f, Func ready)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (true)
{
var state = await StateAsync(f);
if (ready(state) || DateTime.UtcNow > deadline) return state;
await Task.Delay(100);
}
}
private static async Task> WaitForBodiesAsync(FakeUpstream upstream, Func, bool> ready)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (true)
{
List bodies;
lock (upstream.Bodies) bodies = upstream.Bodies.ToList();
if (ready(bodies) || DateTime.UtcNow > deadline) return bodies;
await Task.Delay(100);
}
}
/// Six 502s from one source at a threshold of 3: the streak
/// crosses, the alert is raised, and the upstream never bans anybody.
private static async Task BreakTheUpstreamAsync(EdgeFixture f)
{
for (var i = 0; i < 6; i++)
{
using var probe = await GetAsync(f, "/checkout", Failing);
Assert.Equal(HttpStatusCode.BadGateway, probe.StatusCode);
}
}
[Fact]
public async Task A_raised_alert_is_pushed_to_the_configured_endpoint()
{
await using var f = new EdgeFixture(threshold: 3, alertWebhookPath: "/hook");
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status200OK
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
var bodies = await WaitForBodiesAsync(f.Upstream, b => b.Any(x => x.Contains("server_error_streak")));
var pushed = bodies.FirstOrDefault(x => x.Contains("server_error_streak"));
Assert.NotNull(pushed);
// The alert itself, not a ping: whoever receives this has to be able to
// act without opening the console first.
var payload = JsonDocument.Parse(pushed!).RootElement;
Assert.Equal("server_error_streak", payload.GetProperty("kind").GetString());
Assert.Equal(Failing, payload.GetProperty("sourceKey").GetString());
Assert.True(payload.GetProperty("count").GetInt32() >= 3, pushed);
Assert.Equal(StatusCodes.Status502BadGateway, payload.GetProperty("lastStatusCode").GetInt32());
Assert.Equal("/checkout", payload.GetProperty("lastPath").GetString());
Assert.False(string.IsNullOrEmpty(payload.GetProperty("detail").GetString()));
var state = await WaitForStateAsync(f, s => s.GetProperty("alertWebhookDelivered").GetInt32() >= 1);
Assert.True(state.GetProperty("alertWebhookConfigured").GetBoolean());
// Host, never the URL: the secret in a webhook URL lives in its path.
Assert.Equal("127.0.0.1", state.GetProperty("alertWebhookHost").GetString());
Assert.Equal(0, state.GetProperty("alertWebhookFailures").GetInt32());
Assert.Equal(0, state.GetProperty("alertWebhookLost").GetInt32());
}
[Fact]
public async Task With_no_endpoint_configured_the_edge_says_so_and_still_keeps_every_alert()
{
await using var f = new EdgeFixture(threshold: 3);
f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
var state = await StateAsync(f);
Assert.False(state.GetProperty("alertWebhookConfigured").GetBoolean());
Assert.Equal(JsonValueKind.Null, state.GetProperty("alertWebhookHost").ValueKind);
Assert.Equal(0, state.GetProperty("alertWebhookFailures").GetInt32());
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());
// Nothing was sent anywhere: an unconfigured edge is quiet, not
// silently POSTing to whatever the upstream happens to be.
lock (f.Upstream.Bodies) Assert.Empty(f.Upstream.Bodies);
}
[Fact]
public async Task An_endpoint_that_refuses_does_not_undo_the_alert_and_is_counted()
{
await using var f = new EdgeFixture(threshold: 3, alertWebhookPath: "/hook", alertWebhookTimeoutSeconds: 1);
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
var state = await WaitForStateAsync(f, s => s.GetProperty("alertWebhookFailures").GetInt32() >= 1);
Assert.True(state.GetProperty("alertWebhookFailures").GetInt32() >= 1, state.ToString());
// Named with the status, because "the push failed" is not actionable and
// "the endpoint answered 500" is.
Assert.Contains("answered 500", state.GetProperty("alertWebhookLastError").GetString());
Assert.Equal(0, state.GetProperty("alertWebhookLost").GetInt32());
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());
}
}