From 1ec794dc75e24567438d92e86d2e2ee8aaed2ccf Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 11:22:01 +0200 Subject: [PATCH] the horizon says what stops being enforced soon, and what answers afterwards GET /admin-api/expiring?within= (1..1440, 30 by default) lists the dated entries that stop being enforced inside the window, nearest first, and each address-shaped row carries thenAnswers: the real DecisionEngine.Decide over a snapshot with only that entry removed. An exemption about to lapse therefore says which ban is waiting underneath it ("block_operator by 203.0.113.16/28"), and a block that stands alone says the source goes free. A path rule and a path budget have no single answer: thenAnswers is null and whyNoAnswer points at /admin-api/decide?ip=&path= instead of the surface guessing one. Entries that never expire are not listed; alreadyExpired counts the dated rows whose moment already passed, which is what separates "nothing expires soon" from "there are no dated entries". The listing reads the database, the read-only token can ask it, and six asks write nothing. Rulings: - the probe address for a CIDR is its network address, which is inside the group it describes; a pattern is not probed at all. - the window is capped at a day because that is the longest thing an operator plans for; out of bounds is a 400 naming 1..1440. - the console prints the window it asked for as the first line of the answer and empties the box before the call, so neither a scene nor an operator on a slow link can read the previous answer as the new one. Two product defects fell out of the gates on the way: - the alert push worker was registered as a hosted service above the schema step, and hosted services start in registration order: on a cold start its first queue sweep read alert_push_queue out of a database this process had not created, and "SQLite Error 1: no such table" became alertWebhookLastError - the state page blaming the webhook endpoint for the edge's own startup order. The notifier is now registered below the warmer and the order is asserted. - a listing the edge could not answer was drawn as an empty one: with two of the page's fourteen calls answering an error, the observation line printed "0 sources the edge has recorded" and the streak line "0 of 0 standing streaks listed" over a map holding twelve sources. A count read off a failed answer is 0, and 0 says there is nothing to see. Every count-bearing note and its table now say NOT READ with the error beside them. The gate's own traps, caught and fixed: the budget scene cleared the engine ban its probes caused after the probe that ban was failing, and its reopen retry loop banned itself three refusals deep; the alerts assertion read a row written off the response before the next refresh drew it. gates: build 0 warnings / 0 errors, unit 377/377, integration 375/375 in 35 s, console 142 assertions 0 failed, smoke passed 217 failed 0, compose 324 passed 0 failed against the built image at 262 MB, 0 containers left behind. Refs OPEN-72. --- README.md | 98 ++++++- dotnet/OpenWaf.Edge/Admin/AdminConsole.cs | 176 +++++++++--- dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 177 ++++++++++++ dotnet/OpenWaf.Edge/Program.cs | 10 +- .../EnforcementHorizonTests.cs | 266 ++++++++++++++++++ .../StartupOrderTests.cs | 77 +++++ scripts/compose-smoke.sh | 46 +++ scripts/console-check.cjs | 198 ++++++++++++- scripts/smoke.sh | 117 ++++++++ 9 files changed, 1123 insertions(+), 42 deletions(-) create mode 100644 dotnet/OpenWaf.Tests.Integration/EnforcementHorizonTests.cs create mode 100644 dotnet/OpenWaf.Tests.Integration/StartupOrderTests.cs diff --git a/README.md b/README.md index 33fb9a1..3949dc8 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,10 @@ GET /admin-api/source?ip=&path= everything this edge knows about one address or a range that covers it), the engine's ban, the standing streak, the budgets counting it, its alerts and the netblocks that would cover it +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 ``` `?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept @@ -1311,6 +1315,60 @@ known and its level is the answer; a 401 would tell the operator to go chase a secret. Reading the list spends nothing: N reads leave `count` and `overBudgetNow` where they were, so the page that exists to show a pause cannot cause one. +### The enforcement horizon: what stops answering soon + +`GET /admin-api/expiring?within=` answers the question an operator asks +the evening before. Not "what has an expiry" — a date is a timestamp to interpret +by hand at 05:55 — but "what stops being enforced today, and what answers once it +has". The window is 1..1440 minutes, 30 by default; a day is the ceiling because +that is the longest thing an operator plans for. + +``` +GET /admin-api/expiring?within=120 +{ "withinMinutes": 120, "asOf": "...", "scope": "database", "count": 2, + "expiring": [ + { "kind": "range", "match": "203.0.113.16/28", "expiresAt": "...", + "minutesLeft": 18, "note": "scan burst from the ticket", + "thenAnswers": { "verdict": "pass", "wouldBeRefused": false, "by": "nothing", + "note": "when this entry ages out, nothing else refuses this source" } }, + { "kind": "allow", "match": "203.0.113.21", "expiresAt": "...", + "minutesLeft": 44, "note": "customer on the ticket", + "thenAnswers": { "verdict": "block_operator", "wouldBeRefused": true, + "by": "203.0.113.16/28", + "note": "when this entry ages out, this source is refused again by 203.0.113.16/28" } } ], + "alreadyExpired": { "block": 0, "range": 0, "engineBan": 41, "allow": 0, + "pathRule": 0, "pathBudget": 0 } } +``` + +**`thenAnswers` is the engine, not a guess.** For a block, an engine ban, a range +and an allow the row runs the real `DecisionEngine.Decide` over a snapshot with +**only that entry removed** — `WithoutBlock`, `WithoutAllow`, or a snapshot whose +`OperatorRanges` is the live index minus that one range — and probes the address +the entry names: the key itself, or the network address of a CIDR, which is +inside the group it describes. So the exemption that is about to lapse says which +ban is waiting underneath it, and a block that stands alone says the source goes +free. That is the difference between "expires at 06:00" and "at 06:00 this +customer falls back into the /28 you banned last week". + +**A path rule and a path budget have no single answer, and say so.** Their +`thenAnswers` is `null` and `whyNoAnswer` points at +`/admin-api/decide?ip=&path=`: a pattern describes a set of paths, and the +verdict depends on the path and the source being asked about. Inventing one would +be the surface guessing where it should hand the question back. + +**Entries that never expire are not listed**, and neither are entries expiring +beyond the window. `alreadyExpired` counts the dated rows whose moment has +already passed and which still sit in the tables — retention ages out the +machine's own rows, and an operator's rows are not the machine's to delete. That +is what separates "nothing expires soon" from "there are no dated entries". + +Rows are sorted nearest-first: the entry to act on today is at the top, not the +one with the largest id. The listing reads the database rather than a snapshot, so +it answers about every edge that shares that store. A `within` out of bounds is a +400 naming `1..1440`, an unknown query parameter is a 400 by the same rule as +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. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1352,6 +1410,15 @@ counting is this process's. That bar is the honest limit of the word the runtime image is distroless with no external assets, so there is no world outline and no tile server. A geographic map would be a decoration this page could not load at the moment it is wanted. +Under the dossier sits the horizon (OPEN-72): a window in minutes and one button, +and the page prints one line per dated entry that stops being enforced inside it, +nearest first, each naming what the engine would answer for that source once the +entry is gone — `then: block_operator by 203.0.113.16/28`, or `then: pass by +nothing`. A path rule and a path budget print why they have no single answer +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. 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 @@ -1541,10 +1608,33 @@ 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 and the sources a budget is pausing: -build 0 warnings / 0 errors, unit **377/377**, integration **365/365 in 31 s**, -console **129 assertions, 0 failed**, smoke **passed 202, failed 0**, and compose **317 passed, -0 failed** against the built image at 262 MB, 0 containers left behind. Two console runs earned their keep in a row. The first: the dossier scene waited for "an answer is in the box", which the previous answer still sitting there satisfies, so every assertion after the first read the address asked one click earlier. The second: two scenes failed with `answered 403`, because the gate's own probes are refusals and the streak pillar had by then banned the probe addresses — a correct edge and a scene that could not retry past a one-hour ban. Both now clear that one ban by name (`?source=engine&key=`), which leaves the engine bans the netblock scene reads standing. The smoke story from the +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, +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 +*above* the schema step, hosted services start in registration order, and so on a cold +start its first queue sweep read `alert_push_queue` out of a database this same process +had not created yet. Nothing crashed — the worker counts what it cannot read — but the +sentence it left in `alertWebhookLastError` was "SQLite Error 1: 'no such table: +alert_push_queue'", which sends the operator to fix the webhook endpoint for the edge's +own startup order. The order is now asserted rather than assumed. The console runs caught +a second one: a listing the edge could not answer was drawn as an empty one. With two of +the page's fourteen calls answering an error, the observation line printed "0 sources the +edge has recorded" and the streak line "0 of 0 standing streaks listed" over a map holding +twelve sources — a count read off a failed answer is 0, and 0 is the sentence that says +there is nothing to see. Every count-bearing note and the table under it now say +`NOT READ` with the error beside them. The rest were the gate's own traps: the dossier +scene waited for "an answer is in the box", which the previous answer still sitting there +satisfies, so every assertion after the first read the address asked one click earlier; +and scenes failed with `answered 403`, because the gate's own probes are refusals and the +streak pillar had by then banned the probe addresses — a correct edge and a scene that +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 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 diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 3f2df66..29929cf 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -162,6 +162,13 @@ internal static class AdminConsole
+

