Files
Pavlo Ratushnyi dd10dd9839 the edge notices the netblock behind its bans and offers it as a range
A scanner farm inside one /24 is twenty engine bans and twenty operator
decisions: the streak rule works per source, and nothing in the edge connected
the rows. OPEN-66 made a range enforceable; this is the half that notices the
range is there.

The rulings:

- The evidence is the edge's own live engine bans. An operator's row is a
  decision already taken, and an expired ban is a row the edge stopped
  honouring; neither is evidence about a netblock. Nothing new is observed and
  nothing new is stored.
- An offer is not a ban. A candidate changes nothing on the wire: the operator's
  POST /admin-api/blocks with the CIDR is what enforces it, and the console
  button is that same call. Twenty honest visitors of one provider and one farm
  inside one rented block produce the same number, and only a human tells them
  apart.
- Grouping is one allocation up from the key: v4 to /24, v6 to /48, because the
  v6 streak key is already a /64 and grouping there would only repeat the key.
  The count and both prefixes are policy keys with bounds, because a host that
  hands out /22s should be shown the block it can act on.
- A ban keyed on a block wider than the netblock prefix is skipped: that row
  already claims more than a /24, and counting it as one ban inside a /24 would
  invent a candidate out of it.
- Reading the list is not news — the scan that answers the surface raises no
  alert, so refreshing a page cannot manufacture alert rows. The timer's scan
  raises netblock_candidate through the same durable alert table and push queue
  as every other kind, at most once per block per six hours, and never for a
  block the operator has already banned.
- A failed scan retires the offers instead of repeating the last ones, and
  /admin-api/state says which of off / failed / found-nothing this is.

What the run caught:

- The console's "ban this range" button posted a body with no content type, and
  the edge refused it: the button did nothing and the page looked idle rather
  than wrong. It uses the page's own postJson now, and the console gate asserts
  the row it writes, the wire answer for a source inside it, and the offer
  turning into "already banned".
- The grouping parsed ban keys with SourceKey.TryParse, which fails on the
  "2001:db8:1:2::/64" spelling the engine stores v6 bans under — so no v6 ban
  was ever grouped. Keys are parsed as keys, prefix included.
- An assertion claimed 203.0.113.137 sits under 203.0.113.128/24. That is a /25:
  the arithmetic was wrong in the test, not in the mask.

build 0 warnings / 0 errors, unit 353/353, integration 326/326 in 31 s, console
114 assertions 0 failed, smoke passed 149 failed 0, compose 293 passed 0 failed
against the built image at 262 MB.

Refs OPEN-67.
2026-10-05 07:55:06 +02:00

189 lines
9.7 KiB
C#

using OpenWaf.Domain.Policy;
namespace OpenWaf.Edge.Configuration;
/// <summary>
/// The configuration-shaped mirror of <see cref="EdgePolicy"/>. It exists
/// because <c>appsettings.json</c> is strings: <see cref="StatusRange"/> is a
/// record struct the configuration binder cannot build from "400-499", and a
/// TimeSpan written as "00:05:00" in a deployment file is friendlier than a
/// number of minutes. One explicit mapping, rather than a binder that quietly
/// leaves a default in place when the shape is wrong.
/// </summary>
internal sealed class EdgePolicyOptions
{
public string Mode { get; set; } = "Observe";
public int StreakThreshold { get; set; } = 10;
public string StreakWindow { get; set; } = "00:05:00";
public string BanDuration { get; set; } = "01:00:00";
public string RefusalRange { get; set; } = "400-499";
public string ServerErrorRange { get; set; } = "500-599";
public string Geo { get; set; } = "Off";
public bool TrustProxyHeaders { get; set; }
public int MaxTrackedSources { get; set; } = 10_000;
public int Ipv4KeyPrefixLength { get; set; } = 32;
public int Ipv6KeyPrefixLength { get; set; } = 64;
public int EngineBlockStatus { get; set; } = 403;
public int OperatorBlockStatus { get; set; } = 301;
// The volume pillar (OPEN-56). Off by default, and the limit is validated
// at startup rather than defaulted: a deployment that writes
// rateLimitPerWindow=0 meant something, and reading it as "100" or as
// "refuse everything" are both a lie about what was asked for.
public string Rate { get; set; } = "Off";
public int RateLimitPerWindow { get; set; } = 100;
public double RateWindowSeconds { get; set; } = 60;
// Where the streak counters live. Not a runtime knob: it selects which
// store the process registers at startup, so changing it is a redeploy.
// Off by default — the in-process map costs nothing on the request path,
// and a single-edge deployment loses nothing by it.
public bool SharedStreaks { get; set; }
// Empty by default: the configuration binder appends to an existing
// collection rather than replacing it, so a non-empty default here would
// leave a duplicate target in every deployment.
public string[] DefaultRedirectTargets { get; set; } = [];
// Retention is the privacy promise this project makes: aggregates about a
// source outlive the traffic that produced them by exactly this long
// (OPEN-19). It used to be a constant on the domain record, so the operator
// who wanted either end of that promise — a shorter window, or an incident
// from nine days ago that is still explainable — had no lever at all.
// Two keys, not one: an observation ages out a fact about a source, while a
// ban's evidence row stays readable after the ban itself stopped being
// live. They shared 7 days by coincidence, not by design.
// Out-of-range refuses startup rather than falling back to 7. A silently
// widened window keeps rows a month longer than the deployment asked for,
// and nothing on any surface would say so — the same class of lie this
// project keeps chasing elsewhere.
public int ObservationRetentionDays { get; set; } = 7;
public int BanRetentionDays { get; set; } = 7;
// The change log (OPEN-64) is bounded twice, and both bounds are the
// operator's: an age window, and a row cap that holds even inside the
// window. The age window alone would let a scripted churn grow the table
// without limit; the cap alone would drop last month's incident record the
// week someone did a lot of editing.
public int ChangeRetentionDays { get; set; } = 30;
public int ChangeLogMaxRows { get; set; } = 5000;
// The netblock watch (OPEN-67): how many live engine bans inside one block
// make that block worth offering the operator as a range, and how big the
// block is that they are grouped into. 0 bans is off and is a value, not a
// mistake — the watch only ever suggests. Out of range refuses startup like
// every other key here: a deployment that wrote 33 meant something, and
// reading it as 24 would be this build inventing a network nobody asked for.
public int NetblockCandidateBans { get; set; } = 5;
public int NetblockPrefixV4 { get; set; } = 24;
public int NetblockPrefixV6 { get; set; } = 48;
public const int RetentionDaysFloor = 1;
public const int RetentionDaysCeiling = 365;
public const int ChangeLogRowsFloor = 100;
public const int ChangeLogRowsCeiling = 100_000;
public EdgePolicy ToPolicy() => new()
{
Mode = Enum.TryParse<EnforcementMode>(Mode, true, out var m) ? m : EnforcementMode.Observe,
StreakThreshold = StreakThreshold > 0 ? StreakThreshold : 10,
StreakWindow = ParseWindow(StreakWindow, TimeSpan.FromMinutes(5)),
BanDuration = ParseWindow(BanDuration, TimeSpan.FromHours(1)),
RefusalRange = StatusRange.Parse(RefusalRange, new StatusRange(400, 499)),
ServerErrorRange = StatusRange.Parse(ServerErrorRange, new StatusRange(500, 599)),
Geo = Enum.TryParse<GeoMode>(Geo, true, out var g) ? g : GeoMode.Off,
TrustProxyHeaders = TrustProxyHeaders,
MaxTrackedSources = MaxTrackedSources > 0 ? MaxTrackedSources : 10_000,
Ipv4KeyPrefixLength = Ipv4KeyPrefixLength,
Ipv6KeyPrefixLength = Ipv6KeyPrefixLength,
EngineBlockStatus = EngineBlockStatus,
OperatorBlockStatus = OperatorBlockStatus,
SharedStreaks = SharedStreaks,
Rate = Enum.TryParse<RateMode>(Rate, true, out var rm) ? rm : RateMode.Off,
RateLimitPerWindow = RateWindowLimit(RateLimitPerWindow),
RateWindow = TimeSpan.FromSeconds(RateWindow(RateWindowSeconds)),
DefaultRedirectTargets = DefaultRedirectTargets.Length == 0
? new[] { "https://www.iana.org/help/example-domains" }
: DefaultRedirectTargets,
ObservationRetention = RetentionDays(ObservationRetentionDays, "OpenWaf:Policy:ObservationRetentionDays"),
BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays"),
ChangeRetention = RetentionDays(ChangeRetentionDays, "OpenWaf:Policy:ChangeRetentionDays"),
ChangeLogMaxRows = ChangeLogRows(ChangeLogMaxRows, "OpenWaf:Policy:ChangeLogMaxRows"),
NetblockCandidateBans = NetblockBans(NetblockCandidateBans, "OpenWaf:Policy:NetblockCandidateBans"),
NetblockPrefixV4 = NetblockPrefixV4Value(NetblockPrefixV4, "OpenWaf:Policy:NetblockPrefixV4"),
NetblockPrefixV6 = NetblockPrefixV6Value(NetblockPrefixV6, "OpenWaf:Policy:NetblockPrefixV6")
};
private static int RateWindowLimit(int v)
{
if (v < PolicyBounds.RateLimitPerWindowMin || v > PolicyBounds.RateLimitPerWindowMax)
throw new InvalidOperationException(
$"OpenWaf:Policy:RateLimitPerWindow must be {PolicyBounds.RangeOf("rateLimitPerWindow")}; got {v}");
return v;
}
private static double RateWindow(double v)
{
if (v < PolicyBounds.RateWindowSecondsMin || v > PolicyBounds.RateWindowSecondsMax)
throw new InvalidOperationException(
$"OpenWaf:Policy:RateWindowSeconds must be {PolicyBounds.RangeOf("rateWindowSeconds")}; got {v}");
return v;
}
/// <summary>Whole days, 1..365. Anything else is a deployment mistake and
/// is named as one at startup.</summary>
private static TimeSpan RetentionDays(int days, string configKey)
{
if (days < RetentionDaysFloor || days > RetentionDaysCeiling)
throw new InvalidOperationException(
$"{configKey} must be a whole number of days between {RetentionDaysFloor} and "
+ $"{RetentionDaysCeiling}; got {days}");
return TimeSpan.FromDays(days);
}
/// <summary>Whole rows, 100..100 000. A cap below 100 would drop the record
/// of the very edits it exists to remember, and a cap that high is not a
/// bound, it is a table the operator cannot read.</summary>
private static int ChangeLogRows(int rows, string configKey)
{
if (rows < ChangeLogRowsFloor || rows > ChangeLogRowsCeiling)
throw new InvalidOperationException(
$"{configKey} must be a whole number of rows between {ChangeLogRowsFloor} and "
+ $"{ChangeLogRowsCeiling}; got {rows}");
return rows;
}
/// <summary>0 is off and is honoured as such; anything outside the bound is
/// a deployment mistake named at startup.</summary>
private static int NetblockBans(int v, string configKey)
{
if (!PolicyBounds.NetblockCandidateBansOk(v))
throw new InvalidOperationException(
$"{configKey} must be {PolicyBounds.RangeOf("netblockCandidateBans")}; got {v}");
return v;
}
private static int NetblockPrefixV4Value(int v, string configKey)
{
if (!PolicyBounds.NetblockPrefixV4Ok(v))
throw new InvalidOperationException(
$"{configKey} must be {PolicyBounds.RangeOf("netblockPrefixV4")}; got {v}");
return v;
}
private static int NetblockPrefixV6Value(int v, string configKey)
{
if (!PolicyBounds.NetblockPrefixV6Ok(v))
throw new InvalidOperationException(
$"{configKey} must be {PolicyBounds.RangeOf("netblockPrefixV6")}; got {v}");
return v;
}
/// <summary>Accepts both <c>00:05:00</c> and a bare number of minutes.</summary>
private static TimeSpan ParseWindow(string value, TimeSpan fallback)
{
if (string.IsNullOrWhiteSpace(value)) return fallback;
if (TimeSpan.TryParse(value, out var ts)) return ts;
return double.TryParse(value, out var minutes) && minutes > 0 ? TimeSpan.FromMinutes(minutes) : fallback;
}
}