Files
openwaf/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs
T
Pavlo Ratushnyi b75888fa83 Every source key the console prints is now a question the operator can ask back, and the counts answer it filtered
/streaks learned the ?source= filter the observation and alert listings
learned in OPEN-33, and standingStreaks narrows with the rows while
trackedSources stays the map size. The console narrows observations and
streaks to one key from a box or from a click on any key in any table,
prints the filtered total under each, and says the words 'no recorded
observations for <key>' instead of drawing an empty box.

The first version appended '&source=' to a bare path, which is a
different route: the edge answered 404 and the streak line printed
'unknown scope'. The console gate caught it; the API tests did not,
because they call the API. Hence withSrc, which decides the separator
per path.
2026-10-02 16:21:35 +02:00

334 lines
14 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)
=> 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);
}
}
}