one source through time: every decision this edge made about it, in order

GET /admin-api/history?ip=<address> joins the six dated stores that can name a
source - the operator's block, the ban this edge wrote itself, the range whose
CIDR covers the address, the exemption covering it, the alerts raised about the
key, the change records whose target is the key or a range that covers it, and
the observation row that counts its refusals - and returns them oldest-first with
what each one did. The dossier (OPEN-70) answers now, the horizon (OPEN-72)
answers soon; this answers what already happened, which is the question a
complaint on Monday actually asks.

Rulings:
- the order is the answer. "The exemption, then the ban" and "the ban, then the
  exemption" are different incidents, and an operator assembling this from six
  listings gets whichever one they opened last. Oldest-first is asserted even
  when the rows were written newest-first.
- a range or an exemption is in the story because it covers the address, not
  because a row names it - the distinction the dossier had to learn - and a
  change to that range is a change to this source's conditions, so its change
  record belongs here too.
- inForce is null for the kinds that are events rather than states. An alert, a
  change record and a sighting do not answer "is it in force"; false would say
  the alert had been switched off. Expired rows stay and say when they stopped.
- searched counts what was looked at, so an empty story is not confused with a
  surface that read nothing. Window 1..129600 min (7d default, the retention
  window of the rows that make up most of a story), limit 200 by default and it
  says how much it left out.
- the engine ban's evidence is its stored reason, not the reason plus the same
  fields again: the first run printed "last 404 /wp-login.php - last 404
  /wp-login.php - 3 refusals in a row".

The console carries the same call under the horizon: one address, the joined
timeline, each line stamped and marked in force or EXPIRED, with the header
naming the key the address is filed under and what was searched.

One gate assertion moved rather than the product: the scene asked for the story of
an address "with nothing recorded" and got 34 change records, because the
netblock scene writes and removes 192.0.2.0/24 through the run and a change to a
/24 really is part of the story of every address inside it. The surface was right;
the assertion had picked an address that was not outside anything.

gates: build 0 warnings / 0 errors, unit 377/377, integration 383/383 in 34 s,
console 151 assertions 0 failed, smoke passed 230 failed 0, compose 331 passed
0 failed against the built image at 262 MB, 0 containers left behind.

