Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs
T
Pavlo Ratushnyi 3959f1fe6b a change to the operator's config leaves a record of itself
Every operator write already changes a row; what was missing is the answer an operator actually asks at 03:00 - when did this rule get here, who cleared that ban, did a document bring this edge's config. Since the transfer landed, an edge can be different from yesterday with nothing on it saying how.

config_changes carries one row per deliberate change: the instant, the section (block, allow, rule, country, policy, config), the action (added, removed, changed, imported), the target the operator typed, their own sentence where one was given, and the surface the change came through. GET /admin-api/changes answers it newest first, capped and paged like every other listing, filterable by section and since, readable by the read-only token because it is a read. A policy record says what moved ("mode Enforce->Off, streakThreshold 3->4") rather than only that something did. /admin-api/state counts the rows and the write failures.

The rulings, because each is a decision and not a detail:

 * Engine bans are not in the log. A ban the engine earned is not a decision somebody made, and the block row already carries its evidence - consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic.
 * An import is one record per section, not one per row: "3 added, 1 already there, 0 past expiry, 0 rejected". A 2 000-row document would otherwise bury a table whose whole use is being readable.
 * The record names the surface, never a person. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record.
 * A record that cannot be written never undoes the change it describes. Enforcement is the product, so the change stands and the failure is counted - changeWriteFailures, changesNotWritten, changeLastError - because "the config changed and the record of it did not land" has to be a sentence an operator can read rather than one that silently never happened.
 * Bounded twice, both keys the operator's: ChangeRetentionDays (30) and ChangeLogMaxRows (5000, oldest dropped first). The age window alone would let a scripted churn grow the table without limit; the cap alone would drop last month's incident record the week someone did a lot of editing.

What the run caught, in order: (1) Two gate assertions were wrong rather than the product - a policy record was asserted in a scene where no policy write had happened yet, and "one imported record per section" was asserted against a stack that had already imported twice, so the assertion now reads the newest imported record instead of counting them. (2) DELETE /admin-api/countries/{code} answers 204, and the new assertion expected 200. (3) A shell trap in the new scene: a $VAR inside a single-quoted python -c is not interpolated, so the first version would have handed python a literal "$CHANGES_BEFORE" instead of a number.

Gates on this tree: build 0 warnings / 0 errors, unit 313/313, integration 298/298 in 23s, smoke 127 passed / 0 failed (14 new), image 262 MB, compose-smoke 278 passed / 0 failed with 0 containers left behind (11 new, against the shipped image), console 90 assertions / 0 failed.

Refs OPEN-64.
2026-10-05 05:58:42 +02:00

104 lines
5.0 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Retention (Q8). The edge stores aggregates, not a request log, so the
/// privacy question the reference repo left open for <c>SiteVisit</c> — how
/// long a raw IP may sit in the database — has a bounded answer here: idle
/// observations and expired engine bans age out on a timer.
/// </summary>
public sealed class RetentionWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<RetentionWorker> _log;
private readonly TimeSpan _interval = TimeSpan.FromMinutes(30);
public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, DurabilityHealth health, ILogger<RetentionWorker> log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_health = health;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(_interval, stoppingToken); }
catch (TaskCanceledException) { return; }
try { await PruneAsync(CancellationToken.None); }
catch (Exception ex) { _log.LogWarning(ex, "RetentionWorker: prune failed."); }
}
}
internal async Task PruneAsync(CancellationToken ct)
{
var policy = _policy.Current;
var now = DateTimeOffset.UtcNow;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
try
{
await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Blocks
.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
// key stops being kept after this long without traffic.
await db.Streaks.Where(t => t.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
// The change log (OPEN-64) is bounded twice, and the second bound is
// the one the age window cannot provide: an operator scripting a
// thousand rule edits inside a week would otherwise grow a table
// whose whole use is being readable. The oldest rows go first, so
// what survives is the recent history an operator actually asks for.
var changeAge = now - policy.ChangeRetention;
await db.ConfigChanges.Where(c => c.At < changeAge).ExecuteDeleteAsync(ct);
var held = await db.ConfigChanges.CountAsync(ct);
var excess = held - policy.ChangeLogMaxRows;
if (excess > 0)
{
var oldest = await db.ConfigChanges.OrderBy(c => c.Id).Select(c => c.Id)
.Take(excess).ToListAsync(ct);
await db.ConfigChanges.Where(c => oldest.Contains(c.Id)).ExecuteDeleteAsync(ct);
}
_health.RecordSuccess(DurabilityHealth.Retention);
}
catch (Exception ex)
{
// The retention promise is a privacy promise: aggregates age out on
// purpose. A prune that fails and only logs leaves idle sources in
// the database longer than the README says they are kept, with no
// way for an operator to tell "nothing was due" from "this has not
// run in a week". Counted here and reported on /state; deliberately
// NOT a readiness failure — see Program.cs.
_health.RecordFailure(DurabilityHealth.Retention, ex);
throw;
}
}
}