Files
openwaf/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs
T
Pavlo Ratushnyi 0e2aee6beb A capped listing answered like it was the whole answer, and one said it was capped when it was not
?source= is refused by name now; a limit nobody meant still silently became a
different limit. Measured on the shipped image (openwaf:ci), 1103 sources
recorded:

  GET /admin-api/observations?limit=100000 -> 200, 1000 rows, no total, no
      truncation flag. 103 recorded sources were unreachable and the response
      read like a complete answer.
  GET /admin-api/observations?limit=0 and ?limit=-1 -> 200, one row each.
  GET /admin-api/streaks?limit=1000 -> 200, 2 streaks, trackedSources 3,
      X-Truncated: true. Nothing had been cut: the header compared the page
      against the size of the streak map, and the map keeps a source whose
      streak a clean answer ended while the listing leaves those out on purpose.

The block listing already carried X-Total-Count and X-Truncated, with a comment
saying that is what stops a page reading like a complete answer. The two
listings the console reads most had neither. Now every capped listing carries
both, takes an offset that reaches the rest, and refuses a limit outside its
range by name: "limit must be 1..1000; got 0". /streaks measures truncation
against standing streaks, reports standingStreaks next to trackedSources, and
pages.

The page says what it is showing. The console gate run printed "newest 25 of 42
recorded sources" and "Newest 25 of 274 alerts" — before this change both tables
rendered as if the page were the window, and the volume that survives compose
down is exactly where that matters.

Teeth, each reverted and counted, then restored: headers removed -> 2
integration failures; limit/offset clamped instead of refused -> 13; streak
header counted against the map again -> 1; standingTotal counted as the map size
-> 1 unit + 1 integration.

Gates on this tree: unit 128/128, integration 89/89, smoke passed 19 failed 0,
compose 43 passed 0 failed, console 42 assertions 0 failed.
2026-10-02 02:19:27 +02:00

318 lines
13 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
{
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);
state.LastSeenAt = now;
state.LastStatusCode = statusCode;
if (evidence is not null) state.Apply(evidence.Value);
switch (responseClass)
{
case ResponseClass.Refusal:
var withinWindow = state.LastRefusalAt is not null
&& now - state.LastRefusalAt.Value <= policy.StreakWindow;
if (!withinWindow) state.LastAlertedRefusals = 0;
state.ConsecutiveRefusals = withinWindow ? state.ConsecutiveRefusals + 1 : 1;
state.LastRefusalAt = now;
state.TotalRefusals++;
if (state.ConsecutiveRefusals > state.MaxConsecutiveRefusals)
state.MaxConsecutiveRefusals = state.ConsecutiveRefusals;
// A refusal ends the server-error run, and with it the
// episode: without this, a source that alternates 5xx with
// 4xx keeps the "already alerted at 12" mark while its
// error count restarts at 1, and the next outage is silent
// until the count doubles the old mark.
state.LastAlertedServerErrors = 0;
state.ConsecutiveServerErrors = 0;
break;
case ResponseClass.ServerError:
var withinErrorWindow = state.LastRefusalAt is not null
&& now - state.LastRefusalAt.Value <= policy.StreakWindow;
if (!withinErrorWindow) state.LastAlertedServerErrors = 0;
state.ConsecutiveServerErrors = withinErrorWindow ? state.ConsecutiveServerErrors + 1 : 1;
state.LastRefusalAt = now;
if (state.ConsecutiveServerErrors > state.MaxConsecutiveServerErrors)
state.MaxConsecutiveServerErrors = state.ConsecutiveServerErrors;
// A server error is not a clean answer either, so it does
// not reset the refusal streak; it just does not extend it.
break;
default:
state.ConsecutiveRefusals = 0;
state.ConsecutiveServerErrors = 0;
// A clean answer ends the episode, so the next one is
// allowed (and expected) to raise its own alert.
state.LastAlertedRefusals = 0;
state.LastAlertedServerErrors = 0;
break;
}
var ban = responseClass == ResponseClass.Refusal
&& state.ConsecutiveRefusals >= policy.StreakThreshold;
// Both alerts are edge-triggered. They used to be level-triggered,
// which wrote one alert row per request for as long as the
// condition lasted, and neither condition ends on its own: a 5xx
// never bans, and in Observe mode nothing bans at all, so the
// source stays observable on every request. At N=3 a source
// hammering a broken upstream for 10,000 requests cost 9,998 alert
// rows, kept for the whole retention window, and the operator's
// alert list (newest 100) was one source deep. Silencing alone
// would be worse, because an alert that fires once and never again
// hides a problem that got ten times worse since. So: speak on the
// crossing, then again on every doubling.
var alert = false;
var banAlertDue = false;
if (responseClass == ResponseClass.ServerError
&& state.ConsecutiveServerErrors >= policy.StreakThreshold)
{
alert = IsEscalation(state.LastAlertedServerErrors, state.ConsecutiveServerErrors);
if (alert) state.LastAlertedServerErrors = state.ConsecutiveServerErrors;
}
else if (ban)
{
banAlertDue = IsEscalation(state.LastAlertedRefusals, state.ConsecutiveRefusals);
if (banAlertDue) state.LastAlertedRefusals = state.ConsecutiveRefusals;
}
return new StreakOutcome(
state.ConsecutiveRefusals, state.ConsecutiveServerErrors, ban, alert, banAlertDue);
}
}
/// <summary>
/// Whether a count deserves a fresh alert row. Zero means this episode has
/// not alerted yet, so the crossing always speaks; after that only a
/// doubling does. A storm of S responses therefore costs O(log S) rows
/// instead of S, and the rows that do exist still say the useful thing:
/// the count is climbing and nobody has acted.
/// </summary>
private static bool IsEscalation(int lastAlerted, int current)
=> lastAlerted == 0 || current >= lastAlerted * 2;
/// <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)
{
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 (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);
}
}
}