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

121 lines
5.8 KiB
C#

using OpenWaf.Domain.Policy;
namespace OpenWaf.Domain.Engine;
/// <summary>
/// The streak semantics, in one function, so there is exactly one copy of them.
///
/// Both streak stores apply this and nothing else: the in-process map
/// (<see cref="StreakTracker"/>) and the shared, database-backed one that makes
/// the threshold mean the same thing on every instance behind a load balancer.
/// Two copies of these rules is how a deployment ends up with a threshold that
/// counts one way on one edge and another way on the next — which is the exact
/// failure the shared store exists to remove, reintroduced one level down.
/// </summary>
public static class StreakRules
{
/// <summary>
/// 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 "consecutive"
/// means, and it is what keeps a shared-egress office from accumulating a
/// ban across a whole working day.
/// </summary>
public static StreakOutcome Apply(
StreakState state,
int statusCode,
ResponseClass responseClass,
EdgePolicy policy,
DateTimeOffset now,
RequestEvidence? evidence = null)
{
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>
public static bool IsEscalation(int lastAlerted, int current)
=> lastAlerted == 0 || current >= lastAlerted * 2;
}