Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs
T
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00

127 lines
5.2 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Persists the in-memory streak state on a timer. This is the write
/// amplification protection the reference repo already paid for: a scanner
/// hammering thousands of paths a second must not generate matching writes a
/// second, so the tracker stays in memory and at most one durable upsert per
/// source per <c>ObservationWriteInterval</c> leaves this loop.
/// </summary>
public sealed class ObservationWriter : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly StreakTracker _tracker;
private readonly EdgePolicyProvider _policy;
private readonly ILogger<ObservationWriter> _log;
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
private readonly Dictionary<string, DateTimeOffset> _lastWrittenAt = new(StringComparer.Ordinal);
public ObservationWriter(
IServiceScopeFactory scopeFactory,
StreakTracker tracker,
EdgePolicyProvider policy,
ILogger<ObservationWriter> log)
{
_scopeFactory = scopeFactory;
_tracker = tracker;
_policy = policy;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(_flushInterval, stoppingToken); }
catch (TaskCanceledException) { return; }
await FlushAsync(stoppingToken);
}
await FlushAsync(CancellationToken.None);
}
internal async Task<int> FlushAsync(CancellationToken ct)
{
var policy = _policy.Current;
var now = DateTimeOffset.UtcNow;
var snapshots = _tracker.Snapshot(now, policy);
if (snapshots.Count == 0) return 0;
var due = new List<StreakSnapshot>();
foreach (var s in snapshots)
{
if (_lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval)
continue;
due.Add(s);
_lastWrittenAt[s.SourceKey] = now;
}
if (_lastWrittenAt.Count > policy.MaxTrackedSources)
{
foreach (var key in _lastWrittenAt.Where(kv => now - kv.Value > policy.StateIdleTtl).Select(kv => kv.Key).ToList())
_lastWrittenAt.Remove(key);
}
if (due.Count == 0) return 0;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var keys = due.Select(d => d.SourceKey).ToList();
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(ct);
var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal);
foreach (var s in due)
{
if (byKey.TryGetValue(s.SourceKey, out var row))
{
row.LastSeenAt = s.LastSeenAt;
row.MaxConsecutiveRefusals = Math.Max(row.MaxConsecutiveRefusals, s.MaxConsecutiveRefusals);
row.TotalRefusals = Math.Max(row.TotalRefusals, s.TotalRefusals);
row.TotalServerErrorStreak = Math.Max(row.TotalServerErrorStreak, s.MaxConsecutiveServerErrors);
row.LastStatusCode = s.LastStatusCode ?? row.LastStatusCode;
row.LastPath = s.LastPath ?? row.LastPath;
row.LastUserAgent = s.LastUserAgent ?? row.LastUserAgent;
row.LastCountryCode = s.LastCountryCode ?? row.LastCountryCode;
row.LastCity = s.LastCity ?? row.LastCity;
row.LastRegion = s.LastRegion ?? row.LastRegion;
}
else
{
db.Observations.Add(new SourceObservation
{
SourceKey = s.SourceKey,
FirstSeenAt = s.LastSeenAt,
LastSeenAt = s.LastSeenAt,
MaxConsecutiveRefusals = s.MaxConsecutiveRefusals,
TotalRefusals = s.TotalRefusals,
TotalServerErrorStreak = s.MaxConsecutiveServerErrors,
LastStatusCode = s.LastStatusCode,
LastPath = s.LastPath,
LastUserAgent = s.LastUserAgent,
LastCountryCode = s.LastCountryCode,
LastCity = s.LastCity,
LastRegion = s.LastRegion
});
}
}
await db.SaveChangesAsync(ct);
return due.Count;
}
catch (Exception ex)
{
// The writer must survive: losing observations is better than
// taking the host down over a transient database error.
_log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count);
return 0;
}
}
}