diff --git a/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs b/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs index 686fcd2..7b0a100 100644 --- a/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs +++ b/dotnet/OpenWaf.Domain/Engine/NetworkBanIndex.cs @@ -1,3 +1,4 @@ +using System.Linq; using System.Net.Sockets; using OpenWaf.Domain.Security; @@ -32,6 +33,14 @@ public sealed class NetworkBanIndex /// counts when they ask what this edge has written. public int Count { get; } + /// The ranges the index actually answers with, in the deduplicated + /// shape the request path sees. A count is not enough for the impact preview + /// (OPEN-75), which has to rebuild the index with one more range in it and + /// answer what that changes — and rebuilding from the rows the index was + /// handed rather than from the rows it kept would answer about a state the + /// wire is not running. + public IReadOnlyList Bans { get; } + public NetworkBanIndex(IEnumerable bans) { var buckets = new Dictionary<(AddressFamily, int), Dictionary>(); @@ -56,6 +65,7 @@ public sealed class NetworkBanIndex _buckets = buckets; Count = total; + Bans = buckets.Values.SelectMany(v => v.Values).ToList(); var ordered = new List<(AddressFamily Family, int Prefix)>(buckets.Keys); ordered.Sort((a, b) => b.Prefix.CompareTo(a.Prefix)); _order = ordered.ToArray(); diff --git a/dotnet/OpenWaf.Domain/Security/NetworkBan.cs b/dotnet/OpenWaf.Domain/Security/NetworkBan.cs index c4ba86f..f77127e 100644 --- a/dotnet/OpenWaf.Domain/Security/NetworkBan.cs +++ b/dotnet/OpenWaf.Domain/Security/NetworkBan.cs @@ -86,7 +86,7 @@ public static class NetworkBans var slash = text.IndexOf('/'); if (slash < 0) { - if (!SourceKey.TryParse(text, out _, out var single)) + if (!SourceKey.TryParse(text, out _, out var single) || !IsFullAddressSpelling(text)) { error = $"not an IP address: {written}"; return false; @@ -97,7 +97,8 @@ public static class NetworkBans var networkPart = text[..slash]; var prefixPart = text[(slash + 1)..]; - if (!SourceKey.TryParse(networkPart, out _, out var network)) + if (!SourceKey.TryParse(networkPart, out _, out var network) + || !IsFullAddressSpelling(networkPart)) { error = $"not an IP address: {networkPart} in \"{written}\""; return false; @@ -137,6 +138,30 @@ public static class NetworkBans return true; } + /// Is this the whole dotted-quad spelling of a v4 address, or an + /// abbreviation the parser happens to accept? + /// + /// takes "203.0.113" as + /// 203.0.0.113 — three parts, the last one read as a 16-bit host portion. On + /// a read surface that is a wrong answer about an address that does not + /// exist, and the preview (OPEN-59) refuses it for that reason. On this path + /// it is worse, because the row gets written: an operator missing one octet + /// bans 203.0.0.113, a live address that was never the target, and the + /// listing shows a spelling nobody typed. The write path has to refuse the + /// same string the read surfaces refuse, or the two disagree about whether an + /// address exists and a preview answers about a row the operator cannot find. + /// + /// v6 and IPv4-mapped v6 are not this rule's business: the dotted-quad count + /// is what a v4 address looks like written out, and "::ffff:203.0.113.7" is a + /// whole address by its own spelling. + /// + private static bool IsFullAddressSpelling(string? text) + { + if (!System.Net.IPAddress.TryParse(text, out var parsed)) return false; + if (parsed.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) return true; + return text!.Split('.').Length == 4; + } + /// The family a normalised match belongs to, for the index that /// buckets by prefix length. public static AddressFamily FamilyOf(string normalizedMatch) diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 3bca004..7706c3e 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -183,6 +183,14 @@ internal static class AdminConsole
+

What would this ban touch?

+
+ + + +
+
+

Sources the edge is watching

