Files
openwaf/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs
T
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00

88 lines
3.4 KiB
C#

using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Infrastructure.Geo;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Pipeline;
/// <summary>
/// The only place in the pipeline that may refuse a request. Everything else
/// observes; this decides. That is the point of the design (OPEN-2): the
/// reference repo runs three guards that each short-circuit on their own, which
/// makes precedence a function of registration order. Here the order is fixed
/// in <see cref="DecisionEngine"/> and the answer is one value.
///
/// It reads an in-memory snapshot and never touches the database, so the cost
/// on the request path is a dictionary lookup plus, when the geo pillar is on,
/// one memory-mapped MMDB read.
/// </summary>
public sealed class EdgeGuardMiddleware(
RequestDelegate next,
EdgeStateStore state,
IGeoIpLookup geo,
ILogger<EdgeGuardMiddleware> log)
{
public async Task InvokeAsync(HttpContext ctx)
{
var snapshot = state.GetOrRefresh();
var path = ctx.Request.Path.Value ?? "/";
var now = DateTimeOffset.UtcNow;
var ip = ClientIp.Resolve(ctx, snapshot.Policy.TrustProxyHeaders);
var country = snapshot.Policy.Geo == GeoMode.Off
? null
: ClientIp.HeaderCountry(ctx) ?? geo.Lookup(ip);
var decision = DecisionEngine.Decide(snapshot, ip, path, now, country);
if (!decision.IsBlocked)
{
await next(ctx);
return;
}
log.LogInformation(
"edge: {Verdict} {Ip} {Path} ({Reason})", decision.Verdict, ip, path, decision.Reason ?? "-");
ctx.Response.StatusCode = decision.StatusCode;
switch (decision.Verdict)
{
case EdgeVerdict.BlockOperator when decision.Location is not null:
ctx.Response.Headers.Location = decision.Location;
await ctx.Response.WriteAsync(string.Empty);
break;
case EdgeVerdict.BlockEngine:
if (decision.Location is not null) ctx.Response.Headers.Location = decision.Location;
if (decision.ExpiresAt is { } expires)
{
var seconds = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds));
ctx.Response.Headers.RetryAfter = seconds.ToString();
}
await ctx.Response.WriteAsJsonAsync(new BlockedBody(
"blocked_by_policy",
decision.Reason,
decision.ExpiresAt?.ToString("O"),
"This decision was made automatically from the responses your source produced. " +
"If it is wrong, an operator can clear it."));
break;
case EdgeVerdict.GeoReject:
await ctx.Response.WriteAsJsonAsync(new BlockedBody(
"region_not_supported",
decision.Reason,
null,
"Location is inferred from the address, not known about you; VPNs and misattributed " +
"ranges are wrong sometimes. If you are a real customer, an operator can allow you in."));
break;
default:
await ctx.Response.WriteAsync(string.Empty);
break;
}
}
}
internal sealed record BlockedBody(string Error, string? Reason, string? ExpiresAt, string Note);