An operator running several edges types every rule several times: blocks, allowlist, request rules, country rules and the policy overrides have their own endpoints one row at a time, and nothing moved them as a set. A new deployment starts empty, and a change that turns out wrong has nothing to be restored from. This is the multi-instance finding one level up from the shared streak store: SharedStreaks shares the counters, nothing shared the decisions.
GET /admin-api/export answers one document — version, exportedAt, edgeId, per-section counts, the policy section, and blocks / allowlist / rules / country rules. Only live rows; rules keep their evaluation order; and the document names how many engine bans it left behind, because "0 blocks" and "0 operator blocks, 7 engine bans left behind" are different sentences. A ban the engine earned is a claim about this edge's own traffic, so enforcing it where that traffic was never seen is a decision nobody made.
POST /admin-api/import is additive and idempotent: it never deletes a row the document does not mention — a transfer that silently clears a fleet's exemptions is worse than one that duplicates a block — a live row for the same source is reported as already there rather than rewritten, and expiry travels as an instant, so a block that expires in ten minutes where it came from expires in ten minutes here. Per-section counts (added / alreadyThere / skippedExpired / rejected) and a rejected[] list named by section and index; an unknown version, an oversize body or a malformed document writes nothing at all; a storage failure answers 503 with the report, because "it failed" and "it added 41 of 60" must not collapse into one sentence.
What the run caught, in order: (1) a unit assert used "203.0.113" as the invalid address and passed for the wrong reason — IPAddress.TryParse accepts it as 203.0.113.0, so the assert now names 203.0.113.999. (2) Two smoke asserts were wrong rather than the product: a helper printed a Python boolean where the gate compares text, and a blocks delete was asserted as 204 when the endpoint answers 200 with {"deleted":n}. (3) The metrics-as-a-number test could pass its wait on a cache refreshed between an enqueue and its first attempt — pending > 0 was true a moment before attempts > 0 could be — so the wait now requires both numbers. (4) A real defect, not a test one: the alert notifier left the rows it had claimed claimed when the process stopped, so the next process waited out the five-minute reclaim window to deliver an alert that was already owed. It now releases what it holds on the way out, and the reclaim window is back to being what it is for — a process that was killed and cannot say anything.
Gates on this tree: build 0 warnings / 0 errors, unit 285/285, integration 257/257 in 23s, smoke 82 passed / 0 failed (14 new), image 262 MB, compose-smoke 243 passed / 0 failed with 0 containers left behind (11 new, against the shipped image).
Refs OPEN-61.
400 lines
19 KiB
C#
400 lines
19 KiB
C#
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;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
///
|
|
/// 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 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;
|
|
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;
|
|
}
|
|
|
|
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, 0);
|
|
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;
|
|
|
|
/// <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>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 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;
|
|
|
|
// 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".
|
|
try
|
|
{
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
await DrainAsync(stoppingToken);
|
|
}
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 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: 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) { }
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
// A row this process claimed but never finished must not sit behind its
|
|
// own claim until the reclaim window expires. The window exists for a
|
|
// process that was killed and cannot say anything; a process that is
|
|
// being stopped can, and saying it is the difference between "the next
|
|
// process picks up what is owed" and "it picks it up five minutes
|
|
// later". Measured: with no release here, the restart test below stalled
|
|
// on the claim its own predecessor left.
|
|
await ReleaseOwnClaimsAsync();
|
|
}
|
|
}
|
|
|
|
/// <summary>Give back the owed rows this process holds a claim on. Runs after
|
|
/// the stopping token has fired, so it uses its own bounded one: a database
|
|
/// that is already gone must not hold the process open on shutdown, and the
|
|
/// reclaim window is the backstop for exactly that case.</summary>
|
|
private async Task ReleaseOwnClaimsAsync()
|
|
{
|
|
try
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
var released = await db.AlertPushes
|
|
.Where(p => p.ClaimedBy == _processId && p.PushedAt == null && p.GivenUpAt == null)
|
|
.ExecuteUpdateAsync(s => s
|
|
.SetProperty(p => p.ClaimedBy, (string?)null)
|
|
.SetProperty(p => p.ClaimedAt, (DateTimeOffset?)null), timeout.Token);
|
|
if (released > 0)
|
|
_log.LogInformation("AlertNotifier: released {Rows} owed deliveries this process had claimed.", released);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "AlertNotifier: could not release this process's claims; the reclaim window will do it.");
|
|
}
|
|
}
|
|
|
|
/// <summary>One pass over the owed deliveries: claim a batch atomically, then
|
|
/// send each one.</summary>
|
|
private async Task DrainAsync(CancellationToken ct)
|
|
{
|
|
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)
|
|
{
|
|
// 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)
|
|
{
|
|
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, 0);
|
|
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,
|
|
int Attempts)
|
|
{
|
|
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),
|
|
// Every attempt every row has made, including rows that have since landed. It is
|
|
// the one number that says how hard the edge has been trying: pending and given-up
|
|
// say what the queue holds, this says what it cost.
|
|
(int) await db.AlertPushes.SumAsync(p => p.Attempts, ct));
|
|
}
|
|
}
|