Files
Pavlo Ratushnyi 848ec1a82a an operator can ban a range, not only an address
A scanner rotating through a rented /29 used to cost one row and one write per
address: POST /admin-api/blocks answered "not an IP address" for a CIDR while
the allowlist control beside it accepted one, and the config export could not
carry the operator's answer either. A CIDR now has its own table and is enforced
by containment.

The rulings:

- One list, two shapes. GET /admin-api/blocks merges address rows and range rows
  and says which is which with `kind`; DELETE ?key= takes the CIDR as it was
  typed; ?source=engine still cannot reach an operator's range, while
  ?source=operator clears both operator shapes.
- Containment is checked on the raw peer address, the same field the allowlist is
  matched on, after the exact operator block and before the engine's own ban. The
  verdict stays block_operator, so nothing downstream had to learn a new reason;
  the decision trace names the range that answered, and an allow entry still
  outranks a range.
- What is written is normalised before it is stored: 203.0.113.37/28 is stored as
  203.0.113.32/28, a /32 or /128 is stored as the bare address it already was,
  and the full-width prefix is refused on meaning rather than on form — "0.0.0.0/0"
  covers every address there is, including the one this was written from; that is
  a shutdown, not a ban on a source.
- A request pays for the number of distinct prefix lengths, not for the number of
  ranges: the index buckets by prefix and asks a set for the request address
  masked to it, most specific first, and an expired row does not stop the search
  for a broader live one.
- Export carries ranges in the blocks section and import lands them idempotently,
  so an edge's decisions survive the move. /state counts them apart from address
  blocks, and the console prints the shape beside the row.

What the run caught:

- BlockRow read Range?.Field ?? Entry!.Field. The two rows are mutually
  exclusive, so a range with no expiry, reason or redirect — the common case —
  dereferenced the row that is not there and GET /admin-api/blocks answered 500.
- NetworkBanIndex filed a row under "a.b.c.d/24" while the lookup compared a
  masked address with no prefix, so no range ever matched: ten unit tests red
  before the bucket key was fixed to the network address alone.
- smoke and compose both wrote their JSON bodies with escaped quotes straight
  inside a command substitution, which truncates the body and answers 400 — the
  hazard this file's own header warns about. The payloads are variables now.
- Scene ordering in smoke: the range scene clears the engine's list wholesale,
  which took the expired scanner row a later scene asserts on. It runs after
  those scenes now, and says why in the file.
- Test-side, worth keeping: 203.0.113.37/28 is not the network 203.0.113.16/28
  names, so an assertion that writes one and expects the other is testing the
  mask, not the match.

build 0 warnings / 0 errors, unit 334/334, integration 312/312 in 31 s, console
105 assertions 0 failed, smoke passed 137 failed 0, compose 285 passed 0 failed
against the built image at 262 MB.

Refs OPEN-66.
2026-10-05 07:22:40 +02:00

182 lines
8.7 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. request rules — the only pillar that looks at the request
/// itself; an operator's pattern, first live match wins, and an
/// observe-action match does not stop the rest of the order from running;
/// 4. operator block — the human's list, which the toggle cannot
/// switch off;
/// 5. engine ban — enforced only in <see cref="EnforcementMode.Enforce"/>;
/// 6. geo policy — last, so an allowlisted operator inside a
/// denied country gets one defined answer: through.
///
/// A request rule sits above the two source-level lists because it is the more
/// specific claim about this request: "this path is refused" is what the request
/// is being asked, while "this source is refused" is a claim about who is
/// asking. It sits below the allowlist because the allowlist is the one thing
/// that outranks every other pillar, and an exemption that a path pattern could
/// override is not an exemption.
///
/// 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))
{
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 = string.IsNullOrWhiteSpace(clientIp) ? string.Empty : SourceKey.For(clientIp, policy);
// The request itself, which needs no address to judge. An observe match
// is remembered and the order continues: a rule that watches must not
// become an exemption for a source that is banned two steps down.
EdgeDecision? observed = null;
foreach (var rule in snapshot.RequestRules)
{
if (!rule.IsLive(now)) continue;
if (!Security.PathPattern.Matches(rule.Pattern, path)) continue;
if (rule.Action == Security.RequestRuleAction.Block)
{
return new EdgeDecision(EdgeVerdict.BlockRule, 403,
Reason: $"rule_{rule.Id}", SourceKey: key.Length == 0 ? null : key,
RulePattern: rule.Pattern);
}
// First live match wins, whatever its action — the listing an
// operator reads is the evaluation order, so a rule above another
// is the answer. A later block rule does not get to override an
// earlier observe rule; that would make the order on the page a
// decoration.
observed ??= new EdgeDecision(EdgeVerdict.PassRuleObserved,
Reason: $"rule_{rule.Id}", SourceKey: key.Length == 0 ? null : key,
RulePattern: rule.Pattern);
break;
}
if (key.Length == 0) return observed ?? 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);
}
// The operator's ranges, after the address-level entry and before the
// engine's own ban (OPEN-66). Both halves of that position are the
// ruling: a range is a human's claim about who is refused, so it outranks
// what this edge decided from responses; and it is still the operator's
// list, so the allowlist above it outranks it — an exemption inside a
// banned netblock is an exemption.
//
// Matched on the raw peer address, not on the source key, for the same
// reason the allowlist is: "198.51.100.0/24" has to mean the network the
// operator wrote, not whatever this build's key granularity groups.
if (snapshot.OperatorRanges.TryMatch(clientIp, now, out var range))
{
var (rangeStatus, rangeLocation) = BlockResponse(policy, range.RedirectTo, policy.OperatorBlockStatus);
return new EdgeDecision(EdgeVerdict.BlockOperator, rangeStatus, rangeLocation,
range.Reason, key, range.ExpiresAt, Range: range.Match);
}
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 observed ?? 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)
{
// A per-entry redirect is honoured only if it can actually be sent.
// The shipped image used to write whatever string the entry held
// straight into Location: a CRLF in there made Kestrel refuse the
// header, and the blocked request came back as 500 with no body — the
// operator's own block, accepted with 204, turned into a server error
// for that visitor. Falling back to the kind's default status is the
// defined answer for a target that arrived by a route the API did not
// police (a restored row, a hand edit).
if (Security.RedirectTarget.IsSendable(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;
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;
}
}