one search across every store the operator's decisions live in
ci / lint the workflow and the shell (push) Failing after 12s
ci / build the image and smoke it (push) Failing after 10s
ci / the operator page in a real browser (push) Failing after 1m35s
ci / build, test, smoke (push) Successful in 1m53s

GET /admin-api/find?q=<text>&limit=<n> asks where a phrase appears in one call:
blocks (key, reason, last path), ranges (match, reason), exemptions (match,
note), path rules and path budgets (pattern, note), alerts (kind, key, detail,
last path), change records (target, detail) and country rules (code, name). Each
row names the store it came from, what it is keyed by, when it was written,
whether it is in force, the text that matched and the field it matched in. The
phrase an operator remembers - a ticket number, a customer's name - is not a
field any listing filters on, so asking it used to mean opening eight listings
and reading every row.

Rulings:
- the query is data, not LIKE's grammar. The backslash, the percent and the
  underscore are escaped and the match runs LIKE ... ESCAPE '\', so "100%"
  searches the four characters "100%" and not "anything after 100". Unescaped, a
  percent inside an operator's own sentence answers about rows nobody asked
  about; the gate searches 100%, a_b and a literal backslash to hold this.
- an address query returns the rows that COVER it, not only the rows that name
  it - the part a grep cannot do. Searching .69 returns the /29 that refuses it
  although no row contains that address, and the row says so: "203.0.113.64/29
  covers 203.0.113.69". Blocks are matched on the key this edge files the
  address under, the rule the dossier and the story both had to learn: with a /29
  key, searching .90 finds the ban stored as 203.0.113.88/29.
- a row that matches by text and also covers the address is answered once, with
  the text match as its reason: the row really does name the query.
- counts is per store and is that store's whole answer, not the rows this call
  happened to return, so matched: 0 over eight zeroed stores is a different
  sentence from a surface that read nothing - and a limit truncates the merged
  answer without pretending a store had nothing else in it.
- rows come newest-first. This is a search, not a story: the row an operator
  wants is the one they wrote last. /history reads oldest-first because it
  narrates, and neither default is wrong for the other question.
- q is 2..128 characters - one character is a dump rather than an answer, and 128
  is the longest target the change log stores, so a longer query cannot match the
  thing it was aimed at. limit is 100 by default, 500 at most. An unknown query
  parameter is refused by name. Country rules are searched by name as well as by
  code: "Ukraine" is what an operator remembers, "UA" is what the row stores.
- it is a read. The read-only token can ask it, and eight asks leave every store
  holding the same rows.

The console carries the same call: a phrase in, one line per row that carries it,
and a header counting all eight stores so an empty answer reads as an answer.

