The alerting pillar ended at a table. The rows are right — 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.
OpenWaf:Alerts:WebhookUrl (env fallback OPENWAF_ALERT_WEBHOOK_URL) POSTs each
raised alert as JSON — kind, sourceKey, count, lastStatusCode, lastPath,
createdAt, detail — off the request path, from a bounded queue of 1000, and only
after the row is durably written. Three attempts with a short backoff;
OpenWaf:Alerts:WebhookTimeoutSeconds (1-60, default 5) refuses startup outside
that range rather than falling back, as the other startup-parsed bounds do. The
default is empty, which is no push at all: the shipped stack behaves exactly as
it did before.
The endpoint is counted like every other write side pillar, because a webhook
that has been down for a week is otherwise indistinguishable from a quiet night:
alertWebhookFailures, alertWebhookLost, alertWebhookDelivered,
alertWebhookLastError, alertWebhookLastSuccessAt, plus alertWebhookConfigured and
alertWebhookHost — host, never the URL, since a webhook URL carries its secret
in the path and this is rendered on the operator page. The console's alert line
now ends in "pushed to <host>, N delivered" or "not pushed anywhere: each row
waits for someone to open this page", so "no alerts" and "alerts go nowhere" stay
two different sentences.
Two things the tests caught instead of the design assuming:
* the queue was BoundedChannelFullMode.DropWrite, where TryWrite returns true
and the overflow vanishes with no trace — the counter it was written to feed
stayed at zero. The mode is Wait now, chosen for what TryWrite reports when
the queue is full; nothing here awaits a write, so the response path still
cannot block.
* a refused push counted as an entry lost, which conflated a lost delivery with
a lost record. The alert row is in the table either way, so EntriesLost on
this pillar is reserved for the one case where the push is gone for good.
Measured on this tree: build 0 warnings / 0 errors, unit 151/151 (19 new),
integration 194/194 in 28 s (3 new: the push arrives with the alert in it, an
unconfigured edge sends nothing and keeps every row, an endpoint answering 500 is
counted and does not undo the alert), smoke 29/0, console 79 assertions 0 failed,
compose 209/0 against the built image at 261 MB.
162 lines
7.6 KiB
C#
162 lines
7.6 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public sealed class AlertWebhookTests
|
|
{
|
|
private const string Failing = "203.0.113.81";
|
|
|
|
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<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();
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
private static async Task<JsonElement> WaitForStateAsync(EdgeFixture f, Func<JsonElement, bool> 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<List<string>> WaitForBodiesAsync(FakeUpstream upstream, Func<List<string>, bool> ready)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(15);
|
|
while (true)
|
|
{
|
|
List<string> bodies;
|
|
lock (upstream.Bodies) bodies = upstream.Bodies.ToList();
|
|
if (ready(bodies) || DateTime.UtcNow > deadline) return bodies;
|
|
await Task.Delay(100);
|
|
}
|
|
}
|
|
|
|
/// <summary>Six 502s from one source at a threshold of 3: the streak
|
|
/// crosses, the alert is raised, and the upstream never bans anybody.</summary>
|
|
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<OpenWafDbContext>();
|
|
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<OpenWafDbContext>();
|
|
Assert.NotEmpty(await db.Alerts.AsNoTracking()
|
|
.Where(a => a.Kind == "server_error_streak" && a.SourceKey == Failing).ToListAsync());
|
|
}
|
|
}
|