Files
Pavlo Ratushnyi 8ee6570458 the streak map can live in the database, so N edges mature one streak
The multi-instance research measured the gap rather than guessing it: four
refusals from one address, two per edge, at a threshold of 3, produced no ban
anywhere, because the block list was shared through the database and the streak
map was not (research/2026-10-01-multi-instance/, D1). OpenWaf:Policy:
SharedStreaks=true moves the counters onto a row in source_streaks; the default
stays the in-process map, because that is the deployment that loses nothing.

The rules were extracted into StreakRules.Apply and both stores call it — the
in-process map against a StreakState, the shared one against a row. A second
copy of the streak semantics would put the drift back where this removes it.
Version is a concurrency token, so two edges writing one source produce a retry
against the winner's row rather than a silently dropped refusal; a clean answer
on any edge ends the run on every edge, in one statement. The rows age out on
the same ObservationRetentionDays window as observations. Both surfaces say
which store answered: /admin-api/streaks scope is this-process or
shared-database, /admin-api/state answers streakScope, and the console's streak
note stops claiming "this edge process only" when it is not true.

Found by running it for real rather than in-process: two edge processes on one
SQLite file both create the schema on startup, and the loser of that race died
in StartAsync with 'table "allow_entries" already exists' — hosting failed to
start and the process never listened. The schema step now re-checks existence
and continues, because what has to be true is that the schema exists, not that
this process made it.

Measured on this tree: build 0 warnings / 0 errors, unit 132/132, integration
191/191 in 32 s (6 new, two real edge instances on one SQLite file each), smoke
28/0, console 78 assertions 0 failed. Out of process, two edge binaries on one
file at a 5 s TTL: A answered 404, 404; B answered 404 on the third refusal and
403 after it; both edges then reported consecutiveRefusals: 3 with
scope: shared-database, and A started enforcing 4 s later. Before the schema fix
the second process aborted on startup, which is how that fix was found.
2026-10-04 17:13:21 +02:00

252 lines
9.8 KiB
C#

