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.
This commit is contained in:
Pavlo Ratushnyi
2026-10-04 18:18:25 +02:00
parent 9d47a37ff3
commit 5c7b0bef3b
14 changed files with 564 additions and 18 deletions
+27 -11
View File
@@ -188,6 +188,8 @@ process registers:
| `OpenWaf:Policy:ObservationRetentionDays` | `7` | how long a `source_observations` row survives past its last request. 1–365 whole days; anything else aborts startup naming the key, exactly as `RefreshTtlSeconds` does rather than falling back to 7 — a silently widened window keeps rows longer than the deployment asked for and nothing would say so. Surfaced as `observationRetentionDays` on `/admin-api/state` and `/admin-api/policy`, and as `rows are pruned after Nd` on the console. |
| `OpenWaf:Policy:BanRetentionDays` | `7` | how long an expired engine ban and an alert stay readable after they stopped being live. Same 1–365 bound, same startup refusal, surfaced as `banRetentionDays` and `alerts are pruned after Nd`. Two keys rather than one because the two windows answer different questions, and their sharing 7 days was coincidence. Operator-written rows are never pruned by either window. |
| `OpenWaf:Policy:SharedStreaks` | `false` | where the streak counters live. `false` is the in-process map: no I/O on the request path, and a threshold counted per instance. `true` moves the same rules onto a row in the database, so N edges mature one streak — the gap measured in `research/2026-10-01-multi-instance/` (four refusals split 2+2 over two edges at a threshold of 3 banned nobody). It costs one round trip per observed response and one optimistic-concurrency retry when two edges touch the same source at once. `/admin-api/state` answers `streakScope`, and `/admin-api/streaks` answers `scope` as `this-process` or `shared-database`, because a count is meaningless without the store it came from. |
| `OpenWaf:Alerts:WebhookUrl` (OPEN-53) | empty | where a raised alert is pushed. Empty is no push: the alert table stays the whole record, which is what it was. Set one URL and every alert the edge raises is POSTed there as JSON — `kind`, `sourceKey`, `count`, `lastStatusCode`, `lastPath`, `createdAt`, `detail` — from a bounded queue of 1000, off the request path, after the row is durably written. A failed push never undoes a row. `OPENWAF_ALERT_WEBHOOK_URL` is the environment fallback. `/admin-api/state` answers `alertWebhookConfigured`, `alertWebhookHost` (host only: a webhook URL carries its secret in the path), `alertWebhookDelivered`, `alertWebhookFailures`, `alertWebhookLost`, `alertWebhookLastError`, `alertWebhookLastSuccessAt`, and the console prints the same on its alert line. |
| `OpenWaf:Alerts:WebhookTimeoutSeconds` | `5` | how long one push may take. 1–60 whole seconds; anything else aborts startup naming the key, as the other startup-parsed bounds do — a 0-second timeout drops every push and a 600-second one parks a queue worker on an endpoint that is not answering, and neither is what the operator typed. |
Database: `Database:Provider` = `sqlite` (default) or `postgres`,
`ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`.
@@ -280,7 +282,7 @@ GET /admin-api/alerts server_error_streak | candidate_ban
GET /admin-api/countries PUT /admin-api/countries/{code}?allowed=false
GET /admin-api/countries/summary sources and refusals per country, from the aggregates
GET /admin-api/geo which database is loaded and how old it is
GET /admin-api/state snapshot age, tracked sources, counts
GET /admin-api/state snapshot age, tracked sources, counts, push state
```
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
@@ -687,7 +689,13 @@ bans are not merely unrecorded, they are not in force anywhere.
It shows the alerts the edge raises — `server_error_streak` (your upstream is
failing, and the edge will not ban the visitor who saw it) and `candidate_ban`
(the rule would have banned, but the mode is Observe). That table is the whole
point of the alerting pillar: an alert nobody reads is a log line.
point of the alerting pillar: an alert nobody reads is a log line — which is
why `OpenWaf:Alerts:WebhookUrl` exists: the same reasoning that removed "a human
notices abuse and adds an IP" from blocking applies one level up, and an alert
nobody is told about never fires at 3am either. With an endpoint configured the
page says `pushed to <host>`, with how many landed and how many failed; without
one it says `not pushed anywhere: each row waits for someone to open this page`,
so "no alerts" and "alerts go nowhere" stay two different sentences.
It decides nothing: every control on it is one call to the API above. It is on
the always-pass list, so an operator who is themselves blocked can still reach
the page that clears it, and it is never observed, so fumbling it cannot build a
@@ -817,11 +825,12 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own.
On the head of this file the host suite has been re-run and the container stages
have not, so the two sets of numbers are labelled separately rather than merged
into one green line. macOS host, this tree, re-measured 2026-10-04 with the
retention window as configuration: build 0 warnings / 0 errors, unit **132/132**,
integration **191/191 in 32 s**, console **78 assertions, 0 failed**, smoke
**passed 28, failed 0**, and compose **209 passed, 0 failed** against the built
image — re-run on this tree because the shared-streak store adds a table and two
scope fields the shipped stack answers with. Carried from the 2026-10-02 run and
alert webhook on it: build 0 warnings / 0 errors, unit **151/151**, integration
**194/194 in 28 s**, console **79 assertions, 0 failed**, smoke **passed 29,
failed 0**, and compose **209 passed, 0 failed** against the built image at
261 MB — re-run on this tree because the webhook is a second reader of the alert
table, and the shipped stack has to stay exactly as quiet with no endpoint
configured as it was before. Carried from the 2026-10-02 run and
not re-measured since: image 261 MB, 0 containers left behind, enforcement lag
33 ms (`/tmp/c26_build.log`, `/tmp/c26_unit.log`,
`/tmp/c26_int4.log`, `/tmp/c26_smoke.log`, `/tmp/c26_compose5.log`,
@@ -831,7 +840,7 @@ collections — answered **157 passed, 16 failed**, every one of them `Timed out
waiting for the entry point to build the IHost after 00:05:00`
(`/tmp/c26_int3.log`), and with `xunit.parallelizeTestCollections=false` the same
tree answered **173/173 in 23 s** (`/tmp/c26_int4.log`). Re-measured 2026-10-04,
the default parallel scheduling answered **191/191 in 32 s**, and the same tree
the default parallel scheduling answered **194/194 in 28 s**, and the same tree
run inside a filesystem-and-network sandbox failed **every** fixture with exactly
that timeout — a test host that cannot bind a loopback socket hangs in this
shape. Scheduling is one variable in that symptom; whether the test host can
@@ -988,6 +997,13 @@ Stated, because a defence that hides its failure modes is not a defence.
edges then answered `consecutiveRefusals: 3` with `scope: shared-database`, and
the edge that never saw a third refusal started enforcing the ban 4 s later.
Numbers, method and caveats: `research/2026-10-01-multi-instance/RESULTS.md`.
* **A push is at-most-once.** The alert is the record; the webhook is a copy of
it. Three attempts and a short backoff, then the failure is counted and
surfaced — `alertWebhookFailures`, `alertWebhookLastError` — and the push is
not retried again, because a queue that survives a restart is a second system
with its own outage story. Alerts raised while the process was down are never
pushed at all. The table is what an operator reads; the push is what makes a
03:00 outage reach something that acts.
* **Aggregates, not a request log.** `source_observations` keeps counters and
the last-seen evidence per source, and ages out after
`OpenWaf:Policy:ObservationRetentionDays` (default 7, 1–365). Raw IPs are not
@@ -1000,9 +1016,9 @@ dotnet/
OpenWaf.Domain/ pure decision core: source key, streak, ordered decision
OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo
OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode
OpenWaf.Tests.Unit/ 132 tests over the decision logic and the durability counters
OpenWaf.Tests.Integration/ 173 tests driving the real pipeline against a fake upstream
scripts/smoke.sh 28 assertions against a running edge + a real upstream
OpenWaf.Tests.Unit/ 151 tests over the decision logic and the durability counters
OpenWaf.Tests.Integration/ 194 tests driving the real pipeline against a fake upstream
scripts/smoke.sh 29 assertions against a running edge + a real upstream
scripts/compose-smoke.sh 209 assertions against the built image (compose + nginx)
scripts/console-check.cjs 75 assertions against the page, in a real Chromium
scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2)
+18 -1
View File
@@ -404,7 +404,14 @@ async function load() {
+ '; threshold ' + streaks.threshold
+ ' within ' + streaks.windowMinutes + ' min; '
+ (obsSource ? 'the unfiltered map holds ' : '') + streaks.trackedSources
+ ' sources tracked, map capped at ' + streaks.maxTrackedSources;
+ ' sources tracked, '
+ (streaks.maxTrackedSources == null
// Shared store: no cap exists, so the sentence names the bound that
// does — idle rows leave the listing, and rows are deleted with the
// retention window.
? 'idle ones drop out after ' + streaks.trackedIdleMinutes
+ ' min and rows are pruned after ' + streaks.trackedRetentionDays + 'd'
: 'map capped at ' + streaks.maxTrackedSources);
// The bar is a share of the busiest country, not of some absolute scale:
// what an operator wants out of this table is "where is the traffic coming
// from right now", and that is a comparison. Widths are percentages of the
@@ -437,6 +444,16 @@ async function load() {
: 'no alerts. server_error_streak means the upstream is failing; candidate_ban means a dry run would have banned.';
if (state.banRetentionDays != null)
el('alertnote').textContent += ' · alerts are pruned after ' + state.banRetentionDays + 'd';
// Whether a raised alert reaches anything on its own. A row is read by
// whoever opens this page; a push is what fires at 03:00. The host and not
// the URL: a webhook URL carries its secret in the path, and this page is
// rendered from a response an operator's browser fetches.
el('alertnote').textContent += state.alertWebhookConfigured
? ' · pushed to ' + state.alertWebhookHost
+ (state.alertWebhookDelivered > 0 ? ', ' + state.alertWebhookDelivered + ' delivered' : '')
+ (state.alertWebhookFailures > 0 ? ', ' + state.alertWebhookFailures + ' push failures' : '')
+ (state.alertWebhookLost > 0 ? ', ' + state.alertWebhookLost + ' dropped for a full queue' : '')
: ' · not pushed anywhere: each row waits for someone to open this page';
el('countries').tBodies[0].innerHTML = seen.map((c) => row([
{ v: c.code }, { v: c.sources, n: true }, { v: c.refusals, n: true },
+18 -2
View File
@@ -369,7 +369,13 @@ internal static class AdminEndpoints
// honest reading of "one of these many".
standingStreaks = standing,
sourceFilter = source,
maxTrackedSources = policy.MaxTrackedSources,
// What bounds the count above it. A cap is only true of the
// in-process map: the shared store is bounded by time, not by
// how many sources one process can hold, and printing the cap
// there would name a limit nothing enforces.
maxTrackedSources = policy.SharedStreaks ? (int?)null : policy.MaxTrackedSources,
trackedIdleMinutes = policy.StateIdleTtl.TotalMinutes,
trackedRetentionDays = (int)policy.ObservationRetention.TotalDays,
streaks = streaks.Select(st => new StreakDto(st.SourceKey, st.ConsecutiveRefusals,
st.ConsecutiveServerErrors, st.LastStatusCode, st.LastPath, st.LastCountryCode, st.LastSeenAt))
});
@@ -471,7 +477,7 @@ internal static class AdminEndpoints
});
});
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, HttpContext ctx) =>
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, HttpContext ctx) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
var now = DateTimeOffset.UtcNow;
@@ -547,6 +553,16 @@ internal static class AdminEndpoints
// cannot run keeps aggregates past the age they promise to age out
// at, which the operator has to be able to see, but it does not
// change what this edge enforces. See Program.cs.
// Whether alerts are pushed anywhere, and how the push is doing.
// The host rather than the URL: webhook URLs carry their secret in
// the path, and this response is rendered on a page.
alertWebhookConfigured = notifier.IsConfigured,
alertWebhookHost = notifier.WebhookHost,
alertWebhookFailures = durability.Get(AlertNotifier.Pillar).Failures,
alertWebhookLost = durability.Get(AlertNotifier.Pillar).EntriesLost,
alertWebhookDelivered = durability.Get(AlertNotifier.Pillar).EntriesWritten,
alertWebhookLastError = durability.Get(AlertNotifier.Pillar).LastError,
alertWebhookLastSuccessAt = durability.Get(AlertNotifier.Pillar).LastSuccessAt,
retentionPruneFailures = durability.Get(DurabilityHealth.Retention).Failures,
retentionLastError = durability.Get(DurabilityHealth.Retention).LastError,
retentionLastPruneAt = durability.Get(DurabilityHealth.Retention).LastSuccessAt,
+16
View File
@@ -63,6 +63,22 @@ builder.Services.AddSingleton(sp => new EdgeStateStore(
});
builder.Services.AddSingleton<BlockStore>();
builder.Services.AddSingleton<DurabilityHealth>();
// Alerts used to end at a table: the row is correct and read by nobody until
// someone opens the page. One optional endpoint pushes each raised alert
// somewhere that can act at 03:00. The timeout is validated at startup rather
// than defaulted, for the same reason the refresh TTL is: 0 drops every push
// and 600 parks a worker on a dead endpoint, and neither is what the operator
// meant.
var alertWebhookUrl = builder.Configuration["OpenWaf:Alerts:WebhookUrl"];
if (string.IsNullOrWhiteSpace(alertWebhookUrl))
alertWebhookUrl = Environment.GetEnvironmentVariable("OPENWAF_ALERT_WEBHOOK_URL");
var alertWebhookTimeout = AlertNotifier.ParseTimeoutSeconds(
builder.Configuration["OpenWaf:Alerts:WebhookTimeoutSeconds"]);
builder.Services.AddSingleton<AlertNotifier>(sp => new AlertNotifier(
sp.GetRequiredService<DurabilityHealth>(),
sp.GetRequiredService<ILogger<AlertNotifier>>(),
alertWebhookUrl, alertWebhookTimeout));
builder.Services.AddHostedService(sp => sp.GetRequiredService<AlertNotifier>());
builder.Services.AddSingleton<AlertWriter>();
// An empty string in appsettings.json is not the same as "unset" to the
// configuration system, and it silently defeats the environment fallback —
+4
View File
@@ -23,6 +23,10 @@
"State": {
"RefreshTtlSeconds": 30
},
"Alerts": {
"WebhookUrl": "",
"WebhookTimeoutSeconds": 5
},
"Policy": {
"Mode": "Observe",
"StreakThreshold": 10,
@@ -0,0 +1,170 @@
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);
}
}
}
}
@@ -16,12 +16,16 @@ public sealed class AlertWriter
private readonly IServiceScopeFactory _scopeFactory;
private readonly DurabilityHealth _health;
private readonly ILogger<AlertWriter> _log;
private readonly AlertNotifier _notifier;
public AlertWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> log)
public AlertWriter(
IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> log,
AlertNotifier notifier)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
_notifier = notifier;
}
public async Task RaiseAsync(
@@ -37,7 +41,7 @@ public sealed class AlertWriter
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.Alerts.Add(new EdgeAlert
var alert = new EdgeAlert
{
Kind = kind,
SourceKey = sourceKey,
@@ -46,9 +50,14 @@ public sealed class AlertWriter
LastPath = path,
Detail = detail.Length > 1024 ? detail[..1024] : detail,
CreatedAt = DateTimeOffset.UtcNow
});
};
db.Alerts.Add(alert);
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Alerts, 1);
// Push only what is durably there, and only after the write: the
// table is the record of truth, and a push that arrives before the
// row exists would report an alert the operator then cannot find.
_notifier.Enqueue(alert);
}
catch (Exception ex)
{
@@ -0,0 +1,161 @@
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());
}
}
@@ -37,7 +37,9 @@ internal sealed class EdgeFixture : IAsyncDisposable
int? banRetentionDays = null,
string? adminToken = AdminToken,
string? dbPath = null,
bool sharedStreaks = false)
bool sharedStreaks = false,
string? alertWebhookPath = null,
int? alertWebhookTimeoutSeconds = null)
{
_sharedDb = dbPath is not null;
_dbPath = dbPath ?? Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
@@ -69,6 +71,16 @@ internal sealed class EdgeFixture : IAsyncDisposable
// the shape every other fixture runs; on is the multi-instance case
// where two of these fixtures share one database.
builder.UseSetting("OpenWaf:Policy:SharedStreaks", sharedStreaks ? "true" : "false");
// Where a raised alert is pushed, and how long one push may take.
// Unset is the shipped default: the alert table is the only record.
// The path on this fixture's own upstream, because the upstream is
// the one HTTP endpoint a fixture already owns and can make answer
// whatever the test needs — including "500 to every push".
if (alertWebhookPath is not null)
builder.UseSetting("OpenWaf:Alerts:WebhookUrl",
Upstream.Address.TrimEnd('/') + alertWebhookPath);
if (alertWebhookTimeoutSeconds is { } wts)
builder.UseSetting("OpenWaf:Alerts:WebhookTimeoutSeconds", wts.ToString());
builder.UseSetting("ReverseProxy:Clusters:upstream:Destinations:upstream1:Address", Upstream.Address);
});
}
@@ -19,6 +19,13 @@ internal sealed class FakeUpstream : IAsyncDisposable
public int RequestCount;
public List<string> Paths = [];
/// <summary>What the upstream was asked to hold, per request that sent a
/// body. The edge's alert push POSTs one, and the whole point of that
/// feature is what arrives at the endpoint — a path alone cannot show it.
/// Recorded only when a body was sent, so the proxy traffic that dominates
/// a run stays an empty list.</summary>
public List<string> Bodies = [];
/// <summary>What this upstream answers for a path.</summary>
public Func<string, int> StatusFor { get; set; } = _ => StatusCodes.Status404NotFound;
@@ -47,6 +54,12 @@ internal sealed class FakeUpstream : IAsyncDisposable
var path = context.Request.Url?.AbsolutePath ?? "/";
Interlocked.Increment(ref RequestCount);
lock (Paths) Paths.Add(path);
if (context.Request.HasEntityBody)
{
using var reader = new System.IO.StreamReader(context.Request.InputStream);
var body = reader.ReadToEnd();
lock (Bodies) Bodies.Add(body);
}
context.Response.StatusCode = StatusFor(path);
context.Response.OutputStream.Close();
@@ -134,6 +134,15 @@ public sealed class SharedStreakTests
var state = await (await b.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}")).Content.ReadAsStringAsync();
Assert.Contains("\"streakScope\":\"shared-database\"", state);
// And the bound beside the count is the one that actually applies.
// A cap is a property of one process's memory; the shared store is
// bounded by time, so naming a cap there would name a limit nothing
// enforces.
Assert.Contains("\"maxTrackedSources\":null", shared);
Assert.Contains("\"trackedRetentionDays\":7", shared);
Assert.Contains("\"trackedIdleMinutes\":120", shared);
Assert.Contains("\"maxTrackedSources\":10000", localBody);
}
finally { if (File.Exists(db)) File.Delete(db); }
}
@@ -0,0 +1,93 @@
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);
}
+6
View File
@@ -169,6 +169,12 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
check('both tables state the retention window they age out at',
/rows are pruned after \d+d/.test(obsNote) && /alerts are pruned after \d+d/.test(alertnote),
JSON.stringify([obsNote, alertnote]));
// Whether an alert goes anywhere on its own. This gate's edge runs with no
// webhook configured, and the page has to say that out loud: "the alert
// table is empty" and "the alert table is never pushed" are different facts
// an operator can only act on if the page distinguishes them.
check('the page says whether alerts are pushed anywhere at all',
/pushed to [\w.-]+/.test(alertnote) || /not pushed anywhere/.test(alertnote), alertnote);
const warnCells = await page.$$eval('#alerts tbody tr .warn', (els) => els.map((e) => e.textContent));
check('the kind an operator has to act on is marked, not only printed',
warnCells.includes('server_error_streak'), JSON.stringify(warnCells));
+4
View File
@@ -138,6 +138,10 @@ check 'the state counts failed pillar reads, and there are none' '0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["snapshotRefreshFailures"], d["policyReloadFailures"])')"
check 'the state says the snapshot is inside its ttl' False \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["snapshotStale"])')"
# Whether a raised alert goes anywhere on its own. Off by default, and the
# surface has to say which of "no alerts" and "no push" it is answering.
check 'the state says alerts are not pushed anywhere by default' False \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["alertWebhookConfigured"])')"
check 'the policy answer carries its provenance header' 0 \
"$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy" | tr -d '\r' \