Files
openwaf/dotnet/OpenWaf.Domain/Policy/EdgePolicy.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

85 lines
4.2 KiB
C#

namespace OpenWaf.Domain.Policy;
/// <summary>
/// The whole edge policy as one immutable snapshot, read from configuration
/// and from the <c>policy_settings</c> row (the DB wins where a key is set,
/// so the operator can change the toggle without a redeploy).
///
/// Q1 is settled here: the streak window (M) and the ban duration are two
/// separate parameters. "N раз підряд на M хвилин" bounds the streak; how
/// long a ban then lasts is a different question and gets its own knob.
/// </summary>
public sealed record EdgePolicy
{
public EnforcementMode Mode { get; init; } = EnforcementMode.Observe;
/// <summary>N — consecutive refusals that trigger a ban.</summary>
public int StreakThreshold { get; init; } = 10;
/// <summary>M — the gap between two refusals that still counts as the same
/// streak. A gap longer than this restarts the streak at 1.</summary>
public TimeSpan StreakWindow { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>How long an engine ban stays live.</summary>
public TimeSpan BanDuration { get; init; } = TimeSpan.FromMinutes(60);
/// <summary>Q2: the refusal class is inclusive of 400 — a malformed-body
/// probe answers 400 and must count.</summary>
public StatusRange RefusalRange { get; init; } = new(400, 499);
/// <summary>Q3: 5xx is an alert, never a ban.</summary>
public StatusRange ServerErrorRange { get; init; } = new(500, 599);
/// <summary>Q4: source key granularity. IPv6 is grouped to /64 so a bot
/// rotating addresses inside one provider allocation is one source, and a
/// whole office behind one v4 address stays one source (accepted cost,
/// documented, mitigated by the allowlist).</summary>
public int Ipv4KeyPrefixLength { get; init; } = 32;
public int Ipv6KeyPrefixLength { get; init; } = 64;
/// <summary>Hard bound on the in-memory streak map. Beyond it the oldest
/// sources are evicted, so a scanner farm cannot grow the process.
/// (LEAS-785 is the cautionary tale: an unbounded ConcurrentDictionary.)</summary>
public int MaxTrackedSources { get; init; } = 10_000;
/// <summary>Write-amplification cap: at most one durable observation per
/// source per this interval.</summary>
public TimeSpan ObservationWriteInterval { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A source state nobody has touched for this long is evicted.</summary>
public TimeSpan StateIdleTtl { get; init; } = TimeSpan.FromHours(2);
/// <summary>How long a ban's evidence row survives after it stops being live.</summary>
public TimeSpan BanRetention { get; init; } = TimeSpan.FromDays(7);
/// <summary>How long an observation row survives without traffic.</summary>
public TimeSpan ObservationRetention { get; init; } = TimeSpan.FromDays(7);
public GeoMode Geo { get; init; } = GeoMode.Off;
/// <summary>Whether X-Forwarded-For / CF-Connecting-IP may define the
/// source address. Off by default: if the header is attacker-controlled
/// every request gets a fresh source key and no streak ever matures.</summary>
public bool TrustProxyHeaders { get; init; }
/// <summary>Response the edge gives an engine ban. 403, not 301: a 301 is
/// a good answer to a scanner and a baffling one to a customer whose
/// office IP was caught (Q6).</summary>
public int EngineBlockStatus { get; init; } = 403;
/// <summary>Response the edge gives an operator block when the entry has no
/// per-entry redirect. Defaults to the reference behaviour: 301 to a
/// honey-pot list, because scanners follow redirects and honest users
/// typed nothing.</summary>
public int OperatorBlockStatus { get; init; } = 301;
public IReadOnlyList<string> DefaultRedirectTargets { get; init; } =
new[] { "https://www.iana.org/help/example-domains" };
/// <summary>Paths that never consult the guard, so an operator who blocks
/// their own address can still reach the admin API and undo it.</summary>
public IReadOnlyList<string> AlwaysPassPrefixes { get; init; } =
new[] { "/admin-api", "/admin", "/healthz", "/readyz", "/openapi", "/swagger" };
public static EdgePolicy Default { get; } = new();
}