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/.
113 lines
4.5 KiB
C#
113 lines
4.5 KiB
C#
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Domain.Engine;
|
|
|
|
/// <summary>
|
|
/// The single ordered decision point (architecture decision, OPEN-2).
|
|
///
|
|
/// Order is a documented property, not a side effect of middleware
|
|
/// registration:
|
|
/// 1. always-pass prefixes — an operator who blocked their own address must
|
|
/// still be able to reach the admin API and undo it;
|
|
/// 2. allowlist — the exemption path, evaluated on the raw
|
|
/// address so a CIDR means what the operator wrote;
|
|
/// 3. operator block — the human's list, which the toggle cannot
|
|
/// switch off;
|
|
/// 4. engine ban — enforced only in <see cref="EnforcementMode.Enforce"/>;
|
|
/// 5. geo policy — last, so an allowlisted operator inside a
|
|
/// denied country gets one defined answer: through.
|
|
///
|
|
/// Pure function over an <see cref="EdgeSnapshot"/>. No I/O, no clock of its
|
|
/// own — <c>now</c> is passed in, which is what makes the expiry and streak
|
|
/// rules testable without waiting.
|
|
/// </summary>
|
|
public static class DecisionEngine
|
|
{
|
|
public static EdgeDecision Decide(
|
|
EdgeSnapshot snapshot,
|
|
string? clientIp,
|
|
string path,
|
|
DateTimeOffset now,
|
|
string? countryCode = null)
|
|
{
|
|
var policy = snapshot.Policy;
|
|
|
|
if (IsAlwaysPass(path, policy)) return new EdgeDecision(EdgeVerdict.PassBypassed);
|
|
|
|
if (string.IsNullOrWhiteSpace(clientIp)) return EdgeDecision.Pass;
|
|
|
|
foreach (var entry in snapshot.AllowEntries)
|
|
{
|
|
if (!entry.IsLive(now)) continue;
|
|
if (NetworkMatch.Matches(clientIp, entry.Match))
|
|
{
|
|
return new EdgeDecision(EdgeVerdict.PassAllowlisted, Reason: entry.Note);
|
|
}
|
|
}
|
|
|
|
var key = SourceKey.For(clientIp, policy);
|
|
if (key.Length == 0) return EdgeDecision.Pass;
|
|
|
|
if (snapshot.OperatorBlocks.TryGetValue(key, out var manual) && manual.IsLive(now))
|
|
{
|
|
var (status, location) = BlockResponse(policy, manual.RedirectTo, policy.OperatorBlockStatus);
|
|
return new EdgeDecision(EdgeVerdict.BlockOperator, status, location, manual.Reason, key, manual.ExpiresAt);
|
|
}
|
|
|
|
if (policy.Mode == EnforcementMode.Enforce
|
|
&& snapshot.EngineBans.TryGetValue(key, out var ban) && ban.IsLive(now))
|
|
{
|
|
var (status, location) = BlockResponse(policy, ban.RedirectTo, policy.EngineBlockStatus);
|
|
return new EdgeDecision(EdgeVerdict.BlockEngine, status, location, ban.Reason, key, ban.ExpiresAt);
|
|
}
|
|
|
|
if (policy.Geo != GeoMode.Off && !string.IsNullOrWhiteSpace(countryCode))
|
|
{
|
|
var code = countryCode.Trim().ToUpperInvariant();
|
|
snapshot.Countries.TryGetValue(code, out var rule);
|
|
var denied = policy.Geo switch
|
|
{
|
|
GeoMode.DenyList => rule is { IsAllowed: false },
|
|
GeoMode.AllowList => rule is not { IsAllowed: true },
|
|
_ => false
|
|
};
|
|
if (denied)
|
|
{
|
|
return new EdgeDecision(EdgeVerdict.GeoReject, 451, Reason: $"country_{(policy.Geo == GeoMode.DenyList ? "denied" : "not_allowed")}_{code}", SourceKey: key);
|
|
}
|
|
}
|
|
|
|
return EdgeDecision.Pass;
|
|
}
|
|
|
|
/// <summary>Q6: a per-entry redirect overrides the kind's default. The
|
|
/// engine never sets one, so an engine ban stays a 403 an honest visitor
|
|
/// can read, while an operator can still send a scanner elsewhere.</summary>
|
|
private static (int Status, string? Location) BlockResponse(EdgePolicy policy, string? redirectTo, int defaultStatus)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(redirectTo)) return (301, redirectTo);
|
|
if (defaultStatus == 301)
|
|
{
|
|
var targets = policy.DefaultRedirectTargets;
|
|
var target = targets.Count == 0
|
|
? "https://www.iana.org/help/example-domains"
|
|
: targets.Count == 1 ? targets[0] : targets[Random.Shared.Next(targets.Count)];
|
|
return (301, target);
|
|
}
|
|
return (defaultStatus, null);
|
|
}
|
|
|
|
public static bool IsAlwaysPass(string path, EdgePolicy policy)
|
|
{
|
|
foreach (var prefix in policy.AlwaysPassPrefixes)
|
|
{
|
|
if (path.Equals(prefix, StringComparison.OrdinalIgnoreCase)
|
|
|| path.StartsWith(prefix + "/", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|