@@ -1124,6 +1132,60 @@ el('askFind').onclick = async () => { } }; +el('askImpact').onclick = async () => { + // What would this ban touch? (OPEN-75). The dry run above answers one named + // request and the horizon answers what stops soon; this answers the question + // asked before the write, over the sources this edge is actually watching + // inside the match. The engine that answers is the one on the wire, with the + // proposed entry added to its snapshot and nothing written, so the split + // between newly refused, already refused and still passing is the wire's split. + const match = el('impactMatch').value.trim(); + if (!match) { note('an address or a CIDR first - that is the row being asked about', true); return; } + const path = el('impactPath').value.trim(); + // Emptied before the call, and the first line names the match that was asked + // for: a scene waiting for an answer cannot read the previous one. + el('impactanswer').textContent = ''; + const r = await apiRaw('/admin-api/impact?match=' + encodeURIComponent(match) + + (path ? '&path=' + encodeURIComponent(path) : '')); + if (failed(r)) return; + const d = r.body || {}; + const c = d.counts || {}; + const lines = []; + lines.push('asked: ' + (d.match || match) + ' at ' + (d.path || '/') + ' - ' + + (d.probed === undefined ? '?' : d.probed) + ' sources probed' + + (d.truncated ? ' (more inside, not shown)' : '') + + ' - newly refused ' + (c.newlyRefused === undefined ? '?' : c.newlyRefused) + + ', already refused ' + (c.alreadyRefused === undefined ? '?' : c.alreadyRefused) + + ', still passing ' + (c.stillPassing === undefined ? '?' : c.stillPassing)); + if (d.filedUnder && d.filedUnder !== d.match) lines.push('the write would file it under ' + d.filedUnder); + if (d.alreadyCoveredBy) { + lines.push('already covered at its own address: ' + d.alreadyCoveredBy.verdict + + ' by ' + (d.alreadyCoveredBy.by || '?') + ' - this write would change nothing there'); + } + for (const a of (d.outrankedBy || [])) { + lines.push('an exemption outranks this ban at the match\u0027s own address: ' + a.match + + (a.note ? ' \u00b7 ' + a.note : '') + (a.expiresAt ? ' \u00b7 until ' + a.expiresAt : '')); + } + for (const a of (d.exemptionsInside || [])) { + lines.push('inside the match, and the ban will not reach it: ' + a.match + + (a.note ? ' \u00b7 ' + a.note : '')); + } + for (const row of (d.sources || [])) { + let line = row.source + ' \u00b7 ' + row.kind + ' \u00b7 ' + row.before + ' \u2192 ' + row.after + + ' \u00b7 ' + row.change; + if (row.afterBy) line += ' \u00b7 by ' + row.afterBy; + if (row.refusals) line += ' \u00b7 ' + row.refusals + ' refusals counted'; + lines.push(line); + } + if (d.note) lines.push(d.note); + const box = el('impactanswer'); + for (const line of lines) { + const div = document.createElement('div'); + div.textContent = line; + box.appendChild(div); + } +}; + el('askHorizon').onclick = async () => { // The horizon (OPEN-72). Not "what expires" - a list of dates tells an operator // nothing about what the site will be doing tomorrow. Each row carries the real diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index aab463a..52aadea 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -1757,6 +1757,185 @@ note = t.Note }); }); + // What would this ban touch? (OPEN-75). The dry run answers one named + // request and the horizon answers what stops being enforced soon. Neither + // answers the question asked BEFORE the write, and both failures it + // prevents are silent: a /24 written over an office block refuses people + // who were never the target, and a range written inside an existing + // exemption refuses nobody at all — the operator sees 204 and moves on. + // + // The answer is not a second implementation of the pillar order. It is the + // real DecisionEngine run over a snapshot with the proposed entry added, + // over the sources this edge is actually watching inside the match — the + // same trick the horizon uses for "what answers afterwards", for the same + // reason: a preview that disagrees with the wire is worse than no preview. + group.MapGet("/impact", async (string? match, string? path, int? limit, + EdgeStateStore state, IGeoIpLookup geo, OpenWafDbContext db, + HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "match", "path", "limit")) + return Results.BadRequest(new { error = unknown }); + if (string.IsNullOrWhiteSpace(match)) + return Results.BadRequest(new { + error = "match is required: an address or a CIDR, the same value the write takes" + }); + // Normalised by the write path's own code, so the preview answers + // about the row the write would create and refuses a match the write + // would refuse, in the write's words. 198.51.100.37/24 and + // 198.51.100.0/24 are one row, and a preview of a third spelling + // would be a preview of nothing. + if (!NetworkBans.TryNormalize(match.Trim(), out var normalized, out var inputError)) + return Results.BadRequest(new { error = inputError }); + var askedPath = string.IsNullOrWhiteSpace(path) ? "/" : path!.Trim(); + if (!askedPath.StartsWith('/')) + return Results.BadRequest(new { error = $"path must start with /; got \"{askedPath}\"" }); + var take = limit ?? ImpactDefaultLimit; + if (take < ImpactMinLimit || take > ImpactMaxLimit) + return Results.BadRequest(new { error = $"limit must be {ImpactMinLimit}..{ImpactMaxLimit}; got {limit}" }); + + var now = DateTimeOffset.UtcNow; + var snapshot = state.GetOrRefresh(); + var policy = snapshot.Policy; + var isRange = NetworkBans.IsRangeSyntax(normalized); + + // The address that stands for a match. The network address of a + // network is inside it, so the engine can be asked about it, and a + // source key carries a prefix the engine cannot be asked with. + static string? ProbeOf(string? keyOrMatch) + { + if (string.IsNullOrWhiteSpace(keyOrMatch) || keyOrMatch == "*") return null; + var slash = keyOrMatch.IndexOf('/'); + return slash < 0 ? keyOrMatch : keyOrMatch[..slash]; + } + + var probe = ProbeOf(normalized); + // The key the write would file it under, which for a bare address is + // this edge's group for it — with a /29 key, banning one address + // reaches the whole group, and the preview has to say so rather than + // answer about one address. + var key = SourceKey.For(probe ?? normalized, policy); + + bool Inside(string? sourceKey) + { + var p = ProbeOf(sourceKey); + if (p is null) return false; + return isRange + ? NetworkMatch.Matches(p, normalized) + : string.Equals(SourceKey.For(p, policy), key, StringComparison.Ordinal); + } + + // The snapshot with the proposed entry added and nothing else + // changed. Nothing is written anywhere: this is the state the next + // request would be answered from if the operator pressed save, and + // the engine that reads it is the one on the wire. + var after = isRange + ? snapshot with + { + OperatorRanges = new NetworkBanIndex(snapshot.OperatorRanges.Bans.Append( + new NetworkBan { Match = normalized, CreatedAt = now, Reason = "impact preview" })) + } + : snapshot with + { + OperatorBlocks = WithProposedBlock(snapshot.OperatorBlocks, new BlockEntry + { + SourceKey = key, Source = BlockSource.Operator, CreatedAt = now, + Reason = "impact preview" + }) + }; + + // The sources to ask about: everything this edge is watching inside + // the match. An observation is a source it has seen; a streak is one + // it is counting right now, and that is the one an operator is about + // to ban. The match's own address is always asked, because "nothing + // has been seen inside this range" and "the preview did not look" are + // different answers. + var inside = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var o in await db.Observations.AsNoTracking().ToListAsync(ct)) + { + if (!Inside(o.SourceKey) || !seen.Add(o.SourceKey)) continue; + inside.Add(new ImpactSource(o.SourceKey, o.LastSeenAt, o.TotalRefusals, + o.MaxConsecutiveRefusals, "seen")); + } + foreach (var t in await db.Streaks.AsNoTracking().ToListAsync(ct)) + { + if (!Inside(t.SourceKey) || !seen.Add(t.SourceKey)) continue; + inside.Add(new ImpactSource(t.SourceKey, t.LastSeenAt, t.TotalRefusals, + t.MaxConsecutiveRefusals, "standing streak")); + } + if (seen.Add(key)) + inside.Add(new ImpactSource(key, now, 0, 0, "the match itself")); + inside.Sort((a, b) => b.LastSeenAt.CompareTo(a.LastSeenAt)); + var probed = inside.Take(take).ToList(); + + var newlyRefused = 0; + var alreadyRefused = 0; + var stillPassing = 0; + var rows = new List(); + foreach (var s in probed) + { + var p = ProbeOf(s.Key) ?? s.Key; + var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(p); + var before = DecisionEngine.Decide(snapshot, p, askedPath, now, country); + var then = DecisionEngine.Decide(after, p, askedPath, now, country); + string change; + if (!before.IsBlocked && then.IsBlocked) { change = "newly refused"; newlyRefused++; } + else if (before.IsBlocked) { change = "already refused"; alreadyRefused++; } + else { change = "still passes"; stillPassing++; } + rows.Add(new ImpactRow(s.Key, s.Kind, s.LastSeenAt, s.Refusals, s.WorstRun, + EdgeVerdictLabel.For(before.Verdict), AnsweredBefore(before), + EdgeVerdictLabel.For(then.Verdict), AnsweredAfter(then), change)); + } + + // What already answers for the match's own address, and the live + // exemptions that outrank the write. An exemption is not a footnote + // here: it is the reason a ban can be written and refuse nobody, and + // the operator has to see it before the 204, not after the complaint. + var selfCountry = policy.Geo == GeoMode.Off ? null : geo.Lookup(probe ?? normalized); + var self = DecisionEngine.Decide(snapshot, probe ?? normalized, askedPath, now, selfCountry); + object? alreadyCoveredBy = self.IsBlocked + ? new { verdict = EdgeVerdictLabel.For(self.Verdict), by = AnsweredBefore(self) } + : null; + var outranked = snapshot.AllowEntries + .Where(a => a.IsLive(now) && NetworkMatch.Matches(probe ?? normalized, a.Match)) + .Select(a => (object)new { match = a.Match, note = a.Note, expiresAt = a.ExpiresAt }) + .ToList(); + var exemptionsInside = snapshot.AllowEntries + .Where(a => a.IsLive(now) && Inside(a.Match) + && !NetworkMatch.Matches(probe ?? normalized, a.Match)) + .Select(a => (object)new { match = a.Match, note = a.Note, expiresAt = a.ExpiresAt }) + .ToList(); + + return Results.Ok(new + { + match = normalized, + kind = isRange ? "range" : "address", + filedUnder = key, + path = askedPath, + asOf = now, + scope = "snapshot+database", + probed = probed.Count, + limit = take, + truncated = inside.Count > probed.Count, + counts = new { newlyRefused, alreadyRefused, stillPassing }, + wouldRefuse = newlyRefused > 0, + changesNothing = newlyRefused == 0, + alreadyCoveredBy, + // Live exemptions that cover the match's own address: the ban is + // written after them in the pillar order, so it does not reach + // this address at all. + outrankedBy = outranked, + exemptionsInside, + sources = rows, + note = newlyRefused == 0 + ? "this write would change nothing for any source this edge is watching inside the match; " + + "outrankedBy names the exemptions that already answer there" + : $"{newlyRefused} source(s) this edge is watching inside the match would be refused by " + + "this write and are not refused today; sources outside the match are not probed", + wrote = false + }); + }); + // The enforcement horizon (OPEN-72). Every dated entry this edge holds — // an operator's block, a range, an engine ban, an exemption, a path rule, a // path budget — stops answering on its own, and nothing anywhere shows what @@ -2161,6 +2340,13 @@ note = t.Note private const int HistoryMinLimit = 1; private const int HistoryMaxLimit = 2000; + // What would this ban touch? (OPEN-75). Fifty sources is the default because + // that is more than an operator can read at once, and two hundred is the + // ceiling because past that the preview is a report, not a decision aid. + private const int ImpactDefaultLimit = 50; + private const int ImpactMinLimit = 1; + private const int ImpactMaxLimit = 200; + // Where does this appear? (OPEN-74). Two characters is the floor because a // one-character search is a dump of every store rather than an answer; 128 is // the ceiling because it is the longest target the change log stores, so a @@ -2290,6 +2476,45 @@ note = t.Note /// octet gets "pass" for an address that is not the one they meant, and the /// whole value of the surface is that its answer is about a named request. /// + /// The snapshot's operator blocks plus the one this preview is + /// asking about, without touching the snapshot itself (OPEN-75). The + /// proposed row replaces whatever the operator already has on that key, which + /// is what the write would do — POST on an existing key updates the row. + private static IReadOnlyDictionary WithProposedBlock( + IReadOnlyDictionary existing, BlockEntry proposed) + { + var copy = new Dictionary(StringComparer.Ordinal); + foreach (var kv in existing) copy[kv.Key] = kv.Value; + copy[proposed.SourceKey] = proposed; + return copy; + } + + /// What answers for a source today. Named from the decision the + /// engine returned, never re-derived: the row that refused it is the thing an + /// operator goes looking for in the listings. + private static string? AnsweredBefore(OpenWaf.Domain.Engine.EdgeDecision d) => d.Verdict switch + { + OpenWaf.Domain.Engine.EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list", + OpenWaf.Domain.Engine.EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban", + OpenWaf.Domain.Engine.EdgeVerdict.BlockRule => d.RulePattern is { } p ? $"path rule {p}" : d.Reason ?? "a path rule", + OpenWaf.Domain.Engine.EdgeVerdict.GeoReject => d.Reason ?? "a country rule", + _ => null + }; + + /// What answers for a source once the proposed entry is in place. + /// A pass is answered too, because "still passes, and this exemption is why" + /// is the sentence that tells an operator their ban will do nothing. + private static string? AnsweredAfter(OpenWaf.Domain.Engine.EdgeDecision d) => d.Verdict switch + { + OpenWaf.Domain.Engine.EdgeVerdict.PassAllowlisted => "an allow entry", + OpenWaf.Domain.Engine.EdgeVerdict.PassBypassed => "an always-pass path", + OpenWaf.Domain.Engine.EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list", + OpenWaf.Domain.Engine.EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban", + OpenWaf.Domain.Engine.EdgeVerdict.BlockRule => d.RulePattern is { } p2 ? $"path rule {p2}" : d.Reason ?? "a path rule", + OpenWaf.Domain.Engine.EdgeVerdict.GeoReject => d.Reason ?? "a country rule", + _ => null + }; + private static bool IsAnAddress(string value) { if (!System.Net.IPAddress.TryParse(value, out var parsed)) return false; @@ -2497,3 +2722,31 @@ internal sealed record SearchHit( bool? Live, DateTimeOffset? ExpiresAt, string Why); + +/// A source this edge is watching that falls inside the proposed match +/// (OPEN-75). `Kind` says where it came from: an observation is a source the edge +/// has seen, a standing streak is one it is counting right now, and the match's +/// own address is always asked so an empty answer is not mistaken for an +/// unanswered one. +internal sealed record ImpactSource( + string Key, + DateTimeOffset LastSeenAt, + int Refusals, + int WorstRun, + string Kind); + +/// The same source answered twice: what the edge says today, and what it +/// would say with the proposed entry in the snapshot. `Change` is the whole point +/// of the surface — newly refused, already refused by something else, or still +/// passing because something outranks the ban. +internal sealed record ImpactRow( + string Source, + string Kind, + DateTimeOffset LastSeenAt, + int Refusals, + int WorstRun, + string Before, + string? BeforeBy, + string After, + string? AfterBy, + string Change); diff --git a/dotnet/OpenWaf.Tests.Integration/BanImpactTests.cs b/dotnet/OpenWaf.Tests.Integration/BanImpactTests.cs new file mode 100644 index 0000000..64d81ea --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/BanImpactTests.cs @@ -0,0 +1,315 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// What would this ban touch? (OPEN-75): the blast radius of a range or address +/// before the operator writes it. +/// +/// Both failures the surface exists to catch are silent. A /24 written over an +/// office block refuses people who were never the target, and a range written +/// inside an existing exemption refuses nobody at all — the operator sees 204 and +/// moves on. The dry run answers one named request and the horizon answers what +/// stops being enforced soon; neither answers the question asked before the write. +/// +/// What these tests hold the surface to: the preview runs the real engine over a +/// snapshot with the proposed entry added, so the split between newly refused, +/// already refused and still passing is the wire's split and not a second +/// implementation of it; an exemption outranks the ban and the answer says so; +/// a write that changes nothing is named as one; a bare address is previewed +/// under the key this edge files it under, which with a group prefix is wider +/// than the address typed; the match is normalised by the write path's own code; +/// and asking writes nothing. +/// +public sealed class BanImpactTests +{ + private const string Net = "203.0.113.32/29"; // .32 – .39 + private const string A = "203.0.113.33"; + private const string B = "203.0.113.34"; + private const string Exempt = "203.0.113.35"; + private const string Outside = "203.0.113.50"; + + private static async Task AdminAsync( + EdgeFixture f, HttpMethod method, string url, object? body = null, + string? token = EdgeFixture.AdminToken) + { + using var request = new HttpRequestMessage(method, url); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + if (body is not null) request.Content = JsonContent.Create(body); + return await f.Client.SendAsync(request); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> ImpactAsync( + EdgeFixture f, string query, string? token = EdgeFixture.AdminToken) + { + using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/impact?{query}", token: token); + var text = await r.Content.ReadAsStringAsync(); + var body = string.IsNullOrWhiteSpace(text) + ? default + : JsonDocument.Parse(text).RootElement.Clone(); + return (r.StatusCode, body); + } + + private static async Task AskAsync(EdgeFixture f, string ip) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + using var r = await f.Client.SendAsync(request); + _ = (int)r.StatusCode; + } + + /// Traffic first, so the sources the preview probes are sources this + /// edge really is watching rather than rows the test invented. + private static async Task SeedTrafficAsync(EdgeFixture f, params string[] ips) + { + foreach (var ip in ips) await AskAsync(f, ip); + await f.FlushObservationsAsync(); + } + + private static List Sources(JsonElement body) + => body.GetProperty("sources").EnumerateArray().ToList(); + + private static JsonElement RowFor(JsonElement body, string key) + => Assert.Single(Sources(body), r => r.GetProperty("source").GetString() == key); + + [Fact] + public async Task The_preview_names_the_sources_inside_the_range_it_would_newly_refuse() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A, B, Outside); + + var (status, body) = await ImpactAsync(f, $"match={Net}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(Net, body.GetProperty("match").GetString()); + Assert.Equal("range", body.GetProperty("kind").GetString()); + Assert.Equal("snapshot+database", body.GetProperty("scope").GetString()); + Assert.True(body.GetProperty("wouldRefuse").GetBoolean()); + Assert.False(body.GetProperty("changesNothing").GetBoolean()); + Assert.False(body.GetProperty("wrote").GetBoolean()); + + // The two watched sources inside the range flip; the one outside is not + // probed at all, and the range's own network address always is — so it is + // in the count too, and an answer that left it out would be a preview of + // a range the edge cannot answer about. + Assert.Equal(3, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32()); + Assert.Equal(0, body.GetProperty("counts").GetProperty("alreadyRefused").GetInt32()); + Assert.DoesNotContain(Outside, body.ToString()); + foreach (var key in new[] { A, B, "203.0.113.32" }) + { + var row = RowFor(body, key); + Assert.Equal("pass", row.GetProperty("before").GetString()); + Assert.Equal("block_operator", row.GetProperty("after").GetString()); + Assert.Equal(Net, row.GetProperty("afterBy").GetString()); + Assert.Equal("newly refused", row.GetProperty("change").GetString()); + } + Assert.Contains("would be refused by this write", body.GetProperty("note").GetString()!); + } + + [Fact] + public async Task A_source_already_refused_by_something_else_is_not_counted_as_a_change() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A, B); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = A, reason = "already banned" })) { } + + var (_, body) = await ImpactAsync(f, $"match={Net}"); + var row = RowFor(body, A); + Assert.Equal("block_operator", row.GetProperty("before").GetString()); + Assert.Equal(A, row.GetProperty("beforeBy").GetString()); + Assert.Equal("already refused", row.GetProperty("change").GetString()); + Assert.Equal(2, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32()); + Assert.Equal(1, body.GetProperty("counts").GetProperty("alreadyRefused").GetInt32()); + } + + [Fact] + public async Task An_exemption_inside_the_range_keeps_passing_and_the_answer_says_why() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A, Exempt); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", + new { match = Exempt, note = "the office" })) { } + + var (_, body) = await ImpactAsync(f, $"match={Net}"); + var row = RowFor(body, Exempt); + Assert.Equal("pass_allowlisted", row.GetProperty("before").GetString()); + Assert.Equal("pass_allowlisted", row.GetProperty("after").GetString()); + Assert.Equal("an allow entry", row.GetProperty("afterBy").GetString()); + Assert.Equal("still passes", row.GetProperty("change").GetString()); + + // The exemption is named as sitting inside the match, so the operator + // sees the part of the range the ban will not reach. + var inside = body.GetProperty("exemptionsInside").EnumerateArray().ToList(); + Assert.Equal(Exempt, Assert.Single(inside).GetProperty("match").GetString()); + Assert.Equal("the office", inside[0].GetProperty("note").GetString()); + Assert.Empty(body.GetProperty("outrankedBy").EnumerateArray()); + } + + [Fact] + public async Task A_range_written_under_an_exemption_that_covers_it_refuses_nobody() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A); + // The exemption is broader than the ban about to be written: the pillar + // order answers with the exemption and the ban never speaks. + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", + new { match = Net, note = "the whole block" })) { } + + var (_, body) = await ImpactAsync(f, $"match={Net}"); + Assert.Equal(0, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32()); + Assert.True(body.GetProperty("changesNothing").GetBoolean()); + var outranking = body.GetProperty("outrankedBy").EnumerateArray().ToList(); + Assert.Equal(Net, Assert.Single(outranking).GetProperty("match").GetString()); + Assert.Equal("the whole block", outranking[0].GetProperty("note").GetString()); + Assert.Equal("still passes", RowFor(body, A).GetProperty("change").GetString()); + Assert.Contains("outrankedBy", body.GetProperty("note").GetString()!); + } + + [Fact] + public async Task A_write_that_changes_nothing_is_named_as_one_and_says_what_already_covers_it() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A); + // A broader range is already live, so the /29 about to be written is + // decoration. + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = "203.0.113.32/28", reason = "the whole netblock" })) { } + + var (_, body) = await ImpactAsync(f, $"match={Net}"); + Assert.True(body.GetProperty("changesNothing").GetBoolean()); + Assert.Equal(0, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32()); + var covered = body.GetProperty("alreadyCoveredBy"); + Assert.Equal("block_operator", covered.GetProperty("verdict").GetString()); + Assert.Equal("203.0.113.32/28", covered.GetProperty("by").GetString()); + Assert.Equal("already refused", RowFor(body, A).GetProperty("change").GetString()); + } + + [Fact] + public async Task The_match_is_normalised_by_the_write_paths_own_code() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A); + + // 203.0.113.37/29 and 203.0.113.32/29 are one row; the preview answers + // about the spelling the edge would keep. + var (_, body) = await ImpactAsync(f, "match=203.0.113.37/29"); + Assert.Equal(Net, body.GetProperty("match").GetString()); + + var (bad, badBody) = await ImpactAsync(f, "match=203.0.113.32/40"); + Assert.Equal(HttpStatusCode.BadRequest, bad); + Assert.Contains("prefix must be 0..32", badBody.GetProperty("error").GetString()!); + + // A /0 is refused on meaning by the write path, and the preview refuses it + // in the same words rather than answering about every address there is. + var (zero, zeroBody) = await ImpactAsync(f, "match=203.0.113.0/0"); + Assert.Equal(HttpStatusCode.BadRequest, zero); + Assert.Contains("shutdown, not a ban", zeroBody.GetProperty("error").GetString()!); + + // The abbreviated form is refused in the write's words, not answered + // about: the parser behind the write path reads "203.0.113" as + // 203.0.0.113, and a preview of that row would be a preview of a ban on a + // live address nobody meant. + var (typo, typoBody) = await ImpactAsync(f, "match=203.0.113"); + Assert.Equal(HttpStatusCode.BadRequest, typo); + Assert.Contains("not an IP address", typoBody.GetProperty("error").GetString()!); + } + + [Fact] + public async Task A_bare_address_is_previewed_under_the_key_this_edge_files_it_under() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", + new { ipv4KeyPrefixLength = 29 })) { } + await SeedTrafficAsync(f, A, "203.0.113.41"); + + // With a /29 key the edge files .33 as the group, so the preview of one + // address answers about the group the write would ban — and about no other + // group: .41 is watched too, and is not inside this one. + var (_, body) = await ImpactAsync(f, $"match={A}"); + Assert.Equal("address", body.GetProperty("kind").GetString()); + Assert.Equal("203.0.113.32/29", body.GetProperty("filedUnder").GetString()); + Assert.Equal(1, body.GetProperty("probed").GetInt32()); + Assert.Equal(1, body.GetProperty("counts").GetProperty("newlyRefused").GetInt32()); + var row = RowFor(body, "203.0.113.32/29"); + Assert.Equal("newly refused", row.GetProperty("change").GetString()); + Assert.DoesNotContain("203.0.113.40/29", body.ToString()); + } + + [Fact] + public async Task The_limit_bounds_the_sources_probed_and_says_it_left_some_out() + { + await using var f = new EdgeFixture(); + await SeedTrafficAsync(f, A, B, Exempt, "203.0.113.36", "203.0.113.37"); + + var (_, body) = await ImpactAsync(f, $"match={Net}&limit=2"); + Assert.Equal(2, body.GetProperty("probed").GetInt32()); + Assert.Equal(2, Sources(body).Count); + Assert.True(body.GetProperty("truncated").GetBoolean()); + } + + [Fact] + public async Task A_question_it_cannot_answer_is_refused_by_name() + { + await using var f = new EdgeFixture(); + var cases = new[] + { + ("", "match is required"), + ("match=" + Net + "&path=anything", "path must start with /"), + ("match=" + Net + "&limit=0", "limit must be 1..200"), + ("match=" + Net + "&limit=201", "limit must be 1..200"), + ("match=" + Net + "&source=engine", "unknown query parameter 'source'"), + }; + foreach (var (query, expected) in cases) + { + var (status, body) = await ImpactAsync(f, query); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains(expected, body.GetProperty("error").GetString()!); + } + } + + [Fact] + public async Task Asking_is_a_read_the_read_only_token_can_make_and_that_changes_no_answer_on_the_wire() + { + await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); + await SeedTrafficAsync(f, A, B); + + static async Task RowsAsync(EdgeFixture f) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Blocks.CountAsync() + await db.NetworkBans.CountAsync() + + await db.ConfigChanges.CountAsync(); + } + + var before = await RowsAsync(f); + var (status, _) = await ImpactAsync(f, $"match={Net}", token: EdgeFixture.ReadOnlyToken); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(before, await RowsAsync(f)); + + // The preview promised block_operator for these sources; the wire still + // answers pass, because the preview wrote nothing to the snapshot either. + using var request = new HttpRequestMessage(HttpMethod.Get, "/anything"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", A); + using var live = await f.Client.SendAsync(request); + Assert.NotEqual(HttpStatusCode.Forbidden, live.StatusCode); + + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Net })) { } + using var after = new HttpRequestMessage(HttpMethod.Get, "/anything"); + after.Headers.TryAddWithoutValidation("X-Forwarded-For", A); + using var refused = await f.Client.SendAsync(after); + // The write path's own answer: an operator block goes out with the + // configured status, 301 by default. The point of the assertion is only + // that the row the preview promised is the row the write put in effect. + Assert.Equal(HttpStatusCode.MovedPermanently, refused.StatusCode); + + var (anon, _) = await ImpactAsync(f, $"match={Net}", token: null); + Assert.Equal(HttpStatusCode.Unauthorized, anon); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs b/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs index bd4f348..7288915 100644 --- a/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/NetworkBanTests.cs @@ -375,4 +375,25 @@ public sealed class NetworkBanTests Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); Assert.Empty(await RowsAsync(f)); } + + [Fact] + public async Task An_address_missing_an_octet_is_refused_and_writes_no_row() + { + // The parser behind the write path accepts the legacy short forms and + // fills the missing octets in for you: "203.0.113" parses as 203.0.0.113. + // On a read that is a wrong answer about an address that does not exist; + // here it is a row — a ban on a live address nobody meant, filed under a + // spelling the operator will not find in the listing. The read surfaces + // refuse the string; the write path refuses it too, and says so. + await using var f = new EdgeFixture(); + var (status, body) = await BlockAsync(f, new { ip = "203.0.113" }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("not an IP address", body); + + var (rangeStatus, rangeBody) = await BlockAsync(f, new { ip = "203.0.113/24" }); + Assert.Equal(HttpStatusCode.BadRequest, rangeStatus); + Assert.Contains("not an IP address", rangeBody); + + Assert.Empty(await RowsAsync(f)); + } } diff --git a/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs b/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs index a07600a..8a02077 100644 --- a/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs +++ b/dotnet/OpenWaf.Tests.Unit/NetworkBanTests.cs @@ -65,6 +65,29 @@ public sealed class NetworkBanTests Assert.Equal("203.0.113.0/24", Normalized("::ffff:203.0.113.0/24")); } + [Fact] + public void An_abbreviated_v4_is_refused_because_it_is_not_an_address_anyone_typed() + { + // IPAddress.TryParse accepts the legacy short forms and fills the missing + // octets in: "203.0.113" parses as 203.0.0.113, and "10.1" as 10.0.0.1. + // On this path a parse that guesses writes a row, so an operator missing + // one octet bans a live address that was never the target and then reads + // the listing looking for the spelling they typed. The read surfaces + // (/decide, /history, /find) already refuse these strings; the write path + // has to refuse the same ones or the two disagree about whether the + // address exists at all. + foreach (var written in new[] { "203.0.113", "203.0.113/24", "10.1", "10.1/16", "203" }) + { + Assert.False(NetworkBans.TryNormalize(written, out _, out var error), written); + Assert.Contains("not an IP address", error); + } + + // The whole spelling still passes, mapped v6 included — the rule is about + // a v4 address written in fewer than four parts, not about v6. + Assert.Equal("203.0.113.0/24", Normalized("::ffff:203.0.113.0/24")); + Assert.Equal("203.0.113.7", Normalized("203.0.113.7")); + } + [Fact] public void A_range_over_every_address_is_refused_on_meaning_not_on_form() { diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index a839b0b..e2983ed 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1975,6 +1975,70 @@ check 'the scene cleans itself' 0 \ | python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$FND_IP"'","'"$FND_NET"'","198.51.100.196")]))')" +# What would this ban touch? (OPEN-75), on the shipped image: the preview runs +# against the snapshot and the observations this container actually holds, so the +# answer is about the sources this edge is watching, not about a table the test +# wrote. +echo '- the shipped edge previews what a ban would touch' +IMP_NET=198.51.100.200/29 # .200 - .207 +IMP_NET_Q=198.51.100.200%2F29 +IMP_A=198.51.100.201 +IMP_B=198.51.100.202 +impactq() { admin "$EDGE/admin-api/impact?match=$1${2:+&$2}"; } +imp_seen() { + # The observation writer is a pillar on its own timer, and the preview probes + # the sources the edge has actually recorded. + for _ in $(seq 1 45); do + n=$(admin "$EDGE/admin-api/observations?limit=1000" | python3 -c ' +import json,sys +print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))') + if [ "$n" -ge 2 ]; then return 0; fi + sleep 1 + done + return 0 +} +check 'the shipped edge has seen two sources inside the range' '404 404' \ + "$(code -H "X-Forwarded-For: $IMP_A" "$EDGE/imp-a") $(code -H "X-Forwarded-For: $IMP_B" "$EDGE/imp-b")" +check 'the shipped edge has recorded them as observations' 2 \ + "$(imp_seen; admin "$EDGE/admin-api/observations?limit=1000" | python3 -c ' +import json,sys +print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))')" +check 'the shipped preview names three sources the range would newly refuse' '3 0 0' \ + "$(impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +c=json.load(sys.stdin)["counts"] +print(c["newlyRefused"], c["alreadyRefused"], c["stillPassing"])')" +check 'the shipped preview answers about the row the write would create' yes \ + "$(impactq '198.51.100.205%2F29' | python3 -c ' +import json,sys +d=json.load(sys.stdin) +print("yes" if d["match"]=="198.51.100.200/29" and d["kind"]=="range" else "no")')" +check 'the shipped preview refuses a /0 in the writes words' yes \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/impact?match=198.51.100.0/0" >/dev/null; \ + admin "$EDGE/admin-api/impact?match=198.51.100.0/0" \ + | python3 -c 'import json,sys;print("yes" if "shutdown, not a ban" in json.load(sys.stdin)["error"] else "no")')" +check 'the shipped preview says an exemption over the whole match makes the ban refuse nobody' yes \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"match":"'"$IMP_NET"'","note":"the block is exempt"}' "$EDGE/admin-api/allow" >/dev/null; \ + impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +out=[a["match"] for a in d["outrankedBy"]] +print("yes" if d["changesNothing"] and not d["wouldRefuse"] and out==["198.51.100.200/29"] + else "no")')" +check 'the shipped preview is a read: the wire still answers the upstream' 404 \ + "$(code -H "X-Forwarded-For: $IMP_A" "$EDGE/imp-c")" +check 'the scene cleans itself' 0 \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \ + "$EDGE/admin-api/allow/$(admin "$EDGE/admin-api/allow?live=false" \ + | python3 -c 'import sys,json;print(next((a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$IMP_NET"'"), 0))')" >/dev/null; \ + admin "$EDGE/admin-api/allow?live=false" \ + | python3 -c 'import json,sys;print(len([a for a in json.load(sys.stdin) if a["match"].startswith("198.51.100.20")]))')" +check 'the shipped read-only token previews, no token does not' '200 401' \ + "$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/impact?match=$IMP_NET_Q") \ +$(code "$EDGE/admin-api/impact?match=$IMP_NET_Q")" + + 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 b245598..40b03e8 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -1738,6 +1738,70 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); !torn.includes(FND_IP), JSON.stringify(torn)); } + // What would this ban touch? (OPEN-75): the preview asks the real engine, over + // the sources this edge is watching inside the match, with the proposed entry + // added and nothing written. Written through the page's own forms so the rows + // the panel answers about are rows this run wrote. + { + const IMP_NET = '192.0.2.120/30'; // .120 - .123 + const IMP_WIDE = '192.0.2.112/28'; // .112 - .127, covers it + const IMP_HOST = '192.0.2.120'; + + const askImpact = async (match) => { + await page.evaluate(() => { document.getElementById('impactanswer').textContent = ''; }); + await page.fill('#impactMatch', match); + await page.click('#askImpact'); + await page.waitForFunction((asked) => (document.getElementById('impactanswer').textContent || '') + .indexOf('asked: ' + asked + ' at ') === 0, match, { timeout: 15000 }).catch(() => {}); + return page.$$eval('#impactanswer div', (ds) => ds.map((d) => d.textContent)); + }; + + const first = await askImpact(IMP_NET); + check('the preview answers about the match and counts the three kinds of source', + /^asked: 192\.0\.2\.120\/30 at \/ - \d+ sources probed - newly refused [1-9]\d*, already refused 0, still passing \d+$/.test(first[0] || ''), + JSON.stringify(first[0])); + check('the match\u2019s own address is probed and the answer names the row that would refuse it', + first.some((l) => /^192\.0\.2\.120 \u00b7 the match itself \u00b7 pass \u2192 block_operator \u00b7 newly refused \u00b7 by 192\.0\.2\.120\/30/.test(l || '')), + JSON.stringify(first)); + + await page.fill('#allowMatch', IMP_NET); + await page.fill('#allowNote', 'console gate: impact exempt'); + await page.fill('#allowTtl', '60'); + await page.click('#addAllow'); + await page.waitForFunction((m) => [...document.querySelectorAll('#allow tbody tr')] + .some((tr) => (tr.children[0].textContent || '').trim() === m), IMP_NET, + { timeout: 15000 }).catch(() => {}); + const exempt = await askImpact(IMP_NET); + check('an exemption over the whole match is named, and the preview says the ban would refuse nobody', + exempt.some((l) => /^an exemption outranks this ban at the match\u0027s own address: 192\.0\.2\.120\/30 \u00b7 console gate: impact exempt/.test(l || '')) + && /^asked: 192\.0\.2\.120\/30 at \/ - \d+ sources probed - newly refused 0, already refused 0, still passing [1-9]\d*$/.test(exempt[0] || ''), + JSON.stringify(exempt)); + + await page.fill('#blockIp', IMP_WIDE); + await page.fill('#blockReason', 'console gate: impact wide range'); + await page.click('#addBlock'); + await page.waitForFunction((k) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')] + .some((b) => b.dataset.k === k), IMP_WIDE, { timeout: 15000 }).catch(() => {}); + const covered = await askImpact(IMP_NET); + check('a match already covered by a live range is named as a write that changes nothing', + covered.some((l) => /^already covered at its own address: block_operator by 192\.0\.2\.112\/28 - this write would change nothing there/.test(l || '')), + JSON.stringify(covered)); + + const allowKey = await page.$$eval('#allow tbody tr', (trs, t) => { + const tr = trs.find((r) => (r.children[0].textContent || '').trim() === t); + const b = tr && tr.querySelector('button[data-act="delallow"]'); + return b ? b.dataset.k : ''; + }, IMP_NET); + if (allowKey) await page.click(`#allow tbody button[data-act="delallow"][data-k="${allowKey}"]`); + await page.click(`#blocks tbody button[data-act="delblock"][data-k="${IMP_WIDE}"]`); + await page.waitForFunction((k) => ![...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')] + .some((b) => b.dataset.k === k), IMP_WIDE, { timeout: 15000 }).catch(() => {}); + const torn = await page.$$eval('#blocks tbody button[data-act="delblock"]', + (bs) => bs.map((b) => b.dataset.k)); + check('the impact seeds left the operator list the way they were found', + !torn.includes(IMP_WIDE) && !torn.includes(IMP_NET), JSON.stringify(torn)); + } + // A phone in dark mode is the case an operator actually reaches the console // from — the address that got them blocked is the one they are typing about. // Both halves of this used to be broken and measured: the page overflowed a diff --git a/scripts/smoke.sh b/scripts/smoke.sh index c758ee3..e1ff30a 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -1272,6 +1272,140 @@ check 'the scene cleans itself' '0 0 0 0' \ find_rows)" +# What would this ban touch? (OPEN-75). The dry run answers one named request and +# the horizon answers what stops soon; neither answers the question asked BEFORE +# the write. Both failures are silent: a range written over an office block +# refuses people who were never the target, and a range written under an existing +# exemption refuses nobody at all — the operator sees 204 and moves on. +echo '- what a ban would touch, before it is written' +IMP_NET=192.0.2.192/29 # .192 - .199 +IMP_NET_Q=192.0.2.192%2F29 +IMP_A=192.0.2.193 +IMP_B=192.0.2.194 +IMP_FREE=192.0.2.195 +IMP_OUT=192.0.2.201 +impactq() { curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$1${2:+&$2}"; } +impact_rows() { + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/imp-b.json + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/imp-a.json + python3 -c ' +import json +print(len(json.load(open("/tmp/imp-b.json"))), len(json.load(open("/tmp/imp-a.json"))))' +} +imp_seen() { + # The observation writer is a pillar on its own timer, and the preview probes + # the sources the edge has actually recorded — so the scene has to wait for the + # rows its own traffic earned to land before it asks what a ban would touch. + # The flush interval is fifteen seconds, + # every fifteen seconds, so the wait is longer than one interval. + for _ in $(seq 1 45); do + n=$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/observations" \ + | python3 -c ' +import json,sys +print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))') + if [ "$n" -ge 2 ]; then return 0; fi + sleep 1 + done + # Not found. The scene does not fail here: the check that asked prints what it + # actually saw, and a wait that ends without the rows is a slower failure, not + # a hidden one. + return 0 +} +allow_id_by_match() { + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" \ + | python3 -c 'import sys,json;print(next((a["id"] for a in json.load(sys.stdin) if a["match"]==sys.argv[1]), 0))' "$1" +} +check 'the edge has seen sources inside the range and one outside it' '404 404 404' \ + "$(code -H "X-Forwarded-For: $IMP_A" "$(from imp-a)") \ +$(code -H "X-Forwarded-For: $IMP_B" "$(from imp-b)") \ +$(code -H "X-Forwarded-For: $IMP_OUT" "$(from imp-c)")" +check 'the edge has recorded the sources inside the range it is about to be asked about' 2 \ + "$(imp_seen; curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/observations" \ + | python3 -c ' +import json,sys +print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))')" +check 'the preview names the sources inside the range it would newly refuse' '3 0 0' \ + "$(impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +c=json.load(sys.stdin)["counts"] +print(c["newlyRefused"], c["alreadyRefused"], c["stillPassing"])')" +check 'it probes the watched sources and the ranges own address, not the one outside' yes \ + "$(impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +src={r["source"] for r in d["sources"]} +print("yes" if {"192.0.2.193","192.0.2.194","192.0.2.192"} <= src and "192.0.2.201" not in src + and all(r["change"]=="newly refused" for r in d["sources"]) + and all(r["after"]=="block_operator" and r["afterBy"]=="192.0.2.192/29" for r in d["sources"]) + else "no")')" +check 'a bare address is previewed under the key this edge files it under' yes \ + "$(impactq "$IMP_A" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +print("yes" if d["kind"]=="address" and d["filedUnder"]=="192.0.2.193" + and d["probed"]==1 and d["wouldRefuse"] else "no")')" +check 'the preview is a promise, not a write: the wire still answers the upstream' '404 404' \ + "$(code -H "X-Forwarded-For: $IMP_A" "$(from imp-d)") \ +$(code -H "X-Forwarded-For: 192.0.2.197" "$(from imp-e)")" +check 'an exemption inside the range is named as inside, and the ban will not reach it' yes \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"match":"'"$IMP_FREE"'","note":"the office inside"}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow" >/dev/null; \ + impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +ex=[a["match"] for a in d["exemptionsInside"]] +print("yes" if ex==["192.0.2.195"] and d["counts"]["stillPassing"]==0 + and d["wouldRefuse"] else "no")')" +check 'an exemption that covers the whole match makes the ban refuse nobody' yes \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"match":"'"$IMP_NET"'","note":"the block is exempt"}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow" >/dev/null; \ + impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +out=[a["match"] for a in d["outrankedBy"]] +print("yes" if d["changesNothing"] and not d["wouldRefuse"] and d["counts"]["newlyRefused"]==0 + and out==["192.0.2.192/29"] and d["counts"]["stillPassing"]>=3 else "no")')" +check 'a range already covered by a live one is named as a write that changes nothing' yes \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow/$(allow_id_by_match '192.0.2.192/29')" >/dev/null; \ + code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"ip":"192.0.2.192/28","reason":"the whole netblock"}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null; \ + impactq "$IMP_NET_Q" | python3 -c ' +import json,sys +d=json.load(sys.stdin) +cov=d["alreadyCoveredBy"] +print("yes" if d["changesNothing"] and cov and cov["verdict"]=="block_operator" + and cov["by"]=="192.0.2.192/28" and d["counts"]["alreadyRefused"]>=3 else "no")')" +check 'a match the write would refuse is refused here in the writes words' '400 400 400 400 400' \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact") \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=192.0.2.0/0") \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=192.0.2") \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q&path=wp-login") \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q&limit=0")" +check 'the read-only token previews, no token does not' '200 401' \ + "$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q") \ +$(code "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q")" +check 'previewing it six times wrote nothing: the stores hold the same rows' \ + "$(impact_rows)" \ + "$(for _ in 1 2 3; do impactq "$IMP_NET_Q" >/dev/null; impactq "$IMP_A" >/dev/null; done; impact_rows)" +check 'the scene cleans itself' '0 0' \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.192%2F28" >/dev/null; \ + code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow/$(allow_id_by_match '192.0.2.195')" >/dev/null; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/imp-b2.json; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/imp-a2.json; \ + python3 -c ' +import json +b=json.load(open("/tmp/imp-b2.json")); a=json.load(open("/tmp/imp-a2.json")) +print(len([r for r in b if r["sourceKey"].startswith("192.0.2.19")]), + len([r for r in a if r["match"].startswith("192.0.2.19")]))')" + + 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 \