The enforcement horizon

+
+ + +
+
+

Sources the edge is watching

@@ -309,16 +316,40 @@ async function load() { return; } const state = stateRes.body; - const blocks = blocksRes.body; - const obs = obsRes.body; - const alerts = alertsRes.body; - const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body, - allow = allowRes.body, pathRules = pathRulesRes.body, rate = rateRes.body, geo = geoRes.body, - changes = changesRes.body, netblocks = netblocksRes.body, - pathBudgets = pathBudgetsRes.body; + // A listing that could not be read answers with an error object where an + // array belongs. The notes below say which call failed; the tables still map + // over these values, so the shape is normalised once here instead of at + // fourteen call sites, and a failed read draws the NOT READ row rather than + // throwing the whole refresh half-drawn. + const list = (r) => (Array.isArray(r.body) ? r.body : []); + const blocks = list(blocksRes); + const obs = list(obsRes); + const alerts = list(alertsRes); + const streaks = streaksRes.body && typeof streaksRes.body === 'object' + ? streaksRes.body : { streaks: [] }; + const countries = list(countriesRes), rules = list(rulesRes), + allow = list(allowRes), pathRules = list(pathRulesRes), rate = rateRes.body, geo = geoRes.body, + changes = list(changesRes), netblocks = netblocksRes.body, + pathBudgets = list(pathBudgetsRes); + // A listing that failed is not an empty listing. Every note under here is a + // count, and a count read off a failed answer is 0: measured on a run where + // two of these fourteen calls lost the database for a moment, the + // observation line printed "0 sources the edge has recorded" and the streak + // line "0 of 0 standing streaks listed" over a map holding twelve sources. + // The status line did say the call failed — but the table is what an + // operator reads, and it said there was nothing to see. An empty table and + // an unreadable one are different facts, and this page already has to tell + // "never seen" from "broken" for one filtered row; it has to do it for a + // whole listing too. + const readFailed = (r) => r.status !== 200 || r.body === null; + const failedRead = (r) => 'NOT READ \u2014 ' + + ((r.body && r.body.error) || ('the edge answered ' + r.status)) + + '. This is not an empty table.'; + // The listing is capped server-side. Saying so is the difference between a // console and a misleading one: the delete beside this table is not capped. - el('blocknote').textContent = blocksRes.truncated + el('blocknote').textContent = readFailed(blocksRes) ? failedRead(blocksRes) + : blocksRes.truncated ? 'showing the newest ' + blocks.length + ' of ' + blocksRes.total + ' — clearing by provenance removes all ' + blocksRes.total + ', not just this page' : blocksRes.total + (blocksRes.total === '1' ? ' entry' : ' entries'); // A row here can be a network rather than an address (OPEN-66), and the two @@ -326,7 +357,8 @@ async function load() { // address inside it. The line says which shape the table holds and what // outranks it, because the alternative is an operator reading a /24 as a row // of the same size as any other. - el('blocknote').textContent += ' \u00b7 a range row refuses every address inside it, and an allow entry still outranks it'; + if (!readFailed(blocksRes)) + el('blocknote').textContent += ' \u00b7 a range row refuses every address inside it, and an allow entry still outranks it'; // The observation listing is capped too, and it is the table an operator // reads to decide which sources the edge has actually seen. Until the API // said how many there are, "newest 25" and "the whole window" looked the @@ -335,7 +367,8 @@ async function load() { // count along with the rows — and a source with nothing recorded is named // in words instead of drawn as an empty table. That is how an operator // tells "this address was never seen" from "the page stopped working". - el('obsnote').textContent = obsSource + el('obsnote').textContent = readFailed(obsRes) ? failedRead(obsRes) + : obsSource ? (Number(obsRes.total) === 0 ? 'no recorded observations for ' + obsSource : 'filtered to ' + obsSource + ': ' + (obsRes.truncated @@ -348,7 +381,7 @@ async function load() { // Without the number, "3 sources recorded" reads the same whether the edge // keeps them a week or a year — and the window is the answer to "how far // back can this incident still be explained" (OPEN-19). - if (state.observationRetentionDays != null) + if (!readFailed(obsRes) && state.observationRetentionDays != null) el('obsnote').textContent += ' · rows are pruned after ' + state.observationRetentionDays + 'd'; const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed])); // A failed write is not a stale read: the row never existed, and the @@ -418,7 +451,10 @@ async function load() { // one am I running" is a question an operator can only answer from here. // Marked when it passes the 90-day runtime alarm, the same rule /healthz // reports as geoStale. - ' ' + (geo && geo.loaded + ' ' + (readFailed(geoRes) + ? 'geo not read \u2014 ' + + esc((geo && geo.error) || ('the edge answered ' + geoRes.status)) + '' + : geo && geo.loaded ? 'geo ' + esc(geo.database || 'unknown') + ' \u00b7 built ' + esc((geo.builtAt || '').slice(0, 10)) + ' \u00b7 ' + esc(geo.ageDays) + 'd' @@ -450,7 +486,8 @@ async function load() { ? { h: 'already banned' } : { h: '' } ])).join('') || row([{ v: 'none' }]); - el('netblocknote').textContent = netblocks && netblocks.scanError + el('netblocknote').textContent = readFailed(netblocksRes) ? failedRead(netblocksRes) + : netblocks && netblocks.scanError ? 'the last scan failed: ' + netblocks.scanError + ' - nothing is offered, and the last answer was dropped rather than repeated' : Number(netblocks.threshold) <= 0 ? 'the watch is off (netblockCandidateBans = 0): the edge groups nothing and offers nothing' @@ -471,8 +508,11 @@ async function load() { ? (a.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it' : (a.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, { h: '' } - ])).join('') || row([{ v: 'none — everything not blocked is allowed' }]); - el('allownote').textContent = (allow || []).length + ])).join('') || row([{ v: readFailed(allowRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : 'none — everything not blocked is allowed' }]); + el('allownote').textContent = readFailed(allowRes) ? failedRead(allowRes) + : (allow || []).length ? 'an allow entry outranks every ban, engine or operator — it is the "my customer is locked out" control' + (allowRes.truncated ? ' · showing ' + allow.length + ' of ' + allowRes.total + ' rows' : '') + (allowExpired ? ' · ' + allowExpired + ' EXPIRED: those rows no longer exempt anyone' : '') @@ -492,8 +532,11 @@ async function load() { ? (r.expiresAt || '').replace('T', ' ').slice(0, 19) + ' — EXPIRED, the edge no longer honours it' : (r.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, { h: '' } - ])).join('') || row([{ v: 'none — the edge judges responses, not requests' }]); - el('rulenote').textContent = state.requestRulesAvailable === false + ])).join('') || row([{ v: readFailed(pathRulesRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : 'none — the edge judges responses, not requests' }]); + el('rulenote').textContent = readFailed(pathRulesRes) ? failedRead(pathRulesRes) + : state.requestRulesAvailable === false ? 'NOT READ — this database has no request-rule table (' + (state.requestRulesError || 'no reason given') + '), so no path rule is in force. Apply the schema migration; every other pillar is enforcing.' : (pathRules || []).length @@ -523,8 +566,11 @@ async function load() { : (r.expiresAt || 'never').replace('T', ' ').slice(0, 19) }, { h: ' ' + '' } - ])).join('') || row([{ v: 'none — every path shares the one edge-wide budget above' }]); - el('raterulenote').textContent = state.rateRulesAvailable === false + ])).join('') || row([{ v: readFailed(pathBudgetsRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : 'none — every path shares the one edge-wide budget above' }]); + el('raterulenote').textContent = readFailed(pathBudgetsRes) ? failedRead(pathBudgetsRes) + : state.rateRulesAvailable === false ? 'NOT READ — this database has no rate-rule table (' + (state.rateRulesError || 'no reason given') + '), so no path budget is in force. Apply the schema migration; every other pillar is enforcing.' : (pathBudgets || []).length @@ -546,8 +592,10 @@ async function load() { { v: rate.limitPerWindow, n: true }, { v: r.windowEnd ? new Date(r.windowEnd).toLocaleTimeString() : '-' } ])).join('') - : row([{ v: 'nothing counted' }]); - el('ratenote').textContent = rate && rate.mode && rate.mode !== 'Off' + : row([{ v: readFailed(rateRes) + ? 'NOT READ \u2014 the edge could not answer this call' : 'nothing counted' }]); + el('ratenote').textContent = readFailed(rateRes) ? failedRead(rateRes) + : rate && rate.mode && rate.mode !== 'Off' ? rate.mode.toLowerCase() + ' · ' + rate.limitPerWindow + ' requests per ' + rate.windowSeconds + ' s per source, counted in this process (' + rate.trackedSources + ' sources tracked) · behind more than one edge each edge counts its own traffic' @@ -564,20 +612,25 @@ async function load() { el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([ { h: srcBtn(o.sourceKey) }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, { v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') } - ])).join('') || row([{ v: obsSource ? 'nothing recorded for ' + obsSource : 'none' }]); + ])).join('') || row([{ v: readFailed(obsRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : obsSource ? 'nothing recorded for ' + obsSource : 'none' }]); el('streaks').tBodies[0].innerHTML = (streaks.streaks || []).map((st) => row([ { h: srcBtn(st.sourceKey) }, { v: st.consecutiveRefusals + ' / ' + streaks.threshold, n: true }, { v: st.consecutiveServerErrors, n: true }, { v: st.lastStatusCode }, { v: st.lastPath }, { v: st.lastCountryCode }, { v: (st.lastSeenAt || '').replace('T', ' ').slice(0, 19) } - ])).join('') || row([{ v: obsSource - ? 'nothing standing for ' + obsSource : 'nothing standing — every tracked source last saw a clean answer' }]); + ])).join('') || row([{ v: readFailed(streaksRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : obsSource ? 'nothing standing for ' + obsSource + : 'nothing standing — every tracked source last saw a clean answer' }]); // "this edge process only" is the scope sentence OPEN-16 earned; the filter // sentence is the one OPEN-36 adds. Under a filter standingStreaks is the // FILTERED count while trackedSources stays the whole map, and that pair is // the honest reading of "one of these many". el('streaknote').textContent = - streaks.scope !== 'this-process' && streaks.scope !== 'shared-database' ? 'unknown scope' + readFailed(streaksRes) ? failedRead(streaksRes) + : streaks.scope !== 'this-process' && streaks.scope !== 'shared-database' ? 'unknown scope' : (streaks.scope === 'shared-database' // The streaks in this table were counted by every edge sharing the // database, not only by the one serving this page (OPEN-52). Saying @@ -622,17 +675,21 @@ async function load() { { v: c.target }, { v: c.detail || '' }, { v: c.actor } - ])).join('') || row([{ v: 'nothing recorded yet - every operator write from now on leaves a row here' }]); - el('changenote').textContent = Number(changesRes.total) === 0 + ])).join('') || row([{ v: readFailed(changesRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : 'nothing recorded yet - every operator write from now on leaves a row here' }]); + el('changenote').textContent = readFailed(changesRes) ? failedRead(changesRes) + : Number(changesRes.total) === 0 ? 'no config changes recorded. engine bans are not here: they are not decisions.' : (changesRes.truncated ? 'newest ' + changes.length + ' of ' + changesRes.total + ' records - engine bans are not here, they are not decisions' : changesRes.total + ' ' + plural(Number(changesRes.total), 'record') + ' - engine bans are not here, they are not decisions'); - if (state.changeRetentionDays != null) + if (!readFailed(changesRes) && state.changeRetentionDays != null) el('changenote').textContent += ' - pruned after ' + state.changeRetentionDays + 'd or ' + state.changeLogMaxRows + ' rows, whichever comes first'; - el('countrysum').textContent = seen.length + el('countrysum').textContent = readFailed(countriesRes) ? failedRead(countriesRes) + : seen.length ? seen.length + ' ' + plural(seen.length, 'country') + ', ' + totalSources + ' ' + plural(totalSources, 'source') + ', ' + totalRefusals + ' ' + plural(totalRefusals, 'refusal') + ' total' @@ -648,12 +705,15 @@ async function load() { { v: a.count, n: true }, { v: (a.lastStatusCode || '') + ' ' + (a.lastPath || ''), n: true }, { v: (a.createdAt || '').replace('T', ' ').slice(0, 19) } - ])).join('') || row([{ v: 'nothing — no server-error streaks and no dry-run candidates' }]); - el('alertnote').textContent = (alerts || []).length + ])).join('') || row([{ v: readFailed(alertsRes) + ? 'NOT READ \u2014 the edge could not answer this call' + : 'nothing — no server-error streaks and no dry-run candidates' }]); + el('alertnote').textContent = readFailed(alertsRes) ? failedRead(alertsRes) + : (alerts || []).length ? 'server_error_streak = your upstream is failing, and the edge will not ban the visitor who saw it; candidate_ban = the rule would have banned, mode is Observe. ' + (alertsRes.truncated ? 'Newest ' + alerts.length + ' of ' + alertsRes.total + ' alerts.' : 'All ' + alertsRes.total + ' alerts are listed.') : 'no alerts. server_error_streak means the upstream is failing; candidate_ban means a dry run would have banned.'; - if (state.banRetentionDays != null) + if (!readFailed(alertsRes) && state.banRetentionDays != null) el('alertnote').textContent += ' · alerts are pruned after ' + state.banRetentionDays + 'd'; // Whether a raised alert reaches anything on its own. A row is read by // whoever opens this page; a push is what fires at 03:00. The host and not @@ -961,6 +1021,58 @@ el('askSource').onclick = async () => { } }; +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 + // decision the engine would take for that source with only this entry removed, + // so the answer is "this /28 ages out at 06:00 and the source falls back to the + // engine ban underneath it" rather than a timestamp to interpret by hand. + const raw = el('horizonWithin').value.trim(); + let minutes = 30; + if (raw) { + minutes = Number(raw); + if (!Number.isInteger(minutes) || minutes < 1 || minutes > 1440) { + note('the horizon is a whole number of minutes from 1 to 1440', true); + return; + } + } + // The box is emptied before the call, and the first line names the window that + // was asked for: a scene waiting for an answer cannot read the previous one. + el('horizonanswer').textContent = ''; + const r = await apiRaw('/admin-api/expiring?within=' + minutes); + if (failed(r)) return; + const d = r.body || {}; + const ae = d.alreadyExpired || {}; + const lines = []; + lines.push('asked: within ' + (d.withinMinutes === undefined ? minutes : d.withinMinutes) + + ' minutes of ' + (d.asOf || '?')); + lines.push('expiring: ' + (d.count === undefined ? '?' : d.count) + + ' - already past: block ' + (ae.block === undefined ? '?' : ae.block) + + ', range ' + (ae.range === undefined ? '?' : ae.range) + + ', engine ban ' + (ae.engineBan === undefined ? '?' : ae.engineBan) + + ', allow ' + (ae.allow === undefined ? '?' : ae.allow) + + ', path rule ' + (ae.pathRule === undefined ? '?' : ae.pathRule) + + ', path budget ' + (ae.pathBudget === undefined ? '?' : ae.pathBudget)); + for (const row of (d.expiring || [])) { + const what = row.match || row.pattern || '?'; + let line = row.kind + ' ' + what + ' - ' + + (row.minutesLeft === undefined ? '?' : row.minutesLeft) + ' min left' + + (row.note ? ' - ' + row.note : ''); + if (row.thenAnswers) { + line += ' - then: ' + row.thenAnswers.verdict + ' by ' + row.thenAnswers.by; + } else if (row.whyNoAnswer) { + line += ' - ' + row.whyNoAnswer; + } + lines.push(line); + } + const box = el('horizonanswer'); + for (const line of lines) { + const div = document.createElement('div'); + div.textContent = line; + box.appendChild(div); + } +}; + // One delegated handler for every row button, so no key or country code is ever // spliced into an inline onclick string. The values live in data attributes, // which went through esc() on the way in. diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 3a2c71c..112bdae 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -1321,6 +1321,149 @@ note = t.Note }); }); + // 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 + // stops soon or what takes over when it does. The classic incident: an + // office inside a banned /28 gets a 60-minute exemption, the minute passes, + // the office is refused again, and the person who wrote the exemption no + // longer remembers the range underneath it. + // + // "What takes over" is not a second implementation of the pillar order. It + // is the real DecisionEngine run over a snapshot with exactly this one entry + // removed, so the answer cannot disagree with the wire. + group.MapGet("/expiring", async (int? within, + EdgeStateStore state, IGeoIpLookup geo, OpenWafDbContext db, + HttpContext ctx, CancellationToken ct) => + { + if (!TryKnownQuery(ctx, out var unknown, "within")) return Results.BadRequest(new { error = unknown }); + var minutes = within ?? HorizonDefaultMinutes; + if (minutes < HorizonMinMinutes || minutes > HorizonMaxMinutes) + return Results.BadRequest(new { error = $"within must be {HorizonMinMinutes}..{HorizonMaxMinutes} minutes; got {minutes}" }); + + var now = DateTimeOffset.UtcNow; + var until = now.AddMinutes(minutes); + var snapshot = state.GetOrRefresh(); + var policy = snapshot.Policy; + + var blocks = await db.Blocks.AsNoTracking() + .Where(b => b.ExpiresAt != null && b.ExpiresAt > now && b.ExpiresAt <= until) + .ToListAsync(ct); + var liveRanges = await db.NetworkBans.AsNoTracking() + .Where(b => b.ExpiresAt == null || b.ExpiresAt > now) + .ToListAsync(ct); + var allows = await db.AllowEntries.AsNoTracking() + .Where(a => a.ExpiresAt != null && a.ExpiresAt > now && a.ExpiresAt <= until) + .ToListAsync(ct); + var rules = await db.RequestRules.AsNoTracking() + .Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until) + .ToListAsync(ct); + var budgets = await db.RateRules.AsNoTracking() + .Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until) + .ToListAsync(ct); + + // The address to ask the engine about for a key or a match: the network + // address of the group is inside the group, so it is answered by it. + static string? ProbeOf(string? keyOrMatch) + { + if (string.IsNullOrWhiteSpace(keyOrMatch) || keyOrMatch == "*") return null; + var slash = keyOrMatch.IndexOf('/'); + return slash < 0 ? keyOrMatch : keyOrMatch[..slash]; + } + + static EdgeSnapshot WithoutBlock(EdgeSnapshot s, string key, bool engine) + { + var kept = new Dictionary(StringComparer.Ordinal); + foreach (var kv in (engine ? s.EngineBans : s.OperatorBlocks)) + if (!string.Equals(kv.Key, key, StringComparison.Ordinal)) kept[kv.Key] = kv.Value; + return s with { OperatorBlocks = engine ? s.OperatorBlocks : kept, EngineBans = engine ? kept : s.EngineBans }; + } + + EdgeSnapshot WithoutAllow(EdgeSnapshot s, long id) + => s with { AllowEntries = s.AllowEntries.Where(a => a.Id != id).ToList() }; + + HorizonAfter? AnswersAfter(EdgeSnapshot after, string? probe) + { + if (probe is null) return null; + var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(probe); + var d = DecisionEngine.Decide(after, probe, "/", now, country); + var by = d.Verdict switch + { + EdgeVerdict.PassAllowlisted => "an allow entry", + EdgeVerdict.BlockOperator => d.Range ?? d.SourceKey ?? "the operator's list", + EdgeVerdict.BlockEngine => d.SourceKey ?? "this edge's own ban", + EdgeVerdict.BlockRule => d.RulePattern is { } p ? $"path rule {p}" : d.Reason ?? "a path rule", + EdgeVerdict.PassRuleObserved => d.RulePattern is { } p2 ? $"path rule {p2} (observe)" : "a path rule", + EdgeVerdict.GeoReject => d.Reason ?? "the geo pillar", + EdgeVerdict.PassBypassed => "an always-pass prefix", + _ => "nothing" + }; + return new HorizonAfter( + EdgeVerdictLabel.For(d.Verdict), d.IsBlocked, by, + d.IsBlocked + ? $"when this entry ages out, this source is refused again by {by}" + : $"when this entry ages out, nothing else refuses this source"); + } + + const string PatternHasNoAnswer = + "a path rule and a path budget describe a set of paths, not one request: ask /admin-api/decide?ip=&path= for the path you care about"; + + var rows = new List(); + foreach (var b in blocks.Where(b => b.Source == BlockSource.Operator)) + rows.Add(new HorizonRow("block", b.Id, b.SourceKey, null, b.Reason, b.ExpiresAt!.Value, + MinutesUntil(b.ExpiresAt.Value, now), + AnswersAfter(WithoutBlock(snapshot, b.SourceKey, false), ProbeOf(b.SourceKey)), null)); + foreach (var b in blocks.Where(b => b.Source != BlockSource.Operator)) + rows.Add(new HorizonRow("engine ban", b.Id, b.SourceKey, null, b.Reason, b.ExpiresAt!.Value, + MinutesUntil(b.ExpiresAt.Value, now), + AnswersAfter(WithoutBlock(snapshot, b.SourceKey, true), ProbeOf(b.SourceKey)), null)); + foreach (var r in liveRanges.Where(r => r.ExpiresAt != null && r.ExpiresAt > now && r.ExpiresAt <= until)) + rows.Add(new HorizonRow("range", r.Id, r.Match, null, r.Reason, r.ExpiresAt!.Value, + MinutesUntil(r.ExpiresAt.Value, now), + AnswersAfter(snapshot with { OperatorRanges = new NetworkBanIndex(liveRanges.Where(x => x.Id != r.Id)) }, + ProbeOf(r.Match)), null)); + foreach (var a in allows) + rows.Add(new HorizonRow("allow", a.Id, a.Match, null, a.Note, a.ExpiresAt!.Value, + MinutesUntil(a.ExpiresAt.Value, now), + AnswersAfter(WithoutAllow(snapshot, a.Id), ProbeOf(a.Match)), null)); + foreach (var r in rules) + rows.Add(new HorizonRow("path rule", r.Id, null, r.Pattern, r.Note, r.ExpiresAt!.Value, + MinutesUntil(r.ExpiresAt.Value, now), null, PatternHasNoAnswer)); + foreach (var r in budgets) + rows.Add(new HorizonRow("path budget", r.Id, null, r.Pattern, r.Note, r.ExpiresAt!.Value, + MinutesUntil(r.ExpiresAt.Value, now), null, PatternHasNoAnswer)); + // Nearest first: the entry an operator has to act on today is the one + // at the top of the list, not the one with the largest id. + rows.Sort((x, y) => x.ExpiresAt.CompareTo(y.ExpiresAt)); + + return Results.Ok(new + { + withinMinutes = minutes, + asOf = now, + scope = "database", + count = rows.Count, + expiring = rows, + // Dead rows stay in the tables — retention ages out engine bans and + // observations, an operator's own rows are not the machine's to + // delete — so "nothing expires soon" and "there are no dated + // entries" are different answers. + alreadyExpired = new + { + block = await db.Blocks.CountAsync(b => b.Source == BlockSource.Operator + && b.ExpiresAt != null && b.ExpiresAt <= now, ct), + range = await db.NetworkBans.CountAsync(b => b.ExpiresAt != null && b.ExpiresAt <= now, ct), + engineBan = await db.Blocks.CountAsync(b => b.Source == BlockSource.Engine + && b.ExpiresAt != null && b.ExpiresAt <= now, ct), + allow = await db.AllowEntries.CountAsync(a => a.ExpiresAt != null && a.ExpiresAt <= now, ct), + pathRule = await db.RequestRules.CountAsync(r => r.ExpiresAt != null && r.ExpiresAt <= now, ct), + pathBudget = await db.RateRules.CountAsync(r => r.ExpiresAt != null && r.ExpiresAt <= now, ct) + }, + note = rows.Count == 0 + ? "nothing with an expiry stops being enforced inside this window; `alreadyExpired` says whether there are dated entries at all" + : "thenAnswers is the real DecisionEngine run over the state with only this entry removed; entries that never expire are not listed, and neither are entries expiring beyond this window" + }); + }); + // The record of deliberate changes to the operator's config (OPEN-64). // Newest first, capped and paged like every other listing, and readable // by the read-only token: it is a read, and a dashboard that can see the @@ -1571,6 +1714,19 @@ note = t.Note } }; + // 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. + private const int HorizonDefaultMinutes = 30; + private const int HorizonMinMinutes = 1; + private const int HorizonMaxMinutes = 1440; + + /// Whole minutes until an entry stops being enforced, never negative: + /// an entry inside the window is at least one minute away by the filter that + /// selected it, and "-4" would read as a clock error. + private static int MinutesUntil(DateTimeOffset expiresAt, DateTimeOffset now) + => Math.Max(0, (int)Math.Ceiling((expiresAt - now).TotalMinutes)); + private const int DossierAlertLimit = 5; /// Whole seconds left in a window, never negative: a window that has @@ -1817,3 +1973,24 @@ note = t.Note return SourceKey.TryParse(match, out _, out _); } } + +/// One dated entry that stops being enforced inside the horizon, and — +/// for the address-shaped kinds — what answers once it is gone. +internal sealed record HorizonRow( + string Kind, + long Id, + string? Match, + string? Pattern, + string? Note, + DateTimeOffset ExpiresAt, + int MinutesLeft, + HorizonAfter? ThenAnswers, + string? WhyNoAnswer); + +/// The verdict the edge would give this source with only the named entry +/// removed, in the words the log and the dry run use. +internal sealed record HorizonAfter( + string Verdict, + bool WouldBeRefused, + string By, + string Note); diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index d2348c1..b15b0a2 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -114,7 +114,6 @@ builder.Services.AddSingleton(sp => new AlertNotifier( sp.GetRequiredService(), sp.GetRequiredService>(), alertWebhookUrl, alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds)); -builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); // The record of a deliberate config change (OPEN-64). Best-effort by design: // the change has already been applied when this writes, and a change refused @@ -132,6 +131,15 @@ builder.Services.AddSingleton(sp => new MaxMindGeoIpLookup( // What the schema step did at startup, read back on /admin-api/state (OPEN-55). builder.Services.AddSingleton(); builder.Services.AddHostedService(); +// Hosted services are started in registration order, and the warmer is the step +// that creates the tables. The notifier used to be registered above it, so its +// first queue read ran against a database this same process had not created yet: +// measured on a cold start, the queue sweep failed with SQLite Error 1: +// 'no such table: alert_push_queue', and that sentence became +// alertWebhookLastError — the state page blaming the endpoint for the edge's own +// startup order. Every worker that touches durable state is registered below the +// warmer for that reason; the singleton stays where the endpoints resolve it. +builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Registered as themselves as well as hosted services: the admin surface and // the tests need to reach the writer to force a flush, and AddHostedService // alone does not make the implementation resolvable. diff --git a/dotnet/OpenWaf.Tests.Integration/EnforcementHorizonTests.cs b/dotnet/OpenWaf.Tests.Integration/EnforcementHorizonTests.cs new file mode 100644 index 0000000..b650287 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/EnforcementHorizonTests.cs @@ -0,0 +1,266 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenWaf.Domain.Security; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// The enforcement horizon (OPEN-72): what stops being enforced soon, and what +/// answers once it has. +/// +/// The incident this exists for is a scheduled one. An office inside a banned +/// netblock is given a 60-minute exemption; the minute passes; the office is +/// refused again; and nobody looking at the refusal knows there was ever an +/// exemption, or that a /28 was underneath it. The tables all hold the dates — +/// blocks, ranges, engine bans, exemptions, path rules, path budgets — and no +/// surface reads them forward. +/// +/// What these tests hold the surface to: the answer for an address-shaped entry +/// is the real decision engine run with only that entry removed, so it cannot +/// disagree with the wire; a pattern says why it has no answer instead of +/// inventing one; dead rows are counted apart from "nothing expires soon"; and +/// asking writes nothing. +/// +public sealed class EnforcementHorizonTests +{ + private const string Range = "203.0.113.16/28"; // .16 – .31 + private const string Inside = "203.0.113.21"; + private const string Source = "203.0.113.77"; + + private static async Task AdminAsync( + EdgeFixture f, HttpMethod method, string url, object? body = null, + string token = EdgeFixture.AdminToken) + { + using var request = new HttpRequestMessage(method, url); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + if (body is not null) request.Content = JsonContent.Create(body); + return await f.Client.SendAsync(request); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> HorizonAsync( + EdgeFixture f, string query, string token = EdgeFixture.AdminToken) + { + using var r = await AdminAsync(f, HttpMethod.Get, $"/admin-api/expiring?{query}", token: token); + var body = JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone(); + return (r.StatusCode, body); + } + + private static async Task 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; + } + + /// Rows are written straight to the database when the API would only + /// accept an expiry the test then has to wait out. + private static async Task SeedAllow(EdgeFixture f, string match, DateTimeOffset? expiresAt) + { + using var scope = f.Factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.AllowEntries.Add(new AllowEntry + { + Match = match, Note = "the office", CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = expiresAt + }); + await db.SaveChangesAsync(); + await f.Service().InvalidateAsync(); + } + + private static async Task BanByTheEngineAsync(EdgeFixture f, string ip) + { + for (var i = 0; i < 3; i++) await AskAsync(f, "/wp-login.php", ip); + } + + [Fact] + public async Task An_exemption_inside_a_banned_range_says_what_takes_over_when_it_ages_out() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Range, reason = "netblock scanning" })) { } + await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(10)); + + // The wire today: the exemption outranks the range, the office is served. + Assert.Equal(404, await AskAsync(f, "/anything", Inside)); + + var (status, body) = await HorizonAsync(f, "within=30"); + Assert.Equal(HttpStatusCode.OK, status); + var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(), + r => r.GetProperty("kind").GetString() == "allow"); + Assert.Equal(Inside, row.GetProperty("match").GetString()); + Assert.Equal("the office", row.GetProperty("note").GetString()); + Assert.True(row.GetProperty("minutesLeft").GetInt32() is > 0 and <= 10); + + // The part nobody can assemble from the tables: what answers next. + var after = row.GetProperty("thenAnswers"); + Assert.Equal("block_operator", after.GetProperty("verdict").GetString()); + Assert.True(after.GetProperty("wouldBeRefused").GetBoolean()); + Assert.Equal(Range, after.GetProperty("by").GetString()); + Assert.Contains("refused again", after.GetProperty("note").GetString()!); + } + + [Fact] + public async Task A_block_with_nothing_underneath_says_nothing_else_refuses_the_source() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Source, reason = "incident, time-boxed", expiresInMinutes = 60 })) { } + + var (_, body) = await HorizonAsync(f, "within=120"); + var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(), + r => r.GetProperty("kind").GetString() == "block"); + Assert.Equal(Source, row.GetProperty("match").GetString()); + var after = row.GetProperty("thenAnswers"); + Assert.Equal("pass", after.GetProperty("verdict").GetString()); + Assert.False(after.GetProperty("wouldBeRefused").GetBoolean()); + Assert.Contains("nothing else refuses", after.GetProperty("note").GetString()!); + } + + [Fact] + public async Task An_engine_ban_under_an_operator_block_reports_the_block_that_would_still_answer() + { + await using var f = new EdgeFixture(); + await BanByTheEngineAsync(f, Source); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Source, reason = "written by hand", expiresInMinutes = 600 })) { } + + // The ban the engine wrote ages out in about an hour; the operator's block + // is what keeps refusing after it does. + var (_, body) = await HorizonAsync(f, "within=120"); + var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(), + r => r.GetProperty("kind").GetString() == "engine ban"); + var after = row.GetProperty("thenAnswers"); + Assert.Equal("block_operator", after.GetProperty("verdict").GetString()); + Assert.True(after.GetProperty("wouldBeRefused").GetBoolean()); + Assert.Equal(Source, after.GetProperty("by").GetString()); + } + + [Fact] + public async Task A_pattern_says_why_it_has_no_answer_instead_of_inventing_one() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rules", + new { pattern = "/wp-admin*", action = "block", note = "scan", expiresInMinutes = 60 })) { } + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules", + new { pattern = "/login*", limitPerWindow = 5, expiresInMinutes = 60 })) { } + + var (_, body) = await HorizonAsync(f, "within=120"); + foreach (var kind in new[] { "path rule", "path budget" }) + { + var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(), + r => r.GetProperty("kind").GetString() == kind); + Assert.True(row.GetProperty("thenAnswers").ValueKind == JsonValueKind.Null); + Assert.Contains("/admin-api/decide", row.GetProperty("whyNoAnswer").GetString()!); + } + } + + [Fact] + public async Task Entries_outside_the_window_are_left_out_and_the_bounds_are_said() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Source, reason = "a year", expiresInMinutes = 5256000 })) { } + + var (_, shortWindow) = await HorizonAsync(f, "within=30"); + Assert.Equal(0, shortWindow.GetProperty("count").GetInt32()); + Assert.Empty(shortWindow.GetProperty("expiring").EnumerateArray()); + + var (_, longWindow) = await HorizonAsync(f, "within=1440"); + Assert.Equal(0, longWindow.GetProperty("count").GetInt32()); + + // Out of range is a 400 with the bounds, not a silent clamp: a horizon + // quietly widened to a year is not the question that was asked. + foreach (var bad in new[] { "within=0", "within=99999", "within=-5" }) + { + var (status, body) = await HorizonAsync(f, bad); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("1..1440", body.ToString()); + } + var (unknownStatus, unknownBody) = await HorizonAsync(f, "within=30&kind=allow"); + Assert.Equal(HttpStatusCode.BadRequest, unknownStatus); + Assert.Contains("kind", unknownBody.ToString()); + } + + [Fact] + public async Task Dead_rows_are_counted_apart_from_nothing_expiring() + { + await using var f = new EdgeFixture(); + await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(-30)); + + var (_, body) = await HorizonAsync(f, "within=30"); + Assert.Equal(0, body.GetProperty("count").GetInt32()); + Assert.Equal(1, body.GetProperty("alreadyExpired").GetProperty("allow").GetInt32()); + } + + [Fact] + public async Task Asking_the_horizon_writes_nothing_and_a_read_only_token_can_ask_it() + { + await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Source, expiresInMinutes = 60 })) { } + await SeedAllow(f, Inside, DateTimeOffset.UtcNow.AddMinutes(10)); + + for (var i = 0; i < 5; i++) + { + var (status, _) = await HorizonAsync(f, "within=120", EdgeFixture.ReadOnlyToken); + Assert.Equal(HttpStatusCode.OK, status); + } + + using (var changes = await AdminAsync(f, HttpMethod.Get, "/admin-api/changes", + token: EdgeFixture.ReadOnlyToken)) + { + Assert.Equal(HttpStatusCode.OK, changes.StatusCode); + using var doc = JsonDocument.Parse(await changes.Content.ReadAsStringAsync()); + // One record: the operator's own block. A read that left a record + // would be a write wearing a mask. + Assert.Single(doc.RootElement.EnumerateArray()); + } + + // And the wire still answers the same way it did before the five asks. + Assert.Equal(404, await AskAsync(f, "/anything", Inside)); + Assert.Equal(301, await AskAsync(f, "/anything", Source)); + + using (var anonymous = await f.Client.GetAsync("/admin-api/expiring?within=30")) + Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); + } + + [Fact] + public async Task The_horizon_agrees_with_the_wire_about_what_a_source_would_get() + { + await using var f = new EdgeFixture(); + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = Range, reason = "netblock" })) { } + using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow", + new { match = Inside, note = "the office", expiresInMinutes = 60 })) { } + + var (_, body) = await HorizonAsync(f, "within=120"); + var row = Assert.Single(body.GetProperty("expiring").EnumerateArray(), + r => r.GetProperty("kind").GetString() == "allow"); + var claimed = row.GetProperty("thenAnswers").GetProperty("verdict").GetString(); + + // Remove the exemption for real, and the wire has to answer the way the + // horizon said it would. This is the claim the whole surface makes. + using (var list = await AdminAsync(f, HttpMethod.Get, "/admin-api/allow")) + { + using var doc = JsonDocument.Parse(await list.Content.ReadAsStringAsync()); + var id = doc.RootElement[0].GetProperty("id").GetInt64(); + using (await AdminAsync(f, HttpMethod.Delete, $"/admin-api/allow/{id}")) { } + } + + string? verdict = null; + for (var i = 0; i < 10 && verdict != "block_operator"; i++) + { + using var preview = await AdminAsync(f, HttpMethod.Get, + $"/admin-api/decide?ip={Inside}&path=/anything"); + using var doc = JsonDocument.Parse(await preview.Content.ReadAsStringAsync()); + verdict = doc.RootElement.GetProperty("verdict").GetString(); + if (verdict != "block_operator") await Task.Delay(500); + } + Assert.Equal(claimed, verdict); + Assert.Equal(301, await AskAsync(f, "/anything", Inside)); + } +} diff --git a/dotnet/OpenWaf.Tests.Integration/StartupOrderTests.cs b/dotnet/OpenWaf.Tests.Integration/StartupOrderTests.cs new file mode 100644 index 0000000..fef6356 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/StartupOrderTests.cs @@ -0,0 +1,77 @@ +using System.Net.Http; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using OpenWaf.Edge.Startup; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Tests.Integration; + +/// +/// Startup order, measured rather than intended. +/// +/// Hosted services are started in registration order, and the schema step is one +/// of them. The alert push queue's worker was registered above it, so on a cold +/// start its first queue sweep read alert_push_queue out of a database this +/// same process had not created yet. Nothing crashed — the worker counts what it +/// cannot read — but the sentence it left behind was the operator's answer: +/// alertWebhookLastError carried "SQLite Error 1: 'no such table: +/// alert_push_queue'", and the state page blamed the webhook endpoint for the +/// edge's own startup order. A failure that names the wrong component is worse +/// than no failure, because it sends the operator to fix the wrong thing. +/// +public sealed class StartupOrderTests +{ + private static async Task StateAsync(EdgeFixture f) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state"); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + response.EnsureSuccessStatusCode(); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + [Fact] + public async Task The_schema_step_is_registered_before_every_worker_that_touches_its_tables() + { + await using var f = new EdgeFixture(alertWebhookPath: "/hook"); + var hosts = f.Factory.Services.GetServices().ToList(); + + int IndexOf() => hosts.FindIndex(h => h is T); + var warmer = IndexOf(); + Assert.True(warmer >= 0, "the schema step is not a hosted service of this edge"); + + // Every one of these reads or writes a table the warmer creates. The + // assertion is on the order, not on the count: a worker added tomorrow + // above the warmer reproduces the defect this test exists for. + foreach (var (name, index) in new (string, int)[] + { + ("AlertNotifier", IndexOf()), + ("ObservationWriter", IndexOf()), + ("RetentionWorker", IndexOf()), + ("NetblockWatcher", IndexOf()), + ("PendingBanRetryWorker", IndexOf()) + }) + { + Assert.True(index >= 0, $"{name} is not a hosted service of this edge"); + Assert.True(warmer < index, + $"{name} starts at {index}, before the schema step at {warmer}: " + + $"its first read can hit a table this process has not created. Hosts: " + + string.Join(", ", hosts.Select(h => h.GetType().Name))); + } + } + + [Fact] + public async Task A_cold_start_with_a_webhook_configured_blames_nobody_for_the_edge_own_startup() + { + await using var f = new EdgeFixture(alertWebhookPath: "/hook"); + // The queue sweep runs the moment the worker starts. Give it the moment + // it would have taken to fail, then ask what the edge thinks went wrong: + // an empty queue is not a failure, and a missing table is. + await Task.Delay(500); + var state = await StateAsync(f); + Assert.Equal(0, state.GetProperty("alertWebhookFailures").GetInt32()); + Assert.Equal(JsonValueKind.Null, state.GetProperty("alertWebhookLastError").ValueKind); + Assert.Equal(0, state.GetProperty("alertPushPending").GetInt32()); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index b94d072..ca63055 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1825,6 +1825,52 @@ check 'the scene cleans itself' 0 \ "$EDGE/admin-api/policy" >/dev/null; \ admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +# What stops being enforced soon (OPEN-72), on the shipped image: the horizon is +# read from the database, so it has to answer the same way through the container +# as through the process, and the prediction it makes has to hold on the wire. +echo '- the shipped edge says what stops answering soon' +HOR_IP=198.51.100.171 +HOR_NET=198.51.100.176/29 # .176 - .183 +HOR_INSIDE=198.51.100.179 +check 'the shipped edge takes a block, a range and an allow that all expire today' '204 204 204' \ + "$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"ip":"'"$HOR_IP"'","reason":"horizon block","expiresInMinutes":45}' "$EDGE/admin-api/blocks") \ +$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"ip":"'"$HOR_NET"'","reason":"horizon range","expiresInMinutes":20}' "$EDGE/admin-api/blocks") \ +$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"match":"'"$HOR_INSIDE"'","note":"horizon allow","expiresInMinutes":60}' "$EDGE/admin-api/allow")" +check 'the shipped horizon lists them nearest first and says the range refuses once the allow ages out' yes \ + "$(admin "$EDGE/admin-api/expiring?within=90" | python3 -c ' +import sys,json +d=json.load(sys.stdin) +rows=[r for r in d["expiring"] if r["match"] in ("'"$HOR_IP"'","'"$HOR_NET"'","'"$HOR_INSIDE"'")] +order=[r["match"] for r in rows] +a=[r for r in rows if r["kind"]=="allow"] +t=a[0]["thenAnswers"] if a else None +print("yes" if d["scope"]=="database" and order==["'"$HOR_NET"'","'"$HOR_IP"'","'"$HOR_INSIDE"'"] and t and t["verdict"]=="block_operator" and t["by"]=="'"$HOR_NET"'" else "no")')" +check 'the shipped horizon says a block with nothing underneath leaves the source free' yes \ + "$(admin "$EDGE/admin-api/expiring?within=90" | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="block" and r["match"]=="'"$HOR_IP"'"] +t=rows[0]["thenAnswers"] if rows else None +print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] else "no")')" +check 'the shipped horizon refuses a window of zero minutes or of more than a day' '400 400' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/expiring?within=0") \ +$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/expiring?within=1441")" +check 'the shipped read-only token reads the horizon, no token does not' '200 401' \ + "$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/expiring?within=90") \ +$(code "$EDGE/admin-api/expiring?within=90")" +HOR_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"]=="'"$HOR_INSIDE"'"][0])')" +check 'the shipped prediction holds: with the allow gone the wire refuses that address' block_operator \ + "$(admin -X DELETE "$EDGE/admin-api/allow/$HOR_ALLOW_ID" >/dev/null; \ + admin "$EDGE/admin-api/decide?ip=$HOR_INSIDE&path=/" \ + | python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')" +check 'the scene cleans itself' 0 \ + "$(admin -X DELETE "$EDGE/admin-api/blocks?key=$HOR_IP" >/dev/null; \ + admin -X DELETE "$EDGE/admin-api/blocks?key=${HOR_NET//\//%2F}" >/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 ("'"$HOR_IP"'","'"$HOR_NET"'")]))')" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index 02b9c3a..3537674 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -166,7 +166,17 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); check('a database inside the 90-day alarm is not marked stale', !warnPills.some((x) => /geo/.test(x)), JSON.stringify(warnPills)); - const alertRows = await cells('#alerts tbody tr'); + // The alert row is written after the response that raised it — the seed has its + // own retry loop for exactly that — and the page refreshes on an interval, so + // one read of the table can land before the row reached storage and before the + // next refresh drew it. Bounded retry: the assertion is about the page showing + // the streak this run wrote, not about which refresh was in flight. + let alertRows = []; + for (let i = 0; i < 20; i++) { + alertRows = await cells('#alerts tbody tr'); + if (alertRows.some((r) => r[0] === 'server_error_streak' && r[1] === SEED_ERROR)) break; + await new Promise((r) => setTimeout(r, 500)); + } const errAlerts = alertRows.filter((r) => r[0] === 'server_error_streak' && r[1] === SEED_ERROR); check('the alerts table lists the server-error streak this run wrote', errAlerts.length >= 1 && errAlerts.some((r) => Number(r[2]) >= 3), @@ -588,12 +598,15 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); const letOut = await page.textContent('#status'); check('one button lets one source out and says it is a counter reset, not an exemption', /window dropped for/.test(letOut) && /not an exemption/.test(letOut), letOut); + // The probes this scene drew are refusals (404, 404, 429), so the streak pillar + // has banned this address by now — and an engine ban outlives every retry loop + // in this file. Both probes below are about the budget, so the one ban on this + // one address is cleared by name first; clearing every engine ban would take the + // netblock offers down with it, and a later scene reads those. + await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(PATH_BUDGET_IP)}`); check('the source that was let out reaches the upstream again on that path', (await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH)) === 404, `probe from ${PATH_BUDGET_IP} on ${PATH_BUDGET_PATH} after being let out`); - // Same reason as above: the probes this scene drew are refusals, and the streak - // pillar has now banned this address too. The check below is about the budget - // row, so the engine's own ban on this one address is cleared by name first. await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(PATH_BUDGET_IP)}`); await page.evaluate((pat) => { @@ -605,7 +618,13 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); .some((tr) => tr.children[0].textContent === pat), `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {}); let reopened = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); for (let i = 0; i < 10 && reopened !== 404; i++) { - await new Promise((r) => setTimeout(r, 1000)); reopened = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); + await new Promise((r) => setTimeout(r, 1000)); + // Every probe in this loop is a refusal — 429 until the removal reaches the + // snapshot, then the upstream's 404 — and three refusals in five minutes is + // what the streak pillar bans on. The assertion is about the budget row, so + // the ban this loop causes on this one address is cleared each time round. + await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(PATH_BUDGET_IP)}`); + reopened = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH); } check('one remove button reopens the path for a source that was paused a moment ago', reopened === 404, `probe from ${PATH_BUDGET_IP} answered ${reopened}`); @@ -894,6 +913,12 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); () => /^off/.test(document.getElementById('ratenote').textContent), null, { timeout: 15000 }).catch(() => {}); await clearEngineBan(RATE_IP); + // The page refreshes on an interval, and a refresh that started before this + // PUT lands answers with the mode that was true when it started. The wait above + // can therefore be satisfied and then overwritten by the older answer, so the + // line is waited for again after the ban clear rather than read once. + await page.waitForFunction(() => /^off/.test(document.getElementById('ratenote').textContent), + null, { timeout: 15000 }).catch(() => {}); const backOff = await rateNoteOf(); check('the budget can be switched off from the page', /^off/.test(backOff), JSON.stringify(backOff)); @@ -1374,6 +1399,169 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); && /\d+ of \d+ standing streaks listed/.test(clearedStreakNote), `${JSON.stringify(clearedObsNote)} | ${JSON.stringify(clearedStreakNote)}`); } + // A listing the edge could not answer is not a listing with nothing in it. + // Measured on a run where two of the page's fourteen calls lost the database + // for a moment: the observation line printed "0 sources the edge has recorded" + // and the streak line "0 of 0 standing streaks listed" over a map holding + // twelve sources. The status line said the call failed; the tables an operator + // actually reads said there was nothing to see. + { + const brokenRead = async (path) => page.route(path, (route) => route.fulfill({ + status: 503, + contentType: 'application/json', + body: JSON.stringify({ error: 'gate: this read did not run' }) + })); + await brokenRead('**/admin-api/observations*'); + await brokenRead('**/admin-api/streaks*'); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.fill('#token', TOKEN); + await page.click('#save'); + await page.waitForFunction(() => /NOT READ/.test(document.getElementById('obsnote').textContent), + null, { timeout: 15000 }).catch(() => {}); + const brokenObsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim(); + const brokenStreakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim(); + const brokenRows = await page.$$eval('#obs tbody tr, #streaks tbody tr', + (trs) => trs.map((tr) => (tr.children[0].textContent || '').trim())); + check('a listing the edge could not answer says so instead of counting zero', + brokenObsNote === 'NOT READ \u2014 gate: this read did not run. This is not an empty table.' + && brokenStreakNote === 'NOT READ \u2014 gate: this read did not run. This is not an empty table.', + `${JSON.stringify(brokenObsNote)} | ${JSON.stringify(brokenStreakNote)}`); + check('and neither table is drawn as an empty one', + brokenRows.length === 2 && brokenRows.every((v) => v.startsWith('NOT READ')), + JSON.stringify(brokenRows)); + await page.unroute('**/admin-api/observations*'); + await page.unroute('**/admin-api/streaks*'); + await page.waitForFunction(() => /sources the edge has recorded|newest \d+ of/.test( + document.getElementById('obsnote').textContent), null, { timeout: 15000 }).catch(() => {}); + const healedObsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim(); + const healedStreakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim(); + check('and the count comes back when the read works again', + !/NOT READ/.test(healedObsNote) && !/NOT READ/.test(healedStreakNote) + && /(sources the edge has recorded|recorded sources)/.test(healedObsNote) + && /standing streaks listed/.test(healedStreakNote), + `${JSON.stringify(healedObsNote)} | ${JSON.stringify(healedStreakNote)}`); + } + + // The enforcement horizon (OPEN-72). A dated entry that is about to age out is + // only interesting for what answers afterwards, so the row carries the real + // decision the engine would take with that one entry removed. Seeded through + // the page's own forms: a range expiring in 20 min, an allow inside it + // expiring in 45, and a path rule expiring in 30. + { + const HORIZON_NET = '192.0.2.232/29'; // .232 - .239 + const HORIZON_ALLOW = '192.0.2.235'; // inside that range + const HORIZON_RULE = '/horizon-gate*'; + + await page.fill('#blockIp', HORIZON_NET); + await page.fill('#blockReason', 'console gate: horizon range'); + await page.fill('#blockTtl', '20'); + await page.click('#addBlock'); + await page.waitForFunction((k) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')] + .some((b) => b.dataset.k === k), HORIZON_NET, { timeout: 15000 }).catch(() => {}); + + await page.fill('#allowMatch', HORIZON_ALLOW); + await page.fill('#allowNote', 'console gate: horizon allow'); + await page.fill('#allowTtl', '45'); + await page.click('#addAllow'); + await page.waitForFunction((m) => [...document.querySelectorAll('#allow tbody tr')] + .some((tr) => (tr.children[0].textContent || '').trim() === m), HORIZON_ALLOW, + { timeout: 15000 }).catch(() => {}); + + await page.fill('#rulePattern', HORIZON_RULE); + await page.fill('#ruleNote', 'console gate: horizon rule'); + await page.fill('#ruleTtl', '30'); + await page.click('#addRule'); + await page.waitForFunction((x) => [...document.querySelectorAll('#pathrules tbody tr')] + .some((tr) => (tr.children[0].textContent || '').trim() === x), HORIZON_RULE, + { timeout: 15000 }).catch(() => {}); + + const horizonRows = () => page.$$eval('#horizonanswer div', (ds) => ds.map((d) => d.textContent)); + const askHorizon = async (minutes) => { + // The box is emptied first and the first line names the window that was + // asked for, so a wait for "an answer is in the box" can never be satisfied + // by the answer to the previous ask. + await page.evaluate(() => { document.getElementById('horizonanswer').textContent = ''; }); + await page.fill('#horizonWithin', String(minutes)); + await page.click('#askHorizon'); + await page.waitForFunction((asked) => (document.getElementById('horizonanswer').textContent || '') + .indexOf('asked: within ' + asked + ' minutes') === 0, String(minutes), + { timeout: 15000 }).catch(() => {}); + return horizonRows(); + }; + + const horizonBefore = await page.$$eval('#blocks tbody button[data-act="delblock"]', + (bs) => bs.map((b) => b.dataset.k).sort()); + const wide = await askHorizon(60); + const netLine = wide.find((l) => l.includes(HORIZON_NET)); + const allowLine = wide.find((l) => l.includes(HORIZON_ALLOW)); + const ruleLine = wide.find((l) => l.includes(HORIZON_RULE)); + + check('the horizon lists the range, the allow inside it and the path rule', + !!netLine && !!allowLine && !!ruleLine, JSON.stringify(wide)); + check('the allow says what refuses its address once it ages out', + !!allowLine && /then: block_operator by 192\.0\.2\.232\/29/.test(allowLine), + JSON.stringify(allowLine)); + check('the range says nothing else refuses once it ages out', + !!netLine && /then: pass by nothing/.test(netLine), JSON.stringify(netLine)); + check('a path rule says why it has no single answer and points at the dry run', + !!ruleLine && /a path rule and a path budget describe a set of paths/.test(ruleLine) + && ruleLine.includes('/admin-api/decide?ip=&path='), JSON.stringify(ruleLine)); + check('the horizon is ordered by what ages out first', + !!netLine && !!ruleLine && !!allowLine + && wide.indexOf(netLine) < wide.indexOf(ruleLine) + && wide.indexOf(ruleLine) < wide.indexOf(allowLine), + JSON.stringify(wide.filter((l) => l.includes(' min left')))); + check('the header names the window asked for and the counts of what is already past', + /^asked: within 60 minutes of 2\d{3}-/.test(wide[0] || '') + && /^expiring: \d+ - already past: block \d+, range \d+, engine ban \d+, allow \d+, path rule \d+, path budget \d+$/.test(wide[1] || ''), + JSON.stringify(wide.slice(0, 2))); + + const narrow = await askHorizon(10); + check('a window shorter than every TTL hides all three', + !narrow.some((l) => l.includes(HORIZON_NET) || l.includes(HORIZON_ALLOW) + || l.includes(HORIZON_RULE)), + JSON.stringify(narrow)); + + await page.fill('#horizonWithin', '0'); + await page.click('#askHorizon'); + await page.waitForFunction(() => /whole number of minutes/.test(document.getElementById('status').textContent), + null, { timeout: 5000 }).catch(() => {}); + const horizonStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim(); + const stillNarrow = await horizonRows(); + check('a window of zero minutes is refused by the page before the request goes out', + /whole number of minutes from 1 to 1440/.test(horizonStatus) + && stillNarrow[0] === narrow[0], + `${JSON.stringify(horizonStatus)} box=${JSON.stringify(stillNarrow[0])}`); + + const horizonAfter = await page.$$eval('#blocks tbody button[data-act="delblock"]', + (bs) => bs.map((b) => b.dataset.k).sort()); + check('reading the horizon wrote nothing to the operator list', + JSON.stringify(horizonAfter) === JSON.stringify(horizonBefore), + JSON.stringify(horizonAfter)); + + // Tear the seeds down by id, not by cell: the block row prints a range badge + // where the key belongs, and the allow and rule rows key their remove button + // on the row id. + const rowId = (table, act, cellText) => page.$$eval(`#${table} tbody tr`, + (trs, x) => { + const tr = trs.find((r) => (r.children[0].textContent || '').trim() === x.cell); + if (!tr) return null; + const b = tr.querySelector(`button[data-act="${x.act}"]`); + return b ? b.dataset.k : null; + }, { act, cell: cellText }); + const allowId = await rowId('allow', 'delallow', HORIZON_ALLOW); + const ruleId = await rowId('pathrules', 'delrule', HORIZON_RULE); + if (allowId) await page.click(`#allow tbody button[data-act="delallow"][data-k="${allowId}"]`); + if (ruleId) await page.click(`#pathrules tbody button[data-act="delrule"][data-k="${ruleId}"]`); + await page.click(`#blocks tbody button[data-act="delblock"][data-k="${HORIZON_NET}"]`); + await page.waitForFunction(() => ![...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')] + .some((b) => b.dataset.k === '192.0.2.232/29'), null, { timeout: 15000 }).catch(() => {}); + const horizonTorn = await page.$$eval('#blocks tbody button[data-act="delblock"]', + (bs) => bs.map((b) => b.dataset.k)); + check('the horizon seeds left the operator list the way they were found', + !horizonTorn.includes(HORIZON_NET), JSON.stringify(horizonTorn)); + } + // A phone in dark mode is the case an operator actually reaches the console // from — the address that got them blocked is the one they are typing about. // Both halves of this used to be broken and measured: the page overflowed a diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 90712bd..e023332 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -913,6 +913,123 @@ check 'the scene cleans itself' 0 \ curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \ | python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')" +# What stops being enforced soon (OPEN-72). A list of expiry dates tells an +# operator nothing about what the site will be doing tomorrow: the row has to +# carry the answer that takes over when the entry ages out, or "expires at 06:00" +# is a timestamp to interpret by hand at 05:55. +echo '- the enforcement horizon' +HOR_IP=192.0.2.151 +HOR_NET=192.0.2.152/29 # .152 - .159 +HOR_INSIDE=192.0.2.155 +horizon() { curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=${1:-30}"; } +check 'the operator writes a block, a range, an allow and a path rule that all expire today' '204 204 204 204' \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary '{"ip":"'"$HOR_IP"'","reason":"horizon block","expiresInMinutes":45}' \ + "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":"'"$HOR_NET"'","reason":"horizon range","expiresInMinutes":20}' \ + "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":"192.0.2.155","note":"horizon allow","expiresInMinutes":60}' \ + "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":"/horizon-gate*","action":"block","note":"horizon rule","expiresInMinutes":25}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rules")" +check 'the horizon lists them nearest first, from the database' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +d=json.load(sys.stdin) +rows=[r for r in d["expiring"] if r["match"] in ("192.0.2.151","192.0.2.152/29","192.0.2.155") or r["pattern"]=="/horizon-gate*"] +order=[r["match"] or r["pattern"] for r in rows] +print("yes" if d["scope"]=="database" and d["count"]>=4 and order==["192.0.2.152/29","/horizon-gate*","192.0.2.151","192.0.2.155"] else "no")')" +check 'the allow says which range refuses its address once it ages out' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="allow" and r["match"]=="192.0.2.155"] +t=rows[0]["thenAnswers"] if rows else None +print("yes" if t and t["verdict"]=="block_operator" and t["wouldBeRefused"] and t["by"]=="192.0.2.152/29" else "no")')" +check 'a block with nothing underneath says the source goes free' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="block" and r["match"]=="192.0.2.151"] +t=rows[0]["thenAnswers"] if rows else None +print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] and "nothing else refuses" in t["note"] else "no")')" +check 'a range answers for its own network address, not for the notation' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="range" and r["match"]=="192.0.2.152/29"] +t=rows[0]["thenAnswers"] if rows else None +print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] else "no")')" +check 'a path rule says why it has no single answer and points at the dry run' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if r["pattern"]=="/horizon-gate*"] +r=rows[0] if rows else None +print("yes" if r and r["thenAnswers"] is None and "/admin-api/decide?ip=&path=" in (r["whyNoAnswer"] or "") else "no")')" +check 'every row counts down in whole minutes from now' yes \ + "$(horizon 90 | python3 -c ' +import sys,json +rows=[r for r in json.load(sys.stdin)["expiring"] if (r["match"] or r["pattern"]) in ("192.0.2.151","192.0.2.152/29","192.0.2.155","/horizon-gate*")] +print("yes" if len(rows)==4 and all(0 < r["minutesLeft"] <= 60 for r in rows) else "no")')" +check 'the answer separates "nothing expires soon" from "nothing is dated"' yes \ + "$(horizon 1 | python3 -c ' +import sys,json +d=json.load(sys.stdin) +mine=[r for r in d["expiring"] if (r["match"] or r["pattern"]) in ("192.0.2.151","192.0.2.152/29","192.0.2.155","/horizon-gate*")] +print("yes" if not mine and d["withinMinutes"]==1 and all(k in d["alreadyExpired"] for k in ("block","range","engineBan","allow","pathRule","pathBudget")) else "no")')" +check 'no window asked is answered with the default, and it says so' '30 200' \ + "$(horizon | python3 -c 'import sys,json;print(json.load(sys.stdin)["withinMinutes"])') \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring")" +check 'a window of zero minutes or of more than a day is refused by name' '400 400' \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=0") \ +$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=1441")" +check 'a question it cannot answer is refused by name' 400 \ + "$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=30&nonsense=1")" +check 'the read-only token reads the horizon, no token does not' '200 401' \ + "$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=90") \ +$(code "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=90")" +check 'asking it six times wrote nothing: the dated rows are still the four it was shown' '2 1' \ + "$(for _ in 1 2 3 4 5 6; do horizon 90 >/dev/null; done; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/hor-blocks.json; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/hor-allow.json; \ + python3 -c ' +import json +b=json.load(open("/tmp/hor-blocks.json")); a=json.load(open("/tmp/hor-allow.json")) +print(len([r for r in b if r["sourceKey"] in ("192.0.2.151","192.0.2.152/29")]), + len([r for r in a if r["match"]=="192.0.2.155"]))')" +# The prediction has to be true, not plausible: take the allow away for real and +# ask the wire the same question the horizon answered. +HOR_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.155"][0])')" +check 'the horizon was right: with the allow gone the wire refuses that address' 'block_operator 192.0.2.152/29' \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/allow/$HOR_ALLOW_ID" >/dev/null; \ + curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$HOR_INSIDE&path=/" -o /tmp/hor_decide.json; \ + curl -s -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=$HOR_INSIDE" -o /tmp/hor_dossier.json; \ + python3 -c ' +import json +d=json.load(open("/tmp/hor_decide.json")); e=json.load(open("/tmp/hor_dossier.json"))["operatorBlock"] +print(d["verdict"], e["match"] if e and e["cameFromRange"] else None)')" +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=$HOR_IP" >/dev/null; \ + code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${HOR_NET//\//%2F}" >/dev/null; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules?live=false" -o /tmp/hor-rules.json; \ + HOR_RULE_ID="$(python3 -c 'import json;print([r["id"] for r in json.load(open("/tmp/hor-rules.json")) if r["pattern"]=="/horizon-gate*"][0])')"; \ + code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/rules/$HOR_RULE_ID" >/dev/null; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/hor-blocks2.json; \ + curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules?live=false" -o /tmp/hor-rules2.json; \ + python3 -c ' +import json +b=json.load(open("/tmp/hor-blocks2.json")); r=json.load(open("/tmp/hor-rules2.json")) +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*"]))')" + 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 \