Gates: build 0/0, unit 377/377, integration 394/394 (11 new), console 159
assertions 0 failed (+8), smoke 243/0 (+13), compose 339/0 (+8), image 262 MB.
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 12:24:50 +02:00
parent 3079b536ba
commit 6f92d377e7
7 changed files with 1132 additions and 5 deletions
+72 -5
View File
@@ -434,6 +434,12 @@ GET /admin-api/expiring?within= what stops being enforced inside the window
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)
GET /admin-api/find?q=&limit= where a phrase appears: blocks, ranges,
exemptions, path rules, path budgets, alerts,
change records and country rules, each row
naming its store and the field that matched;
an address query also returns the rows that
COVER it (q=2..128 chars, limit 100, max 500)
```
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
@@ -1424,6 +1430,61 @@ holds no records at all" are different answers. The window is 1..129600 minutes
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.
### Where does this appear?
`GET /admin-api/find?q=<text>&limit=<n>` answers the question no listing can. An
operator has a phrase — a ticket number, a customer's name, the words they typed
into a reason six weeks ago — and nothing else. That phrase is not a field any
listing filters on: it sits in a block's reason, an exemption's note, a path
rule's note, a path budget's note, an alert's detail and the change log's detail,
and asking it by hand means opening eight listings and reading every row.
```
GET /admin-api/find?q=ticket%20441
{ "query": "ticket 441", "scope": "database", "matched": 8, "shown": 8,
"limit": 100, "truncated": false,
"counts": { "block": 1, "range": 0, "allow": 1, "pathRule": 1, "pathBudget": 1,
"alert": 0, "change": 4, "countryRule": 0 },
"matching": { "mode": "substring", "wildcardsEscaped": true, "note": "…" },
"results": [
{ "store": "change", "id": 41, "match": "203.0.113.64/29", "pattern": null,
"text": "netblock from ticket 441", "at": "…", "live": null,
"expiresAt": null, "why": "text matched detail" },
{ "store": "allow", "id": 12, "match": "203.0.113.64/29", "pattern": null,
"text": "ticket 441 window", "at": "…", "live": true, "expiresAt": "…",
"why": "text matched note" },
{ "store": "block", "id": 7, "match": "203.0.113.69", "pattern": null,
"text": "closed after ticket 441", "at": "…", "live": true,
"expiresAt": null, "why": "text matched reason" } ] }
```
**The query is data, not LIKE's grammar.** `q=100%` searches the four characters
`100%`, not "anything that starts with 100": the backslash, the percent and the
underscore are escaped and the match runs as `LIKE … ESCAPE '\'`. Unescaped, a
`%` in an operator's own sentence would answer about rows nobody asked about, so
the gate searches `100%`, `a_b` and a literal backslash to hold that.
**An address query returns the rows that cover it, not only the rows that name
it.** That is the part a grep cannot do. Searching `203.0.113.69` returns the
`/29` that refuses it — no row contains that address — and the row says why it is
there: `"why": "203.0.113.64/29 covers 203.0.113.69"`. Blocks are matched on the
key this edge files the address under, the same rule the dossier and the story
learned: with a `/29` key, searching `.90` finds the ban stored as
`203.0.113.88/29` and prints `this edge files 203.0.113.90 under
203.0.113.88/29`. A row that matches by text *and* covers the address is answered
once, with the text match as its reason.
**`counts` is per store and is that store's whole answer**, not the rows this
call happened to return, so `matched: 0` over eight zeroed stores is a different
sentence from a surface that read nothing — and a `limit` truncates the merged
answer without pretending a store had nothing else in it. Rows come newest-first:
this is a search, not a story, and the row an operator wants is the one they
wrote last. `q` is 2..128 characters — one character is a dump rather than an
answer, and 128 is the longest target the change log stores — `limit` is 100 by
default and 500 at most, and an unknown query parameter is refused by name. It is
a read: the read-only token can ask it, and eight asks leave every store holding
the same rows.
## Console
`GET /admin` serves a single page over those endpoints — mode and snapshot age,
@@ -1480,7 +1541,12 @@ 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.
reads as an answer rather than as a broken panel. Under the story sits the search
(OPEN-74): a phrase in and one button, and the page prints one line per row that
carries it — the store it came from, what it is keyed by, when it was written,
`in force` or `EXPIRED …`, the text that matched and the field it matched in —
or, for an address query, that the row covers the address rather than names it.
The header counts all eight stores, so an empty answer reads as an answer.
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
@@ -1670,10 +1736,11 @@ 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, 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,
answered in one call, the sources a budget is pausing, the enforcement horizon, one
source told in order and one search across every store the operator's decisions
live in:
build 0 warnings / 0 errors, unit **377/377**, integration **394/394 in 1 m 16 s**,
console **159 assertions, 0 failed**, smoke **passed 243, failed 0**, and compose **339 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
+53
View File
@@ -176,6 +176,13 @@ internal static class AdminConsole
</div>
<div id="historyanswer" class="muted"></div>
<h2>Where does this appear?</h2>
<div class="bar">
<input id="findq" placeholder="a note, a reason, a path, an address" autocomplete="off" size="30">
<button id="askFind">search every store</button>
</div>
<div id="findanswer" 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">
@@ -1071,6 +1078,52 @@ el('askHistory').onclick = async () => {
}
};
el('askFind').onclick = async () => {
// Where does this appear? (OPEN-74). The phrase an operator remembers is not a
// field any listing filters on: it sits in a block's reason, an exemption's
// note, a path rule's note and the change log's detail. One box asks all eight
// stores at once. An address is worth more than a substring here - the row that
// answers for it is often a range that never names it - so the endpoint returns
// those too and says that is why they are in the answer.
const q = el('findq').value.trim();
if (!q) { note('some text first - this searches what an operator wrote', true); return; }
if (q.length < 2) { note('two characters at least - one is a dump, not a search', true); return; }
// Emptied before the call, and the first line names the query that was asked
// for: a scene waiting for an answer must never read the previous one.
el('findanswer').textContent = '';
const r = await apiRaw('/admin-api/find?q=' + encodeURIComponent(q));
if (failed(r)) return;
const d = r.body || {};
const c = d.counts || {};
const lines = [];
lines.push('asked: "' + (d.query || q) + '" - ' + (d.matched === undefined ? '?' : d.matched)
+ ' rows' + (d.truncated ? ' (showing ' + d.shown + ' of them)' : '')
+ ' - block ' + (c.block ?? '?') + ', range ' + (c.range ?? '?')
+ ', allow ' + (c.allow ?? '?') + ', path rule ' + (c.pathRule ?? '?')
+ ', path budget ' + (c.pathBudget ?? '?') + ', alert ' + (c.alert ?? '?')
+ ', change ' + (c.change ?? '?') + ', country ' + (c.countryRule ?? '?'));
const a = d.asAddress;
if (a) lines.push('as an address: filed as ' + (a.sourceKey || '?')
+ ' - rows that cover it are in the answer too, and say so');
for (const row of (d.results || [])) {
const when = (row.at || '').replace('T', ' ').slice(0, 19);
const what = row.match || row.pattern || '?';
let line = row.store + ' \u00b7 ' + what + ' \u00b7 ' + when;
if (row.live === true) line += ' \u00b7 in force';
else if (row.live === false) line += ' \u00b7 EXPIRED ' + ((row.expiresAt || '').replace('T', ' ').slice(0, 19));
if (row.text) line += ' \u00b7 ' + row.text;
line += ' \u00b7 ' + (row.why || '');
lines.push(line);
}
if (d.note) lines.push(d.note);
const box = el('findanswer');
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
+314
View File
@@ -1485,6 +1485,278 @@ note = t.Note
});
});
// Where does this appear? (OPEN-74). The words an operator remembers are
// not the fields the listings filter on: "ticket 441" sits in a block's
// reason, in an exemption's note, in a path rule's note and in the change
// log's detail, and six weeks later that phrase is all there is to go on.
// Asking it today means opening eight listings and reading every row,
// because not one of them looks at the text.
//
// Two things make this more than a grep across tables. What an operator
// remembers is often an address, and the row that governs an address does
// not name it — a /28 covers the office without ever carrying its number —
// so an address query also returns the rows that cover it and says that is
// why they are in the answer. And the query is data, not LIKE's grammar:
// "100%" has to search as "100%", which means escaping the wildcards
// instead of answering about everything that happens to start with 100.
group.MapGet("/find", async (string? q, int? limit,
EdgeStateStore state, OpenWafDbContext db, HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "q", "limit"))
return Results.BadRequest(new { error = unknown });
if (string.IsNullOrWhiteSpace(q))
return Results.BadRequest(new { error = "q is required: this surface answers where a text appears" });
var asked = q.Trim();
if (asked.Length < SearchMinQueryLength || asked.Length > SearchMaxQueryLength)
return Results.BadRequest(new {
error = $"q must be {SearchMinQueryLength}..{SearchMaxQueryLength} characters; got {asked.Length}"
});
var take = limit ?? SearchDefaultLimit;
if (take < SearchMinLimit || take > SearchMaxLimit)
return Results.BadRequest(new { error = $"limit must be {SearchMinLimit}..{SearchMaxLimit}; got {take}" });
var now = DateTimeOffset.UtcNow;
var policy = state.GetOrRefresh().Policy;
var pattern = "%" + EscapeLikeWildcards(asked) + "%";
var isAddress = IsAnAddress(asked);
// The key, not the address — the rule the dossier and the story both
// had to learn: a v6 source is filed under its /64, so asking about
// the address the socket carried would miss the ban that answers it.
var key = isAddress ? SourceKey.For(asked, policy) : null;
var hits = new List<SearchHit>();
var seen = new HashSet<string>(StringComparer.Ordinal);
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var store in SearchStoreNames) counts[store] = 0;
bool Add(string store, long? id, string? match, string? rule, string? text,
DateTimeOffset at, bool? live, DateTimeOffset? expiresAt, string why)
{
// One row can arrive twice: a range whose text matches and which
// also covers the queried address. It is still one row, and the
// text match is the better reason for being in the answer.
if (id is not null && !seen.Add(store + "#" + id.Value)) return false;
hits.Add(new SearchHit(store, id, match, rule, text, at, live, expiresAt, why));
return true;
}
// Which field carried the text. The store's own query already decided
// the row belongs here; this names the part, so a hit in a block's
// reason is not mistaken for a hit on a path rule's pattern.
static (string? text, string? field) MatchedIn(string needle,
(string? value, string field)[] candidates)
{
foreach (var c in candidates)
if (c.value is not null && c.value.Contains(needle, StringComparison.OrdinalIgnoreCase))
return (c.value, c.field);
return (null, null);
}
static string Why(string? field) => field is null ? "text matched" : $"text matched {field}";
// 1. The blocks this edge holds — the operator's and its own alike.
counts["block"] = await db.Blocks.AsNoTracking()
.Where(b => EF.Functions.Like(b.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(b.Reason, pattern, LikeEscape)
|| EF.Functions.Like(b.LastPath, pattern, LikeEscape))
.CountAsync(ct);
foreach (var b in await db.Blocks.AsNoTracking()
.Where(b => EF.Functions.Like(b.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(b.Reason, pattern, LikeEscape)
|| EF.Functions.Like(b.LastPath, pattern, LikeEscape))
.OrderByDescending(b => b.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[]
{ (b.Reason, "reason"), (b.LastPath, "last path"), (b.SourceKey, "source key") });
Add("block", b.Id, b.SourceKey, null, m.text, b.CreatedAt,
b.IsLive(now), b.ExpiresAt, Why(m.field));
}
// 2. The ranges the operator banned.
counts["range"] = await db.NetworkBans.AsNoTracking()
.Where(r => EF.Functions.Like(r.Match, pattern, LikeEscape)
|| EF.Functions.Like(r.Reason, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.NetworkBans.AsNoTracking()
.Where(r => EF.Functions.Like(r.Match, pattern, LikeEscape)
|| EF.Functions.Like(r.Reason, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Match, "match"), (r.Reason, "reason") });
Add("range", r.Id, r.Match, null, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
// 3. The exemptions, which outrank every ban and are the first thing
// an operator needs to find before lifting one.
counts["allow"] = await db.AllowEntries.AsNoTracking()
.Where(a => EF.Functions.Like(a.Match, pattern, LikeEscape)
|| EF.Functions.Like(a.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var a in await db.AllowEntries.AsNoTracking()
.Where(a => EF.Functions.Like(a.Match, pattern, LikeEscape)
|| EF.Functions.Like(a.Note, pattern, LikeEscape))
.OrderByDescending(a => a.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (a.Match, "match"), (a.Note, "note") });
Add("allow", a.Id, a.Match, null, m.text, a.CreatedAt, a.IsLive(now), a.ExpiresAt, Why(m.field));
}
// 4 and 5. The path rules and the path budgets.
counts["pathRule"] = await db.RequestRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.RequestRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Pattern, "pattern"), (r.Note, "note") });
Add("pathRule", r.Id, null, r.Pattern, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
counts["pathBudget"] = await db.RateRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.CountAsync(ct);
foreach (var r in await db.RateRules.AsNoTracking()
.Where(r => EF.Functions.Like(r.Pattern, pattern, LikeEscape)
|| EF.Functions.Like(r.Note, pattern, LikeEscape))
.OrderByDescending(r => r.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (r.Pattern, "pattern"), (r.Note, "note") });
Add("pathBudget", r.Id, null, r.Pattern, m.text, r.CreatedAt, r.IsLive(now), r.ExpiresAt, Why(m.field));
}
// 6. The alerts. Their detail is the sentence this edge wrote itself,
// which is often the only place an incident was ever narrated.
counts["alert"] = await db.Alerts.AsNoTracking()
.Where(a => EF.Functions.Like(a.Kind, pattern, LikeEscape)
|| EF.Functions.Like(a.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(a.Detail, pattern, LikeEscape)
|| EF.Functions.Like(a.LastPath, pattern, LikeEscape))
.CountAsync(ct);
foreach (var a in await db.Alerts.AsNoTracking()
.Where(a => EF.Functions.Like(a.Kind, pattern, LikeEscape)
|| EF.Functions.Like(a.SourceKey, pattern, LikeEscape)
|| EF.Functions.Like(a.Detail, pattern, LikeEscape)
|| EF.Functions.Like(a.LastPath, pattern, LikeEscape))
.OrderByDescending(a => a.CreatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[]
{ (a.Detail, "detail"), (a.Kind, "kind"), (a.SourceKey, "source key"), (a.LastPath, "last path") });
Add("alert", a.Id, a.SourceKey, null, m.text, a.CreatedAt, null, null, Why(m.field));
}
// 7. The operator's own change records — including the ones whose
// subject has since been deleted, which is what makes them worth
// searching: the row is gone, the sentence about it is not.
counts["change"] = await db.ConfigChanges.AsNoTracking()
.Where(c => EF.Functions.Like(c.Target, pattern, LikeEscape)
|| EF.Functions.Like(c.Detail, pattern, LikeEscape))
.CountAsync(ct);
foreach (var c in await db.ConfigChanges.AsNoTracking()
.Where(c => EF.Functions.Like(c.Target, pattern, LikeEscape)
|| EF.Functions.Like(c.Detail, pattern, LikeEscape))
.OrderByDescending(c => c.At).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (c.Target, "target"), (c.Detail, "detail") });
Add("change", c.Id, c.Target, null, m.text, c.At, null, null, Why(m.field));
}
// 8. The country rules. Their code is two characters, so the name is
// searched too — "Germany" is what an operator remembers, "DE" is what
// the row stores.
counts["countryRule"] = await db.CountryRules.AsNoTracking()
.Where(c => EF.Functions.Like(c.Code, pattern, LikeEscape)
|| EF.Functions.Like(c.Name, pattern, LikeEscape))
.CountAsync(ct);
foreach (var c in await db.CountryRules.AsNoTracking()
.Where(c => EF.Functions.Like(c.Code, pattern, LikeEscape)
|| EF.Functions.Like(c.Name, pattern, LikeEscape))
.OrderByDescending(c => c.UpdatedAt).Take(take).ToListAsync(ct))
{
var m = MatchedIn(asked, new (string?, string)[] { (c.Code, "code"), (c.Name, "name") });
Add("countryRule", null, c.Code, null, m.text, c.UpdatedAt, c.IsAllowed ? true : (bool?)null, null,
Why(m.field));
}
// The address bonus. A text search finds the rows that name the
// address; the rows that answer for it are the ones that cover it, and
// those never carry its number.
if (isAddress)
{
foreach (var b in await db.Blocks.AsNoTracking()
.Where(b => b.SourceKey == key)
.OrderByDescending(b => b.CreatedAt).Take(take).ToListAsync(ct))
if (Add("block", b.Id, b.SourceKey, null, b.Reason ?? b.LastPath, b.CreatedAt,
b.IsLive(now), b.ExpiresAt, $"this edge files {asked} under {key}"))
counts["block"]++;
foreach (var r in (await db.NetworkBans.AsNoTracking().ToListAsync(ct))
.Where(r => NetworkMatch.Matches(asked, r.Match)))
if (Add("range", r.Id, r.Match, null, r.Reason, r.CreatedAt, r.IsLive(now), r.ExpiresAt,
$"{r.Match} covers {asked}"))
counts["range"]++;
foreach (var a in (await db.AllowEntries.AsNoTracking().ToListAsync(ct))
.Where(a => NetworkMatch.Matches(asked, a.Match)))
if (Add("allow", a.Id, a.Match, null, a.Note, a.CreatedAt, a.IsLive(now), a.ExpiresAt,
$"{a.Match} covers {asked}"))
counts["allow"]++;
foreach (var c in (await db.ConfigChanges.AsNoTracking().ToListAsync(ct))
.Where(c => string.Equals(c.Target, asked, StringComparison.Ordinal)
|| string.Equals(c.Target, key, StringComparison.Ordinal)
|| NetworkMatch.Matches(asked, c.Target)))
if (Add("change", c.Id, c.Target, null, c.Detail, c.At, null, null,
$"a change to {c.Target}, which is this source or a range covering it"))
counts["change"]++;
}
// Newest first. This is a search, not a story: the row an operator
// wants is the one they wrote most recently. (/history reads oldest
// first because it narrates, and reading a story backwards turns "the
// exemption, then the ban" into the opposite. Neither default is wrong
// for the other question.)
hits.Sort((x, y) => y.At.CompareTo(x.At));
var shown = hits.Take(take).ToList();
var matched = counts.Values.Sum();
return Results.Ok(new
{
query = asked,
scope = "database",
matched,
shown = shown.Count,
limit = take,
truncated = matched > shown.Count,
counts,
matching = new
{
mode = "substring",
wildcardsEscaped = true,
note = "case-insensitive as the database does it, which is ASCII-only; the query's own "
+ "backslash, percent and underscore are searched as themselves"
},
asAddress = isAddress
? new
{
ip = asked,
sourceKey = key,
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "the query is an address, so the answer also carries the rows that cover it "
+ "rather than name it"
}
: null,
results = shown,
note = matched == 0
? "nothing matched; `counts` names every store that was searched, so an empty answer is "
+ "an answer and not a surface that read nothing"
: "newest first; each row names the store it came from and the field that matched, or says "
+ "the row covers the queried address"
});
});
// 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
@@ -1889,6 +2161,29 @@ note = t.Note
private const int HistoryMinLimit = 1;
private const int HistoryMaxLimit = 2000;
// 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
// longer query cannot match the thing it was aimed at.
private const int SearchMinQueryLength = 2;
private const int SearchMaxQueryLength = 128;
private const int SearchDefaultLimit = 100;
private const int SearchMinLimit = 1;
private const int SearchMaxLimit = 500;
// LIKE's escape character. These stores are operator prose — reasons, notes,
// alert details — and prose carries percents and underscores, so the query is
// escaped instead of being handed to LIKE as grammar.
private const string LikeEscape = "\\";
private static readonly string[] SearchStoreNames =
["block", "range", "allow", "pathRule", "pathBudget", "alert", "change", "countryRule"];
/// <summary>Escape LIKE's wildcards. The escape character itself goes first,
/// or the escapes the other two add would be escaped by the next pass.</summary>
private static string EscapeLikeWildcards(string value)
=> value.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
// 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.
@@ -2183,3 +2478,22 @@ internal sealed record HorizonAfter(
bool WouldBeRefused,
string By,
string Note);
/// <summary>One row that matched the search (OPEN-74), carrying the store it came
/// from and the field that held the text, so a hit in a block's reason is not
/// mistaken for a hit on a path rule's pattern. `Live` is null for the stores that
/// are events rather than states — an alert, a change record — because "is it in
/// force" is not a question they answer; a `false` there would say the row was
/// switched off. `Why` is the reason the row is in the answer at all: a field name
/// for a text match, a sentence for a row that is here because it covers the
/// queried address.</summary>
internal sealed record SearchHit(
string Store,
long? Id,
string? Match,
string? Pattern,
string? Text,
DateTimeOffset At,
bool? Live,
DateTimeOffset? ExpiresAt,
string Why);
@@ -0,0 +1,423 @@
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.Policy;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// Where does this appear? (OPEN-74): one search across every store the
/// operator's decisions live in.
///
/// The phrase an operator remembers is not a field the listings filter on.
/// "ticket 441" sits in a block's reason, an exemption's note, a path rule's
/// note, a path budget's note and the change log's detail; six weeks later that
/// phrase is all there is, and asking it means opening eight listings.
///
/// What these tests hold the surface to: the search reaches all eight stores and
/// says which one each row came from; the query is data and not LIKE's grammar,
/// so "100%" and "a_b" search as themselves; an address query also returns the
/// rows that cover it rather than name it, and says that is why; a row counted
/// twice is answered once; the per-store counts make "nothing matched"
/// distinguishable from "nothing was searched"; the limit reports what it left
/// out; the refusals name the parameter; and asking writes nothing.
/// </summary>
public sealed class OperatorSearchTests
{
private const string Phrase = "ticket 441";
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 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)> FindAsync(
EdgeFixture f, string query, string? token = EdgeFixture.AdminToken)
{
using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/find?{query}", token: token);
var text = await r.Content.ReadAsStringAsync();
// A refusal carries no body: parsing one would fail the test for the
// wrong reason.
var body = string.IsNullOrWhiteSpace(text)
? default
: JsonDocument.Parse(text).RootElement.Clone();
return (r.StatusCode, body);
}
/// <summary>Rows written straight to storage. The API would do for most of
/// them, but this test needs one row in every store at once, including the
/// alert and the change record the edge writes by itself.</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 async Task SeedPhraseInEveryStoreAsync(EdgeFixture f)
{
var now = DateTimeOffset.UtcNow;
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = now,
Reason = $"closed after {Phrase}", LastPath = "/wp-login.php"
});
await SeedAsync(f, new NetworkBan
{
Match = Range, CreatedAt = now, Reason = $"netblock from {Phrase}"
});
await SeedAsync(f, new AllowEntry
{
Match = Inside, CreatedAt = now, Note = $"the window {Phrase} gave"
});
await SeedAsync(f, new RequestRule
{
Pattern = "/wp-login.php", Action = RequestRuleAction.Block,
CreatedAt = now, Note = Phrase
});
await SeedAsync(f, new RateRule
{
Pattern = "/login", CreatedAt = now, Note = $"loosened for {Phrase}"
});
await SeedAsync(f, new EdgeAlert
{
SourceKey = Source, Kind = "server_error_streak", Count = 3,
CreatedAt = now, Detail = $"upstream down while {Phrase} was open"
});
await SeedAsync(f, new ConfigChange
{
At = now, Section = ConfigChangeLog.SectionBlocks, Action = ConfigChangeLog.ActionAdded,
Target = Source, Detail = $"written for {Phrase}"
});
await SeedAsync(f, new CountryRule
{
Code = "UA", Name = "Ukraine", IsAllowed = false, UpdatedAt = now
});
}
private static List<JsonElement> Results(JsonElement body)
=> body.GetProperty("results").EnumerateArray().ToList();
private static bool HasStore(List<JsonElement> rows, string store)
=> rows.Any(r => r.GetProperty("store").GetString() == store);
[Fact]
public async Task One_phrase_comes_back_from_every_store_that_holds_it()
{
await using var f = new EdgeFixture();
await SeedPhraseInEveryStoreAsync(f);
var (status, body) = await FindAsync(f, $"q={Phrase}");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(Phrase, body.GetProperty("query").GetString());
Assert.Equal("database", body.GetProperty("scope").GetString());
var rows = Results(body);
foreach (var store in new[] { "block", "range", "allow", "pathRule", "pathBudget", "alert", "change" })
Assert.True(HasStore(rows, store), $"no {store} row in {body}");
// Every row says where it came from and which field carried the text, so
// a hit in a reason is not mistaken for a hit on a pattern.
var rule = rows.Single(r => r.GetProperty("store").GetString() == "pathRule");
Assert.Equal("/wp-login.php", rule.GetProperty("pattern").GetString());
Assert.Contains("text matched note", rule.GetProperty("why").GetString()!);
var block = rows.Single(r => r.GetProperty("store").GetString() == "block");
Assert.Equal(Source, block.GetProperty("match").GetString());
Assert.Contains("text matched reason", block.GetProperty("why").GetString()!);
Assert.True(block.GetProperty("live").GetBoolean());
Assert.NotEqual(JsonValueKind.Null, block.GetProperty("id").ValueKind);
// 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.
var alert = rows.Single(r => r.GetProperty("store").GetString() == "alert");
Assert.True(alert.GetProperty("live").ValueKind == JsonValueKind.Null);
// The counts are per store, so the answer says what it looked at and what
// it found there.
var counts = body.GetProperty("counts");
Assert.Equal(1, counts.GetProperty("block").GetInt32());
Assert.Equal(1, counts.GetProperty("alert").GetInt32());
Assert.Equal(7, body.GetProperty("matched").GetInt32());
Assert.False(body.GetProperty("truncated").GetBoolean());
}
[Fact]
public async Task A_country_rule_is_found_by_the_name_the_operator_remembers()
{
await using var f = new EdgeFixture();
await SeedPhraseInEveryStoreAsync(f);
var (_, body) = await FindAsync(f, "q=ukr");
var rule = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "countryRule");
Assert.Equal("UA", rule.GetProperty("match").GetString());
Assert.Contains("text matched name", rule.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("countryRule").GetInt32());
// The code is searched too, and a two-letter query is long enough to ask.
var (_, byCode) = await FindAsync(f, "q=UA");
Assert.Equal(1, byCode.GetProperty("counts").GetProperty("countryRule").GetInt32());
}
[Fact]
public async Task The_query_is_data_and_not_likes_grammar()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = now,
Reason = "100% sure about this one"
});
await SeedAsync(f, new BlockEntry
{
SourceKey = "203.0.113.89", Source = BlockSource.Operator, CreatedAt = now,
Reason = "100 requests a minute"
});
await SeedAsync(f, new AllowEntry { Match = "203.0.113.90", CreatedAt = now, Note = "a_b note" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.91", CreatedAt = now, Note = "axb note" });
// Unescaped, "100%" is LIKE for "100 followed by anything", which answers
// about a row nobody asked about.
var (status, percent) = await FindAsync(f, "q=100%25");
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(1, percent.GetProperty("matched").GetInt32());
var hit = Assert.Single(Results(percent));
Assert.Equal("100% sure about this one", hit.GetProperty("text").GetString());
var (_, underscore) = await FindAsync(f, "q=a_b");
Assert.Equal(1, underscore.GetProperty("matched").GetInt32());
Assert.Equal("a_b note", Assert.Single(Results(underscore)).GetProperty("text").GetString());
// A literal backslash in the query survives its own escaping. It is
// searched inside three characters because a query of one is refused.
await SeedAsync(f, new AllowEntry { Match = "203.0.113.92", CreatedAt = now, Note = @"say a\b here" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.93", CreatedAt = now, Note = "say axb here" });
var (_, backslash) = await FindAsync(f, "q=a%5Cb");
Assert.Equal(1, backslash.GetProperty("matched").GetInt32());
Assert.Equal(@"say a\b here", Assert.Single(Results(backslash)).GetProperty("text").GetString());
Assert.True(percent.GetProperty("matching").GetProperty("wildcardsEscaped").GetBoolean());
}
[Fact]
public async Task Matching_ignores_case_the_way_a_person_expects()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator, CreatedAt = DateTimeOffset.UtcNow,
Reason = "Ticket 441 CLOSED"
});
foreach (var needle in new[] { "ticket 441", "TICKET", "441 closed" })
{
var (_, body) = await FindAsync(f, $"q={Uri.EscapeDataString(needle)}");
Assert.Equal(1, body.GetProperty("matched").GetInt32());
Assert.Contains("Ticket 441 CLOSED", Assert.Single(Results(body)).GetProperty("text").GetString());
}
}
[Fact]
public async Task An_address_query_finds_the_rows_that_cover_it_and_not_only_the_ones_that_name_it()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
// Nothing here names the address except the block. The range, the
// exemption and the change record all name the netblock, which is what
// actually answers for this address.
await SeedAsync(f, new NetworkBan { Match = Range, CreatedAt = now, Reason = "rotating scanner" });
await SeedAsync(f, new AllowEntry { Match = "203.0.113.64/28", CreatedAt = now, Note = "the office" });
await SeedAsync(f, new ConfigChange
{
At = now, Section = ConfigChangeLog.SectionBlocks, Action = ConfigChangeLog.ActionAdded,
Target = Range, Detail = "banned on the ticket"
});
await SeedAsync(f, new BlockEntry
{
SourceKey = Inside, Source = BlockSource.Operator, CreatedAt = now, Reason = "the printer"
});
// A range that does not cover it is not told it does.
await SeedAsync(f, new NetworkBan { Match = "203.0.113.96/29", CreatedAt = now, Reason = "elsewhere" });
var (status, body) = await FindAsync(f, $"q={Inside}");
Assert.Equal(HttpStatusCode.OK, status);
var asAddress = body.GetProperty("asAddress");
Assert.Equal(Inside, asAddress.GetProperty("ip").GetString());
Assert.Equal(Inside, asAddress.GetProperty("sourceKey").GetString());
var rows = Results(body);
var range = rows.Single(r => r.GetProperty("store").GetString() == "range");
Assert.Equal(Range, range.GetProperty("match").GetString());
Assert.Contains($"covers {Inside}", range.GetProperty("why").GetString()!);
var allow = rows.Single(r => r.GetProperty("store").GetString() == "allow");
Assert.Equal("203.0.113.64/28", allow.GetProperty("match").GetString());
Assert.Contains("covers", allow.GetProperty("why").GetString()!);
var change = rows.Single(r => r.GetProperty("store").GetString() == "change");
Assert.Equal(Range, change.GetProperty("match").GetString());
Assert.DoesNotContain("203.0.113.96/29", body.ToString());
// The counts carry the coverage rows, so the answer's totals describe the
// answer rather than only the text matches.
Assert.Equal(1, body.GetProperty("counts").GetProperty("range").GetInt32());
Assert.Equal(4, body.GetProperty("matched").GetInt32());
}
[Fact]
public async Task A_source_is_found_under_the_key_this_edge_files_it_under()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
// The ban is filed under the /29; the operator searches the address the
// socket carried, which no row names.
using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy",
new { ipv4KeyPrefixLength = 29 })) { }
await SeedAsync(f, new BlockEntry
{
SourceKey = "203.0.113.88/29", Source = BlockSource.Engine, CreatedAt = now,
Reason = "3 consecutive refusals"
});
// Nothing in that row contains ".90", so only the key rule can find it.
var (_, body) = await FindAsync(f, "q=203.0.113.90");
Assert.Equal("203.0.113.88/29", body.GetProperty("asAddress").GetProperty("sourceKey").GetString());
var block = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "block");
Assert.Contains("files 203.0.113.90 under 203.0.113.88/29", block.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("block").GetInt32());
// And the address that is named by the key's own text is still one row.
var (_, named) = await FindAsync(f, $"q={Source}");
Assert.Equal(1, named.GetProperty("counts").GetProperty("block").GetInt32());
Assert.Single(Results(named), r => r.GetProperty("store").GetString() == "block");
}
[Fact]
public async Task A_row_that_matches_by_text_and_covers_the_address_is_answered_once()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new AllowEntry
{
Match = Inside, CreatedAt = DateTimeOffset.UtcNow, Note = "named and covering"
});
var (_, body) = await FindAsync(f, $"q={Inside}");
var allow = Assert.Single(Results(body), r => r.GetProperty("store").GetString() == "allow");
// The text match is the better reason: the row does name this address.
Assert.Contains("text matched match", allow.GetProperty("why").GetString()!);
Assert.Equal(1, body.GetProperty("counts").GetProperty("allow").GetInt32());
Assert.Equal(1, body.GetProperty("matched").GetInt32());
}
[Fact]
public async Task An_empty_answer_names_every_store_it_searched()
{
await using var f = new EdgeFixture();
await SeedAsync(f, new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator,
CreatedAt = DateTimeOffset.UtcNow, Reason = "something else entirely"
});
var (_, body) = await FindAsync(f, "q=nothing+like+this");
Assert.Equal(0, body.GetProperty("matched").GetInt32());
Assert.Empty(Results(body));
var counts = body.GetProperty("counts");
foreach (var store in new[]
{ "block", "range", "allow", "pathRule", "pathBudget", "alert", "change", "countryRule" })
Assert.Equal(0, counts.GetProperty(store).GetInt32());
// "Nothing matched" and "nothing was searched" are different answers, and
// an envelope that listed no stores could not tell them apart.
Assert.Contains("counts", body.GetProperty("note").GetString()!);
}
[Fact]
public async Task The_limit_says_how_much_it_left_out()
{
await using var f = new EdgeFixture();
var now = DateTimeOffset.UtcNow;
for (var i = 0; i < 5; i++)
await SeedAsync(f, new BlockEntry
{
SourceKey = $"203.0.113.{100 + i}", Source = BlockSource.Operator,
CreatedAt = now.AddMinutes(i), Reason = Phrase
});
var (_, body) = await FindAsync(f, $"q={Phrase}&limit=2");
Assert.Equal(5, body.GetProperty("matched").GetInt32());
Assert.Equal(2, body.GetProperty("shown").GetInt32());
Assert.Equal(2, body.GetProperty("limit").GetInt32());
Assert.True(body.GetProperty("truncated").GetBoolean());
Assert.Equal(5, body.GetProperty("counts").GetProperty("block").GetInt32());
// Newest first: the row an operator wants is the one they wrote last.
var rows = Results(body);
Assert.Equal(2, rows.Count);
Assert.True(rows[0].GetProperty("at").GetDateTimeOffset()
> rows[1].GetProperty("at").GetDateTimeOffset());
}
[Fact]
public async Task A_bad_query_is_refused_by_name()
{
await using var f = new EdgeFixture();
var cases = new[]
{
("", "q is required"),
("q=x", "q must be 2..128 characters"),
("q=" + Uri.EscapeDataString(new string('x', 129)), "q must be 2..128 characters"),
("q=" + Phrase + "&store=block", "unknown query parameter 'store'"),
("q=" + Phrase + "&limit=0", "limit must be 1..500"),
("q=" + Phrase + "&limit=501", "limit must be 1..500"),
};
foreach (var (query, expected) in cases)
{
var (status, body) = await FindAsync(f, query);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains(expected, body.GetProperty("error").GetString()!);
}
// A query that is only whitespace is the same refusal as no query: it
// names nothing to search for.
var (blank, blankBody) = await FindAsync(f, "q=%20%20");
Assert.Equal(HttpStatusCode.BadRequest, blank);
Assert.Contains("q is required", blankBody.GetProperty("error").GetString()!);
}
[Fact]
public async Task Asking_is_a_read_the_read_only_token_can_make_and_that_writes_nothing()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
await SeedPhraseInEveryStoreAsync(f);
static async Task<int> RowsAsync(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.ConfigChanges.CountAsync() + await db.AllowEntries.CountAsync();
}
var before = await RowsAsync(f);
var (status, _) = await FindAsync(f, $"q={Phrase}", token: EdgeFixture.ReadOnlyToken);
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(before, await RowsAsync(f));
// And nothing at all without a token.
var (anon, _) = await FindAsync(f, $"q={Phrase}", token: null);
Assert.Equal(HttpStatusCode.Unauthorized, anon);
}
}
+56
View File
@@ -1919,6 +1919,62 @@ 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 ("'"$HIS_IP"'","'"$HIS_NET"'")]))')"
# Where does this appear? (OPEN-74), on the shipped image: one query across the
# stores the operator's decisions live in, including the rows that cover an
# address rather than name it.
echo '- the shipped edge searches every store at once'
FND_IP=198.51.100.195
FND_NET=198.51.100.192/29 # .192 - .199
findq() { admin "$EDGE/admin-api/find?q=$1${2:+&$2}"; }
check 'the shipped edge writes the same phrase into three stores' '204 204 204' \
"$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$FND_IP"'","reason":"ticket 441 closed"}' "$EDGE/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$FND_NET"'","note":"ticket 441 window"}' "$EDGE/admin-api/allow") \
$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-gate*","action":"block","note":"ticket 441 path"}' "$EDGE/admin-api/rules")"
check 'the shipped query comes back from every store that holds it' '1 1 1' \
"$(findq 'ticket%20441' | python3 -c '
import sys,json
c=json.load(sys.stdin)["counts"]
print(c["block"], c["allow"], c["pathRule"])')"
check 'the shipped search treats "100%" as text, not as LIKE grammar' yes \
"$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"198.51.100.196","reason":"100% sure"}' "$EDGE/admin-api/blocks" >/dev/null; \
findq '100%25' | python3 -c '
import sys,json
d=json.load(sys.stdin)
print("yes" if d["counts"]["block"]==1 and all("100%" in (r["text"] or "") for r in d["results"])
else "no")')"
check 'the shipped search finds the entry that covers an address and says so' yes \
"$(findq "$FND_IP" | python3 -c '
import sys,json
d=json.load(sys.stdin)
by=[r for r in d["results"] if r["store"]=="allow"]
print("yes" if d["asAddress"]["sourceKey"]=="'"$FND_IP"'" and len(by)==1
and by[0]["match"]=="'"$FND_NET"'" and "covers '"$FND_IP"'" in by[0]["why"] else "no")')"
check 'the shipped search answers an empty query with all eight stores counted' yes \
"$(findq 'nothing%20like%20this' | python3 -c '
import sys,json
d=json.load(sys.stdin); c=d["counts"]
print("yes" if d["matched"]==0 and len(c)==8 and not any(c.values()) else "no")')"
check 'the shipped search refuses a one-character query and an unknown parameter' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/find?q=x") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/find?q=ticket&store=block")"
check 'the shipped read-only token searches, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/find?q=ticket%20441") \
$(code "$EDGE/admin-api/find?q=ticket%20441")"
FND_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"]=="'"$FND_NET"'"][0])')"
FND_RULE_ID="$(admin "$EDGE/admin-api/rules" | python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-gate*"][0])')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$FND_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=198.51.100.196" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/allow/$FND_ALLOW_ID" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/rules/$FND_RULE_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 ("'"$FND_IP"'","'"$FND_NET"'","198.51.100.196")]))')"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+81
View File
@@ -1657,6 +1657,87 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
!torn.includes(HIST_RANGE) && !torn.includes(HIST_IP), JSON.stringify(torn));
}
// Where does this appear? (OPEN-74): one box asks every store the operator's
// decisions live in at once, and an address query returns the rows that cover
// the address rather than name it. Seeded through the page's own forms so the
// rows the panel prints are the rows this run wrote.
{
const FND_NET = '192.0.2.248/29'; // .248 - .255
const FND_IP = '192.0.2.249'; // inside it
const FND_PHRASE = 'console gate: find scene';
await page.fill('#blockIp', FND_IP);
await page.fill('#blockReason', FND_PHRASE);
await page.click('#addBlock');
await page.waitForFunction((k) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === k), FND_IP, { timeout: 15000 }).catch(() => {});
await page.fill('#allowMatch', FND_NET);
await page.fill('#allowNote', FND_PHRASE);
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), FND_NET,
{ timeout: 15000 }).catch(() => {});
const askFind = async (q) => {
await page.evaluate(() => { document.getElementById('findanswer').textContent = ''; });
await page.fill('#findq', q);
await page.click('#askFind');
await page.waitForFunction((asked) => (document.getElementById('findanswer').textContent || '')
.indexOf('asked: "' + asked + '"') === 0, q, { timeout: 15000 }).catch(() => {});
return page.$$eval('#findanswer div', (ds) => ds.map((d) => d.textContent));
};
const foundBefore = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k).sort());
const hits = await askFind(FND_PHRASE);
const blockLine = hits.find((l) => (l || '').startsWith('block \u00b7'));
const allowLine = hits.find((l) => (l || '').startsWith('allow \u00b7'));
const changeLine = hits.find((l) => (l || '').startsWith('change \u00b7'));
check('one box finds one phrase in a block reason, an exemption note and the change log',
!!blockLine && !!allowLine && !!changeLine, JSON.stringify(hits));
check('each hit names its store and the field that carried the text',
/text matched reason/.test(blockLine || '') && /text matched note/.test(allowLine || '')
&& /text matched detail/.test(changeLine || ''), JSON.stringify([blockLine, allowLine, changeLine]));
check('the header counts every store it searched, not only the ones that answered',
/^asked: "console gate: find scene" - \d+ rows - block 1, range \d+, allow 1, path rule \d+, path budget \d+, alert \d+, change \d+, country \d+$/.test(hits[0] || ''),
JSON.stringify(hits[0]));
const covering = await askFind(FND_IP);
const coverLine = covering.find((l) => (l || '').startsWith('allow \u00b7'));
check('an address query returns the exemption that covers it and says that is why',
!!coverLine && coverLine.includes(FND_NET)
&& new RegExp('covers ' + FND_IP.replace(/\./g, '\\.')).test(coverLine),
JSON.stringify(covering));
check('the address query says which key this edge files the address under',
covering.some((l) => /^as an address: filed as 192\.0\.2\.249 - rows that cover it/.test(l || '')),
JSON.stringify(covering.slice(0, 2)));
const none = await askFind('nothing like this at all');
check('an empty answer says so and still counts all eight stores',
/^asked: "nothing like this at all" - 0 rows - block 0, range 0, allow 0, path rule 0, path budget 0, alert 0, change 0, country 0$/.test(none[0] || '')
&& none.some((l) => /nothing matched/.test(l || '')), JSON.stringify(none));
const foundAfter = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k).sort());
check('searching four times wrote nothing to the operator list',
JSON.stringify(foundAfter) === JSON.stringify(foundBefore), JSON.stringify(foundAfter));
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 : '';
}, FND_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="${FND_IP}"]`);
await page.waitForFunction((k) => ![...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === k), FND_IP, { timeout: 15000 }).catch(() => {});
const torn = await page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k));
check('the search seeds left the operator list the way they were found',
!torn.includes(FND_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
+133
View File
@@ -1139,6 +1139,139 @@ b=json.load(open("/tmp/his-blocks2.json")); a=json.load(open("/tmp/his-allow2.js
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"]))')"
# Where does this appear? (OPEN-74). The words an operator remembers are not a
# field any listing filters on: the same phrase sits in a block's reason, an
# exemption's note, a path rule's note and a path budget's note, and asking it
# means opening eight listings. One call asks all eight at once — and an address
# query returns the rows that cover the address rather than name it, which is the
# answer a text match cannot give.
echo '- one search across every store'
FND_IP=192.0.2.181
FND_NET=192.0.2.176/29 # .176 - .183
FND_PHRASE='ticket%20441'
FND_NONE='nothing%20like%20this'
findq() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$1${2:+&$2}"; }
find_rows() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/fnd-b.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/fnd-a.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" -o /tmp/fnd-r.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" -o /tmp/fnd-t.json
python3 -c '
import json
b=json.load(open("/tmp/fnd-b.json")); a=json.load(open("/tmp/fnd-a.json"))
r=json.load(open("/tmp/fnd-r.json")); t=json.load(open("/tmp/fnd-t.json"))
print(sum(1 for x in b if "ticket 441" in (x.get("reason") or "")),
sum(1 for x in a if "ticket 441" in (x.get("note") or "")),
sum(1 for x in r if "ticket 441" in (x.get("note") or "")),
sum(1 for x in t if "ticket 441" in (x.get("note") or "")))'
}
check 'the same phrase is written into four different stores' '204 204 204 204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$FND_IP"'","reason":"ticket 441 closed"}' \
"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":"192.0.2.182","reason":"100% sure about this one"}' \
"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":"'"$FND_NET"'","note":"ticket 441 a_b window"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-gate*","action":"block","note":"ticket 441 path"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-login*","limitPerWindow":3,"windowSeconds":120,"note":"ticket 441 budget"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
check 'one query comes back from every store that holds it, and counts each' '1 0 1 1 1 4 8' \
"$(findq "$FND_PHRASE" | python3 -c '
import json,sys
d=json.load(sys.stdin); c=d["counts"]
print(c["block"], c["range"], c["allow"], c["pathRule"], c["pathBudget"], c["change"], d["matched"])')"
check 'every row names its store and the field that carried the text' yes \
"$(findq "$FND_PHRASE" | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if all(k in by for k in ("block","allow","pathRule","pathBudget","change"))
and by["block"]["why"]=="text matched reason" and by["block"]["match"]=="192.0.2.181"
and by["allow"]["why"]=="text matched note" and by["allow"]["match"]=="192.0.2.176/29"
and by["pathRule"]["why"]=="text matched note" and by["pathRule"]["pattern"]=="/find-gate*"
and by["pathBudget"]["pattern"]=="/find-login*"
and by["change"]["why"]=="text matched detail"
else "no")')"
check 'the query is data and not LIKE grammar: "100%" finds the percent' yes \
"$(findq '100%25' | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if d["counts"]["block"]==1 and by["block"]["text"]=="100% sure about this one"
and all("100%" in (r["text"] or "") for r in d["results"])
and d["matching"]["wildcardsEscaped"] else "no")')"
check 'and an underscore is an underscore, not any one character' yes \
"$(findq 'a_b' | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if d["counts"]["allow"]==1 and by["allow"]["text"]=="ticket 441 a_b window"
and all("a_b" in (r["text"] or "") for r in d["results"]) else "no")')"
check 'an address query finds the entry that covers it and says that is why' yes \
"$(findq "$FND_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
by=[r for r in d["results"] if r["store"]=="allow"]
print("yes" if d["asAddress"]["sourceKey"]=="192.0.2.181" and len(by)==1
and by[0]["match"]=="192.0.2.176/29" and "covers 192.0.2.181" in by[0]["why"]
and d["counts"]["allow"]==1 and d["counts"]["block"]==1 else "no")')"
check 'an address outside the range is not told it is inside it' yes \
"$(findq '192.0.2.190' | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["counts"]["range"]==0 and not d["results"] else "no")')"
check 'an empty answer names all eight stores it searched' yes \
"$(findq "$FND_NONE" | python3 -c '
import json,sys
d=json.load(sys.stdin); c=d["counts"]
print("yes" if d["matched"]==0 and not d["results"] and len(c)==8 and not any(c.values())
and "counts" in d["note"] else "no")')"
check 'a limit says how much it left out' '8 1 1' \
"$(findq "$FND_PHRASE" 'limit=1' | python3 -c '
import json,sys
d=json.load(sys.stdin)
print(d["matched"], d["shown"], 1 if d["truncated"] else 0)')"
check 'a query 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/find") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=x") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE&store=block") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE&limit=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=%20%20")"
check 'the read-only token searches, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE")"
check 'asking it eight times wrote nothing: the stores hold the same rows' \
"$(find_rows)" \
"$(for _ in 1 2 3 4; do findq "$FND_PHRASE" >/dev/null; findq "$FND_IP" >/dev/null; done; find_rows)"
FND_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.176/29"][0])')"
FND_RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" \
| python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-gate*"][0])')"
FND_RATE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-login*"][0])')"
check 'the scene cleans itself' '0 0 0 0' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$FND_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$FND_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.182" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$FND_ALLOW_ID" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules/$FND_RULE_ID" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$FND_RATE_ID" >/dev/null; \
find_rows)"
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 \