diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 56e187f..bb93fd5 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1153,6 +1153,171 @@ check 'the junk that used to be eternal is still not in the table' '0' \ "$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='12' or b['code']=='U.' or b['code']=='??' or b['code']=='USA'")" admin -X PUT -H 'Content-Type: application/json' -d '{"geo":"Off"}' "$EDGE/admin-api/policy" >/dev/null +echo '- an operator command that could not run does not answer like one that did' +# Measured on two shipped images of one stand (the tree before the fix, image sha +# b46f5c20, and after it, 08bebf43) with block_entries and policy_settings dropped +# out from under a running edge that held 3 blocks and 1 policy row: +# DELETE /admin-api/blocks?source=operator -> 200 {"deleted":0} (the list held 3) +# DELETE /admin-api/blocks?key=203.0.113.201 -> 200 {"deleted":0} +# POST /admin-api/blocks -> 400 {"error":"database error"} (blaming the caller) +# PUT /admin-api/policy -> 200 with the mode that was NOT saved +# GET /readyz -> 200 {"status":"ready"} +# The bytes of "there was nothing to delete" and of "the delete failed" were the +# same bytes, so a destructive command that did not run told the operator it had +# found nothing to do. In-process this has been covered since then by +# StorageFailureHonestyTests (7 tests); on the shipped image nothing covered it, +# which is the same gap OPEN-25 closed for country rules. +# A trigger rather than a dropped table on purpose: a missing table also breaks +# the listing, and a listing that answers 500 is honest about being broken. The +# lie this scene is after is the 2xx that still looks complete. The trigger has +# to cover DELETE as well as INSERT and UPDATE — measured on the first run of +# this scene (/tmp/c26_compose1.log, 195/6), a BEFORE INSERT/UPDATE pair left the +# delete path untouched, so the two blocks really were deleted, the answer really +# was 200, and the scene was asserting a failure that had not been produced. +OPEN26_A=203.0.113.181 +OPEN26_B=203.0.113.182 +admin -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$OPEN26_A\",\"reason\":\"open26 first\"}" "$EDGE/admin-api/blocks" >/dev/null +admin -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$OPEN26_B\",\"reason\":\"open26 second\"}" "$EDGE/admin-api/blocks" >/dev/null +check 'the two operator blocks this scene needs are in the table' '2' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['source']=='operator'")" +OPEN26_POLICY=$(admin "$EDGE/admin-api/policy" | jval streakThreshold) +printf ' info the policy in force before the write path breaks: streakThreshold=%s\n' "${OPEN26_POLICY:-none}" +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +for t, ops in (("block_entries", ("INSERT", "UPDATE", "DELETE")), + ("policy_settings", ("INSERT", "UPDATE"))): + for op in ops: + c.execute(f'CREATE TRIGGER "gate_open26_{t}_{op}" BEFORE {op} ON "{t}" ' + "BEGIN SELECT RAISE(ABORT, 'gate: open26 write blocked'); END") +print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")]) +PYSQL +check 'a delete that could not run answers 503, not 200 with a count' '503' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/blocks?source=operator")" +check 'and the sentence says NOTHING was deleted' 'yes' \ + "$(admin -X DELETE "$EDGE/admin-api/blocks?source=operator" | jval error | grep -qi 'NOTHING was deleted' && echo yes || echo no)" +check 'a delete of one named key answers the same way' '503' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$OPEN26_A")" +check 'the blocks the edge could not delete are still in the table' '2' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['source']=='operator'")" +check 'a block the storage refused is not blamed on the request' '503' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \ + -d '{"ip":"203.0.113.183","reason":"open26 refused"}' "$EDGE/admin-api/blocks")" +check 'and the answer says the block is NOT in effect' 'yes' \ + "$(admin -X POST -H 'Content-Type: application/json' -d '{"ip":"203.0.113.184"}' "$EDGE/admin-api/blocks" \ + | jval error | grep -qi 'NOT in effect' && echo yes || echo no)" +check 'and it is not the 400 a validation error would use' 'yes' \ + "$([ "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \ + -d '{"ip":"203.0.113.185"}' "$EDGE/admin-api/blocks")" != "400" ] && echo yes || echo no)" +check 'a policy change the storage refused is not reported as applied' '503' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT -H 'Content-Type: application/json' \ + -d '{"streakThreshold":7}' "$EDGE/admin-api/policy")" +check 'and the answer says the change is NOT in effect' 'yes' \ + "$(admin -X PUT -H 'Content-Type: application/json' -d '{"streakThreshold":7}' "$EDGE/admin-api/policy" \ + | jval error | grep -qi 'NOT in effect' && echo yes || echo no)" +OPEN26_POLICY_AFTER=$(admin "$EDGE/admin-api/policy" | jval streakThreshold) +printf ' info the policy after the refused write: streakThreshold=%s (asked for 7)\n' "${OPEN26_POLICY_AFTER:-none}" +check 'the policy the edge is actually running did not move' "$OPEN26_POLICY" "$OPEN26_POLICY_AFTER" +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +for r in list(c.execute("SELECT name FROM sqlite_master WHERE type='trigger' AND name LIKE 'gate_open26_%'")): + c.execute(f'DROP TRIGGER "{r[0]}"') +print("triggers after cleanup:", c.execute("SELECT count(*) FROM sqlite_master WHERE type='trigger'").fetchone()[0]) +PYSQL +check 'with the write path healthy the same delete answers 200 with what it deleted' '2' \ + "$(admin -X DELETE "$EDGE/admin-api/blocks?source=operator" | jval deleted)" +check 'and the operator table really is empty now' '0' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['source']=='operator'")" +OPEN26_EMPTY=$(admin -w '\n%{http_code}' -X DELETE "$EDGE/admin-api/blocks?source=operator") +OPEN26_EMPTY_CODE=${OPEN26_EMPTY##*$'\n'} +check 'an empty list is still a 200 with a zero, not a failure' '200 {"deleted":0}' \ + "${OPEN26_EMPTY_CODE} ${OPEN26_EMPTY%$'\n'*}" +# The double-click case, with nothing broken: six POSTs of one address used to +# answer 204 204 400 400 400 400, four of them blaming an operator whose block +# was in fact in force. All six have to land, and they have to land as one row. +OPEN26_RACE=203.0.113.186 +for _ in 1 2 3 4 5 6; do + ( admin -o /dev/null -w '%{http_code}\n' -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$OPEN26_RACE\"}" "$EDGE/admin-api/blocks" >> /tmp/open26_race.codes ) & +done +wait +OPEN26_CODES=$(tr -d '\r' < /tmp/open26_race.codes | tr '\n' ' ' | sed 's/[[:space:]]*$//') +rm -f /tmp/open26_race.codes +printf ' info six parallel POSTs of one address answered: %s\n' "$OPEN26_CODES" +check 'every one of the six parallel writes landed' '204 204 204 204 204 204' "$OPEN26_CODES" +check 'and they landed as one row, not six' '1' \ + "$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['sourceKey']=='$OPEN26_RACE'")" +admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$OPEN26_RACE" >/dev/null +echo '- readiness notices a block table that is not there' +# AC4 of this ticket, on the image rather than in TestServer. The read side of +# the block list used to be checked with CanConnectAsync — that a file opens — +# and /readyz answered 200 while every operator command against the block table +# was failing. In-process StorageFailureHonestyTests.Readyz_notices_a_block_table_that_is_not_there +# has covered the fix since then; the shipped image had never been asked. +# Renamed rather than dropped, so the scene can put it back and the run ends the +# way it started. +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +c.execute('ALTER TABLE "block_entries" RENAME TO "block_entries_hidden"') +print("renamed; tables:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'block%'")]) +PYSQL +OPEN26_READY='' +OPEN26_SNAP_FAILS=0 +OPEN26_WHY='' +for _ in $(seq 1 12); do + code "$EDGE/no-such-page" >/dev/null + OPEN26_SNAP_FAILS=$(admin "$EDGE/admin-api/state" | jval snapshotRefreshFailures) + OPEN26_WHY=$(admin "$EDGE/admin-api/state" | jval snapshotLastRefreshError) + OPEN26_READY=$(code "$EDGE/readyz") + [ "${OPEN26_SNAP_FAILS:-0}" != "0" ] && [ "$OPEN26_READY" = "503" ] && break + sleep 3 +done +printf ' info with the block table gone: readyz %s, snapshot refresh failures %s, reason: %s\n' \ + "${OPEN26_READY:-none}" "${OPEN26_SNAP_FAILS:-?}" "${OPEN26_WHY:-(none)}" +check 'readiness stops saying ready when the block table is not there' '503' "${OPEN26_READY:-000}" +check 'and the state counts the snapshot that could not be built' 'yes' \ + "$([ "${OPEN26_SNAP_FAILS:-0}" != "0" ] && echo yes || echo no)" +check 'the reason it quotes names the table' 'yes' \ + "$(printf '%s' "$OPEN26_WHY" | grep -qi 'block_entries' && echo yes || echo no)" +# Which guard answered 503 is the whole question, and the status code does not +# say it. Renaming the table breaks the snapshot build too, so readiness has two +# reasons to refuse at this instant — the block-table read it makes itself, and +# the pillar that stopped refreshing. Measured: with the read put back to +# CanConnectAsync this scene still answered 207 passed / 0 failed, because the +# snapshot guard caught the same table under it and the 503 looked identical +# (/tmp/c26_mutM2_compose.log). The body is what tells them apart: the block read +# answers with the storage error alone, the pillar answers with its own sentence. +OPEN26_READY_WHY=$(curl -s -m 10 "$EDGE/readyz" | tr '\n' ' ') +printf ' info what readiness itself answers: %s\n' "${OPEN26_READY_WHY:0:180}" +check 'the refusal is the block-table read, not a pillar that aged' 'yes' \ + "$(printf '%s' "$OPEN26_READY_WHY" | grep -qi 'no such table: block_entries' \ + && ! printf '%s' "$OPEN26_READY_WHY" | grep -qiE 'snapshot has not refreshed|policy has not been re-read' \ + && echo yes || echo no)" +check 'and the policy read is not the one being blamed here' '0' \ + "$(admin "$EDGE/admin-api/state" | jval policyReloadFailures)" +check 'the block listing says it is broken instead of answering with a list' '500' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks")" +sidecar <<'PYSQL' +import sqlite3 +c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None) +c.execute('ALTER TABLE "block_entries_hidden" RENAME TO "block_entries"') +print("restored; tables:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'block%'")]) +PYSQL +OPEN26_READY_BACK='000' +for _ in $(seq 1 12); do + code "$EDGE/no-such-page" >/dev/null + OPEN26_READY_BACK=$(code "$EDGE/readyz") + [ "$OPEN26_READY_BACK" = "200" ] && break + sleep 3 +done +check 'putting the table back brings readiness back' '200' "$OPEN26_READY_BACK" +check 'and the listing answers again' '200' \ + "$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks")" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index a94431d..632403d 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -457,6 +457,99 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); 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