Refs OPEN-73.
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 11:54:45 +02:00
parent 1ec794dc75
commit 3079b536ba
7 changed files with 849 additions and 4 deletions
+71 -4
View File
@@ -431,6 +431,9 @@ GET /admin-api/expiring?within= what stops being enforced inside the window
(1..1440 min, 30 by default), each row
carrying what the engine WOULD answer for that
source with only that entry removed
GET /admin-api/history?ip= one source's story: every dated record naming
it or covering its address, oldest first
(within=1..129600 min, 7d default; limit=200)
```
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
@@ -1369,6 +1372,58 @@ it answers about every edge that shares that store. A `within` out of bounds is
everywhere else on the surface, and the read-only token can ask it — it writes
nothing, and six asks leave every counter and every row where they were.
### One source through time
`GET /admin-api/history?ip=<address>` answers the Monday question the other two
surfaces do not. The dossier says what this edge knows about an address **now**;
the horizon says what changes **soon**; this says what already happened to that
source, **in the order it happened**.
```
GET /admin-api/history?ip=203.0.113.69
{ "ip": "203.0.113.69", "sourceKey": "203.0.113.69",
"window": { "withinMinutes": 10080, "since": "...", "until": "..." },
"scope": "database", "count": 6, "shown": 6, "truncated": false,
"events": [
{ "at": "...", "kind": "range ban", "what": "the operator banned 203.0.113.64/29, which covers this address",
"detail": "netblock scanning the site", "inForce": true, "expiresAt": null },
{ "at": "...", "kind": "config change", "what": "block added: 203.0.113.64/29",
"detail": "netblock scanning the site", "inForce": null },
{ "at": "...", "kind": "allow entry", "what": "exempted by \"203.0.113.69\" — an exemption outranks every ban",
"detail": "ticket 441", "inForce": false, "expiresAt": "..." },
{ "at": "...", "kind": "alert", "what": "alert server_error_streak raised ×3", "detail": "..." },
{ "at": "...", "kind": "engine ban", "what": "this edge banned the source itself",
"detail": "3 consecutive refusals (400-499) within 5 min; last 404 /wp-login.php",
"inForce": true, "expiresAt": "..." },
{ "at": "...", "kind": "seen", "what": "last seen — answered 403 on /anything",
"detail": "4 refusals counted, worst run 3 in a row", "inForce": null } ],
"searched": { "block": 1, "range": 1, "allow": 1, "alert": 1, "change": 2, "observation": 1 } }
```
**The order is the answer.** "The exemption, then the ban" and "the ban, then the
exemption" are different incidents, and an operator assembling this from six
listings gets whichever one they opened last. Rows come oldest-first whatever
order the writes happened in, and the sort is asserted that way.
**A range is in the story because it covers the address, not because a row names
it.** The same distinction the dossier had to learn: no row says
`203.0.113.69`, and the `/29` that refuses it is still part of its history — as
is the change record for that `/29`, because a change to the range is a change to
this source's conditions.
**`inForce` is null for the kinds that are events, not states.** An alert, a
change record and a sighting do not answer "is it in force"; printing `false`
would say the alert had been switched off. Expired rows stay in the story and
carry `inForce: false` with their `expiresAt`: "this exemption stopped exempting
on Tuesday" is part of what happened, not a row to hide.
**`searched` says what was looked at**, so an empty story is distinguishable from
a surface that read nothing: "nothing recorded about this source" and "this edge
holds no records at all" are different answers. The window is 1..129600 minutes
(7 days by default, because that is how long the observations and alerts that make
up most of a story are kept); `limit` is 200 by default and says how much it left
out. The read-only token can ask it, and six asks write nothing.
## Console
`GET /admin` serves a single page over those endpoints — mode and snapshot age,
@@ -1419,6 +1474,13 @@ instead of guessing at one. The window is checked on the page before the call
goes out, and the answer box is emptied first and headed with the window that was
asked for, so neither a scene nor an operator on a slow link can read the previous
answer as the new one.
Under the horizon sits the story (OPEN-73): the same address box and one button,
and the page prints the joined timeline oldest-first — the range that covers the
address, the block written on it, the exemption, the alerts, the operator's own
change records and the sightings — each line stamped, marked `in force` or
`EXPIRED …`, with the reason the row carries. The header names the key the address
is filed under and counts what was searched, so an address with nothing recorded
reads as an answer rather than as a broken panel.
It also writes, with the two controls an incident actually reaches for: block
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
@@ -1608,9 +1670,10 @@ into one green line. macOS host, this tree, re-measured 2026-10-05 with the dura
alert-push queue, the config transfer, the second token, the startup refusals, the change
log and that log on the console, the operator's ranges, the netblock watch and
the per-path request budgets, the volume answer of the dry run, one address
answered in one call, the sources a budget is pausing and the enforcement horizon:
build 0 warnings / 0 errors, unit **377/377**, integration **375/375 in 35 s**,
console **142 assertions, 0 failed**, smoke **passed 217, failed 0**, and compose **324 passed,
answered in one call, the sources a budget is pausing, the enforcement horizon and one
source told in order:
build 0 warnings / 0 errors, unit **377/377**, integration **383/383 in 34 s**,
console **151 assertions, 0 failed**, smoke **passed 230, failed 0**, and compose **331 passed,
0 failed** against the built image at 262 MB, 0 containers left behind. One integration run and
four console runs earned their keep in this cycle. The integration run caught a product
defect, not a test one: the alert push queue's worker was registered as a hosted service
@@ -1634,7 +1697,11 @@ could not retry past a one-hour ban. Those bans are now cleared by name
(`?source=engine&key=`), which leaves the engine bans the netblock scene reads standing,
and this cycle found the same trap twice more in the budget scene: it cleared the ban
*after* the probe the ban was failing, and its reopen retry loop banned itself three
refusals deep. The smoke story from the
refusals deep. One assertion had to be moved rather than the product: the history scene
asked for the story of an address "with nothing recorded" and got 34 change records,
because the netblock scene writes and removes `192.0.2.0/24` through the run and a
change to a /24 really is part of the story of every address inside it — the surface was
right and the assertion had picked an address that was not outside anything. The smoke story from the
previous cycle is kept here because the numbers are read next to it: the edge used
to be started from the repository root, where there is no `appsettings.json`, so it
loaded no `ReverseProxy` section, logged "Request reached the end of the
+50
View File
@@ -169,6 +169,13 @@ internal static class AdminConsole
</div>
<div id="horizonanswer" class="muted"></div>
<h2>One source through time</h2>
<div class="bar">
<input id="historyIp" placeholder="address" autocomplete="off" size="18">
<button id="askHistory">what happened to it, in order?</button>
</div>
<div id="historyanswer" class="muted"></div>
<h2>Sources the edge is watching</h2>
<div class="bar">
<input id="srcfilter" placeholder="filter observations and streaks by source key" autocomplete="off" size="28">
@@ -1021,6 +1028,49 @@ el('askSource').onclick = async () => {
}
};
el('askHistory').onclick = async () => {
// One source through time (OPEN-73). The dossier above answers now and the
// horizon answers soon; this answers what already happened, in the order it
// happened. The six stores that can name a source are joined by the edge, not
// by whoever last opened a listing, and the rows come oldest-first because the
// order is the answer: "the exemption, then the ban" and "the ban, then the
// exemption" are different incidents.
const ip = el('historyIp').value.trim();
if (!ip) { note('an address first - the story is about one source', true); return; }
// Emptied first, and the first line names the address that was asked for: a
// wait for "an answer is in the box" must never be satisfied by the previous
// answer, which is how the dossier scene once read the wrong address.
el('historyanswer').textContent = '';
const r = await apiRaw('/admin-api/history?ip=' + encodeURIComponent(ip));
if (failed(r)) return;
const d = r.body || {};
const searched = d.searched || {};
const lines = [];
lines.push('asked: ' + (d.ip || ip) + ' filed as ' + (d.sourceKey || '?')
+ ' - ' + (d.count === undefined ? '?' : d.count) + ' events'
+ (d.truncated ? ' (showing ' + d.shown + ')' : '')
+ ' - searched: block ' + (searched.block ?? '?') + ', range ' + (searched.range ?? '?')
+ ', allow ' + (searched.allow ?? '?') + ', alert ' + (searched.alert ?? '?')
+ ', change ' + (searched.change ?? '?') + ', seen ' + (searched.observation ?? '?'));
const w = d.window || {};
if (w.since) lines.push('window: ' + w.since + ' \u2192 ' + w.until);
for (const ev of (d.events || [])) {
const when = (ev.at || '').replace('T', ' ').slice(0, 19);
let line = when + ' \u00b7 ' + (ev.kind || '?') + ' \u00b7 ' + (ev.what || '');
if (ev.inForce === true) line += ' \u00b7 in force';
else if (ev.inForce === false) line += ' \u00b7 EXPIRED ' + ((ev.expiresAt || '').replace('T', ' ').slice(0, 19));
if (ev.detail) line += ' \u00b7 ' + ev.detail;
lines.push(line);
}
if (d.note) lines.push(d.note);
const box = el('historyanswer');
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
+189
View File
@@ -1321,6 +1321,170 @@ note = t.Note
});
});
// One source through time (OPEN-73). The dossier answers what this edge
// knows about an address now; the horizon answers what changes soon. The
// question neither answers is the one a complaint on Monday asks: what
// already happened to this source, in the order it happened. Every record
// is dated and every one is in this database — the block an operator
// wrote, the ban this edge decided on its own, the exemption that let it
// through, the alerts raised about it, the operator's own change records,
// the row that counts its refusals — but they sit in six tables, so the
// story is whatever the last-opened listing happened to show.
//
// The join is here rather than in the page for the same reason the dry run
// is: an answer assembled from six calls can have each part true and the
// whole wrong, and the ordering is the answer.
group.MapGet("/history", async (string? ip, int? within, int? limit,
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "within", "limit"))
return Results.BadRequest(new { error = unknown });
if (string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new { error = "ip is required: this surface answers about one source" });
if (!IsAnAddress(ip.Trim()))
return Results.BadRequest(new { error = $"ip must be an address; got \"{ip}\"" });
var askedIp = ip.Trim();
var minutes = within ?? HistoryDefaultMinutes;
if (minutes < HistoryMinMinutes || minutes > HistoryMaxMinutes)
return Results.BadRequest(new { error = $"within must be {HistoryMinMinutes}..{HistoryMaxMinutes} minutes; got {minutes}" });
var take = limit ?? HistoryDefaultLimit;
if (take < HistoryMinLimit || take > HistoryMaxLimit)
return Results.BadRequest(new { error = $"limit must be {HistoryMinLimit}..{HistoryMaxLimit}; got {take}" });
var now = DateTimeOffset.UtcNow;
var since = now.AddMinutes(-minutes);
var policy = state.GetOrRefresh().Policy;
// The key, not the address — the same rule the dossier had to learn:
// a v6 source is filed under its /64, and looking up the address the
// socket carried would answer "nothing happened to it".
var key = SourceKey.For(askedIp, policy);
var blocks = await db.Blocks.AsNoTracking()
.Where(b => b.SourceKey == key && b.CreatedAt >= since)
.ToListAsync(ct);
var alerts = await db.Alerts.AsNoTracking()
.Where(a => a.SourceKey == key && a.CreatedAt >= since)
.ToListAsync(ct);
var observation = await db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.SourceKey == key, ct);
// A range and an exemption are matched against the address, not the
// key, and both lists are the operator's own — small enough to filter
// here rather than pretend SQL expresses containment for both
// families. The distinction the dossier learned applies to the story
// too: a /28 that covers this address is part of its history even
// though no row names it.
var ranges = (await db.NetworkBans.AsNoTracking().ToListAsync(ct))
.Where(r => NetworkMatch.Matches(askedIp, r.Match) && r.CreatedAt >= since)
.ToList();
var allows = (await db.AllowEntries.AsNoTracking().ToListAsync(ct))
.Where(a => NetworkMatch.Matches(askedIp, a.Match) && a.CreatedAt >= since)
.ToList();
var changes = (await db.ConfigChanges.AsNoTracking()
.Where(c => c.At >= since)
.ToListAsync(ct))
.Where(c => string.Equals(c.Target, key, StringComparison.Ordinal)
|| string.Equals(c.Target, askedIp, StringComparison.Ordinal)
// A change to a range that covers this address is a change to
// this source's conditions, so it belongs in its story.
|| NetworkMatch.Matches(askedIp, c.Target))
.ToList();
var events = new List<HistoryEvent>();
foreach (var b in blocks)
{
// The reason an engine ban carries already narrates its evidence
// ("3 consecutive refusals (400-499) within 5 min; last 404
// /wp-login.php"), so appending the same fields again would print
// the sentence twice with a dash between it. The fields are the
// fallback for a row written without a reason, not a suffix.
var evidence = !string.IsNullOrWhiteSpace(b.Reason)
? b.Reason
: b.LastStatusCode is null && b.LastPath is null
? null
: $"last {b.LastStatusCode?.ToString() ?? "?"} {b.LastPath}"
+ (b.ConsecutiveRefusals is > 0
? $" ({b.ConsecutiveRefusals} refusals in a row)" : "");
events.Add(new HistoryEvent(b.CreatedAt,
b.Source == BlockSource.Operator ? "operator block" : "engine ban",
b.Source == BlockSource.Operator
? "the operator wrote a block on this source"
: "this edge banned the source itself",
string.IsNullOrWhiteSpace(evidence) ? null : evidence,
b.IsLive(now), b.ExpiresAt, key, b.Id));
}
foreach (var r in ranges)
events.Add(new HistoryEvent(r.CreatedAt, "range ban",
$"the operator banned {r.Match}, which covers this address",
string.IsNullOrWhiteSpace(r.Reason) ? null : r.Reason,
r.IsLive(now), r.ExpiresAt, r.Match, r.Id));
foreach (var a in allows)
events.Add(new HistoryEvent(a.CreatedAt, "allow entry",
$"exempted by \"{a.Match}\" \u2014 an exemption outranks every ban",
string.IsNullOrWhiteSpace(a.Note) ? null : a.Note,
a.IsLive(now), a.ExpiresAt, a.Match, a.Id));
foreach (var a in alerts)
events.Add(new HistoryEvent(a.CreatedAt, "alert",
$"alert {a.Kind} raised \u00d7{a.Count}",
string.IsNullOrWhiteSpace(a.Detail)
? $"last {a.LastStatusCode?.ToString() ?? "?"} {a.LastPath}" : a.Detail,
null, null, a.SourceKey, a.Id));
foreach (var c in changes)
events.Add(new HistoryEvent(c.At, "config change",
$"{c.Section} {c.Action}: {c.Target}",
string.IsNullOrWhiteSpace(c.Detail) ? null : c.Detail,
null, null, c.Target, c.Id));
if (observation is not null)
{
if (observation.FirstSeenAt >= since)
events.Add(new HistoryEvent(observation.FirstSeenAt, "seen",
"first seen by this edge", null, null, null, observation.SourceKey, null));
if (observation.LastSeenAt >= since)
events.Add(new HistoryEvent(observation.LastSeenAt, "seen",
$"last seen \u2014 answered {observation.LastStatusCode?.ToString() ?? "?"} on {observation.LastPath}",
$"{observation.TotalRefusals} refusals counted, worst run "
+ $"{observation.MaxConsecutiveRefusals} in a row",
null, null, observation.SourceKey, null));
}
// Oldest first: this is a story, and reading it backwards turns "the
// exemption, then the ban" into "the ban, then the exemption".
events.Sort((x, y) => x.At.CompareTo(y.At));
var shown = events.Take(take).ToList();
return Results.Ok(new
{
ip = askedIp,
sourceKey = key,
keyRule = new
{
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "bans, alerts and observations are filed under sourceKey; ranges and exemptions are matched against ip itself"
},
window = new { withinMinutes = minutes, since, until = now },
scope = "database",
count = events.Count,
shown = shown.Count,
truncated = events.Count > shown.Count,
events = shown,
// What was looked at, so an empty story is distinguishable from a
// surface that read nothing: "nothing happened to this source" and
// "this edge holds no records at all" are different answers.
searched = new
{
block = blocks.Count,
range = ranges.Count,
allow = allows.Count,
alert = alerts.Count,
change = changes.Count,
observation = observation is null ? 0 : 1
},
note = events.Count == 0
? "nothing recorded about this source inside the window; `searched` names what was looked at"
: "oldest first; a range or an exemption is in the story because it covers this address, not because a row names it; expired rows stay and say so"
});
});
// 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
@@ -1714,6 +1878,17 @@ note = t.Note
}
};
// One source through time (OPEN-73). Seven days is the default because that
// is how long the observations and alerts that make up most of a story are
// kept (OPEN-19); ninety is the ceiling because past the retention window the
// rows this joins are gone whatever the window says.
private const int HistoryDefaultMinutes = 10080;
private const int HistoryMinMinutes = 1;
private const int HistoryMaxMinutes = 129600;
private const int HistoryDefaultLimit = 200;
private const int HistoryMinLimit = 1;
private const int HistoryMaxLimit = 2000;
// The enforcement horizon (OPEN-72). A day is the ceiling because that is the
// longest thing an operator plans for; asking for a year would turn a horizon
// into a dump of every dated row.
@@ -1976,6 +2151,20 @@ note = t.Note
/// <summary>One dated entry that stops being enforced inside the horizon, and —
/// for the address-shaped kinds — what answers once it is gone.</summary>
/// <summary>One moment in one source's story (OPEN-73). `InForce` is null for the
/// kinds that are events rather than states — an alert, a change record, a
/// sighting — because "is it in force" is not a question they answer; a `false`
/// there would say the alert was switched off.</summary>
internal sealed record HistoryEvent(
DateTimeOffset At,
string Kind,
string What,
string? Detail,
bool? InForce,
DateTimeOffset? ExpiresAt,
string? Match,
long? Id);
internal sealed record HorizonRow(
string Kind,
long Id,
@@ -0,0 +1,287 @@
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;
/// <summary>
/// One source through time (OPEN-73): every decision this edge made about one
/// address, in the order it made them.
///
/// The records were never the problem. The block, the ban the edge wrote itself,
/// the exemption, the range that covers the address, the alerts raised about it,
/// the operator's change records and the row counting its refusals are all dated
/// and all in this database — in six tables. An operator rebuilding the story by
/// hand gets whichever listing they opened last, and the order — which is the
/// answer — comes from memory.
///
/// What these tests hold the surface to: the join reaches every store that can
/// name the source or cover its address; a range is in the story because it
/// covers the address, not because a row names it; expired rows stay and say so;
/// the order is oldest-first whatever order the rows were written in; an empty
/// story names what was searched; and asking writes nothing.
/// </summary>
public sealed class SourceHistoryTests
{
private const string Range = "203.0.113.64/29"; // .64 – .71
private const string Inside = "203.0.113.69";
private const string Source = "203.0.113.88";
private const string Nobody = "203.0.113.199";
private static async Task<HttpResponseMessage> 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)> HistoryAsync(
EdgeFixture f, string query, string? token = EdgeFixture.AdminToken)
{
using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/history?{query}", token: token);
var text = await r.Content.ReadAsStringAsync();
// A refusal carries no body: an empty answer is an answer, and parsing it
// would fail the test for the wrong reason.
var body = string.IsNullOrWhiteSpace(text)
? default
: JsonDocument.Parse(text).RootElement.Clone();
return (r.StatusCode, body);
}
private static async Task<int> AskAsync(EdgeFixture f, string path, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
using var r = await f.Client.SendAsync(request);
return (int)r.StatusCode;
}
/// <summary>Rows written straight to storage, because the API only accepts an
/// expiry or a creation time relative to now and the test needs the order.</summary>
private static async Task SeedAsync(EdgeFixture f, object row)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.Add(row);
await db.SaveChangesAsync();
await f.Service<EdgeStateStore>().InvalidateAsync();
}
private static List<JsonElement> Events(JsonElement body)
=> body.GetProperty("events").EnumerateArray().ToList();
private static bool HasKind(List<JsonElement> events, string kind)
=> events.Any(e => e.GetProperty("kind").GetString() == kind);
[Fact]
public async Task The_story_joins_every_record_that_names_or_covers_the_address()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Range, reason = "netblock scanning the site" })) { }
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Inside, reason = "the office behind it" })) { }
await SeedAsync(f, new AllowEntry
{
Match = Inside, Note = "ticket 441", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-20)
});
await AskAsync(f, "/anything", Inside);
// The observation row is written off the response, on the writer's own
// timer — the same reason every other surface that reads it flushes first.
await f.FlushObservationsAsync();
var (status, body) = await HistoryAsync(f, $"ip={Inside}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(Inside, body.GetProperty("ip").GetString());
Assert.Equal(Inside, body.GetProperty("sourceKey").GetString());
Assert.Equal("database", body.GetProperty("scope").GetString());
var events = Events(body);
Assert.True(events.Count >= 5, body.ToString());
foreach (var kind in new[] { "operator block", "range ban", "allow entry", "config change", "seen" })
Assert.True(HasKind(events, kind), $"no {kind} event in {body.GetProperty("count").GetInt32()} events");
// The range is in this address's story although no row names the address.
var range = events.Single(e => e.GetProperty("kind").GetString() == "range ban");
Assert.Equal(Range, range.GetProperty("match").GetString());
Assert.True(range.GetProperty("inForce").GetBoolean());
Assert.Contains("covers this address", range.GetProperty("what").GetString()!);
Assert.Contains("netblock scanning", range.GetProperty("detail").GetString()!);
// A change to that range is a change to this source's conditions, so the
// change record belongs in this address's story even though the operator
// typed a CIDR and not this address.
var changes = events.Where(e => e.GetProperty("kind").GetString() == "config change").ToList();
Assert.Contains(changes, e => e.GetProperty("match").GetString() == Range);
Assert.Contains(changes, e => e.GetProperty("match").GetString() == Inside);
Assert.True(body.GetProperty("searched").GetProperty("change").GetInt32() >= 2);
}
[Fact]
public async Task An_alert_and_a_ban_the_edge_wrote_itself_are_both_in_the_source_story()
{
await using var f = new EdgeFixture(threshold: 3);
f.Upstream.StatusFor = _ => StatusCodes.Status502BadGateway;
for (var i = 0; i < 4; i++) await AskAsync(f, "/boom", Source);
f.Upstream.StatusFor = _ => StatusCodes.Status404NotFound;
for (var i = 0; i < 3; i++) await AskAsync(f, "/wp-login.php", Source);
await f.FlushObservationsAsync();
var (_, body) = await HistoryAsync(f, $"ip={Source}");
var events = Events(body);
var ban = Assert.Single(events, e => e.GetProperty("kind").GetString() == "engine ban");
Assert.Equal(Source, ban.GetProperty("match").GetString());
Assert.True(ban.GetProperty("inForce").GetBoolean());
Assert.Contains("banned the source itself", ban.GetProperty("what").GetString()!);
Assert.Contains("last 404 /wp-login.php", ban.GetProperty("detail").GetString()!);
Assert.True(HasKind(events, "alert"), body.ToString());
var alert = events.First(e => e.GetProperty("kind").GetString() == "alert");
Assert.Equal("server_error_streak", alert.GetProperty("what").GetString()!.Split(' ')[1]);
// An alert is an event, not a state: "is it in force" is not a question it
// answers, and false would say it had been switched off.
Assert.True(alert.TryGetProperty("inForce", out var force)
? force.ValueKind == JsonValueKind.Null
: true);
Assert.True(HasKind(events, "seen"), body.ToString());
}
[Fact]
public async Task A_range_that_only_covers_the_address_is_still_part_of_its_history()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Range, reason = "rotating scanner" })) { }
var (_, body) = await HistoryAsync(f, $"ip={Inside}");
var range = Assert.Single(Events(body), e => e.GetProperty("kind").GetString() == "range ban");
Assert.Equal(Range, range.GetProperty("match").GetString());
Assert.Equal(1, body.GetProperty("searched").GetProperty("range").GetInt32());
// An address outside the range is not told it is inside it.
var (_, other) = await HistoryAsync(f, "ip=203.0.113.72");
Assert.Equal(0, other.GetProperty("searched").GetProperty("range").GetInt32());
}
[Fact]
public async Task An_expired_row_stays_in_the_story_and_says_it_stopped_being_in_force()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new AllowEntry
{
Match = Inside, Note = "the window the ticket gave",
CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-60),
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5)
});
var (_, body) = await HistoryAsync(f, $"ip={Inside}");
var allow = Assert.Single(Events(body), e => e.GetProperty("kind").GetString() == "allow entry");
Assert.False(allow.GetProperty("inForce").GetBoolean());
Assert.NotEqual(JsonValueKind.Null, allow.GetProperty("expiresAt").ValueKind);
Assert.Contains("the window the ticket gave", allow.GetProperty("detail").GetString()!);
// The store was searched and the row was found: an expired row is not the
// same answer as nothing having ever been written.
Assert.Equal(1, body.GetProperty("searched").GetProperty("allow").GetInt32());
Assert.Equal(1, body.GetProperty("count").GetInt32());
}
[Fact]
public async Task The_order_is_oldest_first_whatever_order_the_rows_were_written_in()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
// Written newest-first on purpose: the order of the writes is not the
// order of the story, and reading it backwards turns "the exemption, then
// the ban" into "the ban, then the exemption".
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, Reason = "ban, an hour later",
CreatedAt = now.AddMinutes(-30)
});
await SeedAsync(f, new AllowEntry
{
Match = Source, Note = "exemption first", CreatedAt = now.AddMinutes(-90)
});
var (_, body) = await HistoryAsync(f, $"ip={Source}");
var events = Events(body);
Assert.Equal(2, events.Count);
Assert.Equal("allow entry", events[0].GetProperty("kind").GetString());
Assert.Equal("operator block", events[1].GetProperty("kind").GetString());
var stamps = events.Select(e => DateTimeOffset.Parse(e.GetProperty("at").GetString()!)).ToList();
Assert.True(stamps[0] < stamps[1], string.Join(" then ", stamps));
}
[Fact]
public async Task An_address_with_nothing_recorded_is_answered_in_words_with_what_was_searched()
{
await using var f = new EdgeFixture();
var (status, body) = await HistoryAsync(f, $"ip={Nobody}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(0, body.GetProperty("count").GetInt32());
Assert.Empty(Events(body));
foreach (var key in new[] { "block", "range", "allow", "alert", "change", "observation" })
Assert.Equal(0, body.GetProperty("searched").GetProperty(key).GetInt32());
Assert.Contains("nothing recorded", body.GetProperty("note").GetString()!);
}
[Fact]
public async Task A_window_or_a_limit_it_cannot_answer_with_is_refused_by_name()
{
await using var f = new EdgeFixture();
foreach (var query in new[]
{
"ip=203.0.113.88&within=0",
"ip=203.0.113.88&within=129601",
"ip=203.0.113.88&limit=0",
"ip=203.0.113.88&limit=2001",
"ip=203.0.113.88&nonsense=1",
"within=60",
"ip=203.0.113"
})
{
var (status, body) = await HistoryAsync(f, query);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.False(string.IsNullOrWhiteSpace(body.GetProperty("error").GetString()));
}
}
[Fact]
public async Task Reading_a_story_writes_nothing_and_the_read_only_token_may_ask_it()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "incident" })) { }
Assert.Equal(HttpStatusCode.OK, (await HistoryAsync(f, $"ip={Source}")).Status);
// A story is a read: the token that can look but not change may ask it,
// and the answer is the same one the write token gets.
var (readOnly, readOnlyBody) = await HistoryAsync(f, $"ip={Source}",
token: EdgeFixture.ReadOnlyToken);
Assert.Equal(HttpStatusCode.OK, readOnly);
Assert.Equal(1, readOnlyBody.GetProperty("searched").GetProperty("block").GetInt32());
var before = await CountAsync(f);
for (var i = 0; i < 6; i++) await HistoryAsync(f, $"ip={Source}");
Assert.Equal(before, await CountAsync(f));
var (noToken, _) = await HistoryAsync(f, $"ip={Source}", token: null);
Assert.Equal(HttpStatusCode.Unauthorized, noToken);
}
private static async Task<string> CountAsync(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
return $"{await db.Blocks.CountAsync()} {await db.Alerts.CountAsync()} "
+ $"{await db.AllowEntries.CountAsync()} {await db.ConfigChanges.CountAsync()} "
+ $"{await db.Observations.CountAsync()}";
}
}
+48
View File
@@ -1871,6 +1871,54 @@ check 'the scene cleans itself' 0 \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$HOR_IP"'","'"$HOR_NET"'")]))')"
# One source through time (OPEN-73), on the shipped image: the join runs against
# the database the container holds, so the story has to be assembled there too.
echo '- the shipped edge tells one source story in order'
HIS_IP=198.51.100.187
HIS_NET=198.51.100.184/29 # .184 - .191
HIS_NONE=192.31.196.7 # outside every range this run writes
check 'the shipped edge bans the network, the address inside it, then exempts it' '204 204 204' \
"$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_NET"'","reason":"history netblock"}' "$EDGE/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_IP"'","reason":"history address"}' "$EDGE/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$HIS_IP"'","note":"history allow","expiresInMinutes":60}' "$EDGE/admin-api/allow")"
check 'the shipped story names the block, the covering range and the exemption, oldest first' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_IP" | python3 -c '
import sys,json
d=json.load(sys.stdin)
k=[e["kind"] for e in d["events"]]
stamps=[e["at"] for e in d["events"]]
print("yes" if d["sourceKey"]=="'"$HIS_IP"'" and d["scope"]=="database"
and all(x in k for x in ("range ban","operator block","allow entry","config change"))
and stamps == sorted(stamps) else "no")')"
check 'the shipped story says the range is there because it covers the address' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_IP" | python3 -c '
import sys,json
e=[x for x in json.load(sys.stdin)["events"] if x["kind"]=="range ban"]
r=e[0] if e else None
print("yes" if r and r["match"]=="'"$HIS_NET"'" and r["inForce"]
and "covers this address" in r["what"] else "no")')"
check 'the shipped story answers an address with nothing recorded in words' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_NONE" | python3 -c '
import sys,json
d=json.load(sys.stdin); s=d["searched"]
print("yes" if d["count"]==0 and not any(s.values()) and "nothing recorded" in d["note"] else "no")')"
check 'the shipped history refuses a window of zero minutes and a bare address' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/history?ip=$HIS_IP&within=0") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/history?ip=198.51.100")"
check 'the shipped read-only token reads a story, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/history?ip=$HIS_IP") \
$(code "$EDGE/admin-api/history?ip=$HIS_IP")"
HIS_ALLOW_ID="$(admin "$EDGE/admin-api/allow?live=false" | python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$HIS_IP"'"][0])')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$HIS_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=${HIS_NET//\//%2F}" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/allow/$HIS_ALLOW_ID" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$HIS_IP"'","'"$HIS_NET"'")]))')"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+95
View File
@@ -1562,6 +1562,101 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
!horizonTorn.includes(HORIZON_NET), JSON.stringify(horizonTorn));
}
// One source through time (OPEN-73): the six stores that can name a source are
// joined by the edge and returned oldest-first. Seeded through the page's own
// forms — a range that covers the address, a block written on the address
// itself, and an exemption for it — so the story the panel prints is the story
// this run actually wrote.
{
const HIST_RANGE = '192.0.2.240/29'; // .240 - .247
const HIST_IP = '192.0.2.241'; // inside it
// Outside every range this run touches. 192.0.2.248 would not do: the
// netblock scene writes and removes 192.0.2.0/24 through the run, and a
// change to a /24 really is part of the story of an address inside it — the
// surface was right and the assertion had picked the wrong address.
const HIST_NONE = '192.31.196.7';
await page.fill('#blockIp', HIST_RANGE);
await page.fill('#blockReason', 'console gate: history range');
await page.click('#addBlock');
await page.waitForFunction((k) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === k), HIST_RANGE, { timeout: 15000 }).catch(() => {});
await page.fill('#blockIp', HIST_IP);
await page.fill('#blockReason', 'console gate: history block');
await page.click('#addBlock');
await page.waitForFunction((k) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === k), HIST_IP, { timeout: 15000 }).catch(() => {});
await page.fill('#allowMatch', HIST_IP);
await page.fill('#allowNote', 'console gate: history allow');
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), HIST_IP,
{ timeout: 15000 }).catch(() => {});
const historyRows = () => page.$$eval('#historyanswer div', (ds) => ds.map((d) => d.textContent));
const askHistory = async (ip) => {
await page.evaluate(() => { document.getElementById('historyanswer').textContent = ''; });
await page.fill('#historyIp', ip);
await page.click('#askHistory');
await page.waitForFunction((asked) => (document.getElementById('historyanswer').textContent || '')
.indexOf('asked: ' + asked + ' filed as') === 0, ip, { timeout: 15000 }).catch(() => {});
return historyRows();
};
const storyBefore = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k).sort());
const story = await askHistory(HIST_IP);
const rangeLine = story.find((l) => l.includes('\u00b7 range ban \u00b7'));
const blockLine = story.find((l) => l.includes('\u00b7 operator block \u00b7'));
const allowLine = story.find((l) => l.includes('\u00b7 allow entry \u00b7'));
const changeLine = story.find((l) => l.includes('config change') && l.includes(HIST_RANGE));
check('the story names the block on the address, the range covering it and the exemption',
!!rangeLine && !!blockLine && !!allowLine, JSON.stringify(story));
check('the range is in the story because it covers the address, and says so',
!!rangeLine && rangeLine.includes(HIST_RANGE)
&& /covers this address/.test(rangeLine) && /in force/.test(rangeLine),
JSON.stringify(rangeLine));
check('the exemption says it outranks every ban and until when',
!!allowLine && /exempted by/.test(allowLine) && /outranks every ban/.test(allowLine)
&& /console gate: history allow/.test(allowLine), JSON.stringify(allowLine));
check('the story is told oldest first, not in the order the rows were written',
!!rangeLine && !!blockLine && story.indexOf(rangeLine) < story.indexOf(blockLine),
JSON.stringify(story.filter((l) => /\u00b7 (range ban|operator block|allow entry) \u00b7/.test(l))));
check('a change to the range that covers this address is part of this address\u2019s story',
!!changeLine, JSON.stringify(story.filter((l) => l.includes('config change'))));
check('the header names the key the address is filed under and counts what was searched',
/^asked: 192\.0\.2\.241 filed as 192\.0\.2\.241 - \d+ events - searched: block 1, range 1, allow 1, alert \d+, change \d+, seen \d+$/.test(story[0] || ''),
JSON.stringify(story[0]));
const empty = await askHistory(HIST_NONE);
check('an address with nothing recorded is answered in words, with the counts of what was searched',
/^asked: 192\.31\.196\.7 filed as 192\.31\.196\.7 - 0 events - searched: block 0, range 0, allow 0, alert 0, change 0, seen 0$/.test(empty[0] || '')
&& empty.some((l) => /nothing recorded about this source/.test(l)),
JSON.stringify(empty));
const storyAfter = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k).sort());
check('reading a story wrote nothing to the operator list',
JSON.stringify(storyAfter) === JSON.stringify(storyBefore), JSON.stringify(storyAfter));
await page.click(`#allow tbody button[data-act="delallow"][data-k="${
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 : '';
}, HIST_IP)}"]`);
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${HIST_IP}"]`);
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${HIST_RANGE}"]`);
await page.waitForFunction((k) => ![...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === k), HIST_RANGE, { timeout: 15000 }).catch(() => {});
const torn = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k));
check('the history seeds left the operator list the way they were found',
!torn.includes(HIST_RANGE) && !torn.includes(HIST_IP), 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
+109
View File
@@ -1030,6 +1030,115 @@ b=json.load(open("/tmp/hor-blocks2.json")); r=json.load(open("/tmp/hor-rules2.js
print(len([x for x in b if x["sourceKey"] in ("192.0.2.151","192.0.2.152/29")]),
len([x for x in r if x["pattern"]=="/horizon-gate*"]))')"
# One source through time (OPEN-73). Every record is dated and every one is in
# this database — the range, the block, the exemption, the change records, the
# alerts — but they sit in six tables, so an operator rebuilding the story gets
# whichever listing they opened last. The order is the answer: "the exemption,
# then the ban" and "the ban, then the exemption" are different incidents.
echo '- one source through time'
HIS_IP=192.0.2.171
HIS_NET=192.0.2.168/29 # .168 - .175
HIS_NONE=192.31.196.7 # outside every range this run writes
history() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$1${2:+&$2}"; }
hist_counts() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/his-blocks.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/his-allow.json
python3 -c '
import json
b=json.load(open("/tmp/his-blocks.json")); a=json.load(open("/tmp/his-allow.json"))
print(len(b), len(a))'
}
check 'the operator bans the network, then the address inside it, then exempts it' '204 204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_NET"'","reason":"history netblock"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_IP"'","reason":"history address"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$HIS_IP"'","note":"history allow","expiresInMinutes":60}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow")"
check 'the story names the block, the range covering the address and the exemption' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
k=[e["kind"] for e in d["events"]]
print("yes" if d["sourceKey"]=="192.0.2.171" and d["scope"]=="database"
and all(x in k for x in ("range ban","operator block","allow entry","config change"))
else "no")')"
check 'the story is told oldest first, whatever order the rows were written in' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
stamps=[e["at"] for e in json.load(sys.stdin)["events"]]
print("yes" if len(stamps) >= 6 and stamps == sorted(stamps) else "no")')"
check 'the range is in the story because it covers the address, and says so' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
e=[x for x in json.load(sys.stdin)["events"] if x["kind"]=="range ban"]
r=e[0] if e else None
print("yes" if r and r["match"]=="192.0.2.168/29" and r["inForce"]
and "covers this address" in r["what"] and r["detail"]=="history netblock" else "no")')"
check 'the exemption says it outranks every ban and until when it stops' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
e=[x for x in json.load(sys.stdin)["events"] if x["kind"]=="allow entry"]
r=e[0] if e else None
print("yes" if r and r["inForce"] and r["expiresAt"] and r["detail"]=="history allow"
and "outranks every ban" in r["what"] else "no")')"
check 'a change to the range that covers this address is part of this address story' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
ch=[x for x in d["events"] if x["kind"]=="config change"]
print("yes" if any(x["match"]=="192.0.2.168/29" for x in ch)
and d["searched"]["change"] >= 2 else "no")')"
check 'the answer counts what it searched, not only what it found' '1 1 1' \
"$(history "$HIS_IP" | python3 -c '
import json,sys
s=json.load(sys.stdin)["searched"]
print(s["block"], s["range"], s["allow"])')"
check 'a limit says how much it left out' yes \
"$(history "$HIS_IP" "limit=2" | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["shown"]==2 and len(d["events"])==2 and d["truncated"] and d["count"]>2 else "no")')"
check 'an address with nothing recorded is answered in words, with the counts beside it' yes \
"$(history "$HIS_NONE" | python3 -c '
import json,sys
d=json.load(sys.stdin)
s=d["searched"]
print("yes" if d["count"]==0 and not d["events"] and not any(s.values())
and "nothing recorded" in d["note"] else "no")')"
check 'a window or a limit it cannot answer with is refused by name' '400 400 400 400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&within=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&limit=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=192.0.2") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?within=60") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&nonsense=1")"
check 'the read-only token reads a story, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP")"
check 'asking it six times wrote nothing: the listings hold the same rows' \
"$(hist_counts)" \
"$(for _ in 1 2 3 4 5 6; do history "$HIS_IP" >/dev/null; history "$HIS_NONE" >/dev/null; done; hist_counts)"
HIS_ALLOW_ID="$(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([a["id"] for a in json.load(sys.stdin) if a["match"]=="192.0.2.171"][0])')"
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=$HIS_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${HIS_NET//\//%2F}" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$HIS_ALLOW_ID" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/his-blocks2.json; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/his-allow2.json; \
python3 -c '
import json
b=json.load(open("/tmp/his-blocks2.json")); a=json.load(open("/tmp/his-allow2.json"))
print(len([r for r in b if r["sourceKey"] in ("192.0.2.171","192.0.2.168/29")]),
len([r for r in a if r["match"]=="192.0.2.171"]))')"
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 \