using OpenWaf.Domain.Policy;
namespace OpenWaf.Domain.Engine;
/// <summary>
/// The consecutive-streak counter. This is the piece the reference repo
/// already paid for twice over — <c>SuspiciousHitTrackerMiddleware</c> solved
/// write amplification and unbounded memory for a single status code; this
/// generalises the predicate and adds the streak, keeping both protections.
///
/// Two protections, both load-bearing:
/// * <b>Bounded memory.</b> At most <see cref="EdgePolicy.MaxTrackedSources"/>
/// sources are held; the least-recently-touched are evicted. Idle states
/// age out on their own.
/// * <b>No DB on the request path.</b> The tracker is in-memory only; a
/// background writer persists a coalesced snapshot at most once per source
/// per <see cref="EdgePolicy.ObservationWriteInterval"/>.
///
/// Streak semantics (Q1): a refusal counts toward the current streak only if
/// it lands within <see cref="EdgePolicy.StreakWindow"/> of the previous
/// refusal; otherwise the streak restarts at 1. A neutral response (2xx/3xx)
/// resets the refusal streak to zero — that is what "підряд" means, and it is
/// what keeps a shared-egress office from accumulating a ban across a whole
/// working day.
/// </summary>
public sealed class StreakTracker : IStreakTracker
{
private readonly object _gate = new();
private readonly Dictionary<string, StreakState> _states = new(StringComparer.Ordinal);
private readonly LinkedList<string> _lru = new();
public StreakOutcome Observe(
string sourceKey,
int statusCode,
ResponseClass responseClass,
EdgePolicy policy,
DateTimeOffset now,
RequestEvidence? evidence = null)
{
if (string.IsNullOrEmpty(sourceKey)) return StreakOutcome.None;
lock (_gate)
{
var state = GetOrCreate(sourceKey, now);
Touch(state);
// The rules themselves live in one place, because the shared
// streak store (OPEN-52) has to apply exactly these and not a
// second copy of them.
return StreakRules.Apply(state, statusCode, responseClass, policy, now, evidence);
}
}
/// <summary>Snapshot for the durable writer. Copies rather than hands out
/// live objects, so the writer never reads half-updated state.</summary>
public IReadOnlyList<StreakSnapshot> Snapshot(DateTimeOffset now, EdgePolicy policy)
{
lock (_gate)
{
EvictIdle(now, policy);
var list = new List<StreakState>(_states.Count);
foreach (var s in _states.Values)
{
if (s.HasEvidence) list.Add(s);
}
return list.Select(s => new StreakSnapshot(
s.SourceKey,
s.MaxConsecutiveRefusals,
s.TotalRefusals,
s.MaxConsecutiveServerErrors,
s.LastStatusCode,
s.LastPath,
s.LastUserAgent,
s.LastCountryCode,
s.LastCity,
s.LastRegion,
s.LastSeenAt)).ToList();
}
}
public StreakSnapshot? Peek(string sourceKey)
{
lock (_gate)
{
if (!_states.TryGetValue(sourceKey, out var s)) return null;
return new StreakSnapshot(
s.SourceKey, s.MaxConsecutiveRefusals, s.TotalRefusals, s.MaxConsecutiveServerErrors,
s.LastStatusCode, s.LastPath, s.LastUserAgent, s.LastCountryCode, s.LastCity, s.LastRegion,
s.LastSeenAt);
}
}
/// <summary>
/// The streaks standing in this process right now, worst first. A source
/// whose last answer was clean has nothing standing and is left out: an
/// operator reading this is looking for the one source about to trip the
/// threshold, and a list of zeroes is how you lose it.
/// </summary>
public IReadOnlyList<LiveStreak> LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit)
=> LiveStreaks(now, policy, limit, 0, out _);
/// <summary>
/// The same listing, plus the number a caller needs to answer "is there
/// more": how many streaks are standing in this process at all.
///
/// <c>TrackedCount</c> is not that number. The map keeps a source whose
/// streak was ended by a clean answer — that is what <see cref="ResetIfTracked"/>
/// does, and it is deliberate — while this listing leaves such a source out on
/// purpose. Counting the map instead of the listing made the endpoint claim it
/// had cut rows it had not: measured on the shipped image with two standing
/// streaks and one reset source, <c>?limit=1000</c> returned 2 streaks, said
/// <c>trackedSources: 3</c>, and answered <c>X-Truncated: true</c>.
/// </summary>
public IReadOnlyList<LiveStreak> LiveStreaks(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal)
=> LiveStreaks(now, policy, limit, offset, null, out standingTotal);
/// <summary>
/// The same listing with the operator's "tell me about this one address"
/// question, which the console now asks. Exact match on the source key, and
/// standingTotal counts the FILTERED set: the truncation flag is computed
/// against it, so a filtered page cannot claim a cut that did not happen and
/// a source with nothing standing cannot be reported as one of many. This is
/// the same rule the observation and alert listings learned in OPEN-33 — a
/// filter that narrows the rows without narrowing the total is a half-fix.
/// </summary>
public IReadOnlyList<LiveStreak> LiveStreaks(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey,
out int standingTotal)
{
var take = Math.Max(1, limit);
var skip = Math.Max(0, offset);
lock (_gate)
{
EvictIdle(now, policy);
var list = new List<LiveStreak>();
foreach (var s in _states.Values)
{
if (sourceKey is not null && !string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal))
continue;
if (s.ConsecutiveRefusals == 0 && s.ConsecutiveServerErrors == 0) continue;
list.Add(new LiveStreak(
s.SourceKey, s.ConsecutiveRefusals, s.ConsecutiveServerErrors,
s.LastStatusCode, s.LastPath, s.LastCountryCode, s.LastSeenAt));
}
standingTotal = list.Count;
return list
.OrderByDescending(x => x.ConsecutiveRefusals)
.ThenByDescending(x => x.ConsecutiveServerErrors)
.ThenByDescending(x => x.LastSeenAt)
.Skip(skip)
.Take(take)
.ToList();
}
}
public int TrackedCount { get { lock (_gate) return _states.Count; } }
/// <summary>
/// Ends a standing streak when the source just got a clean answer. This is
/// what makes "consecutive" mean what the README says it means: without it
/// a visitor who alternates a 404 with a normal page view still matures a
/// ban, because nothing ever told the tracker the run ended.
///
/// Cheap on purpose — it is called for every 2xx/3xx, which is most of the
/// traffic. A source the map has never seen costs one dictionary lookup and
/// nothing else; no evidence, no MMDB read, no write.
/// </summary>
public void ResetIfTracked(string sourceKey)
{
if (string.IsNullOrEmpty(sourceKey)) return;
lock (_gate)
{
if (!_states.TryGetValue(sourceKey, out var s)) return;
s.ConsecutiveRefusals = 0;
s.ConsecutiveServerErrors = 0;
s.LastAlertedRefusals = 0;
s.LastAlertedServerErrors = 0;
}
}
public void Forget(string sourceKey)
{
lock (_gate)
{
if (_states.Remove(sourceKey, out var s)) RemoveNode(s);
}
}
private StreakState GetOrCreate(string sourceKey, DateTimeOffset now)
{
if (_states.TryGetValue(sourceKey, out var existing)) return existing;
// Eviction happens before insertion, so the cap is a cap rather than
// a target the map drifts past.
while (_states.Count >= MaxCap) RemoveOldest();
var created = new StreakState { SourceKey = sourceKey, LastSeenAt = now };
_states[sourceKey] = created;
created.LruNode = _lru.AddLast(sourceKey);
return created;
}
// Read from the policy once per configuration change so the hot path
// never dereferences the policy record for a bound.
private int MaxCap = 10_000;
public void Configure(EdgePolicy policy) => MaxCap = Math.Max(1, policy.MaxTrackedSources);
private void Touch(StreakState state)
{
if (state.LruNode is null) return;
_lru.Remove(state.LruNode);
state.LruNode = _lru.AddLast(state.SourceKey);
}
private void RemoveOldest()
{
var oldest = _lru.First;
if (oldest is null) return;
_lru.RemoveFirst();
_states.Remove(oldest.Value);
}
private void RemoveNode(StreakState s)
{
if (s.LruNode is not null)
{
_lru.Remove(s.LruNode);
s.LruNode = null;
}
}
private void EvictIdle(DateTimeOffset now, EdgePolicy policy)
{
if (_states.Count == 0) return;
List<string>? stale = null;
foreach (var kv in _states)
{
if (now - kv.Value.LastSeenAt > policy.StateIdleTtl)
{
stale ??= [];
stale.Add(kv.Key);
}
}
if (stale is null) return;
foreach (var key in stale)
{
if (_states.Remove(key, out var s)) RemoveNode(s);
}
}
}