diff --git a/README.md b/README.md index 1e090ae..1084f4c 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,26 @@ already carries an expiry moves it — the second call means its own duration fr now — and 0 or 5,256,001 is a 400 naming the field rather than a permanent block bought by a zero in a box. +An operator's block is an address **or a netblock**. `POST /admin-api/blocks` +answered `not an IP address` for `203.0.113.96/29` while the allowlist control +beside it accepted one, so a scanner rotating through a rented /29 cost one row +and one write per address, and the operator's answer to it — one line — was not +something the config export could carry. A CIDR now has its own table and is +matched by containment 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. +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 one value refused on meaning rather than form is the full-width +prefix — `"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`. One list answers both +shapes: `GET /admin-api/blocks` merges them and says which row is which with +`kind`, `DELETE ?key=` takes the CIDR as it was typed, and `?source=engine` +still cannot reach an operator's range. A request pays for the number of +**distinct prefix lengths** in the table, not the number of ranges — the index +buckets by prefix and asks a set for the address masked to it, most specific +first — so a hundred /24s cost a request no more than one does. + Every capped listing now says how much it cut, and a limit nobody meant is refused instead of reinterpreted. `?limit=` used to be clamped: with 1,103 sources recorded, `GET /admin-api/observations?limit=100000` answered 200 with @@ -1021,9 +1041,13 @@ the runtime image is distroless with no external assets, so there is no world outline and no tile server. A geographic map would be a decoration this page could not load at the moment it is wanted. It also writes, with the two controls an incident actually reaches for: block -one address with a reason, and allowlist an address or CIDR with a note and an -optional expiry (the "my customer is locked out" control — an allow entry -outranks every ban). Each ban row has a delete that removes that row, each allow +one address or netblock with a reason, and allowlist an address or CIDR with a +note and an optional expiry (the "my customer is locked out" control — an allow +entry outranks every ban). A range row prints the CIDR it is stored under and +says `range` beside it, and the delete is the same control keyed by that name; +the summary pill counts ranges apart from address blocks (`ranges 2`), because +"how many things have I blocked" and "how many addresses" stop being the same +question once one row can be a /29. Each ban row has a delete that removes that row, each allow row a remove, and each country row a rule toggle plus — only when a rule actually exists — a "remove rule" button. An allow entry whose expiry has passed stays in the table and says "EXPIRED, the edge no longer honours it", and the pill @@ -1194,9 +1218,9 @@ On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable alert-push queue, the config transfer, the second token, the startup refusals, the change -log and that log on the console: build 0 warnings / 0 errors, unit **313/313**, -integration **298/298 in 34 s**, -console **98 assertions, 0 failed**, smoke **passed 127, failed 0**, and compose **278 passed, +log and that log on the console, and the operator's ranges: build 0 warnings / +0 errors, unit **334/334**, integration **312/312 in 31 s**, +console **105 assertions, 0 failed**, smoke **passed 137, failed 0**, and compose **285 passed, 0 failed** against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs index 4a93adc..7a78ed8 100644 --- a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs +++ b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs @@ -91,6 +91,23 @@ public static class DecisionEngine 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)) { diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionTrace.cs b/dotnet/OpenWaf.Domain/Engine/DecisionTrace.cs index fd8a560..8374eba 100644 --- a/dotnet/OpenWaf.Domain/Engine/DecisionTrace.cs +++ b/dotnet/OpenWaf.Domain/Engine/DecisionTrace.cs @@ -154,7 +154,9 @@ public static class DecisionTrace : $"an allow entry matched this address: {decision.Reason}", EdgeVerdict.BlockRule => $"a request rule blocked this path ({decision.Reason})", EdgeVerdict.PassRuleObserved => $"a request rule matched and is set to observe ({decision.Reason})", - EdgeVerdict.BlockOperator => "the operator's own list", + EdgeVerdict.BlockOperator => decision.Range is null + ? "the operator's own list" + : $"the operator's own list, a range: {decision.Range}", EdgeVerdict.BlockEngine => "a ban this edge wrote from the responses this source produced", EdgeVerdict.GeoReject => decision.Reason, EdgeVerdict.BlockRate => "over the request budget", diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs index de10922..b7c77ac 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeDecision.cs @@ -13,7 +13,12 @@ public sealed record EdgeDecision( /// The pattern that matched, for a rule verdict. The rule id is in /// Reason; the pattern is what an operator reads in the log and the alert, /// because an id means nothing without the page in front of them. - string? RulePattern = null) + string? RulePattern = null, + /// The range that covered this address, for an operator block that + /// came from a range rather than from the address itself (OPEN-66). The + /// verdict is the same claim — the operator's list refused this source — and + /// this is what makes the row that refused it findable. + string? Range = null) { public bool IsBlocked => Verdict is EdgeVerdict.BlockOperator or EdgeVerdict.BlockEngine or EdgeVerdict.GeoReject or EdgeVerdict.BlockRule; diff --git a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs index d81dff9..96d444e 100644 --- a/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs +++ b/dotnet/OpenWaf.Domain/Engine/EdgeSnapshot.cs @@ -20,6 +20,13 @@ public sealed record EdgeSnapshot = new Dictionary(StringComparer.Ordinal); public IReadOnlyDictionary EngineBans { get; init; } = new Dictionary(StringComparer.Ordinal); + /// The operator's range bans (OPEN-66), in the prefix-bucketed + /// shape the request path can afford to ask. Kept out of + /// because a range is not a key: it is a + /// containment claim, and matching it by key would answer "is this address + /// exactly this network address" rather than "is it inside it". + public NetworkBanIndex OperatorRanges { get; init; } = NetworkBanIndex.Empty; + public IReadOnlyList AllowEntries { get; init; } = []; public IReadOnlyDictionary Countries { get; init; } = new Dictionary(StringComparer.OrdinalIgnoreCase); diff --git a/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs b/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs new file mode 100644 index 0000000..686fcd2 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs @@ -0,0 +1,90 @@ +using System.Net.Sockets; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Domain.Engine; + +/// +/// The operator's range bans, arranged so that a request pays for the number of +/// distinct prefix lengths and not for the number of ranges (OPEN-66). +/// +/// The naive match is a scan: for every range, ask whether the address is inside +/// it. That is fine for three ranges and is a per-request cost that grows with +/// the operator's list, which is the shape this project refuses everywhere else. +/// Bucketing by prefix length turns each bucket into a set lookup: mask the +/// request address to that many bits and ask the set. A v4 address has 31 legal +/// prefix lengths and a v6 address 127, so the worst case is a bounded number of +/// hash lookups no matter how many rows the table holds. +/// +/// Built with the snapshot, off the request path, and never mutated in place — +/// the same rule as every other part of . +/// +public sealed class NetworkBanIndex +{ + private readonly Dictionary<(AddressFamily Family, int Prefix), Dictionary> _buckets; + + /// Bucket keys, longest prefix first, so the most specific claim + /// about this address is the one that answers. + private readonly (AddressFamily Family, int Prefix)[] _order; + + public static NetworkBanIndex Empty { get; } = new([]); + + /// How many ranges are held, live or not — the number an operator + /// counts when they ask what this edge has written. + public int Count { get; } + + public NetworkBanIndex(IEnumerable bans) + { + var buckets = new Dictionary<(AddressFamily, int), Dictionary>(); + var total = 0; + foreach (var ban in bans) + { + var prefix = NetworkBans.PrefixOf(ban.Match); + if (prefix < 0) continue; // not a CIDR this code wrote: skip, do not guess + var key = (NetworkBans.FamilyOf(ban.Match), prefix); + if (!buckets.TryGetValue(key, out var set)) + { + set = new Dictionary(StringComparer.Ordinal); + buckets[key] = set; + } + // The bucket already carries the prefix, so the row is filed under + // its network address alone — that is the string a masked request + // address is compared to. + var slash = ban.Match.IndexOf('/'); + set[slash < 0 ? ban.Match : ban.Match[..slash]] = ban; + total++; + } + + _buckets = buckets; + Count = total; + var ordered = new List<(AddressFamily Family, int Prefix)>(buckets.Keys); + ordered.Sort((a, b) => b.Prefix.CompareTo(a.Prefix)); + _order = ordered.ToArray(); + } + + /// The most specific live range that covers this address, if any. + /// An expired range answers nothing, and the search continues to a broader + /// live one rather than stopping at a dead row. + public bool TryMatch(string? address, DateTimeOffset now, out NetworkBan ban) + { + ban = null!; + if (_order.Length == 0) return false; + if (!SourceKey.TryParse(address, out _, out var normalized)) return false; + + foreach (var key in _order) + { + if (key.Family != normalized.AddressFamily) continue; + var candidate = SourceKey.Mask(normalized, key.Prefix).ToString(); + if (_buckets[key].TryGetValue(candidate, out var found) && found.IsLive(now)) + { + ban = found; + return true; + } + } + + return false; + } + + /// Whether any live range covers this address. The preview surface + /// asks this without wanting the row. + public bool Covers(string? address, DateTimeOffset now) => TryMatch(address, now, out _); +} diff --git a/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs index ad52b60..b6a91e6 100644 --- a/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs +++ b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs @@ -77,7 +77,11 @@ public static class ConfigTransfer public static string? ExplainBlock(ExportedBlock block) { if (string.IsNullOrWhiteSpace(block.Ip)) return "ip is required"; - if (!SourceKey.TryParse(block.Ip, out _, out _)) return $"not an IP address: {block.Ip}"; + // An address or a network (OPEN-66): the document that carries an + // edge's decisions has to carry the range ban too, and the guard here is + // the one POST /admin-api/blocks applies, so a row refused one at a time + // is refused in a document too. + if (!NetworkBans.TryNormalize(block.Ip, out _, out var targetProblem)) return targetProblem; if (!EntryLimits.NoteOk(block.Reason)) return $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {block.Reason!.Length}"; if (block.RedirectTo is not null && !RedirectTarget.IsSendable(block.RedirectTo)) diff --git a/dotnet/OpenWaf.Domain/Security/NetworkBan.cs b/dotnet/OpenWaf.Domain/Security/NetworkBan.cs new file mode 100644 index 0000000..c4ba86f --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/NetworkBan.cs @@ -0,0 +1,156 @@ +using System.Net.Sockets; +using OpenWaf.Domain.Engine; + +namespace OpenWaf.Domain.Security; + +// --------------------------------------------------------------------------- +// A ban on a range of addresses rather than on one (OPEN-66). +// +// The edge already understands networks in three places — the allowlist matches +// by CIDR, the volume budget groups sources by prefix, and an IPv6 streak is +// keyed on a /64 — and refused them in the one control an operator reaches for +// during an incident: `POST /admin-api/blocks` answered "not an IP address" for +// 198.51.100.0/24. A scanner rotating inside one netblock therefore cost one +// write and one row per address, and the export of an edge's decisions could not +// carry the range to another edge either. +// +// What this is NOT, stated because the difference is the design: +// +// * It is not a second kind of block with its own verdict. The verdict stays +// `block_operator`: the claim is the operator's, and a list an operator reads +// has to be one list. +// * It is not the engine's. The engine bans the source the traffic named, at +// the granularity of the streak key; a range is always written by a person or +// by an import. +// * It is not evaluated on the source key. A range is matched against the raw +// peer address, the same rule the allowlist uses, so "198.51.100.0/24" means +// what the operator wrote and not what this build's key granularity happens +// to group. +// --------------------------------------------------------------------------- + +/// One deliberate ban on a network rather than on a single address. +public sealed class NetworkBan +{ + public long Id { get; init; } + + /// The network in its one normalised CIDR spelling: "198.51.100.0/24". + /// Unique — two spellings of one network are one row. + public string Match { get; set; } = string.Empty; + + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + + /// Null means "until the operator takes it off", which is what an + /// operator's address block has always meant. + public DateTimeOffset? ExpiresAt { get; set; } + + /// The operator's own reason. Free text: read it as data. + public string? Reason { get; set; } + + /// Per-entry override for the block response, exactly as on an + /// address block: a blocked visitor inside this range is sent here. + public string? RedirectTo { get; set; } + + public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now; +} + +/// The vocabulary and the bounds of that row, as pure functions so the +/// rules a reader has to check sit in one place. +public static class NetworkBans +{ + /// Did the operator write a network rather than an address? Cheap + /// and syntactic on purpose: it decides which table the row lands in, and it + /// must not depend on the parse having happened yet. + public static bool IsRangeSyntax(string? written) => written is not null && written.Contains('/'); + + /// + /// Accept what the operator typed — an address or a CIDR — and answer with + /// the one spelling this row is stored and compared under. + /// + /// Two normalisations are part of the contract, and both exist so that one + /// claim cannot become two rows: a network is masked to its own address + /// (198.51.100.37/24 is 198.51.100.0/24), and a full-length prefix is the + /// same claim as the bare address (198.51.100.7/32 is 198.51.100.7), so it + /// lands in the address list rather than beside it. + /// + public static bool TryNormalize(string? written, out string normalized, out string error) + { + normalized = ""; + error = ""; + if (string.IsNullOrWhiteSpace(written)) + { + error = "ip is required"; + return false; + } + + var text = written.Trim(); + var slash = text.IndexOf('/'); + if (slash < 0) + { + if (!SourceKey.TryParse(text, out _, out var single)) + { + error = $"not an IP address: {written}"; + return false; + } + normalized = single.ToString(); + return true; + } + + var networkPart = text[..slash]; + var prefixPart = text[(slash + 1)..]; + if (!SourceKey.TryParse(networkPart, out _, out var network)) + { + error = $"not an IP address: {networkPart} in \"{written}\""; + return false; + } + if (!int.TryParse(prefixPart, out var prefix)) + { + error = $"the prefix after \"/\" must be a whole number of bits; got \"{written}\""; + return false; + } + + var max = network.AddressFamily == AddressFamily.InterNetwork ? 32 : 128; + if (prefix < 0 || prefix > max) + { + error = $"the prefix must be 0..{max} for this address family; got \"{text}\""; + return false; + } + // The one value refused on meaning rather than on form. A /0 is not a + // claim about a source: it is every address there is, including the one + // this was written from, and it grows the block list into a shutdown the + // operator cannot see past. The control for "stop everything" is not a + // ban on a source. + if (prefix == 0) + { + error = $"\"{text}\" covers every address there is, including the one this was written from; " + + "that is a shutdown, not a ban on a source"; + return false; + } + + // A prefix that names one address is that address, written twice. + if (prefix == max) + { + normalized = network.ToString(); + return true; + } + + normalized = $"{SourceKey.Mask(network, prefix)}/{prefix}"; + return true; + } + + /// The family a normalised match belongs to, for the index that + /// buckets by prefix length. + public static AddressFamily FamilyOf(string normalizedMatch) + { + var slash = normalizedMatch.IndexOf('/'); + var host = slash < 0 ? normalizedMatch : normalizedMatch[..slash]; + return System.Net.IPAddress.TryParse(host, out var ip) + ? ip.AddressFamily + : AddressFamily.InterNetwork; + } + + public static int PrefixOf(string normalizedMatch) + { + var slash = normalizedMatch.IndexOf('/'); + return slash < 0 || !int.TryParse(normalizedMatch[(slash + 1)..], out var prefix) ? -1 : prefix; + } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index eb433c3..6962681 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -95,7 +95,7 @@ internal static class AdminConsole no token
- + @@ -288,6 +288,12 @@ async function load() { el('blocknote').textContent = blocksRes.truncated ? 'showing the newest ' + blocks.length + ' of ' + blocksRes.total + ' — clearing by provenance removes all ' + blocksRes.total + ', not just this page' : blocksRes.total + (blocksRes.total === '1' ? ' entry' : ' entries'); + // A row here can be a network rather than an address (OPEN-66), and the two + // are not the same claim: one refuses one source, the other refuses every + // address inside it. The line says which shape the table holds and what + // outranks it, because the alternative is an operator reading a /24 as a row + // of the same size as any other. + el('blocknote').textContent += ' \u00b7 a range row refuses every address inside it, and an allow entry still outranks it'; // The observation listing is capped too, and it is the table an operator // reads to decide which sources the edge has actually seen. Until the API // said how many there are, "newest 25" and "the whole window" looked the @@ -359,6 +365,10 @@ async function load() { 'tracked ' + esc(state.trackedSources) + ' ' + 'engine bans ' + esc(state.engineBans) + ' ' + 'operator blocks ' + esc(state.operatorBlocks) + ' ' + + // Counted apart from the blocks on purpose: one range row can be a + // thousand addresses, so a single number mixing the two answers neither + // "how many decisions did I write" nor "how wide are they". + 'ranges ' + esc(state.operatorRanges) + ' ' + // Live exemptions, not rows: the pill used to count rows, which is how a // page could say "allow entries 1" about an exemption the edge had // already stopped honouring. @@ -377,7 +387,13 @@ async function load() { : 'geo database not loaded'); el('mode').value = state.mode; el('blocks').tBodies[0].innerHTML = (blocks || []).map((b) => row([ - { h: srcBtn(b.sourceKey) }, { v: b.source }, { v: b.reason }, + // A range is not a source, so it is not offered as a filter question: the + // observations table holds addresses, and clicking a /24 would ask for a + // source that can never be there. + { h: b.kind === 'range' + ? esc(b.sourceKey) + ' range' + : srcBtn(b.sourceKey) }, + { v: b.source }, { v: b.reason }, { v: b.live ? (b.expiresAt || '').replace('T', ' ').slice(0, 19) : 'expired' }, { v: (b.lastStatusCode || '') + ' ' + (b.lastPath || ''), n: true }, { h: '' } diff --git a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs index afec9a4..694ea51 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminDtos.cs @@ -1,4 +1,5 @@ using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Edge.Admin; @@ -6,6 +7,11 @@ internal sealed record BlockDto( long Id, string SourceKey, string Source, + /// "address" or "range" (OPEN-66). One list, two shapes, and the + /// row has to say which it is: a /24 that refuses every visitor inside it is + /// not a narrower claim than one address, and a page that draws them the same + /// way teaches an operator to mis-read their own list. + string Kind, DateTimeOffset CreatedAt, DateTimeOffset? ExpiresAt, bool Live, @@ -125,7 +131,17 @@ internal sealed record ObservationDto( internal static class DtoMapper { public static BlockDto ToDto(this BlockEntry b, DateTimeOffset now) => new( - b.Id, b.SourceKey, b.Source == BlockSource.Operator ? "operator" : "engine", + b.Id, b.SourceKey, b.Source == BlockSource.Operator ? "operator" : "engine", "address", b.CreatedAt, b.ExpiresAt, b.IsLive(now), b.Reason, b.RedirectTo, b.ConsecutiveRefusals, b.LastStatusCode, b.LastPath, b.LastUserAgent, b.LastCountryCode, b.LastCity); + + // The operator's list is one list (OPEN-66), so the row shape is one shape + // whichever table it came from. A range carries no per-source evidence — + // there is no source behind it yet — so those fields are null rather than + // invented. + public static BlockDto ToDto(this BlockStore.BlockRow row, DateTimeOffset now) => new( + row.Id, row.Target, row.Source, row.IsRange ? "range" : "address", + row.CreatedAt, row.ExpiresAt, row.IsLive(now), row.Reason, row.RedirectTo, + row.Entry?.ConsecutiveRefusals, row.Entry?.LastStatusCode, row.Entry?.LastPath, + row.Entry?.LastUserAgent, row.Entry?.LastCountryCode, row.Entry?.LastCity); } diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs index cd09e2c..0ba3be5 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs @@ -61,6 +61,16 @@ internal static partial class AdminEndpoints .OrderBy(b => b.SourceKey) .Select(b => new { b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt }) .ToListAsync(ct); + // A range ban travels in the same section as an address block + // (OPEN-66), because it is the same kind of claim — the operator's — + // and a document whose blocks section means "the operator's blocks + // except the wide ones" is a document that has to be read twice to be + // trusted. The expiry ruling is identical: an instant, not a duration. + var rangeRows = await db.NetworkBans.AsNoTracking() + .Where(b => b.ExpiresAt == null || b.ExpiresAt > now) + .OrderBy(b => b.Match) + .Select(b => new { b.Match, b.Reason, b.RedirectTo, b.ExpiresAt }) + .ToListAsync(ct); var engineLeftBehind = await db.Blocks.AsNoTracking() .CountAsync(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now), ct); @@ -91,7 +101,7 @@ internal static partial class AdminEndpoints edgeId = Environment.MachineName, counts = new { - blocks = blockRows.Count, + blocks = blockRows.Count + rangeRows.Count, allow = allowRows.Count, rules = ruleRows.Count, countries = countryRows.Count @@ -105,7 +115,8 @@ internal static partial class AdminEndpoints p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus, p.OperatorBlockStatus, p.DefaultRedirectTargets.ToArray(), p.Rate.ToString(), p.RateLimitPerWindow, p.RateWindow.TotalSeconds), - blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt)), + blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt)) + .Concat(rangeRows.Select(b => new ExportedBlock(b.Match, b.Reason, b.RedirectTo, b.ExpiresAt))), allow = allowRows.Select(a => new ExportedAllow(a.Match, a.Note, a.ExpiresAt)), rules = ruleRows.Select(r => new ExportedRule( r.Pattern, r.Action.ToString().ToLowerInvariant(), r.Note, r.ExpiresAt)), diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index ac46f14..c2f8a8a 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -73,7 +73,7 @@ internal static partial class AdminEndpoints if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes)) return Results.BadRequest(new { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}" }); - var (added, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, + var (added, error, target) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, req.ExpiresInMinutes, DateTimeOffset.UtcNow, ct); // Two different failures used to arrive as the same 400. A rejected // input and a storage failure are not the same event: one is fixed @@ -90,8 +90,11 @@ internal static partial class AdminEndpoints // instead of it: a rule the operator believes they have is the worse // failure, so a record that cannot be written is counted and the // request still answers what it means. + // The normalised spelling, not what was typed: 198.51.100.37/24 and + // 198.51.100.0/24 are one row, and a change log that recorded both + // spellings would be a log an operator cannot match the table against. await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionAdded, - req.Ip, req.Reason, ct: ct); + target ?? req.Ip, req.Reason, ct: ct); return Results.NoContent(); }); @@ -113,7 +116,12 @@ internal static partial class AdminEndpoints return StorageUnavailable("the block list could not be read or written: NOTHING was deleted"); if (n > 0) await changes.RecordAsync(ConfigChangeLog.SectionBlocks, ConfigChangeLog.ActionRemoved, - key ?? parsed?.ToString().ToLowerInvariant() ?? "all", $"deleted {n}", ct: ct); + // The spelling the row was stored under, so the record of the + // removal names the same target the record of the add did. + key is not null && NetworkBans.TryNormalize(key, out var removed, out _) + ? removed + : key ?? parsed?.ToString().ToLowerInvariant() ?? "all", + $"deleted {n}", ct: ct); return Results.Ok(new { deleted = n }); }); @@ -761,6 +769,10 @@ note = t.Note snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1), trackedSources = tracker.TrackedCount, operatorBlocks = state.Current.OperatorBlocks.Count, + // Ranges are counted apart because they are not comparable: one row + // here can be a thousand addresses, and a number that mixes them + // answers neither "how many things did I write" nor "how wide is it". + operatorRanges = state.Current.OperatorRanges.Count, engineBans = state.Current.EngineBans.Count, // The count of exemptions the engine is honouring, not the count of // rows. Measured on the shipped image: one minute after the edge @@ -861,6 +873,7 @@ note = t.Note // that predates the feature has every other table, and "no rules" // and "the rules table is not there" have to be different answers. requestRulesAvailable = state.RulesAvailable, + operatorRangesAvailable = state.RangesAvailable, requestRulesError = state.RulesError, // The schema this edge is serving against (OPEN-55). A database that // predates a table used to be invisible: the pillar it needs answered diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs index 37bcbcc..9258b73 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -313,14 +313,20 @@ public sealed class BlockStore /// row already had — for a new row, that is no expiry, which is what every /// operator block written before OPEN-51 was. /// - public async Task<(AddResult Result, string? Error)> AddOperatorAsync( - string sourceKey, string? reason, string? redirectTo, int? expiresInMinutes, + public async Task<(AddResult Result, string? Error, string? Target)> AddOperatorAsync( + string written, string? reason, string? redirectTo, int? expiresInMinutes, DateTimeOffset now, CancellationToken ct = default) { - if (!SourceKey.TryParse(sourceKey, out _, out var normalized)) - return (AddResult.InvalidInput, $"not an IP address: {sourceKey}"); + // One control, two shapes (OPEN-66). What the operator typed is either an + // address or a network, and the answer says which one it stored, because + // 198.51.100.37/24 and 198.51.100.0/24 are one row and the operator has + // to be able to find it under the spelling the edge kept. + if (!NetworkBans.TryNormalize(written, out var normalized, out var inputError)) + return (AddResult.InvalidInput, inputError, null); + if (NetworkBans.IsRangeSyntax(normalized)) + return await AddRangeAsync(normalized, reason, redirectTo, expiresInMinutes, now, ct); - var key = SourceKey.For(normalized.ToString(), _policy.Current); + var key = SourceKey.For(normalized, _policy.Current); for (var attempt = 0; attempt < 2; attempt++) { @@ -352,7 +358,7 @@ public sealed class BlockStore } await db.SaveChangesAsync(ct); await _state.InvalidateAsync(ct); - return (AddResult.Ok, null); + return (AddResult.Ok, null, normalized); } catch (DbUpdateException ex) when (attempt == 0) { @@ -366,11 +372,71 @@ public sealed class BlockStore // got the same 400 and moved on, while the block they typed was // never in effect. _log.LogWarning(ex, "BlockStore: add operator block failed for {Key}.", key); - return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null); } } - return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null); + } + + /// + /// Put a network behind an operator block (OPEN-66). + /// + /// Same shape as the address write, on purpose: the same two attempts + /// against a unique index, the same "a write that cannot run is not a + /// success", the same expiry rules. The only difference is the key — a + /// normalised network rather than a source key — and that difference is why + /// this is a separate table: the exact-key lookup that enforces an address + /// block would read "198.51.100.0/24" as an address and answer "no" to every + /// visitor inside the range. + /// + private async Task<(AddResult Result, string? Error, string? Target)> AddRangeAsync( + string match, string? reason, string? redirectTo, int? expiresInMinutes, + DateTimeOffset now, CancellationToken ct) + { + for (var attempt = 0; attempt < 2; attempt++) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.NetworkBans.FirstOrDefaultAsync(b => b.Match == match, ct); + if (row is null) + { + db.NetworkBans.Add(new NetworkBan + { + Match = match, + CreatedAt = now, + Reason = reason, + RedirectTo = redirectTo, + ExpiresAt = expiresInMinutes is { } fresh ? now.AddMinutes(fresh) : null + }); + } + else + { + row.Reason = reason ?? row.Reason; + row.RedirectTo = redirectTo ?? row.RedirectTo; + // Re-writing a range with a duration moves the expiry, exactly + // as it does for an address: the operator who types "240" a + // second time means two hundred and forty minutes from now. + if (expiresInMinutes is { } again) row.ExpiresAt = now.AddMinutes(again); + } + await db.SaveChangesAsync(ct); + await _state.InvalidateAsync(ct); + return (AddResult.Ok, null, match); + } + catch (DbUpdateException ex) when (attempt == 0) + { + _log.LogWarning(ex, "BlockStore: concurrent add on the range {Match}; retrying against the winner's row.", match); + } + catch (Exception ex) + { + _log.LogWarning(ex, "BlockStore: add of the range {Match} failed.", match); + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null); + } + } + + return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect", null); } /// What an imported operator block ended as. Different from @@ -394,10 +460,12 @@ public sealed class BlockStore string address, string? reason, string? redirectTo, DateTimeOffset? expiresAt, DateTimeOffset now, CancellationToken ct = default) { - if (!SourceKey.TryParse(address, out _, out var normalized)) + if (!NetworkBans.TryNormalize(address, out var normalized, out _)) return (ImportResult.StorageFailure, $"not an IP address: {address}"); + if (NetworkBans.IsRangeSyntax(normalized)) + return await ImportRangeAsync(normalized, reason, redirectTo, expiresAt, now, ct); - var key = SourceKey.For(normalized.ToString(), _policy.Current); + var key = SourceKey.For(normalized, _policy.Current); for (var attempt = 0; attempt < 2; attempt++) { @@ -436,6 +504,49 @@ public sealed class BlockStore return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); } + /// Land one range from a transferred document. The expiry is the + /// instant the document carried, and a live row for the same network is not + /// refreshed — the same two rulings as the address import, for the same + /// reason (OPEN-61, OPEN-66). + private async Task<(ImportResult Result, string? Error)> ImportRangeAsync( + string match, string? reason, string? redirectTo, DateTimeOffset? expiresAt, + DateTimeOffset now, CancellationToken ct) + { + for (var attempt = 0; attempt < 2; attempt++) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var live = await db.NetworkBans.AnyAsync( + b => b.Match == match && (b.ExpiresAt == null || b.ExpiresAt > now), ct); + if (live) return (ImportResult.AlreadyThere, null); + + db.NetworkBans.Add(new NetworkBan + { + Match = match, + CreatedAt = now, + Reason = reason, + RedirectTo = redirectTo, + ExpiresAt = expiresAt + }); + await db.SaveChangesAsync(ct); + return (ImportResult.Added, null); + } + catch (DbUpdateException ex) when (attempt == 0) + { + _log.LogWarning(ex, "BlockStore: concurrent import on the range {Match}; retrying against the winner's row.", match); + } + catch (Exception ex) + { + _log.LogWarning(ex, "BlockStore: import of the range {Match} failed.", match); + return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + } + } + + return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + } + /// /// Delete blocks, optionally restricted to one provenance. The provenance /// filter is not cosmetic: "clear the automatic bans" must never be able to @@ -461,10 +572,36 @@ public sealed class BlockStore { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + var n = 0; + + if (NetworkBans.IsRangeSyntax(sourceKey)) + { + // A range asked for by name. It can only ever be an operator's + // row — the engine does not write ranges — so the provenance the + // caller named is checked rather than assumed. + if (source is BlockSource.Engine) + return (DeleteResult.Ok, 0); + var normalized = NetworkBans.TryNormalize(sourceKey!, out var match, out _) + ? match + : sourceKey!; + n += await db.NetworkBans.Where(b => b.Match == normalized).ExecuteDeleteAsync(ct); + await _state.InvalidateAsync(ct); + return (DeleteResult.Ok, n); + } + var q = db.Blocks.AsQueryable(); if (source is not null) q = q.Where(b => b.Source == source.Value); if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey); - var n = await q.ExecuteDeleteAsync(ct); + n += await q.ExecuteDeleteAsync(ct); + + // The listing is one list, so a clear that names the operator's list + // has to clear both shapes of it: answering "deleted 4" while a /24 + // is still refusing visitors inside it is the same lie as reporting an + // empty table that still enforces something. Engine clears never touch + // a range — the engine did not write one. + if (string.IsNullOrWhiteSpace(sourceKey) && source is not BlockSource.Engine) + n += await db.NetworkBans.ExecuteDeleteAsync(ct); + await _state.InvalidateAsync(ct); return (DeleteResult.Ok, n); } @@ -484,20 +621,61 @@ public sealed class BlockStore public const int ListDefaultLimit = 500; public const int ListMaxLimit = 2000; - public async Task> ListAsync(BlockSource? source, bool liveOnly, DateTimeOffset now, + /// One row of the operator's list, whichever table it came from. + /// The listing an operator reads is one list (OPEN-66), so the merge happens + /// here rather than in every caller that would otherwise have to know there + /// are two tables behind one page. + public sealed record BlockRow(BlockEntry? Entry, NetworkBan? Range) + { + // Every accessor picks a row first and then reads the field. The shorter + // `Range?.Field ?? Entry!.Field` is a trap here and threw in the listing: + // the two rows are mutually exclusive, so whenever the range's field is + // null — a range with no expiry, no reason, no redirect, which is the + // common case — the fallback dereferences the row that does not exist. + public bool IsRange => Range is not null; + public long Id => Range is not null ? Range.Id : Entry!.Id; + /// What the operator wrote, in the spelling the edge kept. + public string Target => Range is not null ? Range.Match : Entry!.SourceKey; + public DateTimeOffset CreatedAt => Range is not null ? Range.CreatedAt : Entry!.CreatedAt; + public DateTimeOffset? ExpiresAt => Range is not null ? Range.ExpiresAt : Entry!.ExpiresAt; + public string? Reason => Range is not null ? Range.Reason : Entry!.Reason; + public string? RedirectTo => Range is not null ? Range.RedirectTo : Entry!.RedirectTo; + public string Source => Range is not null ? "operator" : Entry!.Source.ToString().ToLowerInvariant(); + public bool IsLive(DateTimeOffset now) + => (Range is not null ? Range.ExpiresAt : Entry!.ExpiresAt) is not { } expiry || expiry > now; + } + + public async Task> ListAsync(BlockSource? source, bool liveOnly, DateTimeOffset now, int limit = ListDefaultLimit, int offset = 0, CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var q = Filtered(db, source, liveOnly, now); - return await q.OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct); + var blocks = await q.OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct); + + // Ranges are read with the same window rather than re-filtered per page: + // the two tables are small by design, and ordering the union needs both + // sides of the cut. Anything past offset+limit is not shown either way. + var ranges = source == BlockSource.Engine + ? [] + : await FilteredRanges(db, liveOnly, now) + .OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct); + + return blocks.Select(b => new BlockRow(b, null)) + .Concat(ranges.Select(r => new BlockRow(null, r))) + .OrderByDescending(r => r.CreatedAt) + .ToList(); } public async Task CountAsync(BlockSource? source, bool liveOnly, DateTimeOffset now, CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - return await Filtered(db, source, liveOnly, now).CountAsync(ct); + var blocks = await Filtered(db, source, liveOnly, now).CountAsync(ct); + var ranges = source == BlockSource.Engine + ? 0 + : await FilteredRanges(db, liveOnly, now).CountAsync(ct); + return blocks + ranges; } private static IQueryable Filtered(OpenWafDbContext db, BlockSource? source, bool liveOnly, DateTimeOffset now) @@ -507,4 +685,13 @@ public sealed class BlockStore if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now); return q; } + + /// Ranges are always the operator's, so the provenance filter has + /// one answer for them: an engine filter matches nothing. + private static IQueryable FilteredRanges(OpenWafDbContext db, bool liveOnly, DateTimeOffset now) + { + var q = db.NetworkBans.AsNoTracking().AsQueryable(); + if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now); + return q; + } } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index 71d8411..2e7a93e 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -70,6 +70,15 @@ public sealed class EdgeStateStore /// so — see . public bool RulesAvailable { get; private set; } = true; + /// Whether the operator's range bans (OPEN-66) could be read on the + /// last refresh. Same rule as the rules flag: a database that predates the + /// table enforces everything it has and says what it cannot see. + public bool RangesAvailable { get; private set; } = true; + + public string? RangesError => Volatile.Read(ref _rangesError); + + private string? _rangesError; + /// Why the rules could not be read, for the operator surface. public string? RulesError => Volatile.Read(ref _rulesError); @@ -164,6 +173,26 @@ public sealed class EdgeStateStore else engineBans[b.SourceKey] = b; } + // The range read stands alone for the same reason the rule read does: + // `network_bans` is the newest table in the schema, and a database + // created before it has every other table. Failing this read must not + // take a ban written a minute ago down with it. + NetworkBanIndex ranges; + try + { + ranges = new NetworkBanIndex(await db.NetworkBans.AsNoTracking().ToListAsync(ct)); + RangesAvailable = true; + Volatile.Write(ref _rangesError, null); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + ranges = NetworkBanIndex.Empty; + RangesAvailable = false; + Volatile.Write(ref _rangesError, ex.Message); + _log.LogWarning(ex, + "EdgeStateStore: the range-ban table could not be read; enforcing the rest of the list without it."); + } + var countryMap = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var c in countries) countryMap[c.Code] = c; @@ -178,7 +207,8 @@ public sealed class EdgeStateStore EngineBans = engineBans, AllowEntries = allow, Countries = countryMap, - RequestRules = rules + RequestRules = rules, + OperatorRanges = ranges }; } catch (Exception ex) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.Designer.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.Designer.cs new file mode 100644 index 0000000..d7af4b6 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.Designer.cs @@ -0,0 +1,516 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenWaf.Infrastructure.Persistence; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(OpenWafDbContext))] + [Migration("20261005043615_AddNetworkBans")] + partial class AddNetworkBans + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("OpenWaf.Domain.Policy.CountryRule", b => + { + b.Property("Code") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("IsAllowed") + .HasColumnType("boolean"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Code"); + + b.ToTable("country_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AlertPush", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AlertCreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AlertId") + .HasColumnType("bigint"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ClaimedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ClaimedBy") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("GivenUpAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastError") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PushedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("AlertId"); + + b.HasIndex("PushedAt", "GivenUpAt", "NextAttemptAt"); + + b.ToTable("alert_pushes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.AllowEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("allow_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.BlockEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("SourceKey", "Source") + .IsUnique(); + + b.ToTable("block_entries", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.ConfigChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Section") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("At"); + + b.HasIndex("Section"); + + b.ToTable("config_changes", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.EdgeAlert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Detail") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastPath") + .HasColumnType("text"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("SourceKey") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.ToTable("edge_alerts", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.NetworkBan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("network_bans", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Note") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Pattern"); + + b.ToTable("request_rules", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceObservation", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("FirstSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("TotalServerErrorStreak") + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_observations", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Domain.Security.SourceStreak", b => + { + b.Property("SourceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("ConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("LastAlertedRefusals") + .HasColumnType("integer"); + + b.Property("LastAlertedServerErrors") + .HasColumnType("integer"); + + b.Property("LastCity") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastCountryCode") + .HasMaxLength(2) + .HasColumnType("character varying(2)"); + + b.Property("LastPath") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("LastRefusalAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastRegion") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastSeenAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStatusCode") + .HasColumnType("integer"); + + b.Property("LastUserAgent") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("MaxConsecutiveRefusals") + .HasColumnType("integer"); + + b.Property("MaxConsecutiveServerErrors") + .HasColumnType("integer"); + + b.Property("TotalRefusals") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("SourceKey"); + + b.HasIndex("LastSeenAt"); + + b.ToTable("source_streaks", (string)null); + }); + + modelBuilder.Entity("OpenWaf.Infrastructure.Persistence.PolicySetting", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.ToTable("policy_settings", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.cs new file mode 100644 index 0000000..4d33e83 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/20261005043615_AddNetworkBans.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace OpenWaf.Infrastructure.Persistence.Migrations +{ + /// + public partial class AddNetworkBans : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "network_bans", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Match = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + ExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + Reason = table.Column(type: "character varying(1024)", maxLength: 1024, nullable: true), + RedirectTo = table.Column(type: "character varying(512)", maxLength: 512, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_network_bans", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_network_bans_ExpiresAt", + table: "network_bans", + column: "ExpiresAt"); + + migrationBuilder.CreateIndex( + name: "IX_network_bans_Match", + table: "network_bans", + column: "Match", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "network_bans"); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs index bfe086a..87635fe 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Migrations/OpenWafDbContextModelSnapshot.cs @@ -299,6 +299,43 @@ namespace OpenWaf.Infrastructure.Persistence.Migrations b.ToTable("edge_alerts", (string)null); }); + modelBuilder.Entity("OpenWaf.Domain.Security.NetworkBan", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Match") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)"); + + b.Property("RedirectTo") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("Match") + .IsUnique(); + + b.ToTable("network_bans", (string)null); + }); + modelBuilder.Entity("OpenWaf.Domain.Security.RequestRule", b => { b.Property("Id") diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs index af1b65c..7dd13cd 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs @@ -5,7 +5,7 @@ using OpenWaf.Domain.Security; namespace OpenWaf.Infrastructure.Persistence; /// -/// Ten tables, all small. The edge never queries them on the request path — +/// Eleven tables, all small. The edge never queries them on the request path — /// holds the snapshot it reads — so the schema is /// sized for operator inspection and for explaining a ban after the fact, not /// for throughput. @@ -22,6 +22,7 @@ public sealed class OpenWafDbContext(DbContextOptions options) public DbSet RequestRules => Set(); public DbSet AlertPushes => Set(); public DbSet ConfigChanges => Set(); + public DbSet NetworkBans => Set(); protected override void OnModelCreating(ModelBuilder mb) { @@ -46,6 +47,25 @@ public sealed class OpenWafDbContext(DbContextOptions options) e.Property(b => b.Source).HasConversion(); }); + mb.Entity(e => + { + // A ban on a network rather than an address (OPEN-66). Its own table + // rather than a flag on block_entries: block_entries is keyed on the + // source key, and a range is not a key — the exact-key lookup that + // enforces an address block would answer "is this address exactly + // this network address", which is not the question. + e.ToTable("network_bans"); + e.HasKey(b => b.Id); + // One row per normalised network: 198.51.100.37/24 and + // 198.51.100.0/24 are one claim, and two rows for it is two rows an + // operator has to notice and remove. + e.HasIndex(b => b.Match).IsUnique(); + e.HasIndex(b => b.ExpiresAt); + e.Property(b => b.Match).HasMaxLength(64).IsRequired(); + e.Property(b => b.Reason).HasMaxLength(1024); + e.Property(b => b.RedirectTo).HasMaxLength(512); + }); + mb.Entity(e => { // The change log (OPEN-64): one row per deliberate change to the diff --git a/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs b/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs new file mode 100644 index 0000000..bd4f348 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs @@ -0,0 +1,378 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// An operator can ban a range, not only an address (OPEN-66). +/// +/// The edge already understood networks in three places — the allowlist matches +/// by CIDR, the volume budget groups sources by prefix, an IPv6 streak is keyed +/// on a /64 — and refused them in the one control an operator reaches for during +/// an incident: POST /admin-api/blocks answered "not an IP address" for a +/// /24. So a scanner rotating inside one netblock cost one write and one row per +/// address, and the export of an edge's decisions could not carry the range to +/// another edge. +/// +/// What these tests hold the feature to, in order: a range is a block and is +/// enforced by containment; one range is one row however it is spelled; the +/// operator's list stays one list for reading, for deleting by name and for +/// clearing by provenance; a range that covers every address is refused on +/// meaning rather than on form; and the range travels. +/// +public sealed class NetworkBanTests +{ + private const string Range = "203.0.113.16/28"; // .16 – .31 + private const string Inside = "203.0.113.21"; + private const string AlsoInside = "203.0.113.30"; + private const string Outside = "203.0.113.32"; + private const string Address = "203.0.113.44"; + + private static async Task GetAsync(EdgeFixture f, string path, string ip) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + return await f.Client.SendAsync(request); + } + + private static async Task<(HttpStatusCode Status, string Body)> BlockAsync(EdgeFixture f, object body) + { + using var response = await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", body); + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } + + private static async Task> RowsAsync(EdgeFixture f) + { + using var response = await f.Client.GetAsync( + $"/admin-api/blocks?live=false&token={EdgeFixture.AdminToken}"); + var body = await response.Content.ReadAsStringAsync(); + Assert.True(response.StatusCode == HttpStatusCode.OK, $" {(int)response.StatusCode}: {body}"); + return JsonDocument.Parse(body) + .RootElement.EnumerateArray().ToList(); + } + + [Fact] + public async Task A_CIDR_is_a_block_and_the_listing_says_which_shape_it_is() + { + await using var f = new EdgeFixture(); + var (status, _) = await BlockAsync(f, new { ip = Range, reason = "netblock scanning /wp-login" }); + Assert.Equal(HttpStatusCode.NoContent, status); + + // Enforced on containment, not on the address the operator typed: two + // different sources inside the range are both refused, and the neighbour + // one address past its end is served. + using (var first = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, first.StatusCode); + using (var second = await GetAsync(f, "/anything", AlsoInside)) + Assert.Equal(HttpStatusCode.MovedPermanently, second.StatusCode); + using (var outside = await GetAsync(f, "/anything", Outside)) + Assert.Equal(HttpStatusCode.NotFound, outside.StatusCode); + + var rows = await RowsAsync(f); + var row = Assert.Single(rows, r => r.GetProperty("sourceKey").GetString() == Range); + Assert.Equal("range", row.GetProperty("kind").GetString()); + Assert.Equal("operator", row.GetProperty("source").GetString()); + Assert.True(row.GetProperty("live").GetBoolean()); + Assert.Contains("netblock", row.GetProperty("reason").GetString()); + + // The address rows still say what they are; the marker is not a column + // that only one shape of the list can answer. + var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); + Assert.Equal(HttpStatusCode.NoContent, addressStatus); + var addressRow = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Address); + Assert.Equal("address", addressRow.GetProperty("kind").GetString()); + } + + [Fact] + public async Task One_range_is_one_row_however_it_is_spelled() + { + await using var f = new EdgeFixture(); + var (first, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "written sloppily" }); + Assert.Equal(HttpStatusCode.NoContent, first); + var (second, _) = await BlockAsync(f, new { ip = Range, reason = "the same network" }); + Assert.Equal(HttpStatusCode.NoContent, second); + + // Masked to the network address, and the second write found the first + // row rather than standing beside it. + var rows = await RowsAsync(f); + Assert.Equal(1, rows.Count(r => r.GetProperty("kind").GetString() == "range")); + var row = rows.Single(r => r.GetProperty("kind").GetString() == "range"); + Assert.Equal(Range, row.GetProperty("sourceKey").GetString()); + Assert.Equal("the same network", row.GetProperty("reason").GetString()); + } + + [Fact] + public async Task A_prefix_that_names_one_address_is_that_address_and_not_a_second_row() + { + await using var f = new EdgeFixture(); + var (status, _) = await BlockAsync(f, new { ip = "203.0.113.44/32", reason = "one host, written as a range" }); + Assert.Equal(HttpStatusCode.NoContent, status); + + var row = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Address); + Assert.Equal("address", row.GetProperty("kind").GetString()); + using (var blocked = await GetAsync(f, "/anything", Address)) + Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); + } + + [Fact] + public async Task A_range_over_every_address_is_refused_and_says_why() + { + await using var f = new EdgeFixture(); + foreach (var (written, expected) in new[] { ("0.0.0.0/0", "every address"), ("::/0", "every address") }) + { + var (status, body) = await BlockAsync(f, new { ip = written, reason = "shutdown dressed as a ban" }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains(expected, body); + } + + // A refusal is a refusal: nothing was written, and the edge still serves. + Assert.Empty(await RowsAsync(f)); + using (var served = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); + } + + [Fact] + public async Task A_malformed_range_is_refused_by_name() + { + await using var f = new EdgeFixture(); + foreach (var written in new[] { "203.0.113.0/33", "203.0.113.0/-1", "203.0.113.0/abc", "not-an-ip/24" }) + { + var (status, body) = await BlockAsync(f, new { ip = written, reason = "typo" }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains(written, body); + } + Assert.Empty(await RowsAsync(f)); + } + + [Fact] + public async Task An_allow_entry_inside_a_banned_range_still_exempts() + { + await using var f = new EdgeFixture(); + var (blocked, _) = await BlockAsync(f, new { ip = Range, reason = "the whole netblock" }); + Assert.Equal(HttpStatusCode.NoContent, blocked); + using (var inside = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); + + using (var allow = await f.Client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", + new { match = Inside, note = "the one customer in that block" })) + Assert.Equal(HttpStatusCode.NoContent, allow.StatusCode); + + // The exemption outranks the range exactly as it outranks an address + // block, and the rest of the range stays banned. + using (var exempt = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, exempt.StatusCode); + using (var neighbour = await GetAsync(f, "/anything", AlsoInside)) + Assert.Equal(HttpStatusCode.MovedPermanently, neighbour.StatusCode); + } + + [Fact] + public async Task A_range_is_removed_by_name_and_the_count_says_what_was_removed() + { + await using var f = new EdgeFixture(); + var (status, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "typed sloppily" }); + Assert.Equal(HttpStatusCode.NoContent, status); + using (var inside = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); + + // Deleting it by the spelling the operator typed finds the row the edge + // stored, which is the masked one. + using var deleted = await f.Client.DeleteAsync( + $"/admin-api/blocks?key=203.0.113.21/28&token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.OK, deleted.StatusCode); + Assert.Equal(1, JsonDocument.Parse(await deleted.Content.ReadAsStringAsync()) + .RootElement.GetProperty("deleted").GetInt32()); + + using (var served = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); + } + + [Fact] + public async Task Clearing_the_operator_list_clears_the_ranges_and_clearing_the_engine_never_does() + { + await using var f = new EdgeFixture(); + var (rangeStatus, _) = await BlockAsync(f, new { ip = Range, reason = "netblock" }); + Assert.Equal(HttpStatusCode.NoContent, rangeStatus); + var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); + Assert.Equal(HttpStatusCode.NoContent, addressStatus); + + // The provenance the engine owns cannot reach a range: the engine did not + // write one, and a clear that reports the engine's list empty while a /24 + // is still refusing visitors would be a lie about what is in force. + using (var engineClear = await f.Client.DeleteAsync( + $"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) + { + Assert.Equal(HttpStatusCode.OK, engineClear.StatusCode); + Assert.Equal(0, JsonDocument.Parse(await engineClear.Content.ReadAsStringAsync()) + .RootElement.GetProperty("deleted").GetInt32()); + } + using (var stillBanned = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, stillBanned.StatusCode); + + // The operator's list is one list, so the clear that names it removes + // both shapes of it. + using (var operatorClear = await f.Client.DeleteAsync( + $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) + { + Assert.Equal(HttpStatusCode.OK, operatorClear.StatusCode); + Assert.Equal(2, JsonDocument.Parse(await operatorClear.Content.ReadAsStringAsync()) + .RootElement.GetProperty("deleted").GetInt32()); + } + using (var served = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); + using (var addressServed = await GetAsync(f, "/anything", Address)) + Assert.Equal(HttpStatusCode.NotFound, addressServed.StatusCode); + Assert.Empty(await RowsAsync(f)); + } + + [Fact] + public async Task A_range_past_its_expiry_enforces_nothing_and_shows_itself_as_dead() + { + await using var f = new EdgeFixture(); + var (status, _) = await BlockAsync(f, new { ip = Range, reason = "overnight", expiresInMinutes = 60 }); + Assert.Equal(HttpStatusCode.NoContent, status); + using (var inside = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); + + // Move the clock by moving the row, the way the expiry and retention + // tests do: the hour passes for this range and for nothing else. + using (var scope = f.Factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.NetworkBans.SingleAsync(b => b.Match == Range); + row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); + await db.SaveChangesAsync(); + } + await f.Service().InvalidateAsync(CancellationToken.None); + + using (var served = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); + + // The dead row stays in the table that shows it, marked dead, and is out + // of the live view — the same honesty rule as an address block. + var dead = (await RowsAsync(f)).Single(r => r.GetProperty("sourceKey").GetString() == Range); + Assert.False(dead.GetProperty("live").GetBoolean()); + Assert.NotEqual(JsonValueKind.Null, dead.GetProperty("expiresAt").ValueKind); + using var liveListing = await f.Client.GetAsync( + $"/admin-api/blocks?live=true&token={EdgeFixture.AdminToken}"); + var liveRows = JsonDocument.Parse(await liveListing.Content.ReadAsStringAsync()) + .RootElement.EnumerateArray().Select(r => r.GetProperty("sourceKey").GetString()).ToList(); + Assert.DoesNotContain(Range, liveRows); + } + + [Fact] + public async Task The_state_counts_ranges_apart_from_address_blocks() + { + await using var f = new EdgeFixture(); + var (rangeStatus, _) = await BlockAsync(f, new { ip = Range, reason = "netblock" }); + Assert.Equal(HttpStatusCode.NoContent, rangeStatus); + var (addressStatus, _) = await BlockAsync(f, new { ip = Address, reason = "one host" }); + Assert.Equal(HttpStatusCode.NoContent, addressStatus); + + using var response = await f.Client.GetAsync($"/admin-api/state?token={EdgeFixture.AdminToken}"); + var state = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(1, state.GetProperty("operatorRanges").GetInt32()); + Assert.Equal(1, state.GetProperty("operatorBlocks").GetInt32()); + Assert.True(state.GetProperty("operatorRangesAvailable").GetBoolean()); + } + + [Fact] + public async Task A_range_travels_in_the_document_and_is_enforced_on_the_edge_that_imports_it() + { + await using var source = new EdgeFixture(); + var (status, _) = await BlockAsync(source, new { ip = Range, reason = "written here", expiresInMinutes = 60 * 24 }); + Assert.Equal(HttpStatusCode.NoContent, status); + + using var exportResponse = await source.Client.GetAsync($"/admin-api/export?token={EdgeFixture.AdminToken}"); + var document = await exportResponse.Content.ReadAsStringAsync(); + var exported = JsonDocument.Parse(document).RootElement; + Assert.Equal(1, exported.GetProperty("counts").GetProperty("blocks").GetInt32()); + Assert.Contains(Range, exported.GetProperty("blocks").EnumerateArray() + .Select(b => b.GetProperty("ip").GetString())); + + await using var target = new EdgeFixture(); + using (var before = await GetAsync(target, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, before.StatusCode); + + using (var content = new StringContent(document, Encoding.UTF8, "application/json")) + using (var import = await target.Client.PostAsync( + $"/admin-api/import?token={EdgeFixture.AdminToken}", content)) + { + Assert.Equal(HttpStatusCode.OK, import.StatusCode); + var report = JsonDocument.Parse(await import.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); + } + + // The receiving edge enforces it on the wire, not only in its table, and + // the expiry travelled as an instant rather than as a duration. + using (var inside = await GetAsync(target, "/anything", Inside)) + Assert.Equal(HttpStatusCode.MovedPermanently, inside.StatusCode); + using (var outside = await GetAsync(target, "/anything", Outside)) + Assert.Equal(HttpStatusCode.NotFound, outside.StatusCode); + var imported = (await RowsAsync(target)).Single(r => r.GetProperty("sourceKey").GetString() == Range); + Assert.Equal("range", imported.GetProperty("kind").GetString()); + Assert.NotEqual(JsonValueKind.Null, imported.GetProperty("expiresAt").ValueKind); + + // The same document twice lands once. + using (var content = new StringContent(document, Encoding.UTF8, "application/json")) + using (var again = await target.Client.PostAsync( + $"/admin-api/import?token={EdgeFixture.AdminToken}", content)) + { + var report = JsonDocument.Parse(await again.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("alreadyThere").GetInt32()); + } + } + + [Fact] + public async Task A_document_carrying_a_range_over_everything_is_refused_row_by_row() + { + await using var f = new EdgeFixture(); + var document = """ + {"version":1,"blocks":[{"ip":"0.0.0.0/0","reason":"shutdown"}], + "allow":[],"rules":[],"countries":[]} + """; + using var content = new StringContent(document, Encoding.UTF8, "application/json"); + using var import = await f.Client.PostAsync($"/admin-api/import?token={EdgeFixture.AdminToken}", content); + Assert.Equal(HttpStatusCode.OK, import.StatusCode); + var report = JsonDocument.Parse(await import.Content.ReadAsStringAsync()).RootElement; + Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("rejected").GetInt32()); + Assert.Contains("every address", report.GetProperty("rejected").ToString()); + + Assert.Empty(await RowsAsync(f)); + using (var served = await GetAsync(f, "/anything", Inside)) + Assert.Equal(HttpStatusCode.NotFound, served.StatusCode); + } + + [Fact] + public async Task A_range_lands_in_the_change_log_under_the_name_the_row_is_stored_under() + { + await using var f = new EdgeFixture(); + var (status, _) = await BlockAsync(f, new { ip = "203.0.113.21/28", reason = "typed sloppily" }); + Assert.Equal(HttpStatusCode.NoContent, status); + + using var response = await f.Client.GetAsync( + $"/admin-api/changes?section=block&token={EdgeFixture.AdminToken}"); + var body = await response.Content.ReadAsStringAsync(); + // The record names the row, not the typo: one network, one spelling, in + // the table and in the log beside it. + Assert.Contains(Range, body); + Assert.DoesNotContain("203.0.113.21/28", body); + } + + [Fact] + public async Task The_read_only_token_cannot_write_a_range() + { + await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); + using var response = await f.Client.PostAsJsonAsync( + $"/admin-api/blocks?token={EdgeFixture.ReadOnlyToken}", new { ip = Range, reason = "dashboard" }); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Empty(await RowsAsync(f)); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs b/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs new file mode 100644 index 0000000..a07600a --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs @@ -0,0 +1,299 @@ +using System.Net.Sockets; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Policy; +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// The range half of the operator's block list (OPEN-66), as pure functions: +/// what the operator typed becomes which row, and which row answers for an +/// address. The integration tests ask the same questions over a wire; these ask +/// the ones that must hold whatever the wire is doing — the normalisation that +/// keeps one claim to one row, the index that keeps the per-request cost off the +/// table size, and the position of a range in the ordered decision. +/// +public sealed class NetworkBanTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + + private static NetworkBan Ban(string match, DateTimeOffset? expires = null, string? redirect = null) => new() + { + Match = match, + CreatedAt = Now.AddHours(-2), + ExpiresAt = expires, + RedirectTo = redirect, + Reason = "operator: netblock scanning" + }; + + private static string Normalized(string written) + { + Assert.True(NetworkBans.TryNormalize(written, out var normalized, out _), written); + return normalized; + } + + // ---- what the operator typed, and the one spelling it becomes ---- + + [Fact] + public void An_address_stays_an_address() + { + Assert.Equal("203.0.113.7", Normalized("203.0.113.7")); + Assert.Equal("2001:db8::7", Normalized(" 2001:db8::7 ")); + } + + [Fact] + public void A_network_is_masked_to_its_own_address() + { + // The spelling the operator typed is not the spelling the row is stored + // under, and that is the point: 198.51.100.37/28 and 198.51.100.32/28 are + // one claim, and two rows for it are two rows to notice and remove. + Assert.Equal("203.0.113.32/28", Normalized("203.0.113.37/28")); + Assert.Equal("198.51.100.0/24", Normalized("198.51.100.200/24")); + Assert.Equal("2001:db8::/64", Normalized("2001:db8:0:0:1:2:3:4/64")); + } + + [Fact] + public void A_prefix_that_names_one_address_is_that_address() + { + Assert.Equal("203.0.113.7", Normalized("203.0.113.7/32")); + Assert.Equal("2001:db8::7", Normalized("2001:db8::7/128")); + } + + [Fact] + public void An_ipv4_in_mapped_form_is_the_v4_it_is() + { + Assert.Equal("203.0.113.0/24", Normalized("::ffff:203.0.113.0/24")); + } + + [Fact] + public void A_range_over_every_address_is_refused_on_meaning_not_on_form() + { + foreach (var written in new[] { "0.0.0.0/0", "::/0" }) + { + Assert.False(NetworkBans.TryNormalize(written, out _, out var error)); + Assert.Contains("every address", error); + } + } + + [Fact] + public void A_prefix_that_cannot_be_a_prefix_is_refused_by_name() + { + foreach (var (written, expected) in new[] + { + ("203.0.113.0/33", "0..32"), + ("203.0.113.0/-1", "0..32"), + ("2001:db8::/129", "0..128"), + ("203.0.113.0/abc", "whole number of bits"), + ("not-an-ip/24", "not an IP address") + }) + { + Assert.False(NetworkBans.TryNormalize(written, out _, out var error), written); + Assert.Contains(expected, error); + } + } + + [Fact] + public void The_range_test_is_syntactic_so_it_can_decide_the_table_before_the_parse() + { + Assert.True(NetworkBans.IsRangeSyntax("203.0.113.0/24")); + Assert.False(NetworkBans.IsRangeSyntax("203.0.113.1")); + Assert.False(NetworkBans.IsRangeSyntax(null)); + } + + // ---- the index: cost bounded by prefix lengths, not by rows ---- + + [Fact] + public void A_range_answers_for_every_address_inside_it_and_for_none_outside() + { + var index = new NetworkBanIndex([Ban("203.0.113.16/28")]); + + Assert.True(index.TryMatch("203.0.113.16", Now, out var first)); + Assert.Equal("203.0.113.16/28", first.Match); + Assert.True(index.TryMatch("203.0.113.31", Now, out _)); + Assert.False(index.TryMatch("203.0.113.15", Now, out _)); + Assert.False(index.TryMatch("203.0.113.32", Now, out _)); + Assert.False(index.TryMatch(null, Now, out _)); + Assert.False(index.TryMatch("not-an-address", Now, out _)); + } + + [Fact] + public void The_most_specific_range_is_the_one_that_answers() + { + var index = new NetworkBanIndex([Ban("203.0.113.0/24"), Ban("203.0.113.16/28")]); + + Assert.True(index.TryMatch("203.0.113.21", Now, out var winner)); + Assert.Equal("203.0.113.16/28", winner.Match); + // Outside the narrow one, the broad one still speaks. + Assert.True(index.TryMatch("203.0.113.99", Now, out var broad)); + Assert.Equal("203.0.113.0/24", broad.Match); + } + + [Fact] + public void An_expired_range_answers_nothing_and_does_not_hide_a_live_one() + { + var index = new NetworkBanIndex([ + Ban("203.0.113.16/28", Now.AddMinutes(-1)), + Ban("203.0.113.0/24") + ]); + + Assert.True(index.TryMatch("203.0.113.21", Now, out var winner)); + Assert.Equal("203.0.113.0/24", winner.Match); + + var dead = new NetworkBanIndex([Ban("203.0.113.16/28", Now.AddMinutes(-1))]); + Assert.False(dead.TryMatch("203.0.113.21", Now, out _)); + Assert.Equal(1, dead.Count); + } + + [Fact] + public void A_v6_range_covers_v6_and_a_v4_address_is_never_inside_it() + { + var index = new NetworkBanIndex([Ban("2001:db8:1234::/48")]); + + Assert.True(index.TryMatch("2001:db8:1234:5600::1", Now, out _)); + Assert.False(index.TryMatch("2001:db8:1235::1", Now, out _)); + Assert.False(index.TryMatch("203.0.113.21", Now, out _)); + } + + [Fact] + public void A_v4_address_written_in_mapped_form_is_inside_the_v4_range() + { + var index = new NetworkBanIndex([Ban("203.0.113.16/28")]); + Assert.True(index.TryMatch("::ffff:203.0.113.21", Now, out _)); + } + + [Fact] + public void The_index_counts_rows_and_a_match_that_came_from_nowhere_is_skipped() + { + var index = new NetworkBanIndex([Ban("203.0.113.0/24"), Ban("garbage")]); + Assert.Equal(1, index.Count); + Assert.True(index.Covers("203.0.113.9", Now)); + Assert.False(NetworkBanIndex.Empty.TryMatch("203.0.113.9", Now, out _)); + } + + [Fact] + public void The_family_and_prefix_of_a_stored_match_are_the_ones_the_index_buckets_on() + { + Assert.Equal(AddressFamily.InterNetwork, NetworkBans.FamilyOf("203.0.113.0/24")); + Assert.Equal(AddressFamily.InterNetworkV6, NetworkBans.FamilyOf("2001:db8::/48")); + Assert.Equal(24, NetworkBans.PrefixOf("203.0.113.0/24")); + Assert.Equal(-1, NetworkBans.PrefixOf("203.0.113.1")); + } + + // ---- the position of a range in the ordered decision ---- + + private static EdgeSnapshot Snapshot( + EdgePolicy policy, + NetworkBanIndex? ranges = null, + IReadOnlyDictionary? manual = null, + IReadOnlyDictionary? bans = null, + IReadOnlyList? allow = null) => new() + { + GeneratedAt = Now, + Policy = policy, + OperatorRanges = ranges ?? NetworkBanIndex.Empty, + OperatorBlocks = manual ?? new Dictionary(), + EngineBans = bans ?? new Dictionary(), + AllowEntries = allow ?? [] + }; + + [Fact] + public void A_range_refuses_a_source_inside_it_and_leaves_its_neighbour_alone() + { + var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28")])); + + var inside = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + Assert.Equal(EdgeVerdict.BlockOperator, inside.Verdict); + Assert.Equal("203.0.113.16/28", inside.Range); + Assert.Equal("operator: netblock scanning", inside.Reason); + + Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.32", "/x", Now).Verdict); + } + + [Fact] + public void An_allow_entry_inside_a_banned_range_is_still_an_exemption() + { + var snapshot = Snapshot( + EdgePolicy.Default, + new NetworkBanIndex([Ban("203.0.113.16/28")]), + allow: [new AllowEntry { Match = "203.0.113.21", Note = "the one customer in that block" }]); + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + Assert.Equal(EdgeVerdict.PassAllowlisted, decision.Verdict); + Assert.Equal("the one customer in that block", decision.Reason); + } + + [Fact] + public void An_operator_range_outranks_the_ban_this_edge_earned() + { + var engineBan = new BlockEntry + { + SourceKey = "203.0.113.21", + Source = BlockSource.Engine, + CreatedAt = Now.AddMinutes(-5), + ExpiresAt = Now.AddMinutes(55), + Reason = "10 consecutive refusals" + }; + var snapshot = Snapshot( + new EdgePolicy { Mode = EnforcementMode.Enforce }, + new NetworkBanIndex([Ban("203.0.113.16/28")]), + bans: new Dictionary { ["203.0.113.21"] = engineBan }); + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict); + Assert.Equal("203.0.113.16/28", decision.Range); + } + + [Fact] + public void An_address_block_the_operator_wrote_wins_over_the_range_covering_it() + { + var manual = new BlockEntry + { + SourceKey = "203.0.113.21", + Source = BlockSource.Operator, + CreatedAt = Now.AddHours(-1), + Reason = "blocked by name first" + }; + var snapshot = Snapshot( + EdgePolicy.Default, + new NetworkBanIndex([Ban("203.0.113.16/28")]), + manual: new Dictionary { ["203.0.113.21"] = manual }); + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict); + // The row that answered is the address row: no range on the decision, and + // the reason is the one written against the address. + Assert.Null(decision.Range); + Assert.Equal("blocked by name first", decision.Reason); + } + + [Fact] + public void A_range_with_a_redirect_sends_the_blocked_visitor_there() + { + var snapshot = Snapshot( + EdgePolicy.Default, + new NetworkBanIndex([Ban("203.0.113.16/28", redirect: "https://honeypot.example.org/")])); + + var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + Assert.Equal(301, decision.StatusCode); + Assert.Equal("https://honeypot.example.org/", decision.Location); + } + + [Fact] + public void A_range_past_its_expiry_enforces_nothing() + { + var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28", Now.AddMinutes(-1))])); + Assert.Equal(EdgeVerdict.Pass, DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now).Verdict); + } + + [Fact] + public void The_trace_names_the_range_that_answered() + { + var snapshot = Snapshot(EdgePolicy.Default, new NetworkBanIndex([Ban("203.0.113.16/28")])); + var decision = DecisionEngine.Decide(snapshot, "203.0.113.21", "/x", Now); + + var trace = DecisionTrace.For(snapshot, decision, Now, hasAddress: true, hasCountry: false, "203.0.113.21"); + var answered = trace.Single(t => t.Outcome == PillarOutcome.Answered); + Assert.Equal("operatorBlock", answered.Pillar); + Assert.Contains("203.0.113.16/28", answered.Note); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 1603626..baeaced 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1620,6 +1620,37 @@ check 'a removal is recorded as a removal' 'yes' \ admin "$EDGE/admin-api/changes?section=block" | python3 -c "import sys,json;print('yes' if any(c['target']=='$CH_IP' and c['action']=='removed' for c in json.load(sys.stdin)) else 'no')")" check 'the country rule the import wrote is removable, so the volume stays clean' '204' \ "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/countries/fr")" + +echo '- an operator bans a range on the shipped image' +# The same feature on the deployed image (OPEN-66): the operator's block control +# takes a netblock, and the guard enforces it by containment. Aligned base, chosen +# per run, so a row left in the data volume by an earlier run cannot answer for +# this one. +RANGE_BASE=$(( 96 + (RANDOM % 4) * 8 )) +RANGE_NET="203.0.113.$RANGE_BASE/29" +RANGE_INSIDE="203.0.113.$(( RANGE_BASE + 3 ))" +RANGE_OUTSIDE="203.0.113.$(( RANGE_BASE + 8 ))" +# Same rule as the payloads at the top of this file: the body is built in a +# variable, not with escaped quotes inside a command substitution. +RANGE_JSON="{\"ip\":\"$RANGE_NET\",\"reason\":\"shipped netblock\"}" +check 'the shipped edge takes a CIDR as a block' '204' \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$RANGE_JSON" "$EDGE/admin-api/blocks")" +check 'a source inside the range is refused on the wire' '301' \ + "$(code -H "X-Forwarded-For: $RANGE_INSIDE" "$EDGE/anything")" +check 'a source one address past its end is served' '404' \ + "$(code -H "X-Forwarded-For: $RANGE_OUTSIDE" "$EDGE/anything")" +check 'the shipped listing says which shape the row is' 'range' \ + "$(admin "$EDGE/admin-api/blocks" | python3 -c "import sys,json;print(next(c['kind'] for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET'))")" +check 'a range over every address is refused on the shipped image' '400' \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + -d '{"ip":"0.0.0.0/0","reason":"shutdown"}' "$EDGE/admin-api/blocks")" +check 'the shipped state counts ranges apart' 'yes' \ + "$(admin "$EDGE/admin-api/state" | python3 -c "import sys,json;print('yes' if json.load(sys.stdin).get('operatorRanges') == 1 else 'no')")" +check 'the range is removable by its name, so the volume stays clean' '404' \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \ + "$EDGE/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \ + code -H "X-Forwarded-For: $RANGE_INSIDE" "$EDGE/anything")" echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index e1873e3..2bd0449 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -352,6 +352,65 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); (ip) => ![...document.querySelectorAll('#blocks tbody tr')].some((tr) => tr.children[0].textContent === ip), WRITE_IP, { timeout: 15000 }).catch(() => {}); + // A range, written from the same field (OPEN-66). Two things are asserted here + // that an API test cannot see: the page says which shape a row is — a /29 that + // refuses eight addresses is not a row of the same size as any other — and the + // per-row delete removes it under the name the edge stored, not the spelling + // somebody typed into the box. + const RANGE_BASE = 96 + Math.floor(Math.random() * 4) * 8; + const RANGE_NET = `203.0.113.${RANGE_BASE}/29`; + const RANGE_SLOPPY = `203.0.113.${RANGE_BASE + 5}/29`; + const RANGE_INSIDE = `203.0.113.${RANGE_BASE + 3}`; + const RANGE_OUTSIDE = `203.0.113.${RANGE_BASE + 8}`; + + const beforeRange = await probe(RANGE_INSIDE); + check('before the range, an address inside it reaches the upstream', + beforeRange.status === 404, `probe from ${RANGE_INSIDE} answered ${beforeRange.status}`); + + await page.fill('#blockIp', RANGE_SLOPPY); + await page.fill('#blockReason', 'console gate: a netblock'); + await page.click('#addBlock'); + await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody tr')] + .some((tr) => tr.children[0].textContent.startsWith(net) && /range/.test(tr.children[0].textContent)), + RANGE_NET, { timeout: 15000 }).catch(() => {}); + const rangeRows = await cells('#blocks tbody tr'); + check('the page writes a CIDR as one ban and marks the row as a range', + rangeRows.some((r) => r[0].startsWith(RANGE_NET) && /range/.test(r[0]) + && /netblock/.test(r[2] || '')), + JSON.stringify(rangeRows.map((r) => [r[0], r[2]]))); + check('and one range is one row however it is spelled', + rangeRows.filter((r) => r[0].startsWith(RANGE_NET)).length === 1, + JSON.stringify(rangeRows.filter((r) => r[0].startsWith(RANGE_NET)).map((r) => r[0]))); + + let rangeWire = await probe(RANGE_INSIDE); + for (let i = 0; i < 10 && rangeWire.status === 404; i++) { + await new Promise((r) => setTimeout(r, 1000)); rangeWire = await probe(RANGE_INSIDE); + } + check('the range drawn on the page is enforced on the wire for an address inside it', + rangeWire.status === 301 || rangeWire.status === 403, + `probe from ${RANGE_INSIDE} answered ${rangeWire.status}`); + const outsideRange = await probe(RANGE_OUTSIDE); + check('and the address one past its end is served', + outsideRange.status === 404, `probe from ${RANGE_OUTSIDE} answered ${outsideRange.status}`); + + const summaryPills = await page.$$eval('#summary .pill', (els) => els.map((e) => e.textContent.trim())); + check('the summary counts ranges apart from address blocks', + summaryPills.some((p) => /^ranges 1$/.test(p)), JSON.stringify(summaryPills)); + + await page.click(`#blocks tbody button[data-act="delblock"][data-k="${RANGE_NET}"]`); + await page.waitForFunction((net) => ![...document.querySelectorAll('#blocks tbody tr')] + .some((tr) => tr.children[0].textContent.startsWith(net)), + RANGE_NET, { timeout: 15000 }).catch(() => {}); + let rangeWire2 = await probe(RANGE_INSIDE); + for (let i = 0; i < 10 && rangeWire2.status !== 404; i++) { + await new Promise((r) => setTimeout(r, 1000)); rangeWire2 = await probe(RANGE_INSIDE); + } + check('the per-row delete removes the range by the name the edge stored', + !(await cells('#blocks tbody tr')).some((r) => r[0].startsWith(RANGE_NET)) + && rangeWire2.status === 404, + `probe from ${RANGE_INSIDE} answered ${rangeWire2.status}`); + + await page.fill('#allowMatch', WRITE_CIDR); await page.fill('#allowNote', 'console gate: allow entry'); await page.fill('#allowTtl', '60'); diff --git a/scripts/smoke.sh b/scripts/smoke.sh index b80b269..fb60e1b 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -537,6 +537,64 @@ check 'clearing engine bans leaves operator rows' '{"deleted":1}' \ check 'an operator row survives it' 1 \ "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +# This scene clears the engine's list wholesale, so it runs after the scenes +# that live off an engine row of their own; a range is not in that list, but +# the clear is not scoped to it. +echo '- an operator bans a range' +# A netblock, not one address (OPEN-66). The block API answered "not an IP +# address" for a CIDR while the allowlist accepted one, so a scanner rotating +# inside one /29 cost one write and one row per address — and the export of an +# edge's decisions could not carry the range either. The base is aligned to the +# prefix and chosen per run, so a leftover row in the database cannot satisfy the +# assertions. +RANGE_BASE=$(( 96 + (RANDOM % 4) * 8 )) +RANGE_NET="203.0.113.$RANGE_BASE/29" +RANGE_INSIDE="203.0.113.$(( RANGE_BASE + 3 ))" +RANGE_OUTSIDE="203.0.113.$(( RANGE_BASE + 8 ))" +# The bodies live in single-quoted-safe variables: an escaped-quote body +# written straight inside a command substitution is the thing this file has +# been bitten by before (see the payloads at the top). +RANGE_JSON="{\"ip\":\"$RANGE_NET\",\"reason\":\"netblock scanning\"}" +RANGE_SLOPPY_JSON="{\"ip\":\"203.0.113.$(( RANGE_BASE + 5 ))/29\",\"reason\":\"typed sloppily\"}" +check 'a CIDR is a block, not a rejected input' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$RANGE_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" +check 'every address inside the range is refused' 301 \ + "$(code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")" +check 'the address one past its end is served' 404 \ + "$(code -H "X-Forwarded-For: $RANGE_OUTSIDE" "$(from anything)")" +check 'the listing says which shape the row is' range \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \ + | python3 -c "import sys,json;print(next(c['kind'] for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET'))")" +check 'one range is one row however it is spelled' 1 \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$RANGE_SLOPPY_JSON" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \ + | python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET']))")" +check 'a range over every address is refused and says why' yes \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d '{"ip":"0.0.0.0/0","reason":"shutdown dressed as a ban"}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \ + | grep -q 'every address' && echo yes || echo no)" +check 'the range is recorded under the name the row is stored under' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \ + | python3 -c "import sys,json;print('yes' if any(c['target']=='$RANGE_NET' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")" +check 'the state counts ranges apart from address blocks' yes \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \ + | python3 -c "import sys,json;print('yes' if json.load(sys.stdin).get('operatorRanges') == 1 else 'no')")" +# Provenance is part of a clear: the engine's list is not the operator's, and a +# /29 the operator wrote is not in it. +check 'clearing the engine bans leaves the range in force' 301 \ + "$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" >/dev/null; \ + code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")" +check 'and the range is removable by its name' 404 \ + "$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \ + code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")" + echo '- admin surface' check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" check 'the policy is readable' Enforce \