Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.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

171 lines
7.8 KiB
C#

using System.Threading.Channels;
using System.Net.Http.Json;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Pushes the alerts the edge already raised to one HTTP endpoint, so an
/// outage at 03:00 reaches something that acts on it instead of waiting for an
/// operator to open a page (OPEN-53).
///
/// The alerting pillar used to end at a table. That is the same posture this
/// project removed for blocking — "blocking is usually manual: a human notices
/// abuse and adds an IP. That never fires at 3am" — applied to alerts: the row
/// exists, is correct, and is read by nobody until the morning.
///
/// Three properties, each because the alternative was measured elsewhere in
/// this codebase:
/// * It never runs on the request path. Alerts are raised from the response
/// path; a webhook that is slow or down must not slow or break the response.
/// The queue is bounded, and an alert dropped because the queue was full is
/// counted, not silently lost.
/// * The database row stays the record of truth. A failed push does not undo
/// an alert, and the alert table is still what the operator reads.
/// * The endpoint is counted like every other write side pillar — consecutive
/// failures, entries lost, last error, last success — because a push that
/// has been failing for a week is otherwise indistinguishable from a quiet
/// night.
/// </summary>
public sealed class AlertNotifier : BackgroundService
{
public const string Pillar = "alertWebhook";
/// <summary>How long one push may take. Out of range refuses startup rather
/// than falling back: a 0-second timeout drops every push, and a 600-second
/// one parks a queue worker on a dead endpoint — the same reasoning as
/// <c>OpenWaf:State:RefreshTtlSeconds</c>.</summary>
public const int TimeoutSecondsFloor = 1, TimeoutSecondsCeiling = 60;
public static int ParseTimeoutSeconds(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return 5;
if (!int.TryParse(configured, out var seconds)
|| seconds < TimeoutSecondsFloor || seconds > TimeoutSecondsCeiling)
throw new InvalidOperationException(
$"OpenWaf:Alerts:WebhookTimeoutSeconds must be a whole number of seconds between "
+ $"{TimeoutSecondsFloor} and {TimeoutSecondsCeiling}; got {configured}");
return seconds;
}
/// <summary>The queue is bounded on purpose. An edge under a 5xx storm can
/// raise alerts faster than a third-party endpoint accepts them; an
/// unbounded queue turns an outage into an out-of-memory process. Overflow
/// is counted as lost pushes — the alert row still exists.</summary>
private const int QueueCapacity = 1000;
private readonly Channel<EdgeAlert> _queue =
Channel.CreateBounded<EdgeAlert>(new BoundedChannelOptions(QueueCapacity)
{
// Wait, not DropWrite — and nothing here ever awaits a write. The
// mode is chosen for what TryWrite does when the queue is full: in
// Wait mode it returns false, so the overflow is counted; in
// DropWrite mode it returns true and the alert vanishes with no
// trace (measured, not assumed — the first version of this class
// used DropWrite and its own test caught the silence). The response
// path stays safe because it calls TryWrite, which cannot block.
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true
});
private readonly DurabilityHealth _health;
private readonly ILogger<AlertNotifier> _log;
private readonly string? _url;
private readonly HttpClient _http;
/// <summary>Host only, never the URL: webhook URLs routinely carry the
/// secret in the path, and this is echoed to the operator page and the log.</summary>
public string? WebhookHost { get; }
public bool IsConfigured => _url is not null;
public AlertNotifier(DurabilityHealth health, ILogger<AlertNotifier> log, string? webhookUrl, int timeoutSeconds)
{
_health = health;
_log = log;
_url = string.IsNullOrWhiteSpace(webhookUrl) ? null : webhookUrl.Trim();
WebhookHost = _url is null ? null : new Uri(_url).Host;
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(timeoutSeconds) };
}
/// <summary>Called by <see cref="AlertWriter"/> after the row is durably
/// written. Never blocks: a full queue drops this push and counts it.</summary>
public void Enqueue(EdgeAlert alert)
{
if (_url is null) return;
if (!_queue.Writer.TryWrite(alert))
_health.RecordFailure(Pillar, "the push queue was full; the alert exists in the table but was not pushed", 1);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_url is null) return;
await foreach (var alert in _queue.Reader.ReadAllAsync(stoppingToken))
{
try
{
await PushAsync(alert, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
// The third attempt threw — a timeout, a refused connection. A
// delivery was lost, not a record: the alert row is in the
// table either way, so nothing is counted as entries lost.
_health.RecordFailure(Pillar, ex);
_log.LogWarning(ex, "AlertNotifier: could not push a {Kind} alert to {Host}.", alert.Kind, WebhookHost);
}
}
}
private async Task PushAsync(EdgeAlert alert, CancellationToken ct)
{
// Three attempts, short backoff. A webhook that answers 500 once is
// usually a blip at the other end; one that answers 500 three times is
// a broken endpoint, and the counters say so rather than the log.
for (var attempt = 1; ; attempt++)
{
try
{
using var response = await _http.PostAsJsonAsync(_url!, new
{
kind = alert.Kind,
sourceKey = alert.SourceKey,
count = alert.Count,
lastStatusCode = alert.LastStatusCode,
lastPath = alert.LastPath,
createdAt = alert.CreatedAt,
detail = alert.Detail
}, ct);
if (response.IsSuccessStatusCode)
{
_health.RecordSuccess(Pillar, 1);
return;
}
if (attempt >= 3)
{
// Named with the status, because "the push failed" is not
// actionable and "the endpoint answered 404" is. Nothing is
// counted as lost here: the alert row is in the table and
// the operator can still read it, so what this costs is a
// delivery, not a record. EntriesLost stays reserved for
// the one case where the push is gone for good — a queue
// that filled faster than the endpoint drains it.
_health.RecordFailure(Pillar,
$"the endpoint answered {(int)response.StatusCode}");
return;
}
}
catch (Exception ex) when (attempt < 3 && !ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt), ct);
_log.LogDebug(ex, "AlertNotifier: push attempt {Attempt} failed; retrying.", attempt);
}
}
}
}