GET /admin-api/expiring?within=<minutes> (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.
1652 lines
97 KiB
JavaScript
1652 lines
97 KiB
JavaScript
// The console is a page, and a page fails in ways curl cannot see: a typo in the
|
||
// inline script, a fetch that 401s, a table that renders nothing while the
|
||
// summary looks fine. This drives it in a real Chromium and fails the run when
|
||
// the page is wrong, or when the page throws.
|
||
//
|
||
// Run it through scripts/console-smoke.sh, which starts the stack and seeds the
|
||
// state the assertions look for. It needs playwright-core: point PLAYWRIGHT_CORE
|
||
// at it, or install it locally and it resolves by name.
|
||
|
||
const EDGE = process.env.EDGE_URL || 'http://127.0.0.1:8080';
|
||
const TOKEN = process.env.OPENWAF_ADMIN_TOKEN || '';
|
||
// A path without an extension makes Chromium throw "unsupported mime type",
|
||
// which reads like a page failure and is not one.
|
||
const SCREENSHOT = process.env.SCREENSHOT
|
||
? (/\.[a-z0-9]+$/i.test(process.env.SCREENSHOT) ? process.env.SCREENSHOT : process.env.SCREENSHOT + '.png')
|
||
: '';
|
||
const SEED_SOURCE = process.env.SEED_SOURCE || '';
|
||
const SEED_BLOCK = process.env.SEED_BLOCK || '';
|
||
const SEED_ERROR = process.env.SEED_ERROR || '';
|
||
// A path an anonymous visitor asked for, and a block reason somebody typed.
|
||
// Both are API values that end up in a table cell; neither is authored by the
|
||
// person reading this page.
|
||
const SEED_MARKUP_PATH = process.env.SEED_MARKUP_PATH || '';
|
||
const SEED_MARKUP_BLOCK = process.env.SEED_MARKUP_BLOCK || '';
|
||
// An allow entry the seed wrote a minute ago, with a one-minute TTL. The edge
|
||
// stopped honouring it; the row is still in the table.
|
||
const SEED_EXPIRED_CIDR = process.env.SEED_EXPIRED_CIDR || '';
|
||
|
||
let chromium;
|
||
try {
|
||
chromium = (process.env.PLAYWRIGHT_CORE
|
||
? require(process.env.PLAYWRIGHT_CORE)
|
||
: require('playwright-core')).chromium;
|
||
} catch (e) {
|
||
console.error('playwright-core is not resolvable. Set PLAYWRIGHT_CORE=/path/to/playwright-core,');
|
||
console.error('or install it. This gate does not skip quietly: a run that asserts nothing');
|
||
console.error('and reports success is worse than no gate at all.');
|
||
process.exit(2);
|
||
}
|
||
|
||
// A page that cannot be driven at all is the failure worth seeing, and a stack
|
||
// trace from a click timeout says nothing about what the page looked like. The
|
||
// first version of the country bars did exactly this: the class name collided
|
||
// with the toolbar's own .bar, the toolbar collapsed to 0.55em tall, and every
|
||
// assertion after the token click died. Best-effort picture on the way out — a
|
||
// screenshot failure must not mask the real error.
|
||
const failures = [];
|
||
const check = (name, ok, detail) => {
|
||
console.log(` ${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' — ' + detail : ''}`);
|
||
if (!ok) failures.push(name);
|
||
};
|
||
|
||
// WCAG relative luminance, so the assertion is a number and not an opinion.
|
||
const luminance = ([r, g, b]) => {
|
||
const f = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
|
||
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
|
||
};
|
||
const contrast = (a, b) => {
|
||
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p);
|
||
return (x + 0.05) / (y + 0.05);
|
||
};
|
||
const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||
|
||
(async () => {
|
||
const browser = await chromium.launch({ headless: true });
|
||
const page = await browser.newPage({ viewport: { width: 1280, height: 1100 } });
|
||
const jsProblems = [];
|
||
page.on('pageerror', (e) => jsProblems.push('pageerror: ' + e.message));
|
||
page.on('console', (m) => { if (m.type() === 'error') jsProblems.push('console.error: ' + m.text()); });
|
||
|
||
await page.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
|
||
await page.fill('#token', TOKEN);
|
||
await page.click('#save');
|
||
await page.waitForFunction(
|
||
() => /refreshed/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 });
|
||
|
||
const summary = (await page.textContent('#summary')).replace(/\s+/g, ' ').trim();
|
||
const cells = (sel) => page.$$eval(sel, (rows) => rows.map((tr) => [...tr.children].map((td) => td.textContent)));
|
||
// The allow table can hold several rows at once, so a delete has to be aimed at
|
||
// one of them: "click the first remove button" deletes whatever the server
|
||
// happened to sort first, which is not the row this assertion is about.
|
||
const removeRule = async (pattern) => {
|
||
await page.evaluate((pat) => {
|
||
const tr = [...document.querySelectorAll('#pathrules tbody tr')]
|
||
.find((r) => r.children[0].textContent === pat);
|
||
const b = tr && tr.querySelector('button[data-act="delrule"]');
|
||
if (b) b.click();
|
||
}, pattern);
|
||
await page.waitForFunction(
|
||
(pat) => ![...document.querySelectorAll('#pathrules tbody tr')].some((r) => r.children[0].textContent === pat),
|
||
pattern, { timeout: 15000 }).catch(() => {});
|
||
};
|
||
|
||
const removeAllow = async (match) => {
|
||
await page.evaluate((m) => {
|
||
const tr = [...document.querySelectorAll('#allow tbody tr')]
|
||
.find((r) => r.children[0].textContent === m);
|
||
const b = tr && tr.querySelector('button[data-act="delallow"]');
|
||
if (b) b.click();
|
||
}, match);
|
||
await page.waitForFunction(
|
||
(m) => ![...document.querySelectorAll('#allow tbody tr')].some((r) => r.children[0].textContent === m),
|
||
match, { timeout: 15000 }).catch(() => {});
|
||
};
|
||
const streakRows = await cells('#streaks tbody tr');
|
||
const blockRows = await cells('#blocks tbody tr');
|
||
const obsRows = await page.$$eval('#obs tbody tr', (r) => r.length);
|
||
const countryRows = await page.$$eval('#countries tbody tr', (r) => r.length);
|
||
const html = await page.content();
|
||
if (SCREENSHOT) await page.screenshot({ path: SCREENSHOT, fullPage: true });
|
||
|
||
check('the page authenticates and reads the state', /mode Enforce/.test(summary), summary);
|
||
// The age of the snapshot is meaningless without the TTL it is measured
|
||
// against, and on a single edge the TTL is otherwise invisible { yet it is the
|
||
// propagation delay for a ban behind a load balancer (OPEN-12/13).
|
||
check('the summary states the snapshot age against the configured TTL',
|
||
/snapshot [\d.]+s \/ ttl 30s/.test(summary), summary);
|
||
check('a standing streak is listed as current/threshold, not as a historical maximum',
|
||
streakRows.some((r) => r[0] === SEED_SOURCE && /2 \/ 3/.test(r[1] || '')),
|
||
JSON.stringify(streakRows.map((r) => [r[0], r[1]])));
|
||
check('the operator block is listed with its reason',
|
||
blockRows.some((r) => r[0] === SEED_BLOCK && /console gate/.test(r[2] || '')),
|
||
JSON.stringify(blockRows.map((r) => [r[0], r[2]])));
|
||
check('durable observations are listed', obsRows > 0, `${obsRows} rows`);
|
||
// The observation listing is capped server-side, and until the API said how
|
||
// many rows there are, a page of 25 and the whole window rendered the same
|
||
// sentence. Measured on the shipped image: 1103 recorded sources, limit=1000,
|
||
// 1000 rows back, no total and no flag.
|
||
const obsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim();
|
||
check('the observation table states how many sources were recorded, not only the rows it shows',
|
||
/^\d+ sources? the edge has recorded( \u00b7 rows are pruned after \d+d)?$/.test(obsNote) || /^newest \d+ of \d+ recorded sources/.test(obsNote),
|
||
obsNote);
|
||
const streakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim();
|
||
const standing = streakNote.match(/(\d+) of (\d+) standing streaks listed/);
|
||
check('the streak note counts standing streaks, and its listed count matches the table',
|
||
!!standing && Number(standing[1]) === streakRows.length && Number(standing[2]) >= Number(standing[1]),
|
||
streakNote);
|
||
check('the streak note keeps the map size separate, so tracked and standing are not confused',
|
||
/\d+ sources tracked, map capped at \d+/.test(streakNote), streakNote);
|
||
check('the per-country summary is listed', countryRows > 0, `${countryRows} rows`);
|
||
// The country table is the page's answer to "where is this coming from", and a
|
||
// column of numbers does not answer that. The bar has to be a real box with a
|
||
// real width — a span styled to nothing would still pass a text assertion.
|
||
const bars = await page.$$eval('#countries tbody tr .sharebar', (els) => els.map((e) => ({
|
||
w: e.clientWidth, cell: e.parentElement.clientWidth,
|
||
})));
|
||
const countrysum = (await page.textContent('#countrysum')).replace(/\s+/g, ' ').trim();
|
||
check('the country bars are boxes with real width',
|
||
bars.length > 0 && bars.every((b) => b.w >= 2), JSON.stringify(bars));
|
||
check('the busiest country fills its cell, so a bar is a share and not decoration',
|
||
bars.length > 0 && bars.some((b) => b.cell > 0 && b.w >= b.cell * 0.9), JSON.stringify(bars));
|
||
check('the country table states what it counted',
|
||
/^\d+ countr(y|ies), \d+ sources?, \d+ refusals? total$/.test(countrysum), countrysum);
|
||
// The alerting pillar's whole point is a human reading it, and until now no
|
||
// gate read /admin-api/alerts at all — the endpoint could have returned anything
|
||
// and every assertion would have stayed green. The seed hit /boom four times
|
||
// from an address chosen for this run, so a residue alert from an older run
|
||
// cannot satisfy this.
|
||
// Which geo database the edge is enforcing on is a question the operator can
|
||
// only answer from the running process { the pin ages with the image and a named
|
||
// volume is seeded once. /admin-api/geo had no gate at all before this.
|
||
check('the summary names the geo database, its build date and its age',
|
||
/geo DBIP-Country-Lite \u00b7 built \d{4}-\d{2}-\d{2} \u00b7 \d+(\.\d+)?d/.test(summary), summary);
|
||
const warnPills = await page.$$eval('#summary .pill.warn', (els) => els.map((e) => e.textContent.trim()));
|
||
check('a database inside the 90-day alarm is not marked stale',
|
||
!warnPills.some((x) => /geo/.test(x)), JSON.stringify(warnPills));
|
||
|
||
// 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),
|
||
JSON.stringify(errAlerts.map((r) => [r[2], r[3]])));
|
||
const alertnote = (await page.textContent('#alertnote')).replace(/\s+/g, ' ').trim();
|
||
check('the page says a server error is never a reason to ban',
|
||
/will not ban/.test(alertnote), alertnote);
|
||
// The window the rows age out at, printed on the tables it governs
|
||
// (OPEN-19). "3 sources recorded" reads the same whether this edge keeps them
|
||
// a week or a year, and the window is the answer to "how far back can this
|
||
// incident still be explained" — so it is asserted, not just printed.
|
||
check('both tables state the retention window they age out at',
|
||
/rows are pruned after \d+d/.test(obsNote) && /alerts are pruned after \d+d/.test(alertnote),
|
||
JSON.stringify([obsNote, alertnote]));
|
||
// Whether an alert goes anywhere on its own. This gate's edge runs with no
|
||
// webhook configured, and the page has to say that out loud: "the alert
|
||
// table is empty" and "the alert table is never pushed" are different facts
|
||
// an operator can only act on if the page distinguishes them.
|
||
check('the page says whether alerts are pushed anywhere at all',
|
||
/pushed to [\w.-]+/.test(alertnote) || /not pushed anywhere/.test(alertnote), alertnote);
|
||
const warnCells = await page.$$eval('#alerts tbody tr .warn', (els) => els.map((e) => e.textContent));
|
||
check('the kind an operator has to act on is marked, not only printed',
|
||
warnCells.includes('server_error_streak'), JSON.stringify(warnCells));
|
||
|
||
// The record of deliberate config changes (OPEN-64) on the page an operator
|
||
// actually reads (OPEN-65). The seed wrote a policy, an allow entry and two
|
||
// blocks before this page was driven, so an empty table here is a page that
|
||
// did not draw, not a log that is empty.
|
||
const changeRows = await cells('#changes tbody tr');
|
||
check('the change table lists the writes this run made',
|
||
changeRows.length > 0 && changeRows.some((r) =>
|
||
r[1] === 'block' && r[2] === 'added' && r[3] === SEED_BLOCK)
|
||
&& changeRows.some((r) => r[1] === 'allow' && r[2] === 'added'
|
||
&& r[3] === SEED_EXPIRED_CIDR),
|
||
JSON.stringify(changeRows.slice(0, 4).map((r) => [r[1], r[2], r[3], r[5]])));
|
||
// The edge has one admin token, so the honest column is the surface the
|
||
// change came through. A row naming anything else would be a record the edge
|
||
// cannot support.
|
||
check('the change table names the surface, never a person',
|
||
changeRows.every((r) => r[5] === 'operator' || r[5] === 'import'),
|
||
JSON.stringify([...new Set(changeRows.map((r) => r[5]))]));
|
||
const changeNote = (await page.textContent('#changenote')).replace(/\s+/g, ' ').trim();
|
||
check('the note under the table states both bounds of the log',
|
||
/pruned after \d+d or \d+ rows, whichever comes first/.test(changeNote), changeNote);
|
||
// An engine ban is not a decision somebody made, and a table that quietly
|
||
// mixed the two would read as "the operator chose to ban this address".
|
||
check('the note says engine bans are not in this table',
|
||
/engine bans are not here/.test(changeNote), changeNote);
|
||
// The seed's block reason carries markup, and that reason is the detail of a
|
||
// change row. Without this line the injection count below could be zero
|
||
// because the string never reached the table at all.
|
||
const markupChange = changeRows.find((r) => r[3] === SEED_MARKUP_BLOCK);
|
||
check('the markup the seed typed reached the change table as text',
|
||
!!markupChange && (markupChange[4] || '').includes("<svg onload=document.title='XSS2'>"),
|
||
JSON.stringify(markupChange));
|
||
check('no engine ban reached the change table',
|
||
!changeRows.some((r) => r[5] === 'engine'),
|
||
JSON.stringify(changeRows.map((r) => [r[1], r[2], r[5]])));
|
||
|
||
check('the token never appears in the markup', !html.includes(TOKEN));
|
||
|
||
// esc() is the only thing between an anonymous request and the one browser in
|
||
// this system that holds the admin token. The path in an observation row is
|
||
// whatever a visitor asked for and the reason on a block is a form field, so
|
||
// the assertion is not "the page looks fine" — it is "nothing from the API
|
||
// became an element, and the markup is still visible as text".
|
||
// A seed the driver was never given is not a pass — it is an assertion that did
|
||
// not run. Measured on this head: with SEED_MARKUP_PATH and SEED_MARKUP_BLOCK
|
||
// unset the driver prints 65 ok lines instead of 69, zero failures, and "all
|
||
// assertions passed". The escaping invariant this gate exists for is simply
|
||
// gone, and the summary line cannot tell that from a gate that ran. So the
|
||
// absence is named, and the count moves: 69 -> 70.
|
||
check('the markup seeds the escaping invariant needs were given to the driver',
|
||
SEED_MARKUP_PATH !== '' && SEED_MARKUP_BLOCK !== '',
|
||
`SEED_MARKUP_PATH=${JSON.stringify(SEED_MARKUP_PATH)} SEED_MARKUP_BLOCK=${JSON.stringify(SEED_MARKUP_BLOCK)}`);
|
||
if (SEED_MARKUP_PATH) {
|
||
const decoded = decodeURIComponent(SEED_MARKUP_PATH);
|
||
const title = await page.title();
|
||
check('a markup path from an anonymous visitor did not execute in the operator page',
|
||
!/XSS/.test(title), `title: ${JSON.stringify(title)}`);
|
||
const injected = await page.$$eval('#obs tbody, #blocks tbody, #streaks tbody',
|
||
(bodies) => bodies.reduce((n, b) => n + b.querySelectorAll('img,svg,script,iframe,object,embed').length, 0));
|
||
check('no element was created out of a value that came from the API',
|
||
injected === 0, `${injected} injected elements`);
|
||
const obsCells = await page.$$eval('#obs tbody tr', (rows) =>
|
||
rows.map((tr) => [...tr.children].map((td) => td.textContent)));
|
||
check('the markup path is printed as the text it is',
|
||
obsCells.some((r) => (r[4] || '').includes(decoded)),
|
||
JSON.stringify(obsCells.filter((r) => (r[4] || '').includes('xss-probe')).map((r) => r[4])));
|
||
}
|
||
if (SEED_MARKUP_BLOCK) {
|
||
check('a markup block reason is printed as text too',
|
||
blockRows.some((r) => r[0] === SEED_MARKUP_BLOCK && /<svg onload=/.test(r[2] || '')),
|
||
JSON.stringify(blockRows.map((r) => [r[0], r[2]])));
|
||
}
|
||
check('the page threw no javascript', jsProblems.length === 0, jsProblems.join(' | '));
|
||
|
||
// The read side of the page is one thing; the write side is the part that can
|
||
// lock a real customer out. These drive the two forms an incident actually
|
||
// uses and then check the consequence on the wire, not just in the table: a
|
||
// ban drawn on the page has to make the edge answer 403 for that address, and
|
||
// the delete beside it has to stop it. The stack runs with trusted proxy
|
||
// headers, so X-Forwarded-For is how the gate becomes a different client.
|
||
const WRITE_IP = process.env.WRITE_IP || '203.0.113.99';
|
||
const WRITE_CIDR = process.env.WRITE_CIDR || '198.51.100.0/24';
|
||
// redirect:'manual' is not a detail. An operator block answers 301 to the
|
||
// policy's default redirect target (OperatorBlockStatus=301,
|
||
// DefaultRedirectTargets=[iana example]), and a fetch that follows redirects
|
||
// walks out to the public internet and comes back 200 — which is exactly how
|
||
// this check first read "the ban is not enforced" while the edge was refusing
|
||
// the client with a 301 the whole time.
|
||
const probe = async (ip) => {
|
||
const r = await fetch(`${EDGE}/probe`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' });
|
||
await r.body.cancel();
|
||
return { status: r.status, location: r.headers.get('location') };
|
||
};
|
||
|
||
const open = await probe(WRITE_IP);
|
||
check('before the block, that address reaches the upstream',
|
||
open.status === 404, `probe from ${WRITE_IP} answered ${open.status}`);
|
||
|
||
await page.fill('#blockIp', WRITE_IP);
|
||
await page.fill('#blockReason', 'console gate: written from the page');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction(
|
||
(ip) => [...document.querySelectorAll('#blocks tbody tr')].some((tr) =>
|
||
tr.children[0].textContent === ip && /written from the page/.test(tr.children[2].textContent)),
|
||
WRITE_IP, { timeout: 15000 }).catch(() => {});
|
||
const afterBlock = await cells('#blocks tbody tr');
|
||
check('the page can write a ban, and lists it with its reason',
|
||
afterBlock.some((r) => r[0] === WRITE_IP && /written from the page/.test(r[2] || '')),
|
||
JSON.stringify(afterBlock.map((r) => [r[0], r[2]])));
|
||
|
||
let wire = await probe(WRITE_IP);
|
||
for (let i = 0; i < 10 && wire.status === 404; i++) { await new Promise((r) => setTimeout(r, 1000)); wire = await probe(WRITE_IP); }
|
||
check('the ban drawn on the page is enforced on the wire, not just in the table',
|
||
wire.status === 301 || wire.status === 403,
|
||
`probe from ${WRITE_IP} answered ${wire.status}${wire.location ? ' → ' + wire.location : ''}`);
|
||
|
||
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${WRITE_IP}"]`);
|
||
await page.waitForFunction(
|
||
(ip) => ![...document.querySelectorAll('#blocks tbody tr')].some((tr) => tr.children[0].textContent === ip),
|
||
WRITE_IP, { timeout: 15000 }).catch(() => {});
|
||
const afterDelete = await cells('#blocks tbody tr');
|
||
let wire2 = await probe(WRITE_IP);
|
||
for (let i = 0; i < 10 && wire2.status !== 404; i++) { await new Promise((r) => setTimeout(r, 1000)); wire2 = await probe(WRITE_IP); }
|
||
check('the per-row delete removes that one ban from the table',
|
||
!afterDelete.some((r) => r[0] === WRITE_IP), JSON.stringify(afterDelete.map((r) => r[0])));
|
||
check('and the address reaches the upstream again once that row is gone',
|
||
wire2.status === 404, `probe from ${WRITE_IP} answered ${wire2.status}`);
|
||
|
||
// A block can be time-boxed now: the same minutes field the exemption form
|
||
// already had. The permanent write above prints an empty expiry cell, so the
|
||
// date in this row is the difference the field makes.
|
||
await page.fill('#blockIp', WRITE_IP);
|
||
await page.fill('#blockReason', 'console gate: time-boxed');
|
||
await page.fill('#blockTtl', '60');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction(
|
||
(ip) => [...document.querySelectorAll('#blocks tbody tr')].some((tr) =>
|
||
tr.children[0].textContent === ip && /\d{4}-\d{2}-\d{2}/.test(tr.children[3].textContent)),
|
||
WRITE_IP, { timeout: 15000 }).catch(() => {});
|
||
const timeBoxed = await cells('#blocks tbody tr');
|
||
const boxStatus = (await page.textContent('#status')).trim();
|
||
check('a block typed with a duration is listed with the expiry it stops being enforced at',
|
||
timeBoxed.some((r) => r[0] === WRITE_IP && /\d{4}-\d{2}-\d{2}/.test(r[3] || '')) && /for 60 min/.test(boxStatus),
|
||
`${JSON.stringify(boxStatus)} ${JSON.stringify(timeBoxed.find((r) => r[0] === WRITE_IP))}`);
|
||
|
||
// And the same trap the exemption field fell into once: a zero in a minutes
|
||
// box is not a duration, and here it would have meant "block forever".
|
||
await page.fill('#blockIp', WRITE_IP);
|
||
await page.fill('#blockTtl', '0');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction(() => /duration in minutes/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 5000 }).catch(() => {});
|
||
const zeroBox = (await page.textContent('#status')).trim();
|
||
check('a block duration of 0 is refused by the page instead of becoming a permanent block',
|
||
/duration in minutes/.test(zeroBox), JSON.stringify(zeroBox));
|
||
|
||
await page.fill('#blockTtl', '');
|
||
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${WRITE_IP}"]`);
|
||
await page.waitForFunction(
|
||
(ip) => ![...document.querySelectorAll('#blocks tbody tr')].some((tr) => tr.children[0].textContent === ip),
|
||
WRITE_IP, { timeout: 15000 }).catch(() => {});
|
||
|
||
// A range, written from the same field (OPEN-66). Two things are asserted here
|
||
// that an API test cannot see: the page says which shape a row is — a /29 that
|
||
// refuses eight addresses is not a row of the same size as any other — and the
|
||
// per-row delete removes it under the name the edge stored, not the spelling
|
||
// somebody typed into the box.
|
||
const RANGE_BASE = 96 + Math.floor(Math.random() * 4) * 8;
|
||
const RANGE_NET = `203.0.113.${RANGE_BASE}/29`;
|
||
const RANGE_SLOPPY = `203.0.113.${RANGE_BASE + 5}/29`;
|
||
const RANGE_INSIDE = `203.0.113.${RANGE_BASE + 3}`;
|
||
const RANGE_OUTSIDE = `203.0.113.${RANGE_BASE + 8}`;
|
||
|
||
const beforeRange = await probe(RANGE_INSIDE);
|
||
check('before the range, an address inside it reaches the upstream',
|
||
beforeRange.status === 404, `probe from ${RANGE_INSIDE} answered ${beforeRange.status}`);
|
||
|
||
await page.fill('#blockIp', RANGE_SLOPPY);
|
||
await page.fill('#blockReason', 'console gate: a netblock');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody tr')]
|
||
.some((tr) => tr.children[0].textContent.startsWith(net) && /range/.test(tr.children[0].textContent)),
|
||
RANGE_NET, { timeout: 15000 }).catch(() => {});
|
||
const rangeRows = await cells('#blocks tbody tr');
|
||
check('the page writes a CIDR as one ban and marks the row as a range',
|
||
rangeRows.some((r) => r[0].startsWith(RANGE_NET) && /range/.test(r[0])
|
||
&& /netblock/.test(r[2] || '')),
|
||
JSON.stringify(rangeRows.map((r) => [r[0], r[2]])));
|
||
check('and one range is one row however it is spelled',
|
||
rangeRows.filter((r) => r[0].startsWith(RANGE_NET)).length === 1,
|
||
JSON.stringify(rangeRows.filter((r) => r[0].startsWith(RANGE_NET)).map((r) => r[0])));
|
||
|
||
let rangeWire = await probe(RANGE_INSIDE);
|
||
for (let i = 0; i < 10 && rangeWire.status === 404; i++) {
|
||
await new Promise((r) => setTimeout(r, 1000)); rangeWire = await probe(RANGE_INSIDE);
|
||
}
|
||
check('the range drawn on the page is enforced on the wire for an address inside it',
|
||
rangeWire.status === 301 || rangeWire.status === 403,
|
||
`probe from ${RANGE_INSIDE} answered ${rangeWire.status}`);
|
||
const outsideRange = await probe(RANGE_OUTSIDE);
|
||
check('and the address one past its end is served',
|
||
outsideRange.status === 404, `probe from ${RANGE_OUTSIDE} answered ${outsideRange.status}`);
|
||
|
||
const summaryPills = await page.$$eval('#summary .pill', (els) => els.map((e) => e.textContent.trim()));
|
||
check('the summary counts ranges apart from address blocks',
|
||
summaryPills.some((p) => /^ranges 1$/.test(p)), JSON.stringify(summaryPills));
|
||
|
||
// The gate's own probes are refusals — the upstream has no /probe — so by now
|
||
// the streak pillar has banned the probe address on its own, and an engine ban
|
||
// outlives the retry loop below by the whole ban duration. This assertion is
|
||
// about the range row, so that one ban is cleared by name first: clearing every
|
||
// engine ban would take the netblock offers down with it, and the next scene
|
||
// reads those.
|
||
const adminDelete = async (path) => {
|
||
const r = await fetch(`${EDGE}${path}`, { method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } });
|
||
await r.body.cancel();
|
||
};
|
||
await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(RANGE_INSIDE)}`);
|
||
|
||
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${RANGE_NET}"]`);
|
||
await page.waitForFunction((net) => ![...document.querySelectorAll('#blocks tbody tr')]
|
||
.some((tr) => tr.children[0].textContent.startsWith(net)),
|
||
RANGE_NET, { timeout: 15000 }).catch(() => {});
|
||
let rangeWire2 = await probe(RANGE_INSIDE);
|
||
for (let i = 0; i < 10 && rangeWire2.status !== 404; i++) {
|
||
await new Promise((r) => setTimeout(r, 1000)); rangeWire2 = await probe(RANGE_INSIDE);
|
||
}
|
||
check('the per-row delete removes the range by the name the edge stored',
|
||
!(await cells('#blocks tbody tr')).some((r) => r[0].startsWith(RANGE_NET))
|
||
&& rangeWire2.status === 404,
|
||
`probe from ${RANGE_INSIDE} answered ${rangeWire2.status}`);
|
||
|
||
// --- the netblock watch (OPEN-67) -----------------------------------------
|
||
// The seed wrote two engine bans inside one /24 and set the watch threshold to
|
||
// two, so the offer asserted here is this run's and not a residue of the named
|
||
// volume. The point of the scene is the difference between an offer and a ban:
|
||
// the block is on the page, nothing is enforced, one button changes that, and
|
||
// the change is the same call the block form makes.
|
||
const NETBLOCK = process.env.SEED_NETBLOCK || '192.0.2.0/24';
|
||
const NET_FRESH = process.env.SEED_NETBLOCK_FRESH || '192.0.2.203';
|
||
|
||
const netRows = await cells('#netblocks tbody tr');
|
||
const offered = netRows.find((r) => (r[0] || '').startsWith(NETBLOCK));
|
||
check('the page offers the block the edge points at by its own bans',
|
||
!!offered, JSON.stringify(netRows.map((r) => r[0])));
|
||
check('the offer says how many bans sit inside that block',
|
||
!!offered && Number(offered[1]) >= 2, offered ? offered[1] : 'no row');
|
||
const netNote = (await page.textContent('#netblocknote')).replace(/\s+/g, ' ').trim();
|
||
check('the page says an offer is not a ban',
|
||
/nothing here is in force|a candidate is an offer, not a ban/.test(netNote), netNote);
|
||
const beforeTaken = await probe(NET_FRESH);
|
||
check('an address inside the offered block is still served',
|
||
beforeTaken.status === 404, `probe from ${NET_FRESH} answered ${beforeTaken.status}`);
|
||
|
||
await page.click(`#netblocks tbody button[data-act="banrange"][data-k="${NETBLOCK}"]`);
|
||
await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody tr')]
|
||
.some((tr) => tr.children[0].textContent.startsWith(net) && /range/.test(tr.children[0].textContent)),
|
||
NETBLOCK, { timeout: 15000 }).catch(() => {});
|
||
const blocksAfterOffer = await cells('#blocks tbody tr');
|
||
check('one button writes the offered range through the same block form',
|
||
blocksAfterOffer.some((r) => r[0].startsWith(NETBLOCK) && /range/.test(r[0])
|
||
&& /netblock the edge noticed/.test(r[2] || '')),
|
||
JSON.stringify(blocksAfterOffer.filter((r) => r[0].startsWith(NETBLOCK)).map((r) => [r[0], r[2]])));
|
||
|
||
const netRowsAfter = await cells('#netblocks tbody tr');
|
||
const offeredAfter = netRowsAfter.find((r) => (r[0] || '').startsWith(NETBLOCK));
|
||
check('the offer is then marked taken rather than repeated',
|
||
!!offeredAfter && /already banned/.test(offeredAfter.join(' ')), JSON.stringify(offeredAfter));
|
||
|
||
let takenWire = await probe(NET_FRESH);
|
||
for (let i = 0; i < 10 && takenWire.status === 404; i++) {
|
||
await new Promise((r) => setTimeout(r, 1000)); takenWire = await probe(NET_FRESH);
|
||
}
|
||
check('the range the page took is enforced on the wire for a source inside it',
|
||
takenWire.status === 301 || takenWire.status === 403,
|
||
`probe from ${NET_FRESH} answered ${takenWire.status}`);
|
||
const pillsAfterOffer = await page.$$eval('#summary .pill', (els) => els.map((e) => e.textContent.trim()));
|
||
check('the summary counts the offers apart from what is in force',
|
||
pillsAfterOffer.some((p) => /^netblock offers \d+$/.test(p)), JSON.stringify(pillsAfterOffer));
|
||
|
||
// Clean up: the range, and the engine bans that produced it, so the scenes
|
||
// after this one run on the stack they expect.
|
||
await adminDelete(`/admin-api/blocks?source=operator&key=${encodeURIComponent(NETBLOCK)}`);
|
||
await adminDelete('/admin-api/blocks?source=engine');
|
||
let cleanedWire = await probe(NET_FRESH);
|
||
for (let i = 0; i < 10 && cleanedWire.status !== 404; i++) {
|
||
await new Promise((r) => setTimeout(r, 1000)); cleanedWire = await probe(NET_FRESH);
|
||
}
|
||
check('the range and the bans that produced it are cleaned, so the stack stays clean',
|
||
cleanedWire.status === 404, `probe from ${NET_FRESH} answered ${cleanedWire.status}`);
|
||
|
||
// A request budget for one path (OPEN-68). The edge-wide budget above is one
|
||
// number for the whole site; this is the same switch with a path on it. What
|
||
// the page has to get right is the pair of counters next to the row: they are
|
||
// the only answer to "is this budget a defence or my own traffic", and in
|
||
// observe mode they are the only answer to that question at all.
|
||
const PATH_BUDGET_PATH = process.env.SEED_PATH_BUDGET_PATH || '/budget-probe';
|
||
const PATH_BUDGET_IP = process.env.SEED_PATH_BUDGET_IP || '192.0.2.210';
|
||
// (the file already has a probePath further down; this one is aimed at a path
|
||
// of this scene's own and returns only the status)
|
||
const askPath = async (ip, path) => {
|
||
const r = await fetch(`${EDGE}${path}`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' });
|
||
await r.body.cancel();
|
||
return r.status;
|
||
};
|
||
|
||
await page.selectOption('#rateMode', 'enforce');
|
||
await page.fill('#rateLimit', '1000');
|
||
await page.fill('#rateWindow', '120');
|
||
await page.click('#setRate');
|
||
await page.waitForFunction(() => /budget/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
|
||
await page.fill('#rateRulePattern', `${PATH_BUDGET_PATH}*`);
|
||
await page.fill('#rateRuleLimit', '2');
|
||
await page.fill('#rateRuleWindow', '120');
|
||
await page.fill('#rateRuleNote', 'console gate: path budget');
|
||
await page.click('#addRateRule');
|
||
await page.waitForFunction((pat) => [...document.querySelectorAll('#raterules tbody tr')]
|
||
.some((tr) => tr.children[0].textContent === pat), `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {});
|
||
const budgetRows = await cells('#raterules tbody tr');
|
||
const budgetRow = budgetRows.find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||
check('the page writes a budget for one path and lists its own numbers',
|
||
!!budgetRow && budgetRow[1] === '2' && budgetRow[2] === '120' && /console gate/.test(budgetRow[6] || ''),
|
||
JSON.stringify(budgetRow || budgetRows.map((r) => r[0])));
|
||
|
||
const firstAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH);
|
||
const secondAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH);
|
||
const thirdAsked = await askPath(PATH_BUDGET_IP, PATH_BUDGET_PATH);
|
||
check('the third request on that path is answered by the edge, not the upstream',
|
||
firstAsked === 404 && secondAsked === 404 && thirdAsked === 429,
|
||
`${firstAsked} ${secondAsked} ${thirdAsked}`);
|
||
check('the same source is still served on a path the budget does not name',
|
||
(await askPath(PATH_BUDGET_IP, '/probe')) === 404, `probe from ${PATH_BUDGET_IP} answered the other path`);
|
||
|
||
await page.click('#refresh');
|
||
await page.waitForFunction((pat) => {
|
||
const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat);
|
||
return !!tr && Number(tr.children[5].textContent) >= 1;
|
||
}, `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {});
|
||
// The probes this scene drew were refusals (the upstream has no such path), so
|
||
// the streak pillar has by now banned this address on its own — three
|
||
// consecutive 404s is its rule, and it is nothing to do with the budget. The
|
||
// reopen assertion below is about the budget, so the engine's list is cleared
|
||
// first: otherwise the answer is the streak's 403 and the scene proves
|
||
// nothing about the row it removed.
|
||
await adminDelete('/admin-api/blocks?source=engine');
|
||
|
||
// The same question asked from the page (OPEN-69). The dry run answers the
|
||
// volume pillar from the counters the checks above have already shown to be one
|
||
// over budget — and asking it here is a read, so the counters still say the same
|
||
// afterwards.
|
||
await page.fill('#askIp', PATH_BUDGET_IP);
|
||
await page.fill('#askPath', PATH_BUDGET_PATH);
|
||
await page.click('#askDecide');
|
||
await page.waitForFunction(() => /volume:/.test(document.getElementById('askanswer').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const asked = (await page.textContent('#askanswer')).replace(/\s+/g, ' ');
|
||
check('the page can ask what the edge would answer, and the volume pillar answers it',
|
||
/volume: Enforce . refused_now/.test(asked) && /OVER/.test(asked), asked.slice(0, 240));
|
||
const beforeRerender = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||
await page.click('#refresh');
|
||
await page.waitForFunction((pat) => {
|
||
const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat);
|
||
return !!tr && Number(tr.children[5].textContent) >= 1;
|
||
}, `${PATH_BUDGET_PATH}*`, { timeout: 15000 }).catch(() => {});
|
||
const afterRerender = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||
check('asking the dry run from the page did not move the counters',
|
||
!!beforeRerender && !!afterRerender && beforeRerender.join('|') === afterRerender.join('|'),
|
||
`${JSON.stringify(beforeRerender)} then ${JSON.stringify(afterRerender)}`);
|
||
const countedRow = (await cells('#raterules tbody tr')).find((r) => (r[0] || '') === `${PATH_BUDGET_PATH}*`);
|
||
check('the page says who the budget counted and who is over it now',
|
||
!!countedRow && Number(countedRow[3]) >= 1 && Number(countedRow[4]) >= 1 && Number(countedRow[5]) >= 1,
|
||
JSON.stringify(countedRow || 'no row'));
|
||
|
||
// Who the budget is pausing, and letting one source out of it (OPEN-71). The
|
||
// table has always said "1 over budget"; the operator reading it had one lever
|
||
// — remove the budget for every source on the site.
|
||
await page.evaluate((pat) => {
|
||
const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat);
|
||
const b = tr && tr.querySelector('button[data-act="whobudget"]');
|
||
if (b) b.click();
|
||
}, `${PATH_BUDGET_PATH}*`);
|
||
await page.waitForFunction(() => /budget \d+ /.test(document.getElementById('budgetsources').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const who = (await page.textContent('#budgetsources')).replace(/\s+/g, ' ');
|
||
check('the page names the source a path budget is pausing, with its count against the limit',
|
||
/3 of 2 OVER: answered 429 on this path/.test(who) && /this-process/.test(who), who.slice(0, 300));
|
||
|
||
await page.evaluate(() => {
|
||
const b = document.querySelector('#budgetsources button[data-act="letout"]');
|
||
if (b) b.click();
|
||
});
|
||
await page.waitForFunction(() => /window dropped for/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
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`);
|
||
await adminDelete(`/admin-api/blocks?source=engine&key=${encodeURIComponent(PATH_BUDGET_IP)}`);
|
||
|
||
await page.evaluate((pat) => {
|
||
const tr = [...document.querySelectorAll('#raterules tbody tr')].find((r) => r.children[0].textContent === pat);
|
||
const b = tr && tr.querySelector('button[data-act="delraterule"]');
|
||
if (b) b.click();
|
||
}, `${PATH_BUDGET_PATH}*`);
|
||
await page.waitForFunction((pat) => ![...document.querySelectorAll('#raterules tbody tr')]
|
||
.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));
|
||
// 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}`);
|
||
|
||
await page.selectOption('#rateMode', 'off');
|
||
await page.click('#setRate');
|
||
await page.waitForFunction(() => /budget/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
check('the volume switch is left off, as the stack was seeded',
|
||
(await page.$$eval('#rateMode', (s) => s[0].value)) === 'off', await page.$$eval('#rateMode', (s) => s[0].value));
|
||
|
||
// One address, one answer (OPEN-70), asked from the page. Two shapes are worth
|
||
// asserting because they are the two the six separate listings got wrong: a
|
||
// block written on the address itself, and a block written on a network that
|
||
// contains the address - the second is invisible to anything that compares keys.
|
||
const DOSSIER_IP = '192.0.2.211';
|
||
const DOSSIER_NET = '192.0.2.216/29'; // .216 - .223
|
||
const DOSSIER_INSIDE = '192.0.2.219';
|
||
const DOSSIER_OUTSIDE = '192.0.2.224';
|
||
|
||
await page.fill('#blockIp', DOSSIER_IP);
|
||
await page.fill('#blockReason', 'console gate: dossier address');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction((ip) => [...document.querySelectorAll('#blocks tbody tr')]
|
||
.some((tr) => tr.children[0].textContent === ip), DOSSIER_IP, { timeout: 15000 }).catch(() => {});
|
||
await page.fill('#blockIp', DOSSIER_NET);
|
||
await page.fill('#blockReason', 'console gate: dossier range');
|
||
await page.click('#addBlock');
|
||
// The row's first cell carries the `range` badge, so the row is matched by the
|
||
// key its delete button holds - the same name the delete is keyed by.
|
||
const blockKeys = () => page.$$eval('#blocks tbody button[data-act="delblock"]',
|
||
(bs) => bs.map((b) => b.dataset.k));
|
||
await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
|
||
.some((b) => b.dataset.k === net), DOSSIER_NET, { timeout: 15000 }).catch(() => {});
|
||
|
||
const askDossier = async (ip) => {
|
||
// The box is emptied first and then waited on for this address by name. The
|
||
// console gate caught why: waiting only for "an answer is there" is satisfied
|
||
// by the previous answer still sitting in the box, so every assertion after
|
||
// the first reads the address asked one click earlier.
|
||
await page.evaluate(() => { document.getElementById('dossieranswer').textContent = ''; });
|
||
await page.fill('#dossierIp', ip);
|
||
await page.click('#askSource');
|
||
await page.waitForFunction((asked) => (document.getElementById('dossieranswer').textContent || '')
|
||
.indexOf('key: ' + asked) === 0, ip, { timeout: 15000 }).catch(() => {});
|
||
return (await page.textContent('#dossieranswer')).replace(/\s+/g, ' ');
|
||
};
|
||
|
||
const onKey = await askDossier(DOSSIER_IP);
|
||
check('the page answers for an address the operator blocked on its own key',
|
||
/block_operator/.test(onKey) && /written on this key/.test(onKey) && /dossier address/.test(onKey),
|
||
onKey.slice(0, 300));
|
||
|
||
const fromRange = await askDossier(DOSSIER_INSIDE);
|
||
check('an address inside a banned range is answered by that range, not by a row that does not exist',
|
||
/block_operator/.test(fromRange) && /from the range 192\.0\.2\.216\/29/.test(fromRange),
|
||
fromRange.slice(0, 300));
|
||
|
||
const outside = await askDossier(DOSSIER_OUTSIDE);
|
||
check('an address on no list is answered as none rather than as a verdict',
|
||
/- none -/.test(outside) && /operator block: none/.test(outside),
|
||
outside.slice(0, 300));
|
||
|
||
// A read, like the dry run: the dossier wrote nothing, so the operator's table
|
||
// still holds exactly the two rows the page wrote and no third one.
|
||
const dossierRows = await blockKeys();
|
||
check('asking the dossier wrote nothing to the operator list',
|
||
dossierRows.filter((k) => k === DOSSIER_IP || k === DOSSIER_NET).length === 2,
|
||
JSON.stringify(dossierRows));
|
||
|
||
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${DOSSIER_IP}"]`);
|
||
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${DOSSIER_NET}"]`);
|
||
await page.waitForFunction((pair) => ![...document.querySelectorAll('#blocks tbody tr')]
|
||
.some((tr) => pair.indexOf(tr.children[0].textContent) !== -1),
|
||
[DOSSIER_IP, DOSSIER_NET], { timeout: 15000 }).catch(() => {});
|
||
|
||
|
||
|
||
await page.fill('#allowMatch', WRITE_CIDR);
|
||
await page.fill('#allowNote', 'console gate: allow entry');
|
||
await page.fill('#allowTtl', '60');
|
||
await page.click('#addAllow');
|
||
await page.waitForFunction(
|
||
(cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
|
||
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
|
||
const allowRows = await cells('#allow tbody tr');
|
||
check('the page can write an allow entry and lists it with an expiry',
|
||
allowRows.some((r) => r[0] === WRITE_CIDR && /console gate/.test(r[1] || '') && /\d{4}-\d{2}-\d{2}/.test(r[2] || '')),
|
||
JSON.stringify(allowRows.map((r) => [r[0], r[2]])));
|
||
|
||
await removeAllow(WRITE_CIDR);
|
||
check('the allow entry can be removed from the page too',
|
||
(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))).indexOf(WRITE_CIDR) === -1,
|
||
JSON.stringify(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))));
|
||
|
||
// The other quiet failure on this form: a TTL of 0. It used to fall through to
|
||
// null, and null is how the API says "never expires" — so a field left at zero
|
||
// bought the one exemption that outranks every ban. The API refuses it now, and
|
||
// the page refuses it before the round trip; empty is still "never", on purpose.
|
||
await page.fill('#allowMatch', WRITE_CIDR);
|
||
await page.fill('#allowNote', 'console gate: zero ttl');
|
||
await page.fill('#allowTtl', '0');
|
||
await page.click('#addAllow');
|
||
await page.waitForFunction(
|
||
() => /TTL in minutes/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 5000 }).catch(() => {});
|
||
const ttlStatus = (await page.textContent('#status')).trim();
|
||
const rowsAfterZero = await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent));
|
||
check('a TTL of 0 is refused by the page instead of becoming a permanent exemption',
|
||
/TTL in minutes/.test(ttlStatus) && !rowsAfterZero.includes(WRITE_CIDR),
|
||
`${JSON.stringify(ttlStatus)} rows=${JSON.stringify(rowsAfterZero)}`);
|
||
|
||
await page.fill('#allowTtl', '');
|
||
await page.click('#addAllow');
|
||
await page.waitForFunction(
|
||
(cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
|
||
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
|
||
const neverRows = await cells('#allow tbody tr');
|
||
check('leaving the TTL empty is still the way to ask for never',
|
||
neverRows.some((r) => r[0] === WRITE_CIDR && /never/.test(r[2] || '')),
|
||
JSON.stringify(neverRows.map((r) => [r[0], r[2]])));
|
||
await removeAllow(WRITE_CIDR);
|
||
|
||
// The state the page used to get wrong: an allow entry with an expiry stops
|
||
// being obeyed the moment it ages, and the row outlives it — nothing prunes an
|
||
// operator's own rows, and the API cannot be asked for an expiry in the past.
|
||
// Measured on the shipped image: the exempted address answered 502 (through)
|
||
// at 03:58:20 and 301 (blocked again) at 03:59:38, while GET /admin-api/allow
|
||
// at 03:59:39 still printed the row with no liveness field and /admin-api/state
|
||
// still counted it. So the table said "exempted" a minute after the edge
|
||
// stopped honouring it. The seed wrote SEED_EXPIRED_CIDR a minute ago.
|
||
await page.fill('#allowMatch', WRITE_CIDR);
|
||
await page.fill('#allowNote', 'console gate: still live');
|
||
await page.fill('#allowTtl', '60');
|
||
await page.click('#addAllow');
|
||
await page.waitForFunction(
|
||
(cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
|
||
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
|
||
const liveAndDead = await cells('#allow tbody tr');
|
||
check('a live allow entry is listed with no expired marker',
|
||
liveAndDead.some((r) => r[0] === WRITE_CIDR && !/EXPIRED/i.test(r[2] || '')),
|
||
JSON.stringify(liveAndDead.map((r) => [r[0], r[2]])));
|
||
check('an expired allow entry is still listed, and says the edge no longer honours it',
|
||
liveAndDead.some((r) => r[0] === SEED_EXPIRED_CIDR && /EXPIRED/.test(r[2] || '')),
|
||
JSON.stringify(liveAndDead.map((r) => [r[0], r[2]])));
|
||
const allowNote = (await page.textContent('#allownote')).replace(/\s+/g, ' ').trim();
|
||
check('and the line under the table counts the dead rows rather than hiding them',
|
||
/EXPIRED/.test(allowNote), JSON.stringify(allowNote));
|
||
await removeAllow(SEED_EXPIRED_CIDR);
|
||
await removeAllow(WRITE_CIDR);
|
||
|
||
// A path rule is the one control that judges the request rather than the
|
||
// response the upstream gave, and it has two actions that mean opposite
|
||
// things. The gate writes one from the page, asks the edge for that path, and
|
||
// reads the answer back in both the table and the status code.
|
||
const RULE_PATH = '/gate-rule-probe';
|
||
// Its own address, and the engine ban is cleared before the last probe. Every
|
||
// probe here is a 404 refusal, and the seed set the streak threshold to 3 —
|
||
// so the gate itself would otherwise ban its own probe address and the last
|
||
// assertion would read a `blocked_by_policy` as "the rule is still in force".
|
||
const RULE_IP = '203.0.113.188';
|
||
const probePath = async (path, ip) => {
|
||
const r = await fetch(`${EDGE}${path}`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' });
|
||
const text = await r.text();
|
||
return { status: r.status, text };
|
||
};
|
||
const clearEngineBan = async (ip) => {
|
||
const r = await fetch(`${EDGE}/admin-api/blocks?source=engine&key=${encodeURIComponent(ip)}`,
|
||
{ method: 'DELETE', headers: { 'X-Admin-Token': TOKEN } });
|
||
await r.body.cancel();
|
||
};
|
||
|
||
await page.fill('#rulePattern', RULE_PATH + '*');
|
||
// A <select> is not an <input>: fill() waits for something that can be typed
|
||
// into and times out. selectOption is the selector's own verb.
|
||
await page.selectOption('#ruleAction', 'observe');
|
||
await page.fill('#ruleNote', 'console gate: path rule');
|
||
await page.fill('#ruleTtl', '60');
|
||
await page.click('#addRule');
|
||
await page.waitForFunction(
|
||
(pat) => [...document.querySelectorAll('#pathrules tbody tr')]
|
||
.some((r) => r.children[0].textContent === pat),
|
||
RULE_PATH + '*', { timeout: 15000 }).catch(() => {});
|
||
const ruleRows = await cells('#pathrules tbody tr');
|
||
check('the page can write a path rule and lists it with its action and expiry',
|
||
ruleRows.some((r) => r[0] === RULE_PATH + '*' && r[1] === 'observe'
|
||
&& /console gate/.test(r[2] || '') && /\d{4}-\d{2}-\d{2}/.test(r[4] || '')),
|
||
JSON.stringify(ruleRows.map((r) => [r[0], r[1], r[4]])));
|
||
|
||
const observed = await probePath(RULE_PATH, RULE_IP);
|
||
await page.click('#refresh');
|
||
await page.waitForFunction(
|
||
(pat) => {
|
||
const tr = [...document.querySelectorAll('#pathrules tbody tr')]
|
||
.find((r) => r.children[0].textContent === pat);
|
||
return !!tr && Number(tr.children[3].textContent) >= 1;
|
||
},
|
||
RULE_PATH + '*', { timeout: 15000 }).catch(() => {});
|
||
const countedRows = await cells('#pathrules tbody tr');
|
||
check('an observe rule lets the request through and counts the match on the row',
|
||
observed.status === 404
|
||
&& countedRows.some((r) => r[0] === RULE_PATH + '*' && Number(r[3]) >= 1),
|
||
`${observed.status} ${JSON.stringify(countedRows.map((r) => [r[0], r[1], r[3]]))}`);
|
||
|
||
const ruleNote = (await page.textContent('#rulenote')).replace(/\s+/g, ' ').trim();
|
||
check('the line under the rules table says the order is the answer and what each action does',
|
||
/first rule that matches/.test(ruleNote) && /observe counts/.test(ruleNote),
|
||
JSON.stringify(ruleNote));
|
||
|
||
await removeRule(RULE_PATH + '*');
|
||
await page.fill('#rulePattern', RULE_PATH + '*');
|
||
await page.selectOption('#ruleAction', 'block');
|
||
await page.fill('#ruleNote', 'console gate: blocking rule');
|
||
await page.click('#addRule');
|
||
await page.waitForFunction(
|
||
(pat) => [...document.querySelectorAll('#pathrules tbody tr')]
|
||
.some((r) => r.children[0].textContent === pat),
|
||
RULE_PATH + '*', { timeout: 15000 }).catch(() => {});
|
||
const blocked = await probePath(RULE_PATH, RULE_IP);
|
||
check('a block rule refuses the path, and the answer names the rule not the pattern',
|
||
blocked.status === 403 && /blocked_by_rule/.test(blocked.text) && !blocked.text.includes(RULE_PATH),
|
||
`${blocked.status} ${JSON.stringify(blocked.text.slice(0, 160))}`);
|
||
const ruleActionRows = await cells('#pathrules tbody tr');
|
||
check('a blocking rule is marked, not only printed',
|
||
ruleActionRows.some((r) => r[0] === RULE_PATH + '*' && r[1] === 'block'),
|
||
JSON.stringify(ruleActionRows.map((r) => [r[0], r[1]])));
|
||
|
||
await removeRule(RULE_PATH + '*');
|
||
// Asked again, with waits. The row can leave the table a moment before the
|
||
// guard's snapshot is rebuilt — the delete commits, the listing stops showing
|
||
// it, and the snapshot refresh lands milliseconds later. That is the same
|
||
// staleness the TTL documents, so the gate waits for the state to agree rather
|
||
// than pretending the two reads are one.
|
||
let flowed = (await probePath(RULE_PATH, RULE_IP)).status;
|
||
for (let i = 0; i < 10 && flowed !== 404; i++) {
|
||
await clearEngineBan(RULE_IP);
|
||
await new Promise((r) => setTimeout(r, 500));
|
||
flowed = (await probePath(RULE_PATH, RULE_IP)).status;
|
||
}
|
||
check('removing the rule from the page lets the path flow again',
|
||
flowed === 404, `after removal: ${flowed}`);
|
||
|
||
// The volume pillar (OPEN-56). Its own address, and the budget is switched
|
||
// back off at the end: a left-behind budget of two requests would refuse the
|
||
// probes every later scene makes, and the failure would read as a page bug.
|
||
const RATE_IP = '203.0.113.199';
|
||
const rateNoteOf = async () => (await page.textContent('#ratenote')).replace(/\s+/g, ' ').trim();
|
||
const offNote = await rateNoteOf();
|
||
check('the budget line says off means nothing is counted',
|
||
/^off/.test(offNote) && /nothing is being counted/.test(offNote), JSON.stringify(offNote));
|
||
|
||
await page.selectOption('#rateMode', 'enforce');
|
||
await page.fill('#rateLimit', '2');
|
||
await page.fill('#rateWindow', '120');
|
||
await page.click('#setRate');
|
||
await page.waitForFunction(
|
||
() => /enforce · 2 requests per 120 s/.test(document.getElementById('ratenote').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const onNote = await rateNoteOf();
|
||
check('the page can write a budget and the line reads back what is in force',
|
||
/enforce · 2 requests per 120 s per source/.test(onNote) && /this process/.test(onNote),
|
||
JSON.stringify(onNote));
|
||
|
||
const rateProbe1 = await probePath('/gate-rate-probe', RATE_IP);
|
||
const rateProbe2 = await probePath('/gate-rate-probe', RATE_IP);
|
||
const rateProbe3 = await probePath('/gate-rate-probe', RATE_IP);
|
||
check('the request that crosses the budget is answered by the edge, not the application',
|
||
rateProbe3.status === 429 && /rate_limited/.test(rateProbe3.text)
|
||
&& rateProbe1.status === 404 && rateProbe2.status === 404,
|
||
`${rateProbe1.status} ${rateProbe2.status} ${rateProbe3.status} `
|
||
+ JSON.stringify(rateProbe3.text.slice(0, 120)));
|
||
|
||
await page.click('#refresh');
|
||
await page.waitForFunction(
|
||
(ip) => [...document.querySelectorAll('#ratetable tbody tr')]
|
||
.some((r) => r.children[0].textContent === ip),
|
||
RATE_IP, { timeout: 15000 }).catch(() => {});
|
||
const rateRows = await cells('#ratetable tbody tr');
|
||
check('the budget table counts the source and marks it over budget',
|
||
rateRows.some((r) => r[0] === RATE_IP && Number(r[1]) >= 3 && r[2] === '2'),
|
||
JSON.stringify(rateRows.map((r) => [r[0], r[1], r[2]])));
|
||
|
||
await page.selectOption('#rateMode', 'off');
|
||
await page.click('#setRate');
|
||
await page.waitForFunction(
|
||
() => /^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));
|
||
|
||
// The failure mode worth asserting on a write form is the quiet one: the
|
||
// operator believes they blocked an address and did not. A typo in the field
|
||
// must come back as the API's own error, not as a status line that says
|
||
// nothing and a table that gains no row.
|
||
await page.fill('#blockIp', 'not-an-ip');
|
||
await page.click('#addBlock');
|
||
await page.waitForFunction(
|
||
() => /not an IP address/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 10000 }).catch(() => {});
|
||
const errStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const rowsAfterBad = await cells('#blocks tbody tr');
|
||
check('a bad address in the block form surfaces the API error instead of looking like success',
|
||
/not an IP address/.test(errStatus), errStatus);
|
||
check('and no phantom row appears for the address that was rejected',
|
||
!rowsAfterBad.some((r) => r[0] === 'not-an-ip'), JSON.stringify(rowsAfterBad.map((r) => r[0])));
|
||
|
||
// The country rule toggle is the one control here that changes policy for
|
||
// everyone, so the gate turns it and turns it back, and then removes it: PUT
|
||
// allowed=true leaves a row behind, and only DELETE takes the rule out.
|
||
const ruleOf = async (code) => page.$$eval('#countries tbody tr',
|
||
(rows, c) => { const r = rows.find((tr) => tr.children[0].textContent === c); return r ? r.children[4].textContent : 'no row'; }, code);
|
||
const waitRule = (code, want) => page.waitForFunction((a) => {
|
||
const rows = document.querySelectorAll('#countries tbody tr');
|
||
for (const tr of rows) {
|
||
if (tr.children[0].textContent === a.c) return tr.children[4].textContent === a.w;
|
||
}
|
||
return a.w === '—';
|
||
}, { c: code, w: want }, { timeout: 15000 }).catch(() => {});
|
||
const REMOVE_SEL = '#countries tbody button[data-act="countrydel"][data-k="US"]';
|
||
const hasRemove = () => page.$(REMOVE_SEL).then((h) => h !== null);
|
||
|
||
// Start from no rule at all. The gate used to depend on whatever a previous
|
||
// run left in the data volume: with a US rule already present the first click
|
||
// denied the country, and with a fresh volume it allowed it, so the old
|
||
// assertion only ever passed on residue.
|
||
if (await hasRemove()) {
|
||
await page.click(REMOVE_SEL);
|
||
await waitRule('US', '—');
|
||
}
|
||
const before = await ruleOf('US');
|
||
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
|
||
await waitRule('US', 'allowed');
|
||
const first = await ruleOf('US');
|
||
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
|
||
await waitRule('US', 'denied');
|
||
const second = await ruleOf('US');
|
||
check('a country rule can be written from the page and toggled both ways',
|
||
before === '—' && first === 'allowed' && second === 'denied',
|
||
`before ${before} → ${first} → ${second}`);
|
||
|
||
// Setting a rule back to "allowed" is not the same as having no rule: the row
|
||
// stays in the table and claims a policy that does nothing. The page has to be
|
||
// able to take it out.
|
||
check('a rule row offers removal only when a rule actually exists', await hasRemove(), REMOVE_SEL);
|
||
await page.click(REMOVE_SEL);
|
||
await waitRule('US', '—');
|
||
const afterRemove = await ruleOf('US');
|
||
check('a country rule can be removed from the page, not only flipped to allowed',
|
||
afterRemove === '—' && !(await hasRemove()),
|
||
`rule cell after remove: ${afterRemove}, remove button gone: ${!(await hasRemove())}`);
|
||
|
||
// Every destructive row button shares this one handler, and until now the
|
||
// handler wrote its green note whatever came back: a 400 whose body said
|
||
// "refusing to delete every block" still produced "deleted ? block(s)" in the
|
||
// success colour. The button is synthetic because the page only ever renders a
|
||
// remove button for a row that exists; the handler is delegated on the
|
||
// document, so this is the same code a real click runs. An empty key is the
|
||
// refused call — DELETE /admin-api/blocks?key= is the one destructive row
|
||
// request the API answers with a 400 and a reason. (A 404 would not do: the
|
||
// page reads every 404 as "the admin API is switched off", which is its own
|
||
// story and is recorded separately.)
|
||
await page.evaluate(() => {
|
||
const b = document.createElement('button');
|
||
b.id = 'c26-refused-remove';
|
||
b.dataset.act = 'delblock';
|
||
b.dataset.k = '';
|
||
document.body.appendChild(b);
|
||
});
|
||
await page.click('#c26-refused-remove');
|
||
await page.waitForFunction(
|
||
() => /refusing to delete every block/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 10000 }).catch(() => {});
|
||
const refusedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const refusedClass = await page.getAttribute('#status', 'class');
|
||
await page.evaluate(() => { const b = document.getElementById('c26-refused-remove'); if (b) b.remove(); });
|
||
check('a row action does not write a success note over an answer that said it failed',
|
||
/refusing to delete every block/.test(refusedStatus) && refusedClass === 'warn',
|
||
`${refusedClass}: ${refusedStatus}`);
|
||
|
||
// The other half of the same handler: what a 404 means. apiRaw used to read
|
||
// EVERY 404 as "the admin API is switched off" and throw, so a row that is
|
||
// simply not there — the stale-tab case, another operator removed it first —
|
||
// told this operator to go set a token that is already set. The button is
|
||
// synthetic for the same reason as above: the page only renders a remove
|
||
// button for a row it has, and the handler is delegated on the document.
|
||
await page.evaluate(() => {
|
||
const b = document.createElement('button');
|
||
b.id = 'c27-refused-allow';
|
||
b.dataset.act = 'delallow';
|
||
b.dataset.k = '999999';
|
||
document.body.appendChild(b);
|
||
});
|
||
await page.click('#c27-refused-allow');
|
||
await page.waitForFunction(
|
||
() => /allow entry|not found|no allow/i.test(document.getElementById('status').textContent),
|
||
null, { timeout: 10000 }).catch(() => {});
|
||
const missingStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const missingClass = await page.getAttribute('#status', 'class');
|
||
await page.evaluate(() => { const b = document.getElementById('c27-refused-allow'); if (b) b.remove(); });
|
||
check('a missing row is reported as a missing row, not as the admin API being switched off',
|
||
/no allow entry with id 999999/.test(missingStatus) && missingClass === 'warn',
|
||
`${missingClass}: ${missingStatus}`);
|
||
|
||
// "Clear the automatic bans" is the most destructive button on the page and
|
||
// used to read nothing back from the DELETE — cleared 7, cleared 0 and a
|
||
// refused write all looked identical after the reload. The stand has no engine
|
||
// bans at this point, so the honest answer is a count of 0, and the point of
|
||
// the assertion is that a count is said at all.
|
||
await page.click('#clearEngine');
|
||
await page.waitForFunction(
|
||
() => /engine bans cleared/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 10000 }).catch(() => {});
|
||
const clearedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
check('the button that clears automatic bans says what the edge answered',
|
||
/engine bans cleared: \d+/.test(clearedStatus), clearedStatus);
|
||
|
||
// The half of the same fix this gate had never asked about: an answer with no
|
||
// body at all. apiRaw called r.json(), watched it throw, and the caller's
|
||
// catch said "note() already said why" — when nothing had been said. The
|
||
// status line went quiet exactly when the edge had the worst news to report.
|
||
// The shape is not hypothetical: scripts/compose-smoke.sh measures
|
||
// GET /admin-api/blocks answering 500 with an empty body on the shipped image
|
||
// once its table is gone, and the same empty-5xx shape is what a storage
|
||
// failure leaves behind when the handler has no sentence to attach. The 5xx
|
||
// that does carry {error} is proven above through the 400 path (one shared
|
||
// handler); an empty one is the other half, and until now nothing in this file
|
||
// could tell a swallowed 5xx from a page that had simply decided to say
|
||
// "refreshed".
|
||
// The answer is served through a route rather than by breaking the stand: the
|
||
// block table has to stay readable for every assertion after this one, and the
|
||
// route intercepts only the one DELETE this click issues. What is proven here
|
||
// is the page's handling of that answer; that the edge really produces one is
|
||
// what the other gate proves with SQLite triggers on the real table.
|
||
{
|
||
const problemsBefore = jsProblems.length;
|
||
let stateFetches = 0;
|
||
const countLoad = (req) => { if (/\/admin-api\/state(\?|$)/.test(req.url())) stateFetches++; };
|
||
page.on('request', countLoad);
|
||
await page.route('**/admin-api/blocks*', (route) =>
|
||
route.request().method() === 'DELETE'
|
||
? route.fulfill({ status: 503, contentType: 'application/json', body: '' })
|
||
: route.continue());
|
||
await page.evaluate(() => {
|
||
const b = document.createElement('button');
|
||
b.id = 'c26-empty5xx';
|
||
b.dataset.act = 'delblock';
|
||
b.dataset.k = '203.0.113.199';
|
||
document.body.appendChild(b);
|
||
// Every sentence the status line ever wears during this scene, in order.
|
||
// Reading the line once after the click cannot tell a held error from a
|
||
// success note that a later refresh already replaced — and the mutation
|
||
// that swallows the empty answer writes exactly such a note and then loses
|
||
// it under "refreshed". The observer is what lets the second assertion
|
||
// below fail for that regression instead of passing on the timing.
|
||
window.__c26Notes = [];
|
||
const s = document.getElementById('status');
|
||
new MutationObserver(() => window.__c26Notes.push(s.className + ': ' + s.textContent.trim()))
|
||
.observe(s, { childList: true, characterData: true, subtree: true });
|
||
});
|
||
await page.click('#c26-empty5xx');
|
||
await page.waitForFunction(
|
||
() => /no explanation/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 10000 }).catch(() => {});
|
||
const notes = await page.evaluate(() => window.__c26Notes || []);
|
||
const emptyStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const emptyClass = await page.getAttribute('#status', 'class');
|
||
// Every row action ends with load(), and load() writes "refreshed" unless
|
||
// the action before it failed. So the sentence has to still be there AFTER a
|
||
// refresh has demonstrably run — counting the state fetches is what makes
|
||
// this non-vacuous: without it, "still there" could just mean the page never
|
||
// refreshed at all.
|
||
const until = Date.now() + 4000;
|
||
while (stateFetches === 0 && Date.now() < until) await new Promise((r) => setTimeout(r, 100));
|
||
const heldStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const heldClass = await page.getAttribute('#status', 'class');
|
||
// The hold is one-shot on purpose: a note that never clears is its own bug,
|
||
// because the operator then reads yesterday's failure under today's tables.
|
||
await page.waitForFunction(
|
||
() => /refreshed /.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const clearedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||
const clearedClass = await page.getAttribute('#status', 'class');
|
||
await page.evaluate(() => { const b = document.getElementById('c26-empty5xx'); if (b) b.remove(); });
|
||
await page.unroute('**/admin-api/blocks*');
|
||
page.off('request', countLoad);
|
||
check('an answer with no body is said out loud instead of swallowed',
|
||
notes.some((n) => /^warn: the edge answered 503 with no explanation/.test(n))
|
||
&& /no explanation/.test(emptyStatus) && emptyClass === 'warn',
|
||
`line now ${emptyClass}: ${emptyStatus} | notes ${JSON.stringify(notes)}`);
|
||
check('and it is not the success note that button would otherwise write',
|
||
!notes.some((n) => /deleted \d|deleted \?|block\(s\)/.test(n)),
|
||
JSON.stringify(notes));
|
||
check('the failed action keeps its reason across the refresh it triggers itself',
|
||
stateFetches >= 1 && /no explanation/.test(heldStatus) && heldClass === 'warn',
|
||
`${stateFetches} refresh(es) already ran; line is "${heldClass}: ${heldStatus}"`);
|
||
check('and the next refresh says "refreshed" again, so the page does not stay red forever',
|
||
/refreshed /.test(clearedStatus) && clearedClass !== 'warn',
|
||
`${clearedClass}: ${clearedStatus}`);
|
||
// "Threw" means pageerror. A 503 also arrives as a Chromium console.error
|
||
// ("Failed to load resource"), which is the browser reporting the failed
|
||
// fetch the page then handled — counting it here would make the assertion
|
||
// fail on the very thing it wants the page to answer, and the scenes above
|
||
// that listen for pageerror only already draw this line.
|
||
const newProblems = jsProblems.slice(problemsBefore);
|
||
const thrown = newProblems.filter((p) => p.startsWith('pageerror:'));
|
||
check('the page threw no javascript on that empty answer',
|
||
thrown.length === 0, newProblems.join(' | '));
|
||
}
|
||
|
||
// The other honesty fix this round lives in the summary line: a pillar whose
|
||
// table stopped being readable keeps its last good value (the right failure
|
||
// posture) and used to do it invisibly — one log line, a snapshot age that
|
||
// still looked fresh, /readyz saying ready. scripts/compose-smoke.sh proves the
|
||
// API half of that against the shipped image, with the table really dropped.
|
||
// What is proven here is the page half: given that answer, the summary line has
|
||
// to say it. The state body is served through a route rather than produced by
|
||
// breaking the stand, because the guard refreshes the snapshot on every request
|
||
// — a live stand cannot be left to age — and the contract being rendered is the
|
||
// one the other gate already measured end to end.
|
||
{
|
||
const broken = await browser.newPage();
|
||
const brokenProblems = [];
|
||
broken.on('pageerror', (e) => brokenProblems.push('pageerror: ' + e.message));
|
||
await broken.route('**/admin-api/state', (route) => route.fulfill({
|
||
status: 200,
|
||
contentType: 'application/json',
|
||
body: JSON.stringify({
|
||
snapshotAgeSeconds: 412.7, snapshotTtlSeconds: 30, snapshotStale: true,
|
||
snapshotRefreshFailures: 14,
|
||
snapshotLastRefreshError: 'no such table: country_rules',
|
||
policyReloadFailures: 14, policyLastReadAt: '2026-10-02T04:44:43.0000000+00:00',
|
||
trackedSources: 0, operatorBlocks: 2, engineBans: 0,
|
||
allowEntries: 0, allowEntriesExpired: 0, mode: 'Enforce'
|
||
})
|
||
}));
|
||
await broken.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
|
||
await broken.fill('#token', TOKEN);
|
||
await broken.click('#save');
|
||
await broken.waitForFunction(
|
||
() => /older than the ttl/.test([...document.querySelectorAll('#summary .pill')]
|
||
.map((p) => p.textContent).join(' | ')),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const brokenPill = await broken.evaluate(() => {
|
||
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /snapshot/.test(p.textContent));
|
||
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
|
||
});
|
||
check('a snapshot older than its TTL is marked on the page, not only left in the log',
|
||
!!brokenPill && /older than the ttl/.test(brokenPill.text) && /warn/.test(brokenPill.cls),
|
||
JSON.stringify(brokenPill));
|
||
check('and the page names the pillars that stopped reading their tables',
|
||
!!brokenPill && /snapshot refresh failing/.test(brokenPill.text)
|
||
&& /policy not re-read from storage/.test(brokenPill.text),
|
||
JSON.stringify(brokenPill));
|
||
check('the page threw no javascript on that answer', brokenProblems.length === 0, brokenProblems.join(' | '));
|
||
await broken.close();
|
||
}
|
||
|
||
// The write half of the same contract. A failed write loses a row for good —
|
||
// measured on the shipped image with SQLite triggers aborting every INSERT
|
||
// and UPDATE on source_observations and edge_alerts: the observation listing
|
||
// kept answering with the X-Total-Count it had before the break while three
|
||
// new sources were being refused, the alert table kept its one row through a
|
||
// six-request 5xx storm, and /readyz said "ready". scripts/compose-smoke.sh
|
||
// proves that end to end against the image; what is proven here is that the
|
||
// page renders the fields it now has to render, and that a write failure is
|
||
// shown as a write failure rather than folded into the snapshot pill.
|
||
{
|
||
const lost = await browser.newPage();
|
||
const lostProblems = [];
|
||
lost.on('pageerror', (e) => lostProblems.push('pageerror: ' + e.message));
|
||
await lost.route('**/admin-api/state', (route) => route.fulfill({
|
||
status: 200,
|
||
contentType: 'application/json',
|
||
body: JSON.stringify({
|
||
snapshotAgeSeconds: 0.4, snapshotTtlSeconds: 30, snapshotStale: false,
|
||
snapshotRefreshFailures: 0, snapshotLastRefreshError: null,
|
||
policyReloadFailures: 0, policyLastReadAt: '2026-10-02T05:12:07.0000000+00:00',
|
||
banWriteFailures: 2, bansNotWritten: 2,
|
||
banLastWriteError: 'gate: ban write blocked',
|
||
banLastWriteAt: '2026-10-02T05:11:40.0000000+00:00',
|
||
observationWriteFailures: 3, observationsLost: 4,
|
||
observationLastWriteError: 'gate: durable write blocked',
|
||
observationLastWriteAt: '2026-10-02T05:11:52.0000000+00:00',
|
||
alertWriteFailures: 2, alertsLost: 2,
|
||
alertLastWriteError: 'gate: durable write blocked',
|
||
retentionPruneFailures: 1, retentionLastError: 'gate: durable write blocked',
|
||
retentionLastPruneAt: '2026-10-02T04:41:19.0000000+00:00',
|
||
changeWriteFailures: 1, changesNotWritten: 1,
|
||
changeLastError: 'gate: durable write blocked',
|
||
trackedSources: 4, operatorBlocks: 2, engineBans: 0,
|
||
allowEntries: 0, allowEntriesExpired: 0, mode: 'Enforce'
|
||
})
|
||
}));
|
||
await lost.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
|
||
await lost.fill('#token', TOKEN);
|
||
await lost.click('#save');
|
||
await lost.waitForFunction(
|
||
() => /durable writes/.test([...document.querySelectorAll('#summary .pill')]
|
||
.map((p) => p.textContent).join(' | ')),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const writePill = await lost.evaluate(() => {
|
||
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /durable writes/.test(p.textContent));
|
||
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
|
||
});
|
||
const snapshotPill = await lost.evaluate(() => {
|
||
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /snapshot/.test(p.textContent));
|
||
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
|
||
});
|
||
check('a write that never reached storage is marked on the page, with what it cost',
|
||
!!writePill && /observations not persisted/.test(writePill.text)
|
||
&& /4 rows lost/.test(writePill.text) && /alerts not persisted/.test(writePill.text)
|
||
&& /warn/.test(writePill.cls),
|
||
JSON.stringify(writePill));
|
||
// The enforcement-path failure gets named separately, because it is the one
|
||
// that also makes the edge unready: a ban that never reached storage is not
|
||
// enforced by this edge either.
|
||
check('and the page names bans that were never written, apart from the reporting losses',
|
||
!!writePill && /bans not written ×2 \(2 not enforced\)/.test(writePill.text),
|
||
JSON.stringify(writePill));
|
||
check('and it is shown as a write failure, not folded into the snapshot pill',
|
||
!!snapshotPill && !/warn/.test(snapshotPill.cls) && !/not persisted/.test(snapshotPill.text)
|
||
&& /retention not running/.test(writePill.text || ''),
|
||
JSON.stringify({ write: writePill, snapshot: snapshotPill }));
|
||
// The change log is the one write whose failure does not change what the
|
||
// edge enforces, so without this line the config would have changed and
|
||
// nothing would say the record of it is missing.
|
||
check('and it names the change records that never landed, with how many',
|
||
!!writePill && /change records not written \u00d71 \(1 changes unrecorded\)/.test(writePill.text),
|
||
JSON.stringify(writePill));
|
||
check('the page threw no javascript on that answer', lostProblems.length === 0, lostProblems.join(' | '));
|
||
await lost.close();
|
||
}
|
||
|
||
// The clean case, on the real stand rather than a rendered contract: the pill
|
||
// has to say it checked, because a pill that only appears when something is
|
||
// wrong is how "no alerts" and "alerts are not being written" look identical.
|
||
{
|
||
const cleanPill = await page.evaluate(() => {
|
||
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /durable writes/.test(p.textContent));
|
||
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
|
||
});
|
||
check('with the write path healthy the page says so rather than staying quiet',
|
||
!!cleanPill && /durable writes ok/.test(cleanPill.text) && !/warn/.test(cleanPill.cls),
|
||
JSON.stringify(cleanPill));
|
||
}
|
||
|
||
// ── OPEN-36: one source key, every per-source table. The operator's question
|
||
// is "what else does the edge know about THIS address", and until now the
|
||
// console could only answer it by eye: the observations table showed the newest
|
||
// 25 of every source and the streaks table showed every standing source. The
|
||
// API half is proven in scripts/compose-smoke.sh; what is proven here is that
|
||
// the control exists, that a click on a key narrows BOTH tables to it, that
|
||
// the totals printed under them are the FILTERED totals, and that a source
|
||
// with nothing recorded is answered in words rather than with an empty box.
|
||
{
|
||
const srcCells = () => page.$$eval('#obs tbody tr',
|
||
(rows) => rows.map((tr) => tr.children[0].textContent));
|
||
const streakCells = () => page.$$eval('#streaks tbody tr',
|
||
(rows) => rows.map((tr) => tr.children[0].textContent));
|
||
const noteOf = async (sel) => (await page.textContent(sel)).replace(/\s+/g, ' ').trim();
|
||
|
||
const filterBox = await page.$('#srcfilter');
|
||
const acts = await page.$$eval('div.bar button[data-act]', (b) => b.map((x) => x.dataset.act));
|
||
check('the page offers a source filter and a way to clear it',
|
||
!!filterBox && acts.includes('srcfilter') && acts.includes('srcclear'),
|
||
JSON.stringify(acts));
|
||
|
||
// A key printed in one table is a question the operator can ask back without
|
||
// typing it. The key is read out of the streaks table instead of hard-coded
|
||
// to the seed: by the time the write-side scenes have run, the source seeded
|
||
// at the top of the run is legitimately out of the streak window, and an
|
||
// assertion that demanded it still be standing would be the gate disagreeing
|
||
// with the product rather than with the page. The click is on a standing
|
||
// streaks row; the observations table has to follow it, and both notes have
|
||
// to say which key they are answering about.
|
||
const rxEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
const standingKey = await page.$$eval('#streaks tbody tr', (rows) => {
|
||
for (const tr of rows) {
|
||
const b = tr.children[0] && tr.children[0].querySelector('button[data-act="srcfilter"]');
|
||
if (b) return b.textContent;
|
||
}
|
||
return '';
|
||
});
|
||
check('a standing source row offers its key as a filter control',
|
||
standingKey !== '', JSON.stringify(standingKey));
|
||
await page.click(`#streaks tbody button[data-act="srcfilter"][data-k="${standingKey}"]`);
|
||
await page.waitForFunction((k) => new RegExp('^filtered to ' + k + ':')
|
||
.test(document.getElementById('obsnote').textContent.replace(/\s+/g, ' ').trim()),
|
||
rxEsc(standingKey), { timeout: 15000 }).catch(() => {});
|
||
const filteredObs = await srcCells();
|
||
const filteredStreaks = await streakCells();
|
||
const filteredObsNote = await noteOf('#obsnote');
|
||
const filteredStreakNote = await noteOf('#streaknote');
|
||
const filterBoxValue = await page.inputValue('#srcfilter');
|
||
check('clicking a source key narrows the observation table to that key alone',
|
||
filteredObs.length > 0 && filteredObs.every((c) => c === standingKey),
|
||
JSON.stringify(filteredObs));
|
||
check('and the streaks table is narrowed to the same key',
|
||
filteredStreaks.length === 1 && filteredStreaks[0] === standingKey,
|
||
JSON.stringify(filteredStreaks));
|
||
check('the observation line states the FILTERED total, not the whole window',
|
||
new RegExp('^filtered to ' + rxEsc(standingKey)
|
||
+ ': (\\d+ rows? recorded for this source|newest \\d+ of \\d+ rows for this source)')
|
||
.test(filteredObsNote), filteredObsNote);
|
||
check('the streak line counts that source\'s standing streaks and keeps the map size beside it',
|
||
new RegExp('^this edge process only — filtered to ' + rxEsc(standingKey)
|
||
+ ': 1 of 1 standing streaks for this source listed').test(filteredStreakNote)
|
||
&& /the unfiltered map holds \d+ sources tracked/.test(filteredStreakNote),
|
||
filteredStreakNote);
|
||
check('the filter box shows the key the page is actually filtered to',
|
||
filterBoxValue === standingKey, JSON.stringify({ box: filterBoxValue, key: standingKey }));
|
||
|
||
// A key nobody ever saw has to be answered in words. An empty table and a
|
||
// broken page look identical, and this is exactly the case where the page
|
||
// used to print "none" about a filter the operator had just typed.
|
||
const NO_MATCH = '192.0.2.77';
|
||
await page.fill('#srcfilter', NO_MATCH);
|
||
await page.click('div.bar button[data-act="srcfilter"]');
|
||
await page.waitForFunction((k) => document.getElementById('obsnote').textContent.includes(k),
|
||
NO_MATCH, { timeout: 15000 }).catch(() => {});
|
||
const emptyObsNote = await noteOf('#obsnote');
|
||
const emptyObsRow = await srcCells();
|
||
const emptyStreakNote = await noteOf('#streaknote');
|
||
check('a source with nothing recorded is named in words, with a total of zero',
|
||
emptyObsNote === 'no recorded observations for ' + NO_MATCH + ' · rows are pruned after 7d'
|
||
&& emptyObsRow.length === 1 && emptyObsRow[0] === 'nothing recorded for ' + NO_MATCH,
|
||
`${JSON.stringify(emptyObsNote)} row=${JSON.stringify(emptyObsRow)}`);
|
||
check('and the streak line says nothing is standing for that source',
|
||
/filtered to 192\.0\.2\.77: nothing standing for this source/.test(emptyStreakNote),
|
||
emptyStreakNote);
|
||
|
||
// The filter value reaches the page the same way any wire value does —
|
||
// through esc() — and it is also free text a human typed. This is the
|
||
// markup-seed invariant above, proven for the filter echo instead of for a
|
||
// row cell.
|
||
const MARKUP_KEY = '<svg onload=document.title=\'XSS3\'>';
|
||
await page.fill('#srcfilter', MARKUP_KEY);
|
||
await page.click('div.bar button[data-act="srcfilter"]');
|
||
await page.waitForFunction((k) => document.getElementById('obsnote').textContent.includes(k),
|
||
MARKUP_KEY, { timeout: 15000 }).catch(() => {});
|
||
const markupInjected = await page.$$eval('#obs tbody, #streaks tbody, #alerts tbody, #changes tbody',
|
||
(bodies) => bodies.reduce((n, b) => n + b.querySelectorAll('img,svg,script,iframe,object,embed').length, 0));
|
||
const markupNote = await noteOf('#obsnote');
|
||
const markupTitle = await page.title();
|
||
check('a filter value containing markup is printed as text and creates no element',
|
||
markupInjected === 0 && markupTitle.indexOf('XSS3') === -1
|
||
&& markupNote === 'no recorded observations for ' + MARKUP_KEY + ' · rows are pruned after 7d',
|
||
`${markupInjected} injected elements, title ${JSON.stringify(markupTitle)}, note ${JSON.stringify(markupNote)}`);
|
||
|
||
// And back out. Clearing has to restore the unfiltered totals, not leave a
|
||
// narrowed count wearing the unfiltered sentence.
|
||
await page.click('div.bar button[data-act="srcclear"]');
|
||
await page.waitForFunction(
|
||
() => /^(\d+ sources? the edge has recorded|newest \d+ of \d+ recorded sources)/
|
||
.test(document.getElementById('obsnote').textContent.replace(/\s+/g, ' ').trim()),
|
||
null, { timeout: 15000 }).catch(() => {});
|
||
const clearedObsNote = await noteOf('#obsnote');
|
||
const clearedStreakNote = await noteOf('#streaknote');
|
||
const clearedObsCount = (await srcCells()).length;
|
||
const clearedBox = await page.inputValue('#srcfilter');
|
||
check('showing every source restores the unfiltered tables and totals',
|
||
clearedObsCount > 1 && clearedBox === '' && !/filtered to/.test(clearedObsNote)
|
||
&& !/filtered to/.test(clearedStreakNote)
|
||
&& /\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
|
||
// 375 px viewport to 520 px of sideways scroll, and the status line sat on the
|
||
// dark canvas at 2.82:1.
|
||
{
|
||
const phone = await browser.newPage({ viewport: { width: 375, height: 720 }, colorScheme: 'dark' });
|
||
const phoneProblems = [];
|
||
phone.on('pageerror', (e) => phoneProblems.push('pageerror: ' + e.message));
|
||
phone.on('console', (m) => { if (m.type() === 'error') phoneProblems.push('console.error: ' + m.text()); });
|
||
|
||
await phone.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
|
||
await phone.fill('#token', TOKEN);
|
||
await phone.click('#save');
|
||
await phone.waitForFunction(
|
||
() => /refreshed/.test(document.getElementById('status').textContent),
|
||
null, { timeout: 15000 });
|
||
|
||
const m = await phone.evaluate(() => {
|
||
const probe = document.createElement('div');
|
||
probe.style.cssText = 'position:absolute;left:-9999px;background:Canvas;color:CanvasText';
|
||
document.body.appendChild(probe);
|
||
const cs = getComputedStyle(probe);
|
||
const canvas = cs.backgroundColor;
|
||
const statusColor = getComputedStyle(document.getElementById('status')).color;
|
||
probe.remove();
|
||
const streakRow = [...document.querySelectorAll('#streaks tbody tr')]
|
||
.map((tr) => [...tr.children].map((td) => td.textContent));
|
||
return {
|
||
canvas, statusColor,
|
||
scrollWidth: document.documentElement.scrollWidth,
|
||
innerWidth: window.innerWidth,
|
||
html: document.documentElement.outerHTML,
|
||
streakRow,
|
||
barWidths: [...document.querySelectorAll('#countries tbody tr .sharebar')].map((e) => e.clientWidth),
|
||
};
|
||
});
|
||
|
||
const ratio = contrast(rgb(m.statusColor), rgb(m.canvas));
|
||
check('the page fits a 375 px phone without sideways document scroll',
|
||
m.scrollWidth <= m.innerWidth, `scrollWidth ${m.scrollWidth} vs viewport ${m.innerWidth}`);
|
||
check('the status line is readable on the dark canvas (WCAG AA 4.5:1)',
|
||
ratio >= 4.5, `contrast ${ratio.toFixed(2)}:1, status ${m.statusColor} on ${m.canvas}`);
|
||
check('the standing streak is still listed at phone width',
|
||
m.streakRow.some((r) => r[0] === SEED_SOURCE && /2 \/ 3/.test(r[1] || '')),
|
||
JSON.stringify(m.streakRow.map((r) => [r[0], r[1]])));
|
||
check('the token is not in the markup at phone width either', !m.html.includes(TOKEN));
|
||
const phoneAlertRows = await page.$$eval('#alerts tbody tr', (r) => r.length);
|
||
check('the alerts table is still there at phone width', phoneAlertRows > 0, `${phoneAlertRows} rows`);
|
||
const phoneChangeRows = await phone.$$eval('#changes tbody tr', (r) => r.length);
|
||
check('the change table is still there at phone width', phoneChangeRows > 0,
|
||
`${phoneChangeRows} rows`);
|
||
check('the country bars survive the phone layout',
|
||
m.barWidths.length > 0 && m.barWidths.every((w) => w >= 2), JSON.stringify(m.barWidths));
|
||
check('the page threw no javascript at phone width', phoneProblems.length === 0, phoneProblems.join(' | '));
|
||
if (SCREENSHOT) await phone.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.phone$1'), fullPage: true });
|
||
await phone.close();
|
||
}
|
||
|
||
if (failures.length) {
|
||
// The two ways this gate goes red are different and both need a picture:
|
||
// "the page could not be driven" (the catch below) and "the page was driven
|
||
// and is wrong" (here). The first version only covered the first.
|
||
if (SCREENSHOT) {
|
||
try {
|
||
await page.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.failure$1'), fullPage: true });
|
||
} catch (e) { console.error(' (no failure screenshot: ' + e.message + ')'); }
|
||
}
|
||
console.error(`console check: ${failures.length} assertion(s) failed`);
|
||
await browser.close();
|
||
process.exit(1);
|
||
}
|
||
await browser.close();
|
||
console.log('console check: all assertions passed');
|
||
})().catch(async (e) => {
|
||
console.error('console check failed to run:', e.message);
|
||
if (SCREENSHOT) {
|
||
try {
|
||
const b = await chromium.launch({ headless: true });
|
||
const p2 = await b.newPage({ viewport: { width: 1280, height: 1100 } });
|
||
await p2.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
|
||
await p2.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.failure$1'), fullPage: true });
|
||
await b.close();
|
||
} catch (e2) { console.error(' (no failure screenshot: ' + e2.message + ')'); }
|
||
}
|
||
process.exit(1);
|
||
});
|