Files
openwaf/dotnet/OpenWaf.Tests.Unit/AlertWebhookBoundsTests.cs
T
Pavlo Ratushnyi 5c7b0bef3b an alert can be pushed to an endpoint, so a 03:00 outage reaches something that acts
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.
2026-10-04 18:18:25 +02:00

94 lines
3.7 KiB
C#

using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The push timeout is the bound on how long one dead endpoint may hold a queue
/// worker, so it is parsed the way the other startup-parsed bounds are: a typo
/// stops the process and names the key. A 0-second timeout drops every push and
/// a 600-second one parks the worker on an endpoint that is not answering —
/// neither is what the operator typed, and both look like a quiet night.
/// </summary>
public sealed class AlertWebhookBoundsTests
{
[Theory]
[InlineData(null, 5)]
[InlineData("", 5)]
[InlineData(" ", 5)]
[InlineData("1", 1)]
[InlineData(" 7 ", 7)]
[InlineData("60", 60)]
public void Unset_means_five_and_a_whole_number_means_what_it_says(string? configured, int expected)
=> Assert.Equal(expected, AlertNotifier.ParseTimeoutSeconds(configured));
[Theory]
[InlineData("0")]
[InlineData("-5")]
[InlineData("61")]
[InlineData("600")]
[InlineData("abc")]
[InlineData("5.5")]
[InlineData("5s")]
public void Anything_else_names_the_key_and_refuses_to_start(string configured)
{
var ex = Assert.Throws<InvalidOperationException>(() => AlertNotifier.ParseTimeoutSeconds(configured));
Assert.Contains("OpenWaf:Alerts:WebhookTimeoutSeconds", ex.Message);
Assert.Contains(configured, ex.Message);
}
[Theory]
[InlineData(null, false)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData("https://hooks.example.test/abc", true)]
public void An_empty_endpoint_is_no_endpoint(string? url, bool configured)
{
var notifier = Build(url);
Assert.Equal(configured, notifier.IsConfigured);
}
[Fact]
public void The_endpoint_is_reported_as_a_host_never_as_a_url()
{
// A webhook URL carries its secret in the path — that is how the common
// providers work — and this value is echoed to the operator page.
var notifier = Build("https://hooks.example.test/notify/secret-token-123");
Assert.Equal("hooks.example.test", notifier.WebhookHost);
}
[Fact]
public void A_push_dropped_for_a_full_queue_is_counted_and_not_silently_lost()
{
// The queue is bounded on purpose — an edge under a 5xx storm raises
// alerts faster than a third-party endpoint accepts them, and an
// unbounded queue turns an outage into an out-of-memory process. The
// alternative to counting the overflow is the failure this project has
// already measured twice: a loss that looks like a quiet night.
var health = new DurabilityHealth();
var notifier = new AlertNotifier(
health,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
"https://hooks.example.test/notify", 5);
var alert = new EdgeAlert
{
Kind = "server_error_streak", SourceKey = "203.0.113.9", Count = 3,
LastStatusCode = 502, LastPath = "/checkout", Detail = "d",
CreatedAt = DateTimeOffset.UtcNow
};
// Nothing drains this queue — the worker is not running — so every write
// past the capacity is an overflow.
for (var i = 0; i < 2000; i++) notifier.Enqueue(alert);
var pillar = health.Get(AlertNotifier.Pillar);
Assert.True(pillar.EntriesLost >= 1000, pillar.ToString());
Assert.True(pillar.Failing, pillar.ToString());
Assert.Contains("queue was full", pillar.LastError);
}
private static AlertNotifier Build(string? url) => new(
new DurabilityHealth(),
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
url, 5);
}