an alert that could not be pushed is pushed later, and says so while it waits

The push queue was a channel in one process: three attempts inside one request of work, then the row was simply no longer owed to anybody. An endpoint down for ten minutes swallowed every alert raised in that window, and a restart swallowed everything still waiting. The alert table stayed correct the whole time, which is exactly what made the hole invisible from the surface.

What is owed is now a row in alert_pushes: denormalised payload (retention prunes edge_alerts, and a delivery still owed must not go with the row it was copied from), attempts, next-attempt time, last error, and a claim so two edges over one database send each row once. Attempts are configuration (OpenWaf:Alerts:MaxPushAttempts, PushRetrySeconds), validated at startup like the other bounds; when they run out the row records that and the surface says how many were given up, because a counter that cannot tell 'still retrying' from 'stopped retrying' is the blindness this item removes.

Surfaces: /admin-api/state answers alertPushPending/Delivered/GivenUp/OldestPendingAt/LastError from the table, /metrics publishes the same as gauges from a cache no older than 5s (the metrics endpoint's rule is that it never leans on the database per scrape). Retention prunes only rows that are finished.

What the run caught, in order: (1) SchemaUpgradeTests hardcoded the migration count as a literal, so the new migration turned a working upgrade into a red test - the count is now read from the migrations assembly. (2) Two of the new queue tests asserted 'pending == 0' after waiting only for 'delivered >= 1'; one scene raises more than one alert, so the read landed between two rows and failed on a correct product - the wait now requires the queue to have emptied. (3) The whole integration suite answered 9 failures of 251, every one 'Timed out waiting for the entry point to build the IHost after 00:05:00', while the identical build minutes later answered 251/251 in 34s: a test host that cannot bind a loopback socket fails as a timeout, and the README now says so next to the scheduling note that used to be the only explanation on file.

Gates on this tree: build 0 warnings / 0 errors, unit 277/277, integration 251/251 in 34s, smoke 68 passed / 0 failed (3 new), image 261 MB, compose-smoke 232 passed / 0 failed with 0 containers left behind (2 new, including the push-queue table being added by the edge to a volume that predates it), console 90 assertions / 0 failed.

Refs OPEN-60.
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 03:21:39 +02:00
parent 575ef88afe
commit d635a00078
20 changed files with 1565 additions and 122 deletions
+25 -9
View File
@@ -263,8 +263,10 @@ 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: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 **durable queue** — one row in `alert_pushes` per owed delivery, off the request path, written after the alert row is durable (OPEN-60). A failed push never undoes a row, and it is asked again on the schedule below until it lands or the attempts run out; a restart does not lose what is still owed, and two edges sharing one database push each row once, not twice. `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. The queue itself answers `alertPushPending`, `alertPushDelivered`, `alertPushGivenUp`, `alertPushOldestPendingAt` and `alertPushLastError` — counts of rows, so they survive a restart and agree between edges. |
| `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. |
| `OpenWaf:Alerts:MaxPushAttempts` (OPEN-60) | `6` | how many attempts one delivery gets before the edge stops asking. 1–20 whole attempts; anything else aborts startup naming the key. Against an endpoint that refuses, the default spends its last attempt a little over three minutes in (30 s, 60 s, 120 s, 240 s, 480 s — each step capped at 30 min) and then records the row as given up: `alertPushGivenUp` counts those rows and `alertPushLastError` says why in the sentence the row carries (`gave up after 6 attempts: the endpoint answered 500`). A row that has given up is never retried, and the alert row behind it is untouched — what is lost is the telling, not the record. |
| `OpenWaf:Alerts:PushRetrySeconds` | `30` | the base of the backoff between attempts: attempt *n* waits `base × 2^(n−1)`, capped at 30 minutes per step, because exponential growth from a 30-second base reaches a day in eight steps and a day is not a retry interval for a page meant to fire at 03:00. 1–3600 whole seconds, same startup refusal — a 0-second interval against a dead endpoint is a busy loop. |
Database: `Database:Provider` = `sqlite` (default) or `postgres`,
`ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`.
@@ -908,8 +910,8 @@ 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`,
page says `pushed to <host>`, with how many landed, how many failed and how many
are still owed; 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
@@ -1039,11 +1041,11 @@ 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
schema upgrade on it: build 0 warnings / 0 errors, unit **256/256**, integration
**245/245 in 19 s**, console **90 assertions, 0 failed**, smoke **passed 65,
failed 0**, and compose **229 passed, 0 failed** against the built image at
261 MB. The smoke count moved by more than its new scene: the edge was being
into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable
alert-push queue on it: build 0 warnings / 0 errors, unit **277/277**, integration
**251/251 in 34 s**, console **90 assertions, 0 failed**, smoke **passed 68,
failed 0**, and compose **232 passed, 0 failed** against the built image at
261 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being
started from the repository root, where there is no `appsettings.json`, so it
loaded no `ReverseProxy` section, logged "Request reached the end of the
middleware pipeline without being handled by application code" for every request,
@@ -1069,7 +1071,11 @@ the default parallel scheduling answered **208/208 in 25 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
open a socket at all is another, and it is the one that decided the run today. Earlier in the
open a socket at all is another, and it is the one that decided the run today. Re-measured on 2026-10-05 and it decided another run the same way: the same tree
inside a sandbox answered **9 failures of 251**, every one of them that same
`Timed out waiting for the entry point to build the IHost after 00:05:00`, while the
identical build outside it answered **251/251 in 34 s**. The suite is not slow in
there; it cannot bind a loopback socket, and the failure it reports is a timeout. Earlier in the
same cycle two overlapping runs of the suite produced the older OPEN-47 symptom
on `PillarFailureVisibilityTests.The_snapshot_age_is_measured_against_the_ttl_it_is_supposed_to_respect`
— a real `Assert.False`, not a timeout — while that test passed on its own. The
@@ -1226,6 +1232,16 @@ Stated, because a defence that hides its failure modes is not a defence.
same surface as the admin API with the same token, so a scrape is a
credentialed request. Per-source metrics are out for the same reason the project
keeps no request log.
* **The push queue is durable; the delivery is still not guaranteed.** What is owed
is a row in `alert_pushes`, so a restart picks it up and two edges over one
database claim a row before sending it — but the bound is attempts, not time.
After `MaxPushAttempts` the row says `gave up after N attempts: …` and stops,
because an endpoint that has refused for an hour is broken and the honest answer
is to say so rather than keep asking. A process killed mid-delivery leaves its
claim for up to 5 minutes, so a crash delays a delivery instead of losing one.
At-least-once would need the receiver to deduplicate; nothing here promises that.
The alert table stays the record of truth either way — a refused push never
undoes an alert.
* **Geo is a probabilistic claim about an address**, not a fact about a person.
The 451 body says so. The database is pinned by a build argument and ages with
the image, so `/healthz` reports its build date and `geoStale`.
@@ -0,0 +1,64 @@
namespace OpenWaf.Domain.Security;
/// <summary>
/// A delivery this edge owes somebody (OPEN-60).
///
/// The alert table is the record of what happened; this table is the record of
/// whether anyone was told. They are separate rows because they fail separately:
/// an alert that is durably written and never pushed is exactly the blindness
/// the webhook was added to remove, and until now the queue of "not yet pushed"
/// lived in a channel in one process — three attempts, then the delivery was
/// gone for good, and a restart dropped everything still waiting.
///
/// The payload is copied here rather than referenced. Retention prunes
/// <c>edge_alerts</c> on the ban-retention window, and a push that is still due
/// must not die with the row it came from: an alert raised at 03:00 against an
/// endpoint that is down until the morning is the case this exists for.
/// </summary>
public sealed class AlertPush
{
public long Id { get; init; }
/// <summary>The alert this delivery came from. Not a foreign key and not
/// unique-by-constraint across restarts — it is the answer to "have I already
/// promised this alert to somebody", and it is what an operator reads next to
/// the alert row.</summary>
public long AlertId { get; set; }
// ---- the payload, copied (see the class note) ----
public string Kind { get; set; } = string.Empty;
public string SourceKey { get; set; } = string.Empty;
public int Count { get; set; }
public int? LastStatusCode { get; set; }
public string? LastPath { get; set; }
public string Detail { get; set; } = string.Empty;
public DateTimeOffset AlertCreatedAt { get; set; } = DateTimeOffset.UtcNow;
// ---- the delivery state ----
public int Attempts { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
/// <summary>When this row may be tried again. Null while a process holds a
/// claim on it.</summary>
public DateTimeOffset? NextAttemptAt { get; set; }
public string? LastError { get; set; }
/// <summary>Set once, when the endpoint accepted the push. A delivered row
/// keeps its row until retention ages it out, so "how many did we tell people
/// about" is a count of rows rather than a counter that resets on restart.</summary>
public DateTimeOffset? PushedAt { get; set; }
/// <summary>Set once, when the attempts ran out. The difference between this
/// and a pending row is the difference between "the endpoint is down" and
/// "we stopped asking", and an operator is entitled to know which one they
/// are reading.</summary>
public DateTimeOffset? GivenUpAt { get; set; }
/// <summary>Which process is trying this row right now. Two edges sharing one
/// database would otherwise push the same alert twice, and a duplicate page
/// at 03:00 is not a harmless bug. A claim older than the reclaim window
/// belongs to a process that died and is taken over.</summary>
public string? ClaimedBy { get; set; }
public DateTimeOffset? ClaimedAt { get; set; }
}
+15 -1
View File
@@ -697,10 +697,15 @@ note = t.Note
});
});
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, HttpContext ctx) =>
group.MapGet("/state", async (EdgeStateStore state, EdgePolicyProvider policyProvider, IStreakTracker tracker, RateTracker rateTracker, DurabilityHealth durability, BlockStore blockStore, AlertNotifier notifier, SchemaUpgradeReport schema, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
var now = DateTimeOffset.UtcNow;
// The push queue read straight from the table: an operator at this
// page is asking now, and "how many alerts is the edge still trying
// to tell someone about" is the question that has an answer only in
// the rows (OPEN-60).
var pushQueue = await notifier.ReadCountsAsync(ct);
var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now));
var allowExpired = state.Current.AllowEntries.Count - allowLive;
return Results.Ok(new
@@ -783,6 +788,15 @@ note = t.Note
alertWebhookDelivered = durability.Get(AlertNotifier.Pillar).EntriesWritten,
alertWebhookLastError = durability.Get(AlertNotifier.Pillar).LastError,
alertWebhookLastSuccessAt = durability.Get(AlertNotifier.Pillar).LastSuccessAt,
// The queue behind the push (OPEN-60). The counters above say how the
// attempts are going; these say what is still owed, and the difference
// between "the endpoint is down and we are still asking" and "we
// stopped asking" is the difference an operator acts on.
alertPushPending = pushQueue.Pending,
alertPushDelivered = pushQueue.Delivered,
alertPushGivenUp = pushQueue.GivenUp,
alertPushLastError = pushQueue.LastError,
alertPushOldestPendingAt = pushQueue.OldestPendingAt,
retentionPruneFailures = durability.Get(DurabilityHealth.Retention).Failures,
retentionLastError = durability.Get(DurabilityHealth.Retention).LastError,
retentionLastPruneAt = durability.Get(DurabilityHealth.Retention).LastSuccessAt,
@@ -175,6 +175,30 @@ internal static class MetricsEndpoint
webhook.With(notifier.IsConfigured ? 1 : 0, ("outcome", "configured"));
families.Add(webhook);
// The queue behind the push (OPEN-60). Cached rather than queried:
// this endpoint's rule is that a scrape never leans on the database,
// so the gauge is at most five seconds behind the rows and says so.
var queue = notifier.Counts;
families.Add(MetricFamily.Gauge("openwaf_alert_push_pending",
"Deliveries this edge still owes the webhook, including the ones a "
+ "previous process left behind. Read at most five seconds stale.")
.With(queue.Pending));
families.Add(MetricFamily.Counter("openwaf_alert_push_delivered_total",
"Deliveries the endpoint accepted, counted as rows rather than as an "
+ "in-process counter, so the answer survives a restart.")
.With(queue.Delivered));
families.Add(MetricFamily.Counter("openwaf_alert_push_given_up_total",
"Deliveries that ran out of attempts. This is the number that says "
+ "'nobody was told', as distinct from 'we are still asking'.")
.With(queue.GivenUp));
if (queue.Pending > 0 && queue.OldestPendingAt is { } oldest)
{
families.Add(MetricFamily.Gauge("openwaf_alert_push_oldest_pending_age_seconds",
"How long the longest-owed delivery has been waiting. A webhook that "
+ "is down looks idle until this number moves.")
.With(Math.Round((now - oldest).TotalSeconds, 1)));
}
// 6. How current what this edge enforces actually is.
families.Add(MetricFamily.Gauge("openwaf_snapshot_age_seconds",
"How old the guard's snapshot is right now. Behind a load balancer this is the "
+10 -1
View File
@@ -87,10 +87,19 @@ if (string.IsNullOrWhiteSpace(alertWebhookUrl))
alertWebhookUrl = Environment.GetEnvironmentVariable("OPENWAF_ALERT_WEBHOOK_URL");
var alertWebhookTimeout = AlertNotifier.ParseTimeoutSeconds(
builder.Configuration["OpenWaf:Alerts:WebhookTimeoutSeconds"]);
// How hard to try, and how long to wait between tries (OPEN-60). Validated here
// rather than defaulted: MaxPushAttempts=0 means "never tell anybody" and a
// 0-second retry against a dead endpoint is a busy loop, and neither is what the
// operator meant when they wrote the number.
var alertPushAttempts = PushRetryPolicy.ParseMaxAttempts(
builder.Configuration["OpenWaf:Alerts:MaxPushAttempts"]);
var alertPushRetrySeconds = PushRetryPolicy.ParseRetrySeconds(
builder.Configuration["OpenWaf:Alerts:PushRetrySeconds"]);
builder.Services.AddSingleton<AlertNotifier>(sp => new AlertNotifier(
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<DurabilityHealth>(),
sp.GetRequiredService<ILogger<AlertNotifier>>(),
alertWebhookUrl, alertWebhookTimeout));
alertWebhookUrl, alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds));
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
@@ -1,5 +1,7 @@
using System.Threading.Channels;
using System.Net.Http.Json;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
@@ -7,38 +9,63 @@ 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).
/// Tells somebody about the alerts the edge raised (OPEN-53), and keeps trying
/// until it can (OPEN-60).
///
/// 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.
/// The first version of the push fixed that and introduced a quieter hole: the
/// queue of "not pushed yet" was a channel in one process, so a delivery got
/// three attempts inside one attempt, and then it was gone for good. An endpoint
/// down for ten minutes swallowed every alert raised in that window, and a
/// restart swallowed everything still waiting. Measured here rather than assumed:
/// with the endpoint refusing, the alert row was there, the counter said the push
/// failed, and nothing ever asked again.
///
/// So the queue is a table now. Three properties follow from that and each is a
/// decision:
///
/// * <b>Eventually, across a restart.</b> A row that is still owed is picked up
/// by the next process that starts, which is the difference between "the
/// endpoint was down during the outage" and "the operator was never told".
/// * <b>Bounded, and honest about the bound.</b> Attempts are configuration,
/// validated at startup; when they run out the row records that, and the
/// surface says how many were given up. A counter that cannot tell "still
/// retrying" from "stopped retrying" is the blindness this item removes.
/// * <b>Claimed before it is sent.</b> Two edges sharing one database would
/// otherwise push the same alert twice, and a duplicate page at 03:00 is not a
/// harmless bug. A claim left by a process that died is taken over after a
/// bounded window, so a crash delays a delivery rather than losing it.
///
/// The database row of the alert stays the record of truth: a refused push does
/// not undo an alert, and the request path never waits on the webhook.
/// </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
/// <summary>How long one HTTP attempt may take. Out of range refuses startup
/// rather than falling back: a 0-second timeout drops every push, and a
/// 600-second one parks the worker on a dead endpoint — the same reasoning as
/// <c>OpenWaf:State:RefreshTtlSeconds</c>.</summary>
public const int TimeoutSecondsFloor = 1, TimeoutSecondsCeiling = 60;
/// <summary>How often the worker looks for owed deliveries. Not on any
/// request path, and a fresh enqueue wakes it immediately, so this is only
/// the ceiling on how long a delivery waits when nothing else is happening.</summary>
private const int PollSeconds = 2;
private const int BatchSize = 20;
/// <summary>How often the cached queue counts are refreshed. <c>/metrics</c>
/// reads the cache rather than issuing a query per scrape — the metrics
/// endpoint's rule is that it never leans on the database — so the gauge is
/// labelled with that bound. <c>/admin-api/state</c> reads the table, because
/// an operator asking directly should get the current answer.</summary>
private static readonly TimeSpan CountsRefresh = TimeSpan.FromSeconds(5);
public static int ParseTimeoutSeconds(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return 5;
@@ -50,62 +77,97 @@ public sealed class AlertNotifier : BackgroundService
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 IServiceScopeFactory _scopeFactory;
private readonly DurabilityHealth _health;
private readonly ILogger<AlertNotifier> _log;
private readonly string? _url;
private readonly HttpClient _http;
private readonly int _maxAttempts;
private readonly int _retryBaseSeconds;
/// <summary>Identifies this process in a claim. Machine plus pid plus a
/// random suffix, because two edges on one host share a pid namespace in a
/// container and a stale claim has to name who left it.</summary>
private readonly string _processId =
$"{Environment.MachineName}-{Environment.ProcessId}-{Guid.NewGuid().ToString("N")[..8]}";
private readonly Channel<byte> _wake = Channel.CreateBounded<byte>(
new BoundedChannelOptions(16) { FullMode = BoundedChannelFullMode.DropWrite, SingleReader = true });
private volatile PushQueueCounts _counts = new(0, 0, 0, null, null);
private DateTimeOffset _countsAt = DateTimeOffset.MinValue;
/// <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)
/// <summary>The queue as this process last measured it. Cached on purpose:
/// <c>/metrics</c> and <c>/admin-api/state</c> read it without touching the
/// database, so a scrape cannot become a query per poll.</summary>
public PushQueueCounts Counts => _counts;
public AlertNotifier(
IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertNotifier> log,
string? webhookUrl, int timeoutSeconds, int maxPushAttempts, int retryBaseSeconds)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
_url = string.IsNullOrWhiteSpace(webhookUrl) ? null : webhookUrl.Trim();
WebhookHost = _url is null ? null : new Uri(_url).Host;
_maxAttempts = maxPushAttempts;
_retryBaseSeconds = retryBaseSeconds;
_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)
/// <summary>Queue one delivery, durably. Returns false when the queue itself
/// could not be written, which is a lost delivery and is counted as one —
/// the alert row still exists, so what is lost is the telling.</summary>
public async Task<bool> EnqueueAsync(EdgeAlert alert, CancellationToken ct = default)
{
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);
if (_url is null) return false;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.AlertPushes.Add(new AlertPush
{
AlertId = alert.Id,
Kind = alert.Kind,
SourceKey = alert.SourceKey,
Count = alert.Count,
LastStatusCode = alert.LastStatusCode,
LastPath = alert.LastPath,
Detail = alert.Detail,
AlertCreatedAt = alert.CreatedAt,
CreatedAt = DateTimeOffset.UtcNow,
NextAttemptAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync(ct);
_wake.Writer.TryWrite(0);
return true;
}
catch (Exception ex)
{
_health.RecordFailure(Pillar, $"the delivery could not be queued: {ex.Message}", 1);
_log.LogWarning(ex, "AlertNotifier: could not queue a {Kind} delivery for {Key}.", alert.Kind, alert.SourceKey);
return false;
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_url is null) return;
await foreach (var alert in _queue.Reader.ReadAllAsync(stoppingToken))
// Nothing is replayed from memory on purpose: whatever this process was
// holding is in the table, and whatever a previous process left is picked
// up here. That is the whole of "eventually".
while (!stoppingToken.IsCancellationRequested)
{
try
{
await PushAsync(alert, stoppingToken);
await DrainAsync(stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
@@ -113,58 +175,181 @@ public sealed class AlertNotifier : BackgroundService
}
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.
// The queue itself is unreachable. Counted, because a worker that
// cannot read its own queue is the same blindness as an endpoint
// that is down, and quieter.
_health.RecordFailure(Pillar, ex);
_log.LogWarning(ex, "AlertNotifier: could not push a {Kind} alert to {Host}.", alert.Kind, WebhookHost);
_log.LogWarning(ex, "AlertNotifier: the delivery queue could not be read.");
}
using var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
wait.CancelAfter(TimeSpan.FromSeconds(PollSeconds));
try { _ = await _wake.Reader.ReadAsync(wait.Token); }
catch (OperationCanceledException) { }
}
}
private async Task PushAsync(EdgeAlert alert, CancellationToken ct)
/// <summary>One pass over the owed deliveries: claim a batch atomically, then
/// send each one.</summary>
private async Task DrainAsync(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++)
var now = DateTimeOffset.UtcNow;
var staleClaim = now - PushRetryPolicy.ClaimReclaimWindow;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var due = await db.AlertPushes
.Where(p => p.PushedAt == null && p.GivenUpAt == null
&& (p.NextAttemptAt == null || p.NextAttemptAt <= now)
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.OrderBy(p => p.Id)
.Select(p => p.Id)
.Take(BatchSize)
.ToListAsync(ct);
if (due.Count > 0)
{
try
// The guard is in the UPDATE, not in the code around it: two edges
// reading the same due list at the same moment must end up with the
// row claimed by exactly one of them, and the loser simply finds
// nothing of its own to send.
await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.PushedAt == null && p.GivenUpAt == null
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.ClaimedBy, _processId)
.SetProperty(p => p.ClaimedAt, now), ct);
var rows = await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.ClaimedBy == _processId)
.OrderBy(p => p.Id)
.ToListAsync(ct);
// Saved per row rather than once per batch: a process killed between
// two deliveries must not lose the record of the one it already made,
// because that record is what decides whether the next process retries
// it or gives up on it.
foreach (var row in rows)
{
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);
await DeliverAsync(db, row, now, ct);
await db.SaveChangesAsync(ct);
}
}
await RefreshCountsAsync(db, now, ct);
}
private async Task DeliverAsync(OpenWafDbContext db, AlertPush row, DateTimeOffset now, CancellationToken ct)
{
var (ok, error) = await TryPushAsync(row, ct);
row.Attempts++;
row.ClaimedBy = null;
row.ClaimedAt = null;
row.LastError = error;
if (ok)
{
row.PushedAt = now;
row.NextAttemptAt = null;
_health.RecordSuccess(Pillar, 1);
return;
}
if (PushRetryPolicy.HasGivenUp(row.Attempts, _maxAttempts))
{
// The one case where a delivery is gone for good, so it is the one
// case counted as lost. The alert row is still there; what is lost is
// that nobody was told, and the surface has to be able to say so.
row.GivenUpAt = now;
row.NextAttemptAt = null;
// The row says why it stopped, not only what the last attempt said,
// because the row is what an operator reads an hour later.
row.LastError = $"gave up after {row.Attempts} attempts: {error}";
_health.RecordFailure(Pillar, $"gave up after {row.Attempts} attempts: {error}", 1);
_log.LogWarning(
"AlertNotifier: gave up pushing a {Kind} alert to {Host} after {Attempts} attempts ({Error}).",
row.Kind, WebhookHost, row.Attempts, error);
return;
}
row.NextAttemptAt = now + PushRetryPolicy.NextDelay(row.Attempts, _retryBaseSeconds);
_health.RecordFailure(Pillar, error ?? "the push failed");
_log.LogDebug("AlertNotifier: attempt {Attempt} for a {Kind} alert failed ({Error}); next try at {Next}.",
row.Attempts, row.Kind, error, row.NextAttemptAt);
}
/// <summary>One HTTP attempt. The retry policy lives in the queue now, so the
/// old three-tries-in-a-row loop is gone: a durable backoff and an in-line
/// backoff are the same decision made twice, and the one that survives a
/// restart is the one worth keeping.</summary>
private async Task<(bool Ok, string? Error)> TryPushAsync(AlertPush row, CancellationToken ct)
{
try
{
using var response = await _http.PostAsJsonAsync(_url!, new
{
kind = row.Kind,
sourceKey = row.SourceKey,
count = row.Count,
lastStatusCode = row.LastStatusCode,
lastPath = row.LastPath,
createdAt = row.AlertCreatedAt,
detail = row.Detail,
attempts = row.Attempts + 1
}, ct);
if (response.IsSuccessStatusCode) return (true, null);
// Named with the status, because "the push failed" is not actionable
// and "the endpoint answered 404" is.
return (false, $"the endpoint answered {(int)response.StatusCode}");
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
private async Task RefreshCountsAsync(OpenWafDbContext db, DateTimeOffset now, CancellationToken ct)
{
if (now - _countsAt < CountsRefresh) return;
_counts = await PushQueueCounts.QueryAsync(db, ct);
_countsAt = now;
}
/// <summary>For the surfaces and the tests: the queue as the database holds
/// it, not as this process last cached it.</summary>
public async Task<PushQueueCounts> ReadCountsAsync(CancellationToken ct = default)
{
if (_url is null) return new PushQueueCounts(0, 0, 0, null, null);
using var scope = _scopeFactory.CreateScope();
return await PushQueueCounts.QueryAsync(scope.ServiceProvider.GetRequiredService<OpenWafDbContext>(), ct);
}
/// <summary>Force one pass, for tests and for an operator who wants the queue
/// drained now rather than on the next poll.</summary>
public Task PumpAsync(CancellationToken ct = default) => DrainAsync(ct);
}
/// <summary>The push queue in four numbers and one error. Every one of them is a
/// count of rows rather than an in-process counter, so the answer survives a
/// restart and agrees between edges sharing the database.</summary>
public sealed record PushQueueCounts(
int Pending, int Delivered, int GivenUp, string? LastError, DateTimeOffset? OldestPendingAt)
{
public static async Task<PushQueueCounts> QueryAsync(OpenWafDbContext db, CancellationToken ct)
{
var pending = db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null);
return new PushQueueCounts(
await pending.CountAsync(ct),
await db.AlertPushes.CountAsync(p => p.PushedAt != null, ct),
await db.AlertPushes.CountAsync(p => p.GivenUpAt != null, ct),
await db.AlertPushes.Where(p => p.LastError != null)
.OrderByDescending(p => p.Attempts).Select(p => p.LastError).FirstOrDefaultAsync(ct),
await pending.OrderBy(p => p.CreatedAt).Select(p => p.CreatedAt).FirstOrDefaultAsync(ct));
}
}
@@ -76,7 +76,10 @@ public sealed class AlertWriter
// 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);
// Queuing is awaited now because the queue is a row: a delivery that
// was never written down is a delivery that will not happen, and the
// caller has to know that rather than assume it (OPEN-60).
await _notifier.EnqueueAsync(alert, ct);
}
catch (Exception ex)
{
@@ -0,0 +1,435 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using OpenWaf.Infrastructure.Persistence;
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.Migrations
{
[DbContext(typeof(OpenWafDbContext))]
[Migration("20261004234529_AddAlertPushQueue")]
partial class AddAlertPushQueue
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("OpenWaf.Domain.Policy.CountryRule", b =>
{
b.Property<string>("Code")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<bool>("IsAllowed")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Code");
b.ToTable("country_rules", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.AlertPush", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AlertCreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("AlertId")
.HasColumnType("bigint");
b.Property<int>("Attempts")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ClaimedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ClaimedBy")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<DateTimeOffset?>("GivenUpAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("LastError")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("LastPath")
.HasColumnType("text");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("NextAttemptAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("PushedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("SourceKey")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.HasKey("Id");
b.HasIndex("AlertId");
b.HasIndex("PushedAt", "GivenUpAt", "NextAttemptAt");
b.ToTable("alert_pushes", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.AllowEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Match")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Note")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.HasKey("Id");
b.HasIndex("Match")
.IsUnique();
b.ToTable("allow_entries", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.BlockEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int?>("ConsecutiveRefusals")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("LastCity")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("LastCountryCode")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<string>("LastPath")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("LastRegion")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<string>("LastUserAgent")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("Reason")
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<string>("RedirectTo")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<int>("Source")
.HasColumnType("integer");
b.Property<string>("SourceKey")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
b.HasIndex("SourceKey", "Source")
.IsUnique();
b.ToTable("block_entries", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.EdgeAlert", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("LastPath")
.HasColumnType("text");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<string>("SourceKey")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.ToTable("edge_alerts", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("Action")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Note")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("ExpiresAt");
b.HasIndex("Pattern");
b.ToTable("request_rules", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.SourceObservation", b =>
{
b.Property<string>("SourceKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<DateTimeOffset>("FirstSeenAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("LastCity")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("LastCountryCode")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<string>("LastPath")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("LastRegion")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<string>("LastUserAgent")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int>("MaxConsecutiveRefusals")
.HasColumnType("integer");
b.Property<int>("TotalRefusals")
.HasColumnType("integer");
b.Property<int>("TotalServerErrorStreak")
.HasColumnType("integer");
b.HasKey("SourceKey");
b.HasIndex("LastSeenAt");
b.ToTable("source_observations", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.SourceStreak", b =>
{
b.Property<string>("SourceKey")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<int>("ConsecutiveRefusals")
.HasColumnType("integer");
b.Property<int>("ConsecutiveServerErrors")
.HasColumnType("integer");
b.Property<int>("LastAlertedRefusals")
.HasColumnType("integer");
b.Property<int>("LastAlertedServerErrors")
.HasColumnType("integer");
b.Property<string>("LastCity")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("LastCountryCode")
.HasMaxLength(2)
.HasColumnType("character varying(2)");
b.Property<string>("LastPath")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<DateTimeOffset?>("LastRefusalAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("LastRegion")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<DateTimeOffset>("LastSeenAt")
.HasColumnType("timestamp with time zone");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<string>("LastUserAgent")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<int>("MaxConsecutiveRefusals")
.HasColumnType("integer");
b.Property<int>("MaxConsecutiveServerErrors")
.HasColumnType("integer");
b.Property<int>("TotalRefusals")
.HasColumnType("integer");
b.Property<int>("Version")
.IsConcurrencyToken()
.HasColumnType("integer");
b.HasKey("SourceKey");
b.HasIndex("LastSeenAt");
b.ToTable("source_streaks", (string)null);
});
modelBuilder.Entity("OpenWaf.Infrastructure.Persistence.PolicySetting", b =>
{
b.Property<string>("Key")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Key");
b.ToTable("policy_settings", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,61 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddAlertPushQueue : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "alert_pushes",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
AlertId = table.Column<long>(type: "bigint", nullable: false),
Kind = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
SourceKey = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
LastStatusCode = table.Column<int>(type: "integer", nullable: true),
LastPath = table.Column<string>(type: "text", nullable: true),
Detail = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
AlertCreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Attempts = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
NextAttemptAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LastError = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true),
PushedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
GivenUpAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
ClaimedBy = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
ClaimedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_alert_pushes", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_alert_pushes_AlertId",
table: "alert_pushes",
column: "AlertId");
migrationBuilder.CreateIndex(
name: "IX_alert_pushes_PushedAt_GivenUpAt_NextAttemptAt",
table: "alert_pushes",
columns: new[] { "PushedAt", "GivenUpAt", "NextAttemptAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "alert_pushes");
}
}
}
@@ -43,6 +43,79 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations
b.ToTable("country_rules", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.AlertPush", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("AlertCreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("AlertId")
.HasColumnType("bigint");
b.Property<int>("Attempts")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("ClaimedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ClaimedBy")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("character varying(1024)");
b.Property<DateTimeOffset?>("GivenUpAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("LastError")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("LastPath")
.HasColumnType("text");
b.Property<int?>("LastStatusCode")
.HasColumnType("integer");
b.Property<DateTimeOffset?>("NextAttemptAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("PushedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("SourceKey")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.HasKey("Id");
b.HasIndex("AlertId");
b.HasIndex("PushedAt", "GivenUpAt", "NextAttemptAt");
b.ToTable("alert_pushes", (string)null);
});
modelBuilder.Entity("OpenWaf.Domain.Security.AllowEntry", b =>
{
b.Property<long>("Id")
@@ -20,6 +20,7 @@ public sealed class OpenWafDbContext(DbContextOptions<OpenWafDbContext> options)
public DbSet<PolicySetting> PolicySettings => Set<PolicySetting>();
public DbSet<SourceStreak> Streaks => Set<SourceStreak>();
public DbSet<RequestRule> RequestRules => Set<RequestRule>();
public DbSet<AlertPush> AlertPushes => Set<AlertPush>();
protected override void OnModelCreating(ModelBuilder mb)
{
@@ -117,6 +118,23 @@ public sealed class OpenWafDbContext(DbContextOptions<OpenWafDbContext> options)
e.Property(r => r.Action).HasConversion<int>();
});
mb.Entity<AlertPush>(e =>
{
e.ToTable("alert_pushes");
e.HasKey(a => a.Id);
// The worker's query is "not delivered, not given up, due now, not
// claimed", and it runs every couple of seconds against a table that
// retention keeps short. Without this index that query is a scan of
// every delivery this edge has ever owed.
e.HasIndex(a => new { a.PushedAt, a.GivenUpAt, a.NextAttemptAt });
e.HasIndex(a => a.AlertId);
e.Property(a => a.Kind).HasMaxLength(64).IsRequired();
e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired();
e.Property(a => a.Detail).HasMaxLength(1024).IsRequired();
e.Property(a => a.LastError).HasMaxLength(512);
e.Property(a => a.ClaimedBy).HasMaxLength(128);
});
mb.Entity<PolicySetting>(e =>
{
e.ToTable("policy_settings");
@@ -0,0 +1,68 @@
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// When the next attempt at a delivery is allowed, and when to stop (OPEN-60).
///
/// Pure, because the two failure modes of a retry loop are both arithmetic: a
/// loop that never stops turns an outage at the receiver into load here, and a
/// loop that stops after one try is the at-most-once behaviour this item exists
/// to remove. Neither needs a running edge to check.
///
/// The bound is deliberate. An endpoint that has refused for an hour is broken,
/// and the honest answer at that point is to say so on the surface rather than to
/// keep asking — which is why giving up is a recorded state and not a dropped row.
/// </summary>
public static class PushRetryPolicy
{
public const int MaxAttemptsFloor = 1, MaxAttemptsCeiling = 20;
public const int RetrySecondsFloor = 1, RetrySecondsCeiling = 3600;
/// <summary>The cap on a single backoff step. Exponential growth from a
/// 30-second base reaches a day in eight steps, and a day is not a retry
/// interval for a page that was supposed to fire at 03:00.</summary>
public static readonly TimeSpan MaxDelay = TimeSpan.FromMinutes(30);
/// <summary>How long a claim may be held before another process may take the
/// row over. Longer than one push timeout times the attempts inside one push,
/// shorter than the retry interval, so a crashed process delays a delivery
/// rather than losing it.</summary>
public static readonly TimeSpan ClaimReclaimWindow = TimeSpan.FromMinutes(5);
public static int ParseMaxAttempts(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return 6;
if (!int.TryParse(configured, out var attempts)
|| attempts < MaxAttemptsFloor || attempts > MaxAttemptsCeiling)
throw new InvalidOperationException(
$"OpenWaf:Alerts:MaxPushAttempts must be a whole number of attempts between "
+ $"{MaxAttemptsFloor} and {MaxAttemptsCeiling}; got {configured}");
return attempts;
}
public static int ParseRetrySeconds(string? configured)
{
if (string.IsNullOrWhiteSpace(configured)) return 30;
if (!int.TryParse(configured, out var seconds)
|| seconds < RetrySecondsFloor || seconds > RetrySecondsCeiling)
throw new InvalidOperationException(
$"OpenWaf:Alerts:PushRetrySeconds must be a whole number of seconds between "
+ $"{RetrySecondsFloor} and {RetrySecondsCeiling}; got {configured}");
return seconds;
}
/// <summary>The delay before attempt number <c>attempts + 1</c>, given that
/// <c>attempts</c> have already failed. Exponential from the base, capped, and
/// never zero — a zero delay against a dead endpoint is a busy loop.</summary>
public static TimeSpan NextDelay(int attempts, int baseSeconds)
{
if (attempts <= 0) return TimeSpan.Zero;
var exponent = Math.Min(attempts, 16);
var seconds = (double)baseSeconds * Math.Pow(2, exponent - 1);
return TimeSpan.FromSeconds(Math.Min(seconds, MaxDelay.TotalSeconds));
}
/// <summary>Has this delivery run out of attempts? Compared against the
/// configured bound rather than a constant, because the bound is
/// configuration and a test has to be able to ask for a small one.</summary>
public static bool HasGivenUp(int attempts, int maxAttempts) => attempts >= maxAttempts;
}
@@ -54,6 +54,17 @@ public sealed class RetentionWorker : BackgroundService
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct);
// The push queue keeps its rows after they resolve, so "how many were
// delivered" and "what did we give up on" are counts of rows rather
// than counters that reset on restart. That only holds while the table
// stays short, so resolved rows age out on the same window as the
// alerts they came from. Still-pending rows are never pruned: a
// delivery that is owed outlives the alert row it was copied from
// (OPEN-60), which is exactly why the payload is copied.
await db.AlertPushes
.Where(p => (p.PushedAt != null || p.GivenUpAt != null) && p.CreatedAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
// The shared streak map (OPEN-52) is the one table this edge writes
// on the request path, so it is also the one that could grow without
// bound if nothing swept it. Same window as observations: a source
@@ -0,0 +1,288 @@
using System.Net;
using System.Net.Http.Json;
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 delivery, not the alert (OPEN-60).
///
/// The alert table already had these tests. What is under test here is the
/// separate promise the webhook added — that somebody is told — and the way that
/// promise used to fail quietly: the queue of "not pushed yet" lived in one
/// process's memory, so an endpoint down for ten minutes swallowed every alert
/// raised in that window, and a restart swallowed everything still waiting. The
/// alert row was correct the whole time, which is what made it invisible.
///
/// So every test here asks the same question in a different way: an alert was
/// raised, the endpoint could not take it, and does the operator still hear about
/// it later?
/// </summary>
public sealed class AlertPushQueueTests
{
private const string Failing = "203.0.113.81";
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();
}
private static async Task<JsonElement> WaitForStateAsync(EdgeFixture f, Func<JsonElement, bool> ready)
{
var deadline = DateTime.UtcNow.AddSeconds(25);
while (true)
{
var state = await StateAsync(f);
if (ready(state) || DateTime.UtcNow > deadline) return state;
await Task.Delay(150);
}
}
/// <summary>
/// The queue has emptied and at least one delivery landed. Waiting on
/// "delivered >= 1" alone reads the queue between two rows: one scene can
/// raise more than one alert, and the second row is still owed the moment the
/// first lands — which is how this suite first failed, on a correct product.
/// </summary>
private static bool Settled(JsonElement s) =>
s.GetProperty("alertPushPending").GetInt32() == 0
&& s.GetProperty("alertPushDelivered").GetInt32() >= 1;
private static int PushesTo(FakeUpstream upstream, string marker)
{
lock (upstream.Bodies) return upstream.Bodies.Count(b => b.Contains(marker));
}
/// <summary>Six 502s from one source: the 5xx streak alert fires.</summary>
private static async Task BreakTheUpstreamAsync(EdgeFixture f)
{
for (var i = 0; i < 6; i++)
{
using var probe = new HttpRequestMessage(HttpMethod.Get, "/checkout");
probe.Headers.TryAddWithoutValidation("X-Forwarded-For", Failing);
using var r = await f.Client.SendAsync(probe);
}
}
[Fact]
public async Task An_endpoint_that_refused_is_asked_again_once_it_heals()
{
await using var f = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
// Wait for an attempt to have happened, not merely for a row to exist: a
// row that has not been tried yet has no error to name, and an assertion
// written against it passes for the wrong reason.
var failing = await WaitForStateAsync(f,
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
Assert.True(failing.GetProperty("alertWebhookFailures").GetInt32() >= 1, failing.ToString());
Assert.Equal(0, failing.GetProperty("alertPushDelivered").GetInt32());
Assert.Equal(0, failing.GetProperty("alertPushGivenUp").GetInt32());
// The queue says what it is waiting on, in words an operator can act on.
Assert.Contains("500", failing.GetProperty("alertPushLastError").GetString());
// The endpoint heals. Nothing new happens at the edge — no new alert, no
// operator action — and the delivery still goes out.
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status200OK
: StatusCodes.Status502BadGateway;
var healed = await WaitForStateAsync(f, Settled);
Assert.True(PushesTo(f.Upstream, "server_error_streak") >= 1, "the healed endpoint never got the alert");
Assert.Equal(0, healed.GetProperty("alertPushPending").GetInt32());
}
[Fact]
public async Task A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one()
{
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
// First process: the endpoint refuses, so the delivery is owed and stays
// owed after this process is gone.
string? owed = null;
await using (var first = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
maxPushAttempts: 20, pushRetrySeconds: 1))
{
first.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(first);
var state = await WaitForStateAsync(first,
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
Assert.True(state.GetProperty("alertPushPending").GetInt32() >= 1, state.ToString());
owed = state.GetProperty("alertPushOldestPendingAt").GetString();
}
Assert.NotNull(owed);
// Second process, same database, working endpoint. It raised nothing and
// nobody asked it to remember anything: the queue is rows, so the promise
// outlives the process that made it.
await using var second = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
second.Upstream.StatusFor = _ => StatusCodes.Status200OK;
var state2 = await WaitForStateAsync(second, Settled);
Assert.Equal(0, state2.GetProperty("alertPushPending").GetInt32());
var pushed = PushesTo(second.Upstream, "server_error_streak");
Assert.True(pushed >= 1, "the new process never delivered what the old one owed");
// The payload came with the row, not out of the old process's memory.
lock (second.Upstream.Bodies)
Assert.Contains(second.Upstream.Bodies, b => b.Contains(Failing));
}
[Fact]
public async Task Attempts_run_out_and_the_surface_says_who_was_never_told()
{
await using var f = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 2, pushRetrySeconds: 1);
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
var state = await WaitForStateAsync(f, s => s.GetProperty("alertPushGivenUp").GetInt32() >= 1);
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
Assert.True(state.GetProperty("alertPushGivenUp").GetInt32() >= 1, state.ToString());
// The distinction this item exists for: a failing counter alone cannot
// tell "still asking" from "stopped asking".
Assert.Contains("gave up after 2 attempts", state.GetProperty("alertPushLastError").GetString());
// And giving up on the delivery does not undo the alert.
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());
}
[Fact]
public async Task A_delivery_owed_outlives_the_alert_row_it_was_copied_from()
{
await using var f = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
await WaitForStateAsync(f,
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
// Retention prunes edge_alerts on the ban-retention window. A delivery
// still owed must not go with them, which is why the payload is copied
// onto the queue row rather than read back from the alert.
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
Assert.True(await db.Alerts.ExecuteDeleteAsync() >= 1);
}
f.Upstream.StatusFor = _ => StatusCodes.Status200OK;
var state = await WaitForStateAsync(f, Settled);
Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32());
lock (f.Upstream.Bodies)
Assert.Contains(f.Upstream.Bodies, b => b.Contains("server_error_streak") && b.Contains(Failing));
}
[Fact]
public async Task Two_edges_on_one_database_do_not_tell_the_same_person_twice()
{
var dbPath = Path.Combine(Path.GetTempPath(), $"openwaf-test-{Guid.NewGuid():N}.db");
await using (var first = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath,
maxPushAttempts: 20, pushRetrySeconds: 1))
{
first.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(first);
await WaitForStateAsync(first,
s => s.GetProperty("alertPushPending").GetInt32() >= 1 && s.GetProperty("alertPushLastError").ValueKind != JsonValueKind.Null);
}
// Two processes, one database, one owed delivery each, two working
// endpoints. A duplicate page at 03:00 is not a harmless bug, so the row
// is claimed before it is sent and exactly one process sends it.
await using var a = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
await using var b = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1);
a.Upstream.StatusFor = _ => StatusCodes.Status200OK;
b.Upstream.StatusFor = _ => StatusCodes.Status200OK;
// Wait on the queue, not on the bodies: a body arrives a moment before the
// row that produced it is marked delivered, and an assertion written
// against the wire would read the database mid-write.
PushQueueCounts queueA = new(0, 0, 0, null, null), queueB = new(0, 0, 0, null, null);
var deadline = DateTime.UtcNow.AddSeconds(25);
while (DateTime.UtcNow < deadline)
{
queueA = await a.Service<AlertNotifier>().ReadCountsAsync();
queueB = await b.Service<AlertNotifier>().ReadCountsAsync();
if (queueA.Pending == 0 && queueA.Delivered >= 1) break;
await Task.Delay(250);
}
Assert.Equal(0, queueA.Pending);
Assert.True(queueA.Delivered >= 1, $"nothing was delivered — A: {queueA}, B: {queueB}");
Assert.Equal(0, queueA.GivenUp);
// The count that proves the claim works: every owed row was sent, and no
// row was sent twice. Two processes polling the same table on the same
// interval is exactly where a duplicate would appear.
var total = PushesTo(a.Upstream, Failing) + PushesTo(b.Upstream, Failing);
Assert.Equal(queueA.Delivered, total);
}
[Fact]
public async Task The_queue_is_a_number_a_scraper_can_put_an_alert_rule_on()
{
await using var f = new EdgeFixture(
threshold: 3, alertWebhookPath: "/hook", maxPushAttempts: 20, pushRetrySeconds: 1);
f.Upstream.StatusFor = p => p == "/hook"
? StatusCodes.Status500InternalServerError
: StatusCodes.Status502BadGateway;
await BreakTheUpstreamAsync(f);
await WaitForStateAsync(f, s => s.GetProperty("alertPushPending").GetInt32() >= 1);
// The gauge is cached, so it is at most five seconds behind the rows and
// the test has to wait for the cache rather than assume it.
string body = "";
var scrapeDeadline = DateTime.UtcNow.AddSeconds(15);
while (DateTime.UtcNow < scrapeDeadline)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/metrics");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
body = await response.Content.ReadAsStringAsync();
if (System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_pending [1-9]")) break;
await Task.Delay(250);
}
// A count of rows, not of one alert: a storm can owe more than one
// delivery, so the assertion is that the gauge is non-zero and the other
// two are still zero.
Assert.Matches(@"openwaf_alert_push_pending [1-9]", body);
Assert.Contains("openwaf_alert_push_delivered_total 0", body);
Assert.Contains("openwaf_alert_push_given_up_total 0", body);
Assert.Contains("openwaf_alert_push_oldest_pending_age_seconds", body);
}
}
@@ -40,6 +40,8 @@ internal sealed class EdgeFixture : IAsyncDisposable
bool sharedStreaks = false,
string? alertWebhookPath = null,
int? alertWebhookTimeoutSeconds = null,
int? maxPushAttempts = null,
int? pushRetrySeconds = null,
string rate = "Off",
int rateLimitPerWindow = 100,
double rateWindowSeconds = 60,
@@ -85,6 +87,13 @@ internal sealed class EdgeFixture : IAsyncDisposable
Upstream.Address.TrimEnd('/') + alertWebhookPath);
if (alertWebhookTimeoutSeconds is { } wts)
builder.UseSetting("OpenWaf:Alerts:WebhookTimeoutSeconds", wts.ToString());
// How hard the delivery queue tries, and how long it waits between
// tries (OPEN-60). A test that asks about giving up has to be able to
// ask for a small bound rather than wait out an hour.
if (maxPushAttempts is { } mpa)
builder.UseSetting("OpenWaf:Alerts:MaxPushAttempts", mpa.ToString());
if (pushRetrySeconds is { } prs)
builder.UseSetting("OpenWaf:Alerts:PushRetrySeconds", prs.ToString());
// The volume pillar (OPEN-56). Off by default here exactly as in the
// shipped default, so every other test in this suite proves the
// counter costs nothing when the pillar is not asked for.
@@ -1,7 +1,10 @@
using System.Net;
using System.Net.Http.Json;
using System.Reflection;
using System.Text.Json;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Migrations;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
@@ -33,6 +36,18 @@ public sealed class SchemaUpgradeTests
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
}
/// <summary>
/// How many migrations the shipped assembly carries. The baseline test wants
/// this number to come from the same place the upgrader reads it, so adding a
/// migration never turns a working upgrade into a red test.
/// </summary>
private static int MigrationCount() =>
typeof(OpenWafDbContext).Assembly
.GetTypes()
.Count(t => !t.IsAbstract
&& typeof(Migration).IsAssignableFrom(t)
&& t.GetCustomAttribute<MigrationAttribute>() is not null);
/// <summary>
/// The host starts on first use, and the schema step runs when it starts — so
/// a test that wants a database on disk has to make a request before it can
@@ -234,10 +249,15 @@ public sealed class SchemaUpgradeTests
{
var state = await StateAsync(second);
Assert.Equal("migrate", state.GetProperty("schemaStrategy").GetString());
// Both migrations are demonstrably applied to a database that
// Every migration is demonstrably applied to a database that
// already has every table they describe, so nothing is left to
// run — and that is stated as a number, not assumed.
Assert.Equal(2, state.GetProperty("schemaMigrationsBaselined").GetInt32());
// run — and that is stated as a number, not assumed. The number
// is counted from the migrations assembly, not typed here: a
// literal would make the next migration fail this test with a
// passing product.
Assert.Equal(
MigrationCount(),
state.GetProperty("schemaMigrationsBaselined").GetInt32());
Assert.Equal(0, state.GetProperty("schemaMigrationsApplied").GetInt32());
Assert.Empty(state.GetProperty("schemaMissingTables").EnumerateArray());
}
@@ -1,3 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
@@ -58,36 +59,53 @@ public sealed class AlertWebhookBoundsTests
}
[Fact]
public void A_push_dropped_for_a_full_queue_is_counted_and_not_silently_lost()
public async Task A_delivery_that_could_not_be_queued_is_counted_as_lost_rather_than_assumed_sent()
{
// 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.
// The queue used to be a bounded channel in this process, and its
// overflow was the counted loss. The queue is a table now, so the
// equivalent failure is the write that never happened: the alert row is
// in the database, the operator can read it, and nobody was ever going to
// be told. Assuming the delivery in that moment is the silence this
// whole pillar exists to remove.
var health = new DurabilityHealth();
var notifier = new AlertNotifier(
new Microsoft.Extensions.DependencyInjection.ServiceCollection().BuildServiceProvider()
.GetRequiredService<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>(),
health,
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
"https://hooks.example.test/notify", 5);
var alert = new EdgeAlert
"https://hooks.example.test/notify", 5, 6, 30);
var queued = await notifier.EnqueueAsync(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);
});
Assert.False(queued);
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);
Assert.Equal(1, pillar.EntriesLost);
Assert.Contains("could not be queued", pillar.LastError);
}
[Fact]
public async Task An_unconfigured_endpoint_queues_nothing_and_reports_nothing()
{
// "No webhook" is a configuration, not a failure: no row is written, no
// counter moves, and the surface says the push is off rather than that it
// is failing.
var health = new DurabilityHealth();
var notifier = Build(null);
var queued = await notifier.EnqueueAsync(new EdgeAlert { Kind = "candidate_ban", SourceKey = "203.0.113.9" });
Assert.False(queued);
Assert.False(health.Get(AlertNotifier.Pillar).Failing);
}
private static AlertNotifier Build(string? url) => new(
new Microsoft.Extensions.DependencyInjection.ServiceCollection().BuildServiceProvider()
.GetRequiredService<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>(),
new DurabilityHealth(),
Microsoft.Extensions.Logging.Abstractions.NullLogger<AlertNotifier>.Instance,
url, 5);
url, 5, 6, 30);
}
@@ -0,0 +1,92 @@
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// The arithmetic of retrying (OPEN-60). Both ways a retry loop fails are
/// arithmetic — a loop that never stops, and a loop that stops too early — and
/// neither needs a running edge and a refusing endpoint to check.
/// </summary>
public sealed class PushRetryPolicyTests
{
[Theory]
[InlineData(null, 6)]
[InlineData("", 6)]
[InlineData("1", 1)]
[InlineData(" 9 ", 9)]
[InlineData("20", 20)]
public void Unset_means_six_and_a_whole_number_means_what_it_says(string? configured, int expected)
=> Assert.Equal(expected, PushRetryPolicy.ParseMaxAttempts(configured));
[Theory]
[InlineData("0")]
[InlineData("-1")]
[InlineData("21")]
[InlineData("abc")]
[InlineData("6.5")]
public void A_bound_that_could_not_mean_what_the_operator_wrote_refuses_startup(string configured)
{
var ex = Assert.Throws<InvalidOperationException>(() => PushRetryPolicy.ParseMaxAttempts(configured));
Assert.Contains("OpenWaf:Alerts:MaxPushAttempts", ex.Message);
Assert.Contains(configured, ex.Message);
}
[Theory]
[InlineData(null, 30)]
[InlineData("1", 1)]
[InlineData("3600", 3600)]
public void The_backoff_base_is_parsed_the_same_way(string? configured, int expected)
=> Assert.Equal(expected, PushRetryPolicy.ParseRetrySeconds(configured));
[Theory]
[InlineData("0")]
[InlineData("3601")]
[InlineData("-2")]
public void A_zero_backoff_against_a_dead_endpoint_is_a_busy_loop_and_is_refused(string configured)
{
var ex = Assert.Throws<InvalidOperationException>(() => PushRetryPolicy.ParseRetrySeconds(configured));
Assert.Contains("OpenWaf:Alerts:PushRetrySeconds", ex.Message);
}
[Fact]
public void Backoff_grows_and_stays_inside_its_cap()
{
Assert.Equal(TimeSpan.FromSeconds(30), PushRetryPolicy.NextDelay(1, 30));
Assert.Equal(TimeSpan.FromSeconds(60), PushRetryPolicy.NextDelay(2, 30));
Assert.Equal(TimeSpan.FromSeconds(120), PushRetryPolicy.NextDelay(3, 30));
Assert.Equal(TimeSpan.FromMinutes(4), PushRetryPolicy.NextDelay(4, 30));
Assert.Equal(TimeSpan.FromMinutes(8), PushRetryPolicy.NextDelay(5, 30));
// The cap is the point: exponential from a 30-second base reaches a day
// in eight steps, and a day is not a retry interval for a page that was
// meant to fire at 03:00.
Assert.Equal(TimeSpan.FromMinutes(30), PushRetryPolicy.NextDelay(9, 30));
Assert.Equal(TimeSpan.FromMinutes(30), PushRetryPolicy.NextDelay(40, 30));
}
[Fact]
public void No_attempts_means_no_delay_and_a_zero_base_never_produces_a_zero_delay()
{
Assert.Equal(TimeSpan.Zero, PushRetryPolicy.NextDelay(0, 30));
// One failed attempt always waits at least the base, so the worker cannot
// spin against an endpoint that is refusing.
Assert.True(PushRetryPolicy.NextDelay(1, 1) >= TimeSpan.FromSeconds(1));
}
[Fact]
public void Giving_up_is_a_bound_an_operator_can_set_and_a_state_the_surface_can_name()
{
Assert.False(PushRetryPolicy.HasGivenUp(5, 6));
Assert.True(PushRetryPolicy.HasGivenUp(6, 6));
Assert.True(PushRetryPolicy.HasGivenUp(7, 6));
// The bound is configuration, so a test — and an operator who wants the
// edge to stop asking sooner — can ask for a small one.
Assert.True(PushRetryPolicy.HasGivenUp(1, 1));
}
[Fact]
public void A_claim_is_reclaimable_sooner_than_a_retry_interval_so_a_crash_delays_rather_than_loses()
{
Assert.True(PushRetryPolicy.ClaimReclaimWindow < PushRetryPolicy.MaxDelay);
Assert.True(PushRetryPolicy.ClaimReclaimWindow > TimeSpan.FromSeconds(AlertNotifier.TimeoutSecondsCeiling));
}
}
+23 -1
View File
@@ -1332,6 +1332,10 @@ import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
c.execute("DROP TABLE request_rules")
c.execute("DROP TABLE source_streaks")
# OPEN-60 added a table. A volume written by the previous release is exactly the
# state an upgrading operator is in, so the queue table goes too: the edge has to
# put it back by itself, with no operator migration step.
c.execute("DROP TABLE alert_pushes")
print("dropped; tables now:", sorted(r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")))
PYSQL
docker compose restart edge >/dev/null 2>&1
@@ -1347,7 +1351,23 @@ OPEN55_STATE=$(admin "$EDGE/admin-api/state")
OPEN55_ADDED=$(printf '%s' "$OPEN55_STATE" | jval schemaTablesAdded)
printf ' info tables this start had to create: %s\n' "${OPEN55_ADDED:-none}"
check 'the state names the tables it had to add' 'yes' \
"$([ "${OPEN55_ADDED:-0}" -ge 2 ] && echo yes || echo no)"
"$([ "${OPEN55_ADDED:-0}" -ge 3 ] && echo yes || echo no)"
# The table the durable push queue (OPEN-60) lives in, added by the edge to a
# database that predates it. A restart is the only thing that ran between the
# drop and this read.
OPEN55_PUSH_TABLE=$(sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
print("yes" if c.execute(
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='alert_pushes'"
).fetchone()[0] else "no")
PYSQL
)
check 'the push queue table was added to a database that predates it' 'yes' "$OPEN55_PUSH_TABLE"
check 'and the state counts the queue it now keeps' '0 0 0' \
"$(printf '%s' "$OPEN55_STATE" | jval alertPushPending) \
$(printf '%s' "$OPEN55_STATE" | jval alertPushDelivered) \
$(printf '%s' "$OPEN55_STATE" | jval alertPushGivenUp)"
check 'and says nothing the build needs is missing now' '[]' \
"$(printf '%s' "$OPEN55_STATE" | jval schemaMissingTables)"
check 'the rules pillar is reading again' 'true' \
@@ -1386,6 +1406,8 @@ check 'the verdict counter counts the rule refusal this stack just made' 'yes' \
"$([ "$(msample 'openwaf_requests_total{verdict="block_rule"} ')" -gt 0 ] 2>/dev/null && echo yes || echo no)"
check 'the schema gauge says nothing the build needs is missing' '0' \
"$(msample 'openwaf_schema_missing_tables ')"
check 'the push queue is published as gauges on the shipped image' '0 0 0' \
"$(msample 'openwaf_alert_push_pending ') $(msample 'openwaf_alert_push_delivered_total ') $(msample 'openwaf_alert_push_given_up_total ')"
check 'the write counters are published even on a healthy stack' '0' \
"$(msample 'openwaf_write_failures_total{pillar="bans"} ')"
check 'the body names no address from the scene above' 'yes' \
+13
View File
@@ -145,6 +145,12 @@ check 'the verdict counter counts the ban this scene just made' yes \
"$([ "${BLOCK_ENGINE:-0}" -gt 0 ] 2>/dev/null && echo yes || echo no)"
check 'the live blocks gauge counts the engine ban' 1 \
"$(msample 'openwaf_blocks_live{source="engine"} ')"
# The push queue (OPEN-60) is a table, so its numbers are publishable the same
# way. No endpoint is configured in this scene, so the honest answer is three
# zeros — and a gauge that is missing is a different failure from a gauge that
# says 0, which is why msample's empty answer fails the check.
check 'the push queue is published as gauges as well' '0 0 0' \
"$(msample 'openwaf_alert_push_pending ') $(msample 'openwaf_alert_push_delivered_total ') $(msample 'openwaf_alert_push_given_up_total ')"
# The aggregate-only invariant, asserted over the whole body with the markers
# from the scene above actually in the database behind it.
check 'the body names no address, no path and no operator note' yes \
@@ -300,6 +306,13 @@ check 'the state says the snapshot is inside its ttl' False \
# 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"])')"
# What the push queue holds (OPEN-60): owed, delivered, given up. The keys are
# asserted before the values, because "0" from a surface that never writes the
# queue is indistinguishable from "0" from one that does.
check 'the state names the push queue it keeps' True \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("alertPushPending","alertPushDelivered","alertPushGivenUp","alertPushLastError","alertPushOldestPendingAt")))')"
check 'and with no endpoint configured it keeps nothing' '0 0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["alertPushPending"], d["alertPushDelivered"], d["alertPushGivenUp"])')"
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' \