diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
index aa65ab3..b366f33 100644
--- a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
+++ b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
@@ -86,6 +86,13 @@ public static class DecisionEngine
private static (int Status, string? Location) BlockResponse(EdgePolicy policy, string? redirectTo, int defaultStatus)
{
if (!string.IsNullOrWhiteSpace(redirectTo)) return (301, redirectTo);
+ // The last line of defence, and the only one that is not the operator's
+ // problem to fix. A status the wire cannot carry does not produce a bad
+ // answer, it produces no answer: measured on the shipped image,
+ // engineBlockStatus=1000 made every banned request die as
+ // "curl: (1) Unsupported HTTP/1 subversion in response". The admin API
+ // refuses such a value; this is for a row that got there another way.
+ if (!PolicyBounds.IsSendableStatus(defaultStatus)) return (403, null);
if (defaultStatus == 301)
{
var targets = policy.DefaultRedirectTargets;
diff --git a/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs b/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs
new file mode 100644
index 0000000..fc7342d
--- /dev/null
+++ b/dotnet/OpenWaf.Domain/Policy/PolicyBounds.cs
@@ -0,0 +1,121 @@
+namespace OpenWaf.Domain.Policy;
+
+///
+/// What a policy value is allowed to be, said once.
+///
+/// Before this existed the admin API answered 200 to anything. Two different
+/// failures hid behind that:
+///
+/// * a value the code did not want was dropped without a word — the operator
+/// saw "200 OK", the policy in the response was the old one, and nothing in
+/// the body or the log said the write had been ignored;
+/// * a value the code did want was stored and obeyed literally, including
+/// engineBlockStatus=1000, which the edge then tried to put on the wire:
+/// the client got no HTTP response at all ("curl: (1) Unsupported HTTP/1
+/// subversion in response"), so one typo in one admin call turns every
+/// banned visitor into a connection error.
+///
+/// So the range lives here, next to the reason for it, and both the admin
+/// endpoint and the DB override path check the same numbers. A rejected value
+/// is a 400 that names the key and the range — the same shape the mode and geo
+/// fields already used, and the same shape the state TTL uses at startup.
+///
+public static class PolicyBounds
+{
+ /// N. 0 or negative is not "never ban" — that is mode=Off — it is a
+ /// streak that can never mature, which is exactly the silent no-op this
+ /// class exists to stop. The ceiling keeps one operator call from turning
+ /// the guard off by asking for a threshold no source will ever reach.
+ public const int StreakThresholdMin = 1, StreakThresholdMax = 1000;
+
+ /// M. Minutes, so the floor is well under a second and the ceiling
+ /// is a day: a longer window is not a streak, it is a permanent record, and
+ /// permanent records are what the observation table is for.
+ public const double StreakWindowMinutesMin = 0.01, StreakWindowMinutesMax = 1440;
+
+ /// How long a ban lives. Ceiling is a week, matching the retention
+ /// window: a ban that outlives its own evidence row is a ban nobody can
+ /// explain.
+ public const double BanDurationMinutesMin = 0.01, BanDurationMinutesMax = 10_080;
+
+ /// The in-memory map bound. Below 1 the guard tracks nobody; above
+ /// a million the operator has asked the edge to grow the process, which is
+ /// the denial-of-service this bound exists to prevent.
+ public const int MaxTrackedSourcesMin = 1, MaxTrackedSourcesMax = 1_000_000;
+
+ /// Source-key granularity. The floor is the point: a /0 key is the
+ /// literal string "*" and every IPv4 address on the internet shares one
+ /// streak and one ban — measured, one 404 from one address banned the key
+ /// "*" and the next three addresses were refused on their first request.
+ /// An /8 is the largest thing that is still one provider's allocation;
+ /// below that a single key is most of the address space. IPv6 keeps its
+ /// documented /64 default and allows down to an /32 provider block.
+ public const int Ipv4KeyPrefixLengthMin = 8, Ipv4KeyPrefixLengthMax = 32;
+ public const int Ipv6KeyPrefixLengthMin = 32, Ipv6KeyPrefixLengthMax = 128;
+
+ /// The status the edge answers for a ban. It has to be a status
+ /// that means "you are not getting this": 400-599. Anything else is either
+ /// unsendable (1000 closed the connection) or a lie (200 says the request
+ /// worked while the body says blocked_by_policy).
+ public const int BlockStatusMin = 400, BlockStatusMax = 599;
+
+ /// The one non-4xx the operator block may answer, because 301 is
+ /// the reference behaviour: a redirect to a honey-pot target. Any other
+ /// 3xx would be a redirect with no Location, which is not a redirect.
+ public const int OperatorRedirectStatus = 301;
+
+ /// A status the HTTP/1.1 wire format can carry. Kestrel accepts
+ /// 100-999 and nothing else; outside that the response never reaches the
+ /// client. This is the last line of defence, not the first — the API
+ /// refuses these values long before they get here.
+ public const int SendableStatusMin = 100, SendableStatusMax = 999;
+
+ /// A status range is a classifier over real responses. 100-599 is
+ /// the whole space of statuses a server can answer; a range outside it
+ /// matches nothing, which would silently retire a pillar.
+ public const int ClassifiableStatusMin = 100, ClassifiableStatusMax = 599;
+
+ public static bool StreakThresholdOk(int v) => v is >= StreakThresholdMin and <= StreakThresholdMax;
+ public static bool StreakWindowMinutesOk(double v) => v is >= StreakWindowMinutesMin and <= StreakWindowMinutesMax;
+ public static bool BanDurationMinutesOk(double v) => v is >= BanDurationMinutesMin and <= BanDurationMinutesMax;
+ public static bool MaxTrackedSourcesOk(int v) => v is >= MaxTrackedSourcesMin and <= MaxTrackedSourcesMax;
+ public static bool Ipv4KeyPrefixLengthOk(int v) => v is >= Ipv4KeyPrefixLengthMin and <= Ipv4KeyPrefixLengthMax;
+ public static bool Ipv6KeyPrefixLengthOk(int v) => v is >= Ipv6KeyPrefixLengthMin and <= Ipv6KeyPrefixLengthMax;
+ public static bool EngineBlockStatusOk(int v) => v is >= BlockStatusMin and <= BlockStatusMax;
+ public static bool OperatorBlockStatusOk(int v) =>
+ v == OperatorRedirectStatus || (v is >= BlockStatusMin and <= BlockStatusMax);
+ public static bool IsSendableStatus(int status) => status is >= SendableStatusMin and <= SendableStatusMax;
+
+ /// The range as an operator reads it in a 400 body.
+ public static string RangeOf(string key) => key switch
+ {
+ "streakThreshold" => $"{StreakThresholdMin}..{StreakThresholdMax}",
+ "streakWindowMinutes" => $"{StreakWindowMinutesMin}..{StreakWindowMinutesMax}",
+ "banDurationMinutes" => $"{BanDurationMinutesMin}..{BanDurationMinutesMax}",
+ "maxTrackedSources" => $"{MaxTrackedSourcesMin}..{MaxTrackedSourcesMax}",
+ "ipv4KeyPrefixLength" => $"{Ipv4KeyPrefixLengthMin}..{Ipv4KeyPrefixLengthMax}",
+ "ipv6KeyPrefixLength" => $"{Ipv6KeyPrefixLengthMin}..{Ipv6KeyPrefixLengthMax}",
+ "engineBlockStatus" => $"{BlockStatusMin}..{BlockStatusMax}",
+ "operatorBlockStatus" => $"{OperatorRedirectStatus} or {BlockStatusMin}..{BlockStatusMax}",
+ "refusalRange" or "serverErrorRange" =>
+ $"low-high with {ClassifiableStatusMin} <= low <= high <= {ClassifiableStatusMax}",
+ _ => "a defined value"
+ };
+
+ /// True when a stored row or a request field for this key is
+ /// usable. Unknown keys are the caller's business, not this one's.
+ public static bool ValueOk(string key, string? value) => value is not null && key switch
+ {
+ "streakThreshold" => int.TryParse(value, out var v) && StreakThresholdOk(v),
+ "streakWindowMinutes" => double.TryParse(value, out var v) && StreakWindowMinutesOk(v),
+ "banDurationMinutes" => double.TryParse(value, out var v) && BanDurationMinutesOk(v),
+ "maxTrackedSources" => int.TryParse(value, out var v) && MaxTrackedSourcesOk(v),
+ "ipv4KeyPrefixLength" => int.TryParse(value, out var v) && Ipv4KeyPrefixLengthOk(v),
+ "ipv6KeyPrefixLength" => int.TryParse(value, out var v) && Ipv6KeyPrefixLengthOk(v),
+ "engineBlockStatus" => int.TryParse(value, out var v) && EngineBlockStatusOk(v),
+ "operatorBlockStatus" => int.TryParse(value, out var v) && OperatorBlockStatusOk(v),
+ "refusalRange" or "serverErrorRange" => StatusRange.TryParse(value, out var r)
+ && r.Low >= ClassifiableStatusMin && r.High <= ClassifiableStatusMax,
+ _ => true
+ };
+}
diff --git a/dotnet/OpenWaf.Domain/Policy/StatusRange.cs b/dotnet/OpenWaf.Domain/Policy/StatusRange.cs
index bde9b08..b39e302 100644
--- a/dotnet/OpenWaf.Domain/Policy/StatusRange.cs
+++ b/dotnet/OpenWaf.Domain/Policy/StatusRange.cs
@@ -7,13 +7,21 @@ public readonly record struct StatusRange(int Low, int High)
public override string ToString() => $"{Low}-{High}";
+ /// Configuration path: a value that does not parse is not a
+ /// reason to refuse to start, so it falls back. The admin API does not use
+ /// this — it uses and answers 400, because an
+ /// operator's write deserves to be told, not quietly ignored.
public static StatusRange Parse(string? value, StatusRange fallback)
+ => TryParse(value, out var parsed) ? parsed : fallback;
+
+ public static bool TryParse(string? value, out StatusRange range)
{
- if (string.IsNullOrWhiteSpace(value)) return fallback;
+ range = default;
+ if (string.IsNullOrWhiteSpace(value)) return false;
var parts = value.Split('-', StringSplitOptions.TrimEntries);
- if (parts.Length != 2) return fallback;
- return int.TryParse(parts[0], out var lo) && int.TryParse(parts[1], out var hi) && lo <= hi
- ? new StatusRange(lo, hi)
- : fallback;
+ if (parts.Length != 2) return false;
+ if (!int.TryParse(parts[0], out var lo) || !int.TryParse(parts[1], out var hi) || lo > hi) return false;
+ range = new StatusRange(lo, hi);
+ return true;
}
}
diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
index af7917a..740741c 100644
--- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
+++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
@@ -147,17 +147,27 @@ internal static class AdminEndpoints
return Results.BadRequest(new { error = "geo must be Off|DenyList|AllowList" });
overrides["geo"] = geo.ToString();
}
- if (req.StreakThreshold is > 0) overrides["streakThreshold"] = req.StreakThreshold.Value.ToString();
- if (req.StreakWindowMinutes is > 0) overrides["streakWindowMinutes"] = req.StreakWindowMinutes.Value.ToString();
- if (req.BanDurationMinutes is > 0) overrides["banDurationMinutes"] = req.BanDurationMinutes.Value.ToString();
- if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange;
- if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange;
+ // A field that is present but out of range is a 400, not a silent
+ // no-op. The old shape — `if (req.X is > 0)` — answered 200 with the
+ // old policy in the body for streakThreshold=0, maxTrackedSources=0,
+ // banDurationMinutes=-1 and refusalRange="not-a-range", and it
+ // stored engineBlockStatus=1000 and ipv4KeyPrefixLength=0, which the
+ // edge then obeyed: the first closed the connection on every banned
+ // request, the second made one ban apply to every IPv4 address.
+ var problem = PolicyProblem(req);
+ if (problem is not null) return Results.BadRequest(new { error = problem });
+
+ if (req.StreakThreshold is { } streakThreshold) overrides["streakThreshold"] = streakThreshold.ToString();
+ if (req.StreakWindowMinutes is { } windowMinutes) overrides["streakWindowMinutes"] = windowMinutes.ToString();
+ if (req.BanDurationMinutes is { } banMinutes) overrides["banDurationMinutes"] = banMinutes.ToString();
+ if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange.Trim();
+ if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange.Trim();
if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant();
- if (req.MaxTrackedSources is > 0) overrides["maxTrackedSources"] = req.MaxTrackedSources.Value.ToString();
- if (req.Ipv4KeyPrefixLength is >= 0) overrides["ipv4KeyPrefixLength"] = req.Ipv4KeyPrefixLength.Value.ToString();
- if (req.Ipv6KeyPrefixLength is >= 0) overrides["ipv6KeyPrefixLength"] = req.Ipv6KeyPrefixLength.Value.ToString();
- if (req.EngineBlockStatus is > 0) overrides["engineBlockStatus"] = req.EngineBlockStatus.Value.ToString();
- if (req.OperatorBlockStatus is > 0) overrides["operatorBlockStatus"] = req.OperatorBlockStatus.Value.ToString();
+ if (req.MaxTrackedSources is { } maxSources) overrides["maxTrackedSources"] = maxSources.ToString();
+ if (req.Ipv4KeyPrefixLength is { } v4) overrides["ipv4KeyPrefixLength"] = v4.ToString();
+ if (req.Ipv6KeyPrefixLength is { } v6) overrides["ipv6KeyPrefixLength"] = v6.ToString();
+ if (req.EngineBlockStatus is { } engineStatus) overrides["engineBlockStatus"] = engineStatus.ToString();
+ if (req.OperatorBlockStatus is { } operatorStatus) overrides["operatorBlockStatus"] = operatorStatus.ToString();
if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets);
// The toggle is a policy change, never a data change: switching
@@ -270,6 +280,62 @@ internal static class AdminEndpoints
return app;
}
+ ///
+ /// The one place that says no to a policy value, and says it with the key
+ /// and the range so the operator can fix the call rather than guess which
+ /// field was dropped. Returns null when every present field is usable.
+ ///
+ private static string? PolicyProblem(PolicyUpdateRequest req)
+ {
+ if (req.StreakThreshold is { } n && !PolicyBounds.StreakThresholdOk(n))
+ return $"streakThreshold must be {PolicyBounds.RangeOf("streakThreshold")}; got {n}";
+ if (req.StreakWindowMinutes is { } m && !PolicyBounds.StreakWindowMinutesOk(m))
+ return $"streakWindowMinutes must be {PolicyBounds.RangeOf("streakWindowMinutes")}; got {m}";
+ if (req.BanDurationMinutes is { } b && !PolicyBounds.BanDurationMinutesOk(b))
+ return $"banDurationMinutes must be {PolicyBounds.RangeOf("banDurationMinutes")}; got {b}";
+ if (req.MaxTrackedSources is { } t && !PolicyBounds.MaxTrackedSourcesOk(t))
+ return $"maxTrackedSources must be {PolicyBounds.RangeOf("maxTrackedSources")}; got {t}";
+ if (req.Ipv4KeyPrefixLength is { } v4 && !PolicyBounds.Ipv4KeyPrefixLengthOk(v4))
+ return $"ipv4KeyPrefixLength must be {PolicyBounds.RangeOf("ipv4KeyPrefixLength")}; got {v4}";
+ if (req.Ipv6KeyPrefixLength is { } v6 && !PolicyBounds.Ipv6KeyPrefixLengthOk(v6))
+ return $"ipv6KeyPrefixLength must be {PolicyBounds.RangeOf("ipv6KeyPrefixLength")}; got {v6}";
+ if (req.EngineBlockStatus is { } e && !PolicyBounds.EngineBlockStatusOk(e))
+ return $"engineBlockStatus must be {PolicyBounds.RangeOf("engineBlockStatus")}; got {e}";
+ if (req.OperatorBlockStatus is { } o && !PolicyBounds.OperatorBlockStatusOk(o))
+ return $"operatorBlockStatus must be {PolicyBounds.RangeOf("operatorBlockStatus")}; got {o}";
+ if (req.RefusalRange is not null && !StatusRangeUsable(req.RefusalRange))
+ return $"refusalRange must be {PolicyBounds.RangeOf("refusalRange")}; got \"{req.RefusalRange}\"";
+ if (req.ServerErrorRange is not null && !StatusRangeUsable(req.ServerErrorRange))
+ return $"serverErrorRange must be {PolicyBounds.RangeOf("serverErrorRange")}; got \"{req.ServerErrorRange}\"";
+ if (req.DefaultRedirectTargets is { Length: > 0 })
+ {
+ foreach (var target in req.DefaultRedirectTargets)
+ {
+ if (!IsHttpUrl(target))
+ return $"redirectTargets must be absolute http(s) URLs; got \"{target}\"";
+ }
+ }
+ return null;
+ }
+
+ /// A range that classifies nothing is a pillar switched off by a
+ /// typo, so it is refused rather than stored.
+ private static bool StatusRangeUsable(string value)
+ => StatusRange.TryParse(value, out var range)
+ && range.Low >= PolicyBounds.ClassifiableStatusMin
+ && range.High <= PolicyBounds.ClassifiableStatusMax;
+
+ /// A redirect target goes into a Location header, so it has to be
+ /// a URL: measured, "http://bad target" was stored and shipped as
+ /// `Location: http://bad target`, which no client can follow.
+ private static bool IsHttpUrl(string? value)
+ => value is not null
+ && !string.IsNullOrWhiteSpace(value)
+ && value.Trim() == value
+ && value.IndexOf(' ') < 0
+ && Uri.TryCreate(value, UriKind.Absolute, out var uri)
+ && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
+
private static PolicyDto ToDto(EdgePolicy p) => new(
p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes,
p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders,
diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
index 9d36eae..daba7ef 100644
--- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
+++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs
@@ -15,6 +15,10 @@ public sealed class EdgePolicyProvider
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger _log;
private EdgePolicy _current;
+ // Warn once per key, not once per refresh: ReloadAsync runs on every
+ // snapshot refresh, and a log line every 30 seconds is how an operator
+ // stops reading the log.
+ private readonly HashSet _warned = new(StringComparer.OrdinalIgnoreCase);
public EdgePolicyProvider(
IServiceScopeFactory scopeFactory,
@@ -72,25 +76,43 @@ public sealed class EdgePolicyProvider
}
}
- private static EdgePolicy ApplyOverrides(EdgePolicy basePolicy, IReadOnlyCollection rows)
+ ///
+ /// The DB is not only written by the admin API: a row can be edited by
+ /// hand, or restored from a backup taken before a key had a range. So the
+ /// range is checked here too, and a row outside it is skipped with a
+ /// warning that names the key and the value. Skipping is the safe half of
+ /// the rule — the other half is that the guard never trusts a status it
+ /// cannot put on the wire (DecisionEngine.BlockResponse).
+ ///
+ private EdgePolicy ApplyOverrides(EdgePolicy basePolicy, IReadOnlyCollection rows)
{
if (rows.Count == 0) return basePolicy;
var map = rows.ToDictionary(r => r.Key, r => r.Value, StringComparer.OrdinalIgnoreCase);
var p = basePolicy;
+ foreach (var row in rows)
+ {
+ if (row.Value is not null && !PolicyBounds.ValueOk(row.Key, row.Value) && _warned.Add(row.Key))
+ _log.LogWarning(
+ "policy_settings row {Key}={Value} is outside {Range}; ignoring it. The policy keeps its previous value for this key.",
+ row.Key, row.Value, PolicyBounds.RangeOf(row.Key));
+ }
+
+ bool Usable(string key) => !map.TryGetValue(key, out var v) || v is null || PolicyBounds.ValueOk(key, v);
+
if (map.TryGetValue("mode", out var mode) && Enum.TryParse(mode, true, out var m)) p = p with { Mode = m };
- if (map.TryGetValue("streakThreshold", out var n) && int.TryParse(n, out var nv) && nv > 0) p = p with { StreakThreshold = nv };
- if (map.TryGetValue("streakWindowMinutes", out var mw) && double.TryParse(mw, out var mwv) && mwv > 0) p = p with { StreakWindow = TimeSpan.FromMinutes(mwv) };
- if (map.TryGetValue("banDurationMinutes", out var bd) && double.TryParse(bd, out var bdv) && bdv > 0) p = p with { BanDuration = TimeSpan.FromMinutes(bdv) };
- if (map.TryGetValue("refusalRange", out var rr)) p = p with { RefusalRange = StatusRange.Parse(rr, p.RefusalRange) };
- if (map.TryGetValue("serverErrorRange", out var sr)) p = p with { ServerErrorRange = StatusRange.Parse(sr, p.ServerErrorRange) };
+ if (Usable("streakThreshold") && map.TryGetValue("streakThreshold", out var n) && int.TryParse(n, out var nv) && nv > 0) p = p with { StreakThreshold = nv };
+ if (Usable("streakWindowMinutes") && map.TryGetValue("streakWindowMinutes", out var mw) && double.TryParse(mw, out var mwv) && mwv > 0) p = p with { StreakWindow = TimeSpan.FromMinutes(mwv) };
+ if (Usable("banDurationMinutes") && map.TryGetValue("banDurationMinutes", out var bd) && double.TryParse(bd, out var bdv) && bdv > 0) p = p with { BanDuration = TimeSpan.FromMinutes(bdv) };
+ if (Usable("refusalRange") && map.TryGetValue("refusalRange", out var rr)) p = p with { RefusalRange = StatusRange.Parse(rr, p.RefusalRange) };
+ if (Usable("serverErrorRange") && map.TryGetValue("serverErrorRange", out var sr)) p = p with { ServerErrorRange = StatusRange.Parse(sr, p.ServerErrorRange) };
if (map.TryGetValue("trustProxyHeaders", out var tph) && bool.TryParse(tph, out var tphv)) p = p with { TrustProxyHeaders = tphv };
if (map.TryGetValue("geo", out var geo) && Enum.TryParse(geo, true, out var gm)) p = p with { Geo = gm };
- if (map.TryGetValue("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv };
- if (map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v };
- if (map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v };
- if (map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv };
- if (map.TryGetValue("operatorBlockStatus", out var obs) && int.TryParse(obs, out var obsv)) p = p with { OperatorBlockStatus = obsv };
+ if (Usable("maxTrackedSources") && map.TryGetValue("maxTrackedSources", out var mts) && int.TryParse(mts, out var mtsv) && mtsv > 0) p = p with { MaxTrackedSources = mtsv };
+ if (Usable("ipv6KeyPrefixLength") && map.TryGetValue("ipv6KeyPrefixLength", out var p6) && int.TryParse(p6, out var p6v)) p = p with { Ipv6KeyPrefixLength = p6v };
+ if (Usable("ipv4KeyPrefixLength") && map.TryGetValue("ipv4KeyPrefixLength", out var p4) && int.TryParse(p4, out var p4v)) p = p with { Ipv4KeyPrefixLength = p4v };
+ if (Usable("engineBlockStatus") && map.TryGetValue("engineBlockStatus", out var ebs) && int.TryParse(ebs, out var ebsv)) p = p with { EngineBlockStatus = ebsv };
+ if (Usable("operatorBlockStatus") && map.TryGetValue("operatorBlockStatus", out var obs) && int.TryParse(obs, out var obsv)) p = p with { OperatorBlockStatus = obsv };
if (map.TryGetValue("redirectTargets", out var rt) && !string.IsNullOrWhiteSpace(rt))
p = p with { DefaultRedirectTargets = rt.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) };
diff --git a/dotnet/OpenWaf.Tests.Integration/PolicyValidationTests.cs b/dotnet/OpenWaf.Tests.Integration/PolicyValidationTests.cs
new file mode 100644
index 0000000..40fa265
--- /dev/null
+++ b/dotnet/OpenWaf.Tests.Integration/PolicyValidationTests.cs
@@ -0,0 +1,167 @@
+using System.Net;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using OpenWaf.Domain.Security;
+using OpenWaf.Infrastructure.Persistence;
+
+namespace OpenWaf.Tests.Integration;
+
+///
+/// A policy write that is not believed is worse than a policy write that fails.
+///
+/// Measured on the shipped image (openwaf:ci) before these tests existed:
+/// PUT {"streakThreshold":0} -> 200, streakThreshold still 1, 0 log lines
+/// PUT {"maxTrackedSources":0} -> 200, unchanged
+/// PUT {"banDurationMinutes":-1} -> 200, unchanged
+/// PUT {"streakWindowMinutes":0} -> 200, unchanged
+/// PUT {"refusalRange":"not-a-range"} -> 200, unchanged
+/// PUT {"engineBlockStatus":999} -> 200, and the edge then answered HTTP/1.1 999
+/// PUT {"engineBlockStatus":1000} -> 200, and every banned request died as
+/// "curl: (1) Unsupported HTTP/1 subversion in response"
+/// PUT {"ipv4KeyPrefixLength":0} -> 200, and one 404 banned the key "*", after which
+/// three addresses that had never been seen were
+/// refused on their first request
+/// PUT {"ipv4KeyPrefixLength":999} -> 200, GET echoed 999, enforcement used 32
+///
+/// So the API now answers 400 naming the key and the range, and the guard has a
+/// last line for a value that arrives by another route (a hand-edited row).
+///
+public sealed class PolicyValidationTests
+{
+ private const string Scanner = "203.0.113.66";
+ private const string Bystander = "198.51.100.7";
+
+ private static async Task<(HttpStatusCode Status, string Body)> PutAsync(EdgeFixture f, string json)
+ {
+ using var request = new HttpRequestMessage(new HttpMethod("PUT"), "/admin-api/policy")
+ {
+ Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
+ };
+ request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
+ var response = await f.Client.SendAsync(request);
+ return (response.StatusCode, await response.Content.ReadAsStringAsync());
+ }
+
+ private static async Task GetPolicyAsync(EdgeFixture f)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/policy");
+ request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
+ return await (await f.Client.SendAsync(request)).Content.ReadAsStringAsync();
+ }
+
+ private static async Task GetAsync(EdgeFixture f, string path, string sourceIp)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, path);
+ request.Headers.TryAddWithoutValidation("X-Forwarded-For", sourceIp);
+ return (await f.Client.SendAsync(request)).StatusCode;
+ }
+
+ [Theory]
+ [InlineData("{\"streakThreshold\":0}", "streakThreshold", "1..1000")]
+ [InlineData("{\"streakThreshold\":-5}", "streakThreshold", "1..1000")]
+ [InlineData("{\"streakWindowMinutes\":0}", "streakWindowMinutes", "0.01..1440")]
+ [InlineData("{\"banDurationMinutes\":-1}", "banDurationMinutes", "0.01..10080")]
+ [InlineData("{\"maxTrackedSources\":0}", "maxTrackedSources", "1..1000000")]
+ [InlineData("{\"refusalRange\":\"not-a-range\"}", "refusalRange", "low-high")]
+ [InlineData("{\"refusalRange\":\"600-700\"}", "refusalRange", "100 <= low <= high <= 599")]
+ [InlineData("{\"ipv4KeyPrefixLength\":0}", "ipv4KeyPrefixLength", "8..32")]
+ [InlineData("{\"ipv4KeyPrefixLength\":999}", "ipv4KeyPrefixLength", "8..32")]
+ [InlineData("{\"ipv6KeyPrefixLength\":999}", "ipv6KeyPrefixLength", "32..128")]
+ [InlineData("{\"engineBlockStatus\":999}", "engineBlockStatus", "400..599")]
+ [InlineData("{\"engineBlockStatus\":1000}", "engineBlockStatus", "400..599")]
+ [InlineData("{\"operatorBlockStatus\":302}", "operatorBlockStatus", "301 or 400..599")]
+ [InlineData("{\"defaultRedirectTargets\":[\"http://bad target\"]}", "redirectTargets", "absolute http(s) URLs")]
+ public async Task An_out_of_range_value_is_refused_by_name_instead_of_answering_200_and_changing_nothing(
+ string json, string key, string range)
+ {
+ await using var f = new EdgeFixture(threshold: 3);
+
+ var (status, body) = await PutAsync(f, json);
+
+ Assert.Equal(HttpStatusCode.BadRequest, status);
+ Assert.Contains(key, body);
+ Assert.Contains(range, body);
+ }
+
+ [Fact]
+ public async Task A_refused_write_leaves_the_policy_exactly_where_it_was_and_the_pillar_still_works()
+ {
+ await using var f = new EdgeFixture(threshold: 3);
+
+ var before = await GetPolicyAsync(f);
+ var (status, _) = await PutAsync(f, "{\"engineBlockStatus\":1000}");
+ Assert.Equal(HttpStatusCode.BadRequest, status);
+ Assert.Equal(before, await GetPolicyAsync(f));
+
+ for (var i = 0; i < 3; i++)
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
+
+ // The point of the whole file in one assertion: the banned visitor gets
+ // an answer, not a closed connection.
+ Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
+ }
+
+ [Fact]
+ public async Task A_policy_value_that_is_accepted_reaches_the_wire_and_not_only_the_api()
+ {
+ await using var f = new EdgeFixture(threshold: 3);
+
+ var (status, body) = await PutAsync(f, "{\"engineBlockStatus\":451}");
+ Assert.Equal(HttpStatusCode.OK, status);
+ using var doc = JsonDocument.Parse(body);
+ Assert.Equal(451, doc.RootElement.GetProperty("engineBlockStatus").GetInt32());
+
+ for (var i = 0; i < 3; i++)
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
+
+ Assert.Equal((HttpStatusCode)451, await GetAsync(f, "/nope", Scanner));
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Bystander));
+ }
+
+ [Fact]
+ public async Task Asking_for_a_source_key_that_covers_the_whole_address_family_is_refused_and_the_ban_stays_one_address()
+ {
+ await using var f = new EdgeFixture(threshold: 1);
+
+ var (status, _) = await PutAsync(f, "{\"ipv4KeyPrefixLength\":0}");
+ Assert.Equal(HttpStatusCode.BadRequest, status);
+
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
+ Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
+
+ // With the key collapsed to "*" this bystander's first-ever request
+ // would have been refused, which is what was measured on the image.
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Bystander));
+
+ using var scope = f.Factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var keys = await db.Blocks.Where(b => b.Source == BlockSource.Engine).Select(b => b.SourceKey).ToListAsync();
+ Assert.DoesNotContain("*", keys);
+ Assert.Contains(Scanner, keys);
+ }
+
+ [Fact]
+ public async Task A_row_edited_by_hand_outside_the_range_is_ignored_rather_than_put_on_the_wire()
+ {
+ await using var f = new EdgeFixture(threshold: 3);
+
+ // Not through the API: a restored backup or a hand edit. The API guard
+ // cannot see this, so the loader has to.
+ using (var scope = f.Factory.Services.CreateScope())
+ {
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.PolicySettings.Add(new PolicySetting { Key = "engineBlockStatus", Value = "1000" });
+ await db.SaveChangesAsync();
+ }
+
+ await f.Service().InvalidateAsync();
+ using var doc = JsonDocument.Parse(await GetPolicyAsync(f));
+ Assert.Equal(403, doc.RootElement.GetProperty("engineBlockStatus").GetInt32());
+
+ for (var i = 0; i < 3; i++)
+ Assert.Equal(HttpStatusCode.NotFound, await GetAsync(f, "/nope", Scanner));
+
+ Assert.Equal(HttpStatusCode.Forbidden, await GetAsync(f, "/nope", Scanner));
+ }
+}
diff --git a/dotnet/OpenWaf.Tests.Unit/PolicyBoundsTests.cs b/dotnet/OpenWaf.Tests.Unit/PolicyBoundsTests.cs
new file mode 100644
index 0000000..f1e4fb8
--- /dev/null
+++ b/dotnet/OpenWaf.Tests.Unit/PolicyBoundsTests.cs
@@ -0,0 +1,143 @@
+using OpenWaf.Domain.Engine;
+using OpenWaf.Domain.Policy;
+using OpenWaf.Domain.Security;
+
+namespace OpenWaf.Tests.Unit;
+
+///
+/// The numbers that say what a policy value may be, and the guard that keeps a
+/// value which slipped past them off the wire.
+///
+/// These exist because the shipped image used to answer 200 to everything.
+/// Measured on openwaf:ci before the fix: streakThreshold=0, maxTrackedSources=0,
+/// banDurationMinutes=-1, streakWindowMinutes=0 and refusalRange="not-a-range"
+/// each returned 200 with the old policy in the body and no word that the write
+/// had been ignored; engineBlockStatus=999 was obeyed literally (the edge
+/// answered "HTTP/1.1 999"); engineBlockStatus=1000 was obeyed too and the
+/// client got no HTTP response at all; ipv4KeyPrefixLength=0 was obeyed and one
+/// 404 banned the key "*", which is every IPv4 address at once.
+///
+public sealed class PolicyBoundsTests
+{
+ private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero);
+
+ [Theory]
+ [InlineData("streakThreshold", "0", false)]
+ [InlineData("streakThreshold", "-5", false)]
+ [InlineData("streakThreshold", "1", true)]
+ [InlineData("streakThreshold", "1000", true)]
+ [InlineData("streakThreshold", "1001", false)]
+ [InlineData("streakWindowMinutes", "0", false)]
+ [InlineData("streakWindowMinutes", "1440", true)]
+ [InlineData("streakWindowMinutes", "1441", false)]
+ [InlineData("banDurationMinutes", "-1", false)]
+ [InlineData("banDurationMinutes", "10080", true)]
+ [InlineData("banDurationMinutes", "10081", false)]
+ [InlineData("maxTrackedSources", "0", false)]
+ [InlineData("maxTrackedSources", "1000001", false)]
+ [InlineData("ipv4KeyPrefixLength", "0", false)]
+ [InlineData("ipv4KeyPrefixLength", "7", false)]
+ [InlineData("ipv4KeyPrefixLength", "8", true)]
+ [InlineData("ipv4KeyPrefixLength", "32", true)]
+ [InlineData("ipv4KeyPrefixLength", "999", false)]
+ [InlineData("ipv6KeyPrefixLength", "31", false)]
+ [InlineData("ipv6KeyPrefixLength", "64", true)]
+ [InlineData("ipv6KeyPrefixLength", "128", true)]
+ [InlineData("ipv6KeyPrefixLength", "999", false)]
+ [InlineData("engineBlockStatus", "1", false)]
+ [InlineData("engineBlockStatus", "200", false)]
+ [InlineData("engineBlockStatus", "403", true)]
+ [InlineData("engineBlockStatus", "451", true)]
+ [InlineData("engineBlockStatus", "599", true)]
+ [InlineData("engineBlockStatus", "999", false)]
+ [InlineData("engineBlockStatus", "1000", false)]
+ [InlineData("operatorBlockStatus", "301", true)]
+ [InlineData("operatorBlockStatus", "302", false)]
+ [InlineData("operatorBlockStatus", "403", true)]
+ [InlineData("refusalRange", "not-a-range", false)]
+ [InlineData("refusalRange", "400-499", true)]
+ [InlineData("refusalRange", "499-400", false)]
+ [InlineData("refusalRange", "600-700", false)]
+ [InlineData("serverErrorRange", "500-599", true)]
+ [InlineData("serverErrorRange", "0-2000", false)]
+ public void A_policy_row_is_judged_by_the_same_numbers_the_api_uses(string key, string value, bool usable)
+ => Assert.Equal(usable, PolicyBounds.ValueOk(key, value));
+
+ [Fact]
+ public void Every_key_with_a_range_states_it_in_words_an_operator_can_act_on()
+ {
+ foreach (var key in new[]
+ {
+ "streakThreshold", "streakWindowMinutes", "banDurationMinutes", "maxTrackedSources",
+ "ipv4KeyPrefixLength", "ipv6KeyPrefixLength", "engineBlockStatus", "operatorBlockStatus",
+ "refusalRange", "serverErrorRange"
+ })
+ {
+ var range = PolicyBounds.RangeOf(key);
+ Assert.False(string.IsNullOrWhiteSpace(range), $"{key} has no range text");
+ Assert.True(range != "a defined value", $"{key} fell through to the placeholder");
+ }
+ }
+
+ [Fact]
+ public void A_prefix_of_zero_is_what_the_floor_exists_to_stop_because_it_is_one_source_for_the_whole_family()
+ {
+ // Not a claim that 0 is unreachable — it is a claim about what it means,
+ // measured on the shipped image: three addresses that had never been
+ // seen were refused on their first request once the key was "*".
+ var policy = new EdgePolicy { Ipv4KeyPrefixLength = 0 };
+ Assert.Equal("*", SourceKey.For("203.0.113.7", policy));
+ Assert.Equal("*", SourceKey.For("198.51.100.9", policy));
+
+ var honest = new EdgePolicy { Ipv4KeyPrefixLength = 8 };
+ Assert.Equal("203.0.0.0/8", SourceKey.For("203.0.113.7", honest));
+ Assert.True(
+ SourceKey.For("203.0.113.7", honest) != SourceKey.For("198.51.100.9", honest),
+ "an /8 must not merge two providers into one source");
+ }
+
+ private static EdgeSnapshot WithBan(EdgePolicy policy, string key) => new()
+ {
+ GeneratedAt = Now,
+ Policy = policy,
+ EngineBans = new Dictionary
+ {
+ [key] = new BlockEntry
+ {
+ SourceKey = key,
+ Source = BlockSource.Engine,
+ CreatedAt = Now.AddMinutes(-1),
+ ExpiresAt = Now.AddMinutes(30),
+ Reason = "3 consecutive refusals (400-499) within 5 min; last 404 /nope"
+ }
+ }
+ };
+
+ [Theory]
+ [InlineData(1000)]
+ [InlineData(1)]
+ [InlineData(0)]
+ public void A_status_the_wire_cannot_carry_is_answered_as_403_instead_of_nothing_at_all(int configured)
+ {
+ var decision = DecisionEngine.Decide(
+ WithBan(new EdgePolicy { Mode = EnforcementMode.Enforce, EngineBlockStatus = configured }, "203.0.113.7"),
+ "203.0.113.7", "/nope", Now);
+
+ Assert.Equal(EdgeVerdict.BlockEngine, decision.Verdict);
+ Assert.Equal(403, decision.StatusCode);
+ }
+
+ [Theory]
+ [InlineData(403)]
+ [InlineData(451)]
+ [InlineData(503)]
+ public void A_status_inside_the_range_is_answered_exactly_as_the_operator_wrote_it(int configured)
+ {
+ var decision = DecisionEngine.Decide(
+ WithBan(new EdgePolicy { Mode = EnforcementMode.Enforce, EngineBlockStatus = configured }, "203.0.113.7"),
+ "203.0.113.7", "/nope", Now);
+
+ Assert.Equal(EdgeVerdict.BlockEngine, decision.Verdict);
+ Assert.Equal(configured, decision.StatusCode);
+ }
+}