using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Security; namespace OpenWaf.Infrastructure.Persistence; /// /// The watch that turns the edge's own bans into an offer (OPEN-67). /// /// A scanner farm inside one /24 is twenty engine bans and twenty operator /// decisions. OPEN-66 made a range enforceable; this is the half that notices /// the range exists. It reads only what is already there — live engine bans — /// and it writes nothing to the block list. The only thing it produces is a row /// in the alert table and a line on a surface, both of which say the same /// sentence: "these N bans sit inside this block, and here is the call that /// would replace them". /// /// Why a timer rather than the request path: the answer changes on the scale of /// minutes, and a per-request grouping over the block table would price a /// decision nobody is reading. Why not a database view: the grouping has to /// consult the operator's ranges to know whether the offer was already taken, /// and the rules of that comparison live in where the /// unit tests can reach them. /// public sealed class NetblockWatcher : BackgroundService { /// The alert kind. It is one of the fixed kinds this codebase /// writes, which is what lets it be a metric label and a table filter. public const string AlertKind = "netblock_candidate"; private static readonly TimeSpan Interval = TimeSpan.FromMinutes(5); /// How often the same block may raise the same alert. A /24 that is /// still producing bans every five minutes is the same news, and an alert /// that repeats is an alert the operator stops reading — the same reasoning /// that made the push queue count attempts instead of firing more payloads. private static readonly TimeSpan AlertCooldown = TimeSpan.FromHours(6); private readonly IServiceScopeFactory _scopeFactory; private readonly EdgePolicyProvider _policy; private readonly AlertWriter _alerts; private readonly ILogger _log; private readonly ConcurrentDictionary _alerted = new(StringComparer.Ordinal); private long _lastScanTicks; private IReadOnlyList _last = []; private string? _lastError; public NetblockWatcher( IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, AlertWriter alerts, ILogger log) { _scopeFactory = scopeFactory; _policy = policy; _alerts = alerts; _log = log; } /// When this process last looked, and what it saw. The state /// surface shows both: a watch that is off, a watch that is failing and a /// watch that found nothing have to read differently from the outside. public DateTimeOffset LastScanAt => new(Interlocked.Read(ref _lastScanTicks), TimeSpan.Zero); /// The last scan's answer, without running one. Cheap enough for a /// status surface that is scraped more often than anyone reads it. public IReadOnlyList LastCandidates() => _last; public string? LastError => Volatile.Read(ref _lastError); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { await Task.Delay(Interval, stoppingToken); } catch (TaskCanceledException) { return; } try { await ScanAndAlertAsync(CancellationToken.None); } catch (Exception ex) { _log.LogWarning(ex, "NetblockWatcher: the scan failed."); } } } /// One scan. is false when a surface /// asked for the answer: reading the list is not news, and an operator /// refreshing a page must not be able to raise an alert per refresh. public async Task> ScanAndAlertAsync(CancellationToken ct) => await ScanAsync(true, ct); public async Task> ScanAsync(bool raiseAlerts, CancellationToken ct) { var policy = _policy.Current; var now = DateTimeOffset.UtcNow; if (policy.NetblockCandidateBans <= 0) { // Off is an answer, not a failure: the cache is cleared so a surface // cannot keep showing candidates the operator switched off. _last = []; Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); Volatile.Write(ref _lastError, null); return _last; } IReadOnlyList candidates; try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var token = ct; var bans = await db.Blocks .Where(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now)) .Select(b => new { b.SourceKey, b.CreatedAt }) .AsNoTracking() .ToListAsync(token); var ranges = await db.NetworkBans .Where(r => r.ExpiresAt == null || r.ExpiresAt > now) .AsNoTracking() .ToListAsync(token); candidates = Netblocks.Candidates( bans.Select(b => (b.SourceKey, b.CreatedAt)), policy, new NetworkBanIndex(ranges), now); Volatile.Write(ref _lastError, null); } catch (Exception ex) { // The watch is a suggestion engine, so a failure here retires the // suggestions rather than repeating the last ones: an operator // offering a range from a scan that never ran is offering a fact // that stopped being true. _last = []; Volatile.Write(ref _lastError, ex.Message); _log.LogWarning(ex, "NetblockWatcher: the scan failed; no candidates are offered."); Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); return _last; } _last = candidates; Interlocked.Exchange(ref _lastScanTicks, now.UtcTicks); if (raiseAlerts) { foreach (var candidate in candidates) { if (candidate.AlreadyBanned) continue; if (_alerted.TryGetValue(candidate.Match, out var at) && now - at < AlertCooldown) continue; _alerted[candidate.Match] = now; await _alerts.RaiseAsync( AlertKind, candidate.Match, candidate.Bans, null, null, $"{candidate.Bans} live engine bans sit inside {candidate.Match}; " + $"the oldest is from {candidate.FirstBanAt:u} and the newest from {candidate.LastBanAt:u}. " + "Nothing was banned: POST /admin-api/blocks with this CIDR would replace those rows with one.", ct); } } return candidates; } }