Files
openwaf/dotnet/OpenWaf.Edge/Pipeline/ResponseObservationMiddleware.cs
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

150 lines
6.8 KiB
C#

using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Infrastructure.Geo;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Pipeline;
/// <summary>
/// Runs after the guard, awaits the upstream, and classifies what the
/// application actually answered. This is the seam the reference repo already
/// established in <c>SuspiciousHitTrackerMiddleware</c> — inspect the status
/// after the pipeline, not before it — widened from "one status code" to a
/// configurable predicate plus a streak.
///
/// Being inside the guard is load-bearing in two directions:
/// * a request the guard already refused is not observed, so a ban can never
/// feed its own streak (a 403 we generate would otherwise re-ban forever);
/// * the status it sees is the upstream's, which is the whole signal.
///
/// Nothing here blocks. It records, and the only durable consequence is a ban
/// row written once, out of band, when a streak matures.
/// </summary>
public sealed class ResponseObservationMiddleware(
RequestDelegate next,
EdgeStateStore state,
IStreakTracker tracker,
BlockStore blocks,
AlertWriter alerts,
IGeoIpLookup geo,
ILogger<ResponseObservationMiddleware> log)
{
public async Task InvokeAsync(HttpContext ctx)
{
await next(ctx);
var snapshot = state.Current;
var policy = snapshot.Policy;
if (policy.Mode == EnforcementMode.Off && policy.Geo == GeoMode.Off) return;
var status = ctx.Response.StatusCode;
var responseClass = ResponseClassifier.Classify(status, policy);
if (responseClass == ResponseClass.Neutral)
{
// A clean answer is the end of a run of refusals, and the tracker
// only knows that if it is told. Returning here — which is what this
// used to do — left the documented mitigation ("one honest click
// resets it", README) unenforced end to end: a visitor alternating
// 404 and a normal page view accumulated refusals across every
// honest request and still got banned. The reset is the only thing
// done for a 2xx: no evidence is built, so no MMDB read is paid.
var neutralIp = ClientIp.Resolve(ctx, policy.TrustProxyHeaders);
if (string.IsNullOrWhiteSpace(neutralIp)) return;
tracker.ResetIfTracked(SourceKey.For(neutralIp, policy));
return;
}
var ip = ClientIp.Resolve(ctx, policy.TrustProxyHeaders);
if (string.IsNullOrWhiteSpace(ip)) return;
var key = SourceKey.For(ip, policy);
if (key.Length == 0) return;
var path = ctx.Request.Path.Value ?? string.Empty;
// The always-pass surface is also never observed. The guard lets an
// operator through to the admin API even from a blocked address; if a
// mistyped admin call still counted as a refusal, the operator would
// ban themselves with a syntax error — the one failure mode a recovery
// hatch must not have.
if (DecisionEngine.IsAlwaysPass(path, policy)) return;
var evidence = BuildEvidence(ctx, ip, responseClass);
var outcome = tracker.Observe(key, status, responseClass, policy, DateTimeOffset.UtcNow, evidence);
if (outcome.AlertTriggered)
{
log.LogWarning(
"edge: {Count} consecutive server errors from {Key} (last {Status} {Path}) — alerting, not banning",
outcome.ConsecutiveServerErrors, key, status, path);
await alerts.RaiseAsync(
"server_error_streak", key, outcome.ConsecutiveServerErrors, status, path,
$"{outcome.ConsecutiveServerErrors} consecutive responses in {policy.ServerErrorRange} " +
$"within {policy.StreakWindow.TotalMinutes:0.#} min. Server errors never ban: a broken deploy " +
$"must not lock out the site's own visitors.");
}
if (!outcome.BanTriggered) return;
var streak = tracker.Peek(key);
if (streak is null) return;
if (policy.Mode == EnforcementMode.Observe)
{
// Dry run: the decision is recorded so an operator can judge the
// rule before it is allowed to act, but nothing is blocked.
//
// Gated on BanAlertDue, not BanTriggered. BanTriggered is true on
// every response once the threshold is behind it, and in Observe
// mode nothing ever blocks, so the source keeps being observed:
// raising on that flag made the dry run write one alert row per
// request, which turns the safest mode into the one an attacker
// can use to grow the operator's alert table at request rate.
if (!outcome.BanAlertDue) return;
await alerts.RaiseAsync(
"candidate_ban", key, outcome.ConsecutiveRefusals, status, path,
$"would ban for {policy.BanDuration.TotalMinutes:0.#} min at N={policy.StreakThreshold} " +
$"within {policy.StreakWindow.TotalMinutes:0.#} min (mode=Observe, not enforced)");
return;
}
// Deliberately not ctx.RequestAborted: this runs after the response
// has been written, so the client is free to hang up at any moment and
// a cancelled token would silently drop the ban — the request that
// proves the source is abusive would be the one that fails to record
// it. The write is bounded by the database, not by the visitor.
var ban = await blocks.BanAsync(streak, status, DateTimeOffset.UtcNow);
if (ban is not null)
{
log.LogWarning("edge: banned {Key} until {Until} — {Reason}", key, ban.ExpiresAt, ban.Reason);
}
}
/// <summary>Geo is resolved only for responses that mean something, so an
/// MMDB read is not paid on every 200.</summary>
private RequestEvidence BuildEvidence(HttpContext ctx, string ip, ResponseClass responseClass)
{
_ = responseClass;
var headerCountry = ClientIp.HeaderCountry(ctx);
var detail = headerCountry is null ? geo.LookupDetail(ip) : new GeoIpResult(headerCountry, null, null);
if (headerCountry is not null && detail.City is null)
{
var local = geo.LookupDetail(ip);
detail = detail with { City = local.City, Region = local.Region };
}
return new RequestEvidence(
Truncate(ctx.Request.Path.Value, 512),
Truncate(ctx.Request.Headers.UserAgent.ToString(), 256),
detail.CountryCode,
Truncate(detail.City, 128),
Truncate(detail.Region, 128));
}
private static string? Truncate(string? value, int max)
=> string.IsNullOrEmpty(value) ? null : (value.Length <= max ? value : value[..max]);
}