Files
Pavlo Ratushnyi 925fc62d4b
ci / lint the workflow and the shell (push) Successful in 8s
ci / build, test, smoke (push) Successful in 1m45s
ci / the operator page in a real browser (push) Successful in 2m12s
ci / the same smoke on an image with no base (push) Successful in 4m20s
ci / build the image and smoke it (push) Successful in 4m20s
the gate's claim about its own writes was false, and the gate now counts it
a8f440b wrote that the gate's admin writes go through `admin_write`. Measured
against the same file an hour later: of its 60 writes that do not go through
`admin`, 34 did — 25 still answered through the un-retried `code` and one went
straight to `curl`. The other 91 writes and 157 reads went through `admin`, which
carried no part of OPEN-39's rule at all: a read that reached nothing answered
NO_JSON_BODY and the log said nothing about why, because the sentinel names the
missing body, not the missing request. The dead-edge scene asserted the opposite
of the fix — that those dead reads write no line to stderr — so the gate was not
only un-instrumented there, it was guarding the missing instrument.

Call sites, counted on this file with comment lines excluded: 261 `admin` (91
writes, 157 reads, 8 carrying -D/-o/-w), 59 `admin_write`, 139 `code`.

What changed:

  * `curl_retry` puts OPEN-39's rule under the body-returning helpers. A transport
    failure is retried three times and each retry prints the container it sampled;
    an HTTP answer — 400, 403, 500 — is an answer and comes back after one attempt.
    `admin` and a new `body`, for the scenes that carry their own token, sit on it.
  * the body comes back byte for byte. `$(curl ...)` strips trailing newlines and
    the six-parallel-POSTs scene writes six `%{http_code}` lines into one shared
    file; a wrapper that re-printed carelessly would have turned that assertion
    into "204204204204204204". The exit status rides in on a marker suffix instead
    of riding on the output.
  * the 25 and the 1 joined `admin_write`.
  * the dead-edge assertion asks for the nine diagnosis lines and for the absence
    of a traceback instead of for silence. It also carried the bug that hid the gap
    for one run: `a | b 2>f` captures only b's stderr, so the first version read
    back an empty file while the nine lines went to the terminal.
  * the claim is now a gate: the file greps its own source and goes red, printing
    the count, if any write answers through the un-retried status helper or goes
    straight to curl — and fails closed when it cannot read itself.

Three assertions added, one removed: 375 -> 379.

Measured. compose-smoke 379 passed / 0 failed at load average 12 (21:07,
/tmp/compose-retry2.log); that run is one comment rewrap away from this text, and
the two self-audit greps were re-run against the committed file and answer 0 and 0.
readme-counts agrees against that run's totals (379=379, exit 0). shellcheck 0.11.0
and bash -n clean. The retry was again proved against a stub rather than a caught
flake: unreachable twice then a body -> two diagnosis lines and the body's trailing
newline intact (xxd: 610a 620a); always unreachable -> three lines and an empty
body; a 400 -> none; a body ending in `x` -> returned unchanged.

Not measured green: this text against the scratch image. The shared host has held
load average 26-72 since 21:10 and four runs of this tree went red on it — 375/4
at load 31, 377/2 at load 39, 378/1 at load 48 — with every failure in a scene that
reads a projection right after a write that was answered: the two alert-escalation
scenes, and once "the shipped story names the block, the covering range and the
exemption, oldest first" in a run where both alert scenes were green. No `000` near
any of them, and the same tree at load 10-12 was 379/0. That is OPEN-78, filed
today; the README's Gates section now carries those red numbers instead of a green
one it does not have.
2026-10-06 21:49:08 +02:00

2453 lines
157 KiB
Bash
Executable File

#!/usr/bin/env bash
# End-to-end smoke test against the *deployed image*, not the source tree.
#
# scripts/smoke.sh proves the binary. This proves the ship shape: the chiseled
# image starts, its HEALTHCHECK reports healthy, and the four pillars behave
# over a real socket with a real upstream (nginx) behind them — streak ban,
# per-source isolation, operator block, allowlist precedence, country deny.
#
# Sources are simulated with X-Forwarded-For and TrustProxyHeaders turned on
# through the admin API, which is the only way to exercise "this source is
# banned, that one is not" from one client, and doubles as a check that the
# admin policy write lands on the wire rather than only in the API.
#
# Usage: OPENWAF_ADMIN_TOKEN=... scripts/compose-smoke.sh
# KEEP_UP=1 ... to leave the stack running afterwards.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT" || exit 1
: "${OPENWAF_ADMIN_TOKEN:?set OPENWAF_ADMIN_TOKEN before running, or run scripts/ci-gates.sh compose-smoke (it defaults a throwaway for the stack it starts itself)}"
export OPENWAF_ADMIN_TOKEN
# The second token (OPEN-62), for the section that is about it. A throwaway like
# the admin one. Unset would be the shipped default and would make every
# assertion below about a level that does not exist, so the gate asks for one.
export OPENWAF_READ_ONLY_TOKEN="${OPENWAF_READ_ONLY_TOKEN:-ci-only-throwaway-readonly}"
EDGE=${EDGE:-http://127.0.0.1:8080}
SCANNER=203.0.113.66
BYSTANDER=198.51.100.99
OFFICE=198.51.100.7
GEO_IP=${GEO_IP:-8.8.8.8}
PASS=0; FAIL=0
check() {
if [ "$2" = "$3" ]; then PASS=$((PASS+1)); printf ' ok %-54s %s\n' "$1" "$3"
else FAIL=$((FAIL+1)); printf ' FAIL %-54s expected %s, got %s\n' "$1" "$2" "$3"; fi
}
# The body-returning half of the gate's instruments. `code` asks curl for the
# status and throws the body away; `admin` and `body` keep the bytes, and until
# now neither of them carried OPEN-39's rule at all. Measured on this file before
# the change: of its 60 writes that answer with a status code, 34 went through
# `admin_write`, 25 answered through the un-retried `code` and one went straight
# to curl; and 91 writes plus 157 reads went through `admin`, which printed
# nothing at all when the request never reached the stack. So a read that hit nothing answered NO_JSON_BODY and the log
# said nothing about why — the sentinel names the missing body, not the missing
# request. Same rule as `admin_write`, one place: a transport failure is retried
# three times and each retry prints the container's own state; an HTTP answer —
# 400, 403, 500 — is an answer and comes back after one attempt.
#
# The trailing bytes are preserved on purpose. `$(curl …)` strips trailing
# newlines, and one caller writes six `%{http_code}\n` lines into one shared file
# from six parallel POSTs; a helper that re-printed the body without its newline
# would turn that assertion into "204204204204204204". So the exit status rides
# in on a marker suffix and the body is handed back byte for byte.
curl_retry() {
local n=0 out rc
while :; do
out=$(curl -s -m 10 "$@"; printf 'x%s' "$?")
rc=${out##*x}
out=${out%x*}
if [ "$rc" = 0 ] || [ "$n" -ge 3 ]; then break; fi
n=$((n + 1))
printf ' info the request reached nothing: attempt %s of 4 (curl exit %s), the edge reports %s\n' \
"$n" "$rc" "$(edge_state)" >&2
sleep 2
done
printf '%s' "$out"
}
admin() { curl_retry -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; }
# The same read/write with no token of the gate's own, for the scenes that carry
# their own (the read-only token, the capability export).
body() { curl_retry "$@"; }
# jcount/jget evaluate a python expression over the JSON on stdin. `b`/`o` is
# the list, and the predicate is written once here instead of being re-sedged
# per assertion — sed over JSON silently returns the first match of anything.
#
# Three states, three answers — the rule OPEN-48 wrote for jval, which these two
# never received. Measured in the NativeAOT measurement run of 2026-10-06
# (/tmp/aot-smoke.log, the tree that became d08ec30), which is what a run against
# an edge that dies at startup looks like: 125 Python tracebacks and 32 `integer
# expression expected` shell errors, every one of them one of these two helpers
# handed a body that was not there. jcount now answers -1 — the sentinel
# streaks_where has used since it was written, a number that can never be a real
# count — and jget answers the same NO_JSON_BODY jval prints. A count read off a
# failed answer is still a wrong number; what it is no longer is indistinguishable
# from an empty one, and it no longer reaches `[ -ge ]` as one.
jcount() { python3 -c "import json,sys
try:
d=json.load(sys.stdin); print(sum(1 for b in d if $1))
except Exception:
print(-1)"; }
jget() { python3 -c "import json,sys
try:
d=json.load(sys.stdin)
except Exception:
print('NO_JSON_BODY'); raise SystemExit(0)
for o in d:
if $1: print(o.get('$2') or ''); break"; }
# /admin-api/streaks answers with an OBJECT that wraps the list, so a predicate
# written for jcount walks the object's keys instead and compares strings to
# dicts. streaks_where runs the predicate over the wrapped list and answers -1
# for a body it cannot parse, so a broken fetch shows up as a wrong number
# rather than as a python traceback in the middle of the gate.
streaks_where() { python3 -c "import json,sys
try:
d=json.load(sys.stdin); print(sum(1 for b in d['streaks'] if $1))
except Exception:
print(-1)"; }
# Fetched with polling, not sampled once: the first attempt right after a burst
# has been measured answering a completely empty body while the next answered
# complete, and an assertion on one instant is not a contract.
streaks_fetch() {
STREAKS_JSON=''
for _ in $(seq 1 6); do
STREAKS_JSON=$(admin "$EDGE/admin-api/streaks?limit=1000")
[ -n "$STREAKS_JSON" ] && break
sleep 2
done
}
# Lines reach the daemon's log store a moment after the /state field they belong
# to is updated — measured on the shipped image: the grep run immediately after
# the burst answered 0 and the same grep two seconds later answered 3. So the
# log assertions poll, and print the count they saw, instead of sampling one
# instant and calling it a contract.
log_count() { docker compose logs edge 2>/dev/null | grep -ci "$1" || true; }
log_wait_for() {
n=0
for _ in $(seq 1 10); do
n=$(log_count "$1")
[ "${n:-0}" != 0 ] && break
sleep 2
done
printf '%s' "${n:-0}"
}
streaks_info() {
printf ' info the live streak map: %s tracked, %s standing\n' \
"$(printf '%s' "$STREAKS_JSON" | jval trackedSources)" \
"$(printf '%s' "$STREAKS_JSON" | jval standingStreaks)"
}
# OPEN-39: curl's 000 is not an answer from the edge, it is the gate failing to
# reach it — and the gate used to print it as if it were a product answer.
# Measured on Linux: `geo off restores the country` read 000 once and the log
# said nothing about whether the container had died or was merely slow. Those are
# different news and they lead to different fixes, so every 000 now samples the
# container the request was aimed at and prints what it found. On stderr, so the
# diagnosis cannot leak into the value an assertion is comparing.
DEAD_LOG=$(mktemp "${TMPDIR:-/tmp}/openwaf-dead-codes.XXXXXX")
edge_state() {
local cid
# -a, not the default: `compose ps` hides a stopped service, and "the container
# is not in the listing" is the wrong thing to print about an edge that exists
# and has exited — naming that difference is the whole reason this helper
# exists (OPEN-39).
cid=$(docker compose ps -aq edge 2>/dev/null)
if [ -z "$cid" ]; then printf 'no-container'; return; fi
printf '%s/%s' \
"$(docker inspect -f '{{.State.Status}}' "$cid" 2>/dev/null)" \
"$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}no-healthcheck{{end}}' "$cid" 2>/dev/null)"
}
code() {
local http_code
http_code=$(curl -s -m 10 -o /dev/null -w '%{http_code}' "$@")
if [ "$http_code" = 000 ]; then
# A file, not a shell variable: every caller reaches this through
# `$(code …)`, which is a subshell, so a counter incremented here is gone
# before the assertion that wants to read it. Measured in the first run of
# this scene: the diagnosis printed, the count stayed zero, and the count's
# assertion went red on the line directly under the proof it worked.
printf '000\t%s\n' "$*" >> "$DEAD_LOG"
printf ' info curl answered 000 for %s; the edge container reports %s\n' "$*" "$(edge_state)" >&2
fi
printf '%s' "$http_code"
}
dead_codes() { wc -l < "$DEAD_LOG" | tr -d ' '; }
# An admin write, differing from `code` in exactly one case. A 000 is the gate
# failing to reach the stack, not an answer from the edge (OPEN-39) — and for a
# write that is worse than a wrong number, because every assertion after it
# measures a scene that never happened. Measured 2026-10-06 (/tmp/compose-diag.log,
# recorded in the README): one POST of a /29 answered 000 while the container
# reported running/healthy — another project's dotnet suite was running on the
# same daemon — and four range assertions went red about a row that was never
# written. So the write is retried, three times, and every retry is printed.
# Retrying a write that got no response is safe on this surface because every
# write it takes is keyed and idempotent: the six-parallel-POSTs scene asserts
# that one address lands as one row, and the transfer scene asserts that
# importing the same document twice adds nothing. A refusal is an answer, so 400
# and 403 come back untouched; only the non-answer is retried.
admin_write() {
local n=0 out
out=$(code "$@")
while [ "$out" = 000 ] && [ "$n" -lt 3 ]; do
n=$((n + 1))
printf ' info the write reached nothing: attempt %s of 4, the edge reports %s\n' \
"$n" "$(edge_state)" >&2
sleep 2
out=$(code "$@")
done
printf '%s' "$out"
}
hdr() { curl -s -m 10 -D - -o /dev/null "$@" | tr -d '\r'; }
xff() { printf 'X-Forwarded-For: %s' "$1"; }
# One scalar field out of a JSON object, for the endpoints that answer with an
# object rather than a list (jcount/jget read lists).
# Booleans are printed as JSON spells them (json.dumps), not as Python spells
# them: the first version of this helper answered `True` and the assertion
# against a JSON `true` failed on the spelling, not on the product.
# Three states, three answers. The first version of this helper piped the body
# straight into json.load, so a request that produced no body at all — a refused
# connection, a container that had just died — printed a Python traceback into the
# middle of an assertion and the assertion compared an empty string (OPEN-48). That
# is the same defect this file keeps naming elsewhere: a gate that answers like a
# measurement when it is really reporting its own failure. So: no body prints
# NO_JSON_BODY, a field the object does not carry prints the empty string, and a
# field that is there prints its value. A wrong assertion still fails, but it fails
# with a value a reader can tell apart from "the field is missing".
jval() { python3 -c "import json,sys
s=sys.stdin.read().strip()
if not s:
print('NO_JSON_BODY'); raise SystemExit(0)
try:
d=json.loads(s)
except ValueError:
print('NO_JSON_BODY'); raise SystemExit(0)
v=d.get('$1')
print('' if v is None else (json.dumps(v) if isinstance(v,(bool,int,float)) else v))"; }
# A count the edge actually answered is a run of digits. The three helpers above
# answer NO_JSON_BODY, -1 or the empty string when it answered nothing, and
# handing any of those to `[ -ge ]` makes the shell complain rather than the
# assertion fail: `[: NO_JSON_BODY: integer expression expected`, ten times in
# the ten-iteration poll of the ban-pillar scene, in the run named above. A
# comparison is the assertion, so it has to be able to lose quietly.
is_count() { case $1 in (''|*[!0-9]*) return 1 ;; (*) return 0 ;; esac; }
count_ge() { is_count "$1" && [ "$1" -ge "$2" ]; }
count_gt() { is_count "$1" && is_count "$2" && [ "$1" -gt "$2" ]; }
# `!= 0` was the shape these scenes used, and it is the dangerous one: a body
# that was never read is not the string "0", so the loop stopped early and the
# assertion that followed reported the counter as moved. It did not move. It was
# not read.
count_moved() { is_count "$1" && [ "$1" != 0 ]; }
count_sub() { if is_count "$1" && is_count "$2"; then printf '%s' "$(( $1 - $2 ))"; else printf '%s' -1; fi; }
# Alerts are counted as a delta (see the alert sections): the data volume
# survives `compose down`, so an absolute count would be history, not this run.
# jcount's loop variable is `b` (jget's is `o`) — the two helpers read the same
# JSON with different names, and mixing them up is a NameError inside an
# assertion, which is exactly the kind of gate that reports nothing.
alerts_for() { admin "$EDGE/admin-api/alerts?limit=500" | jcount "b['kind']=='$1' and b['sourceKey']=='$2'"; }
# Read the alert rows for a source once they have stopped moving. The alert is
# written after the response is, so a count taken the instant the last request
# returns undercounts — and a fixed pause is a coin toss on a loaded host: the
# same tree read 3 rows on one run and 1 on the next, and the assertion that
# follows is about a settled number either way. Three equal reads in a row is the
# definition of settled here, with a bounded wait so a queue that never settles
# fails the gate rather than hiding.
settle_alerts() {
local prev=-1 stable=0 now
for _ in $(seq 1 24); do
now=$(alerts_for "$1" "$2")
if [ "$now" = "$prev" ]; then
stable=$((stable + 1))
[ "$stable" -ge 3 ] && { printf '%s' "$now"; return; }
else
stable=0; prev=$now
fi
sleep 0.5
done
printf '%s' "${prev:-0}"
}
cleanup() {
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","geo":"Off","streakThreshold":10,"trustProxyHeaders":false}' "$EDGE/admin-api/policy" >/dev/null
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
[ "${KEEP_UP:-0}" = 1 ] || docker compose down >/dev/null 2>&1
rm -f "$DEAD_LOG"
}
trap cleanup EXIT
echo '- starting the stack'
# What compose said has to reach the log. `compose up failed` with the output
# thrown away is the gate going blind at the one moment that decides whether the
# rest of the run means anything — the same complaint OPEN-39 records about a
# later assertion. Measured: on the Gitea runner this step failed after 5s and
# the job log carried the words `compose up failed` and nothing else.
UP_LOG=$(mktemp "${TMPDIR:-/tmp}/openwaf-compose-up.XXXXXX")
if ! docker compose up -d --build >"$UP_LOG" 2>&1; then
echo 'compose up failed — what compose said:'
cat "$UP_LOG"
exit 1
fi
rm -f "$UP_LOG"
for _ in $(seq 1 120); do curl -fsS "$EDGE/healthz" >/dev/null 2>&1 && break; sleep 0.5; done
CID=$(docker compose ps -q edge)
# The same three states edge_state gives a stopped container: an empty id is not
# a container whose health can be asked about. In the NativeAOT measurement run
# of 2026-10-06 this loop asked `docker inspect ""` once per half-second of the
# wait, and the log carried `invalid container name or ID: value is empty` 121
# times — the gate's own absent container, reported as a docker usage error.
health_of() {
if [ -z "${CID:-}" ]; then printf 'no-container'; return; fi
docker inspect --format '{{.State.Health.Status}}' "$CID" 2>/dev/null \
|| printf 'uninspectable'
}
# The image's own HEALTHCHECK is the probe (a chiseled base has no shell), so
# this waits for it rather than for the port: the port answers long before the
# first check has run.
for _ in $(seq 1 120); do
[ "$(health_of)" = healthy ] && break
sleep 0.5
done
check 'image HEALTHCHECK reports healthy' 'healthy' "$(health_of)"
check 'healthz says ok' 'ok' "$(curl -s "$EDGE/healthz" | sed -n 's/.*"status":"\([^"]*\)".*/\1/p')"
check 'geo database is loaded' 'true' "$(curl -s "$EDGE/healthz" | sed -n 's/.*"geoLoaded":\([^,]*\).*/\1/p')"
check 'healthz names the geo database' 'yes' "$(curl -s "$EDGE/healthz" | grep -q '"geoDatabase":"DBIP' && echo yes || echo no)"
# The console's geo pill is behavioural coverage of this endpoint; this is the
# contract itself, so a change to the field names or to what "loaded" means fails
# here rather than only as a missing pill on a page.
check 'the geo endpoint says a database is loaded' 'true' "$(admin "$EDGE/admin-api/geo" | jval loaded)"
check 'the geo endpoint names what it loaded' 'DBIP-Country-Lite' "$(admin "$EDGE/admin-api/geo" | jval database)"
check 'the geo endpoint reports an age in days' 'yes' "$(admin "$EDGE/admin-api/geo" | python3 -c 'import json,sys
a=json.load(sys.stdin)
print("yes" if isinstance(a.get("ageDays"), (int,float)) and a["ageDays"] >= 0 else "no")')"
# The geo pin is a build ARG, and this compose file mounts a named volume at
# /app/geoip that Docker seeds from the image only when the volume is first
# created. So a rebuilt image can be running last month's database and every
# geo assertion below still passes — the policy is enforced on a database nobody
# chose. Compare what the container loaded with what the Dockerfile asked for.
# The month prefix is enough because dbip stamps the release with the 1st of its
# own month (observed: 2026-09-01T01:32:45 and 2026-10-01). If that ever changes,
# this assertion goes red first, which is the safer direction for a gate.
PINNED=$(awk -F= '/^ARG DBIP_VERSION=/{print $2; exit}' Dockerfile)
BUILT=$(curl -s "$EDGE/healthz" | sed -n 's/.*"geoBuiltAt":"\([0-9]\{4\}-[0-9]\{2\}\)[^"]*".*/\1/p')
if [ -n "$BUILT" ] && [ "$BUILT" = "$PINNED" ]; then
PASS=$((PASS+1)); printf ' ok %-54s %s\n' 'the loaded geo database is the pinned one' "$BUILT"
else
FAIL=$((FAIL+1))
printf ' FAIL %-54s Dockerfile pins %s, the container loaded %s\n' \
'the loaded geo database is the pinned one' "$PINNED" "${BUILT:-no build date}"
printf ' a named volume is seeded once: docker volume rm %s\n' \
"$(docker compose config --name 2>/dev/null || basename "$PWD")_openwaf-geoip"
fi
check 'admin api rejects no token' '401' "$(code "$EDGE/admin-api/blocks")"
# Start from a known state. Engine bans only — an operator's manual list is
# never touched by this script, and the volume may hold a real deployment's
# rows, so `compose down -v` is deliberately not used here.
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
echo '- admin policy write reaches the wire'
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","geo":"Off","streakThreshold":3,"banDurationMinutes":60,"trustProxyHeaders":true}' \
"$EDGE/admin-api/policy" >/dev/null
check 'mode is Enforce on the wire' 'Enforce' "$(curl -s "$EDGE/healthz" | sed -n 's/.*"mode":"\([^"]*\)".*/\1/p')"
echo '- streak ban (N=3)'
for i in 1 2 3; do
check "probe $i from the scanner reaches the upstream" '404' "$(code -H "$(xff "$SCANNER")" "$EDGE/wp-login.php")"
done
now_ms() { python3 -c 'import time;print(int(time.time()*1000))'; }
t0=$(now_ms); lag=0; c=''
for _ in $(seq 1 40); do
c=$(code -H "$(xff "$SCANNER")" "$EDGE/xmlrpc.php")
[ "$c" = 403 ] && break
lag=$(( $(now_ms) - t0 ))
sleep 0.25
done
check 'the scanner is now banned' '403' "$c"
check 'a bystander is unaffected' '404' "$(code -H "$(xff "$BYSTANDER")" "$EDGE/wp-login.php")"
check 'ban carries Retry-After' 'yes' "$(hdr -H "$(xff "$SCANNER")" "$EDGE/xmlrpc.php" | grep -qi '^retry-after:' && echo yes || echo no)"
check 'ban names its reason' 'yes' "$(curl -s -H "$(xff "$SCANNER")" "$EDGE/xmlrpc.php" | grep -q 'consecutive refusals' && echo yes || echo no)"
check 'engine ban is listed for the scanner' '1' "$(admin "$EDGE/admin-api/blocks" | jcount "b['sourceKey']=='$SCANNER'")"
# /admin-api/state is what the console's summary line reads, and until now no
# gate called it at all: the page could have been reporting a mode the edge is
# not in, or a TTL nobody configured. Asserted at the moment the ban above
# exists, so the numbers have a known value rather than "some number".
check 'state names the mode in force' 'Enforce' "$(admin "$EDGE/admin-api/state" | jval mode)"
check 'state reports the snapshot TTL as configured' '30' "$(admin "$EDGE/admin-api/state" | jval snapshotTtlSeconds)"
check 'state counts the engine ban the streak wrote' '1' "$(admin "$EDGE/admin-api/state" | jval engineBans)"
check 'a banned source still reaches the console' '200' "$(code -H "$(xff "$SCANNER")" "$EDGE/admin")"
check 'the console markup carries no token' 'yes' "$(curl -s "$EDGE/admin" | grep -q "$OPENWAF_ADMIN_TOKEN" && echo no || echo yes)"
check 'the console is html, not a proxy miss' 'text/html' "$(curl -s -o /dev/null -w '%{content_type}' "$EDGE/admin" | cut -d';' -f1)"
printf ' info enforcement lag after the ban was written: %s ms\n' "${lag:-0}"
echo '- clearing only engine bans leaves the operator list alone'
admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$OFFICE\",\"reason\":\"confirmed scraper\",\"redirectTo\":\"https://honeypot.example.org/\"}" \
"$EDGE/admin-api/blocks" >/dev/null
check 'operator block redirects' '301' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")"
check 'redirect target is honoured' 'https://honeypot.example.org/' \
"$(hdr -H "$(xff "$OFFICE")" "$EDGE/any/path" | sed -n 's/^[Ll]ocation: //p')"
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
check 'the scanner passes again once its ban is cleared' '404' "$(code -H "$(xff "$SCANNER")" "$EDGE/xmlrpc.php")"
check 'operator block survives the clear' '301' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")"
echo '- a redirect target the edge cannot send is refused before it is written'
# OPEN-21 measured this on the shipped image: POST with redirectTo
# "http://x.invalid/<CRLF>X-Injected: 1" answered 204, and the next request from
# that address answered 500 with no Location at all — Kestrel refused to write the
# header, so the block became an outage for that visitor. "javascript:alert(1)"
# answered 204 and then 301 with Location: javascript:alert(1). The integration
# suite proves the guard; what is proven here is that the image an operator
# deploys refuses it too, and that a refused write leaves no half-blocked address
# behind — which is the part that matters, because the block list is read by the
# next request, not by this one.
CRLF_SRC=203.0.113.246
JS_SRC=203.0.113.247
check 'a target with a CRLF in it is refused, not stored' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$CRLF_SRC\",\"reason\":\"crlf target\",\"redirectTo\":\"http://x.invalid/\\r\\nX-Injected: 1\"}" \
"$EDGE/admin-api/blocks")"
# The body is captured first and matched without a pipe into grep -q. Under
# `set -o pipefail` — which this script runs with — `curl | grep -q` reports the
# pipeline as failed: grep exits on the first match, curl dies of SIGPIPE, and
# the assertion reads "no" about a body that says exactly what it says. Measured
# in this very scene: the same request answered the right sentence and the
# assertion still went red.
REFUSED_TARGET=$(admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$CRLF_SRC\",\"redirectTo\":\"http://x.invalid/\\r\\nX-Injected: 1\"}" \
"$EDGE/admin-api/blocks")
# Not inside $( ): a case pattern ending in `*)` closes an enclosing command
# substitution, so the first version of this printed the rest of the line as the
# value under test.
names_field=no
case "$REFUSED_TARGET" in
*'redirectTo must be an absolute http(s) URL'*) names_field=yes ;;
esac
check 'and the refusal names the field it refused' 'yes' "$names_field"
check 'a javascript: target is refused too' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$JS_SRC\",\"redirectTo\":\"javascript:alert(1)\"}" "$EDGE/admin-api/blocks")"
check 'a relative target is refused too' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$JS_SRC\",\"redirectTo\":\"not-a-url\"}" "$EDGE/admin-api/blocks")"
check 'neither address was written as a block at all' '0' \
"$(admin "$EDGE/admin-api/blocks?live=false" \
| jcount "b['sourceKey']=='$CRLF_SRC' or b['sourceKey']=='$JS_SRC'")"
check 'and both still reach the upstream, which is what no half-blocked visitor means' '404 404' \
"$(code -H "$(xff "$CRLF_SRC")" "$EDGE/any/path") $(code -H "$(xff "$JS_SRC")" "$EDGE/any/path")"
echo '- allowlist outranks the operator block'
admin -X POST -H 'Content-Type: application/json' -d "{\"match\":\"$OFFICE\",\"note\":\"smoke\"}" "$EDGE/admin-api/allow" >/dev/null
check 'allowlisted source gets through' '404' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")"
# The exemption listing was the one listing with no ceiling and no liveness.
# Measured on the shipped image: 1101 rows came back in 130,386 bytes with no
# X-Total-Count and no X-Truncated, ?limit=10 / ?offset=1000 / ?limit=0 /
# ?limit=100000 each returned all 1101, and a row whose minute had passed was
# printed as an exemption the edge still honoured (it was not — that address had
# gone back to 301 a minute earlier). The row is not the answer, so the answer
# now travels with it.
check 'the allow listing says how many rows there are' 'yes' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/allow" | grep -qi '^x-total-count:' && echo yes || echo no)"
check 'the allow listing marks the entry live' '1' \
"$(admin "$EDGE/admin-api/allow" | jcount "b['match']=='$OFFICE' and b['live']")"
check 'the allow listing refuses a limit nobody meant' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/allow?limit=0")"
check 'and names the parameter it is refusing' 'limit must be 1..2000; got 0' \
"$(admin "$EDGE/admin-api/allow?limit=0" | jval error)"
ALLOW_ID=$(admin "$EDGE/admin-api/allow" | sed -n 's/.*"id":\([0-9]*\).*/\1/p' | head -1)
admin -X DELETE "$EDGE/admin-api/allow/$ALLOW_ID" >/dev/null
check 'block returns when the allow entry goes' '301' "$(code -H "$(xff "$OFFICE")" "$EDGE/any/path")"
admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null
echo '- server errors alert, and never ban'
# The most important safety property in this project: a broken deploy must not
# lock out the site's own visitors. Until now it was proven only in-process,
# against a fake upstream. deploy/upstream.conf makes the demo upstream answer 502
# on /boom, so the shipped image is what gets tested here.
ERR_SRC=203.0.113.88
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","geo":"Off","streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
# Counted as a delta, not an absolute: the data volume survives `compose down`,
# so an alert from yesterday's run would otherwise satisfy the assertion and the
# gate would be checking history instead of this run.
BEFORE_ERR=$(alerts_for server_error_streak "$ERR_SRC")
last=''
for _ in $(seq 1 12); do last=$(code -H "$(xff "$ERR_SRC")" "$EDGE/boom"); done
check 'a 502 from the upstream reaches the client through the edge' '502' "$last"
check 'twelve 502s did not ban the source that saw them' '404' "$(code -H "$(xff "$ERR_SRC")" "$EDGE/no-such-page")"
check 'and no engine ban was written for it' '0' "$(admin "$EDGE/admin-api/blocks" | jcount "b['sourceKey']=='$ERR_SRC'")"
ACOUNT=0
for _ in $(seq 1 20); do
ACOUNT=$(alerts_for server_error_streak "$ERR_SRC")
count_gt "${ACOUNT:-0}" "${BEFORE_ERR:-0}" && break
sleep 0.5
done
ERR_DELTA=$(count_sub "${ACOUNT:-0}" "${BEFORE_ERR:-0}")
check 'a server_error_streak alert was written for that source' 'yes' "$(count_ge "$ERR_DELTA" 1 && echo yes || echo no)"
# A measurement *and* an assertion. The alert is edge-triggered: it speaks when
# the streak crosses N and then when the count doubles, so twelve 502s at N=3
# cost three rows (at 3, 6 and 12) and not ten. Before this was level-triggered
# the number was one row per response past N, which is attacker-shaped growth:
# a 5xx never bans, so the source is observed on every request, and the alerts
# table grew at request rate for the whole retention window while the operator's
# alert list (newest 100 in the console, limit 500 on the endpoint) filled with
# a single source.
#
# The count is taken after a pause on purpose: the alert is written after the
# response is, so a count read the instant the last request returns undercounts
# — the first version of this line read 1 where the settled number was 2, and a
# number that is wrong by a race is worse than no number.
ERR_SETTLED=$(settle_alerts server_error_streak "$ERR_SRC")
ERR_ROWS=$(count_sub "${ERR_SETTLED:-0}" "${BEFORE_ERR:-0}")
printf ' info alert rows for 12 server errors at N=3: %s (expected 3: the crossing, then the doublings)\n' "$ERR_ROWS"
check 'a 5xx storm alerts per escalation, not per request' '3' "$ERR_ROWS"
echo '- Observe mode records the decision and blocks nothing'
# The claim is that a dry run is *judgeable*: without the alert there is nothing
# to judge, and without the missing ban there is nothing safe about the dry run.
OBS_SRC=203.0.113.120
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Observe","geo":"Off","streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
BEFORE_OBS=$(alerts_for candidate_ban "$OBS_SRC")
for _ in $(seq 1 10); do code -H "$(xff "$OBS_SRC")" "$EDGE/no-such-page" >/dev/null; done
check 'ten refusals in Observe mode still reach the upstream' '404' "$(code -H "$(xff "$OBS_SRC")" "$EDGE/no-such-page")"
check 'and no engine ban was written in Observe mode' '0' "$(admin "$EDGE/admin-api/blocks" | jcount "b['sourceKey']=='$OBS_SRC'")"
OBS_ALERT=no
for _ in $(seq 1 20); do
count_gt "$(alerts_for candidate_ban "$OBS_SRC")" "${BEFORE_OBS:-0}" && OBS_ALERT=yes && break
sleep 0.5
done
check 'the dry run is visible as a candidate_ban alert' 'yes' "$OBS_ALERT"
# Same edge-triggered rule on the other alert kind, and the one that matters
# more: Observe mode blocks nothing, so every refusal from that source is
# observed and the threshold stays "triggered" on all eight past N. A dry run
# that writes a row per request is the safest mode doubling as a way to grow the
# operator's tables.
OBS_ROWS=$(count_sub "$(settle_alerts candidate_ban "$OBS_SRC")" "${BEFORE_OBS:-0}")
printf ' info candidate_ban rows for 10 refusals at N=3: %s (expected 2: at 3 and at 6)\n' "$OBS_ROWS"
check 'a dry run announces a candidate ban per escalation, not per request' '2' "$OBS_ROWS"
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","geo":"Off","streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
echo '- country deny list'
check 'the geo source reaches the upstream while geo is off' '404' "$(code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page")"
# The observation stream is deliberately coalesced (one durable upsert per
# source per ObservationWriteInterval), so the evidence appears on a timer, not
# on the request. Wait for it instead of assuming a second is enough.
for _ in $(seq 1 40); do
COUNTRY=$(admin "$EDGE/admin-api/observations?limit=200" | jget "o['sourceKey']=='$GEO_IP'" lastCountryCode)
[ -n "${COUNTRY:-}" ] && break
sleep 0.5
done
printf ' info %s resolves to %s in the bundled database\n' "$GEO_IP" "${COUNTRY:-unknown}"
if [ -n "${COUNTRY:-}" ]; then
admin -X PUT "$EDGE/admin-api/countries/$COUNTRY?allowed=false" >/dev/null
admin -X PUT -H 'Content-Type: application/json' -d '{"geo":"DenyList"}' "$EDGE/admin-api/policy" >/dev/null
check "a denied country is refused" '451' "$(code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page")"
check 'another source still passes' '404' "$(code -H "$(xff "$BYSTANDER")" "$EDGE/wp-login.php")"
admin -X PUT "$EDGE/admin-api/countries/$COUNTRY?allowed=true" >/dev/null
admin -X PUT -H 'Content-Type: application/json' -d '{"geo":"Off"}' "$EDGE/admin-api/policy" >/dev/null
check 'geo off restores the country' '404' "$(code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page")"
else
FAIL=$((FAIL+1)); printf ' FAIL %-54s no country resolved for %s\n' 'geo pillar' "$GEO_IP"
fi
echo '- a filter nobody implemented is refused, and the one that is filters'
# Measured on the shipped image before this scene existed: with 16 recorded
# sources, GET /admin-api/observations?source=203.0.113.11 answered 200 with all
# 16 rows over 16 different addresses and X-Total-Count: 16. The filter was not
# applied and not refused — it was absent, because minimal APIs bind the
# parameters a handler declares and drop the rest. ?src= did the same. An
# operator investigating one address was handed fifteen other addresses and a
# total that matched those fifteen.
code -H "$(xff 203.0.113.250)" "$EDGE/filter-me" >/dev/null
FILTER_ROWS=0
for _ in $(seq 1 12); do
FILTER_ROWS=$(admin "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" \
| jcount "b['sourceKey']=='203.0.113.250'")
count_moved "${FILTER_ROWS:-0}" && break
sleep 3
done
printf ' info rows the source filter returns for a source this run just created: %s\n' "$FILTER_ROWS"
check 'the source filter returns the source it was asked for' '1' "$FILTER_ROWS"
check 'and no other source' '0' \
"$(admin "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" | jcount "b['sourceKey']!='203.0.113.250'")"
check 'the total counts the filtered set, not the table' 'X-Total-Count: 1' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1000&source=203.0.113.250" \
| grep -i '^x-total-count:' | tr -d '\r')"
check 'a parameter this endpoint has never heard of is refused, by name' 'yes' \
"$(admin "$EDGE/admin-api/observations?limit=1000&zzz=1" | grep -qi "unknown query parameter 'zzz'" && echo yes || echo no)"
check 'and so is a near miss of the parameter that does work' 'yes' \
"$(admin "$EDGE/admin-api/observations?limit=1000&src=203.0.113.250" | grep -qi "unknown query parameter 'src'" && echo yes || echo no)"
check 'the alert listing refuses it the same way' 'yes' \
"$(admin "$EDGE/admin-api/alerts?limit=1000&zzz=1" | grep -qi "unknown query parameter 'zzz'" && echo yes || echo no)"
# The live streak map is the other per-source listing the console shows, and it
# had the same hole: ?source= was a parameter it had never heard of, so it was
# dropped and the answer kept its shape. The source this scene just created has
# one standing refusal, so it is in the map — and the filtered answer has to
# count one standing streak while still naming the whole map size next to it.
check 'the streak map answers the same source filter, and only that source' '1' \
"$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | streaks_where "b['sourceKey']=='203.0.113.250'")"
check 'and it leaves every other standing source out' '0' \
"$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | streaks_where "b['sourceKey']!='203.0.113.250'")"
check 'its standing count is the FILTERED count while the map size stays the map size' 'yes' \
"$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | python3 -c "import json,sys
try:
d=json.load(sys.stdin)
print('yes' if d['standingStreaks']==1 and d['sourceFilter']=='203.0.113.250'
and d['trackedSources']>=2 and len(d['streaks'])==1 else 'no')
except Exception:
print('no')")"
check 'an unfiltered streak answer names no filter at all' 'yes' \
"$(admin "$EDGE/admin-api/streaks?limit=1000" | python3 -c "import json,sys
d=json.load(sys.stdin); print('yes' if d.get('sourceFilter') is None else 'no')")"
check 'an empty source is refused there too, not read as every source' 'yes' \
"$(admin "$EDGE/admin-api/streaks?limit=1000&source=" | grep -qi 'source must not be empty' && echo yes || echo no)"
check 'and a near miss on the streak endpoint is refused by name' 'yes' \
"$(admin "$EDGE/admin-api/streaks?limit=1000&src=203.0.113.250" | grep -qi "unknown query parameter 'src'" && echo yes || echo no)"
# The guard is only worth having if it never fires on a parameter the endpoint
# really does honour — the console calls this one with live/source/limit every
# page load, and a refusal there would be a worse bug than the one prevented.
check 'while the parameters the endpoint really does honour still work' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?live=false&source=engine&limit=500")"
echo '- a write refuses a parameter it never implemented, before it changes anything'
# The query guard landed on the read endpoints first, and the image that carried
# it then answered the same request two ways depending on the verb. Measured on
# that image: POST /admin-api/blocks?zzz=1 answered 204 and wrote the ban, PUT
# /admin-api/policy?zzz=1 answered 200 and changed the policy, DELETE
# /admin-api/blocks?key=...&zzz=1 answered 200 {"deleted":1}, and GET
# /admin-api/countries?limit=2 answered 200 with every row. That last one is the
# same bug one level down: the guard assumed limit/offset were always legal, and
# this listing has no paging to honour, so the parameter was accepted, dropped
# and answered with the whole table. The silent half was the half that changes
# state — a mistyped scoping parameter on a write acts with a wider scope than
# the caller meant.
WRITE_SRC=203.0.113.251
POLICY_BEFORE=$(admin "$EDGE/admin-api/policy" | jval streakThreshold)
printf ' info the policy this edge is enforcing before the refused write: streakThreshold=%s\n' "$POLICY_BEFORE"
check 'a write refuses a query parameter it never implemented' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$WRITE_SRC\"}" "$EDGE/admin-api/blocks?zzz=1")"
check 'and the ban it refused was never written' '0' \
"$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['sourceKey']=='$WRITE_SRC'")"
check 'the same write with no unknown parameter is served' '204' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$WRITE_SRC\"}" "$EDGE/admin-api/blocks")"
check 'a delete whose scope is misspelled is refused, not run' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE \
"$EDGE/admin-api/blocks?key=$WRITE_SRC&src=operator")"
check 'and the row it was asked to remove is still there' '1' \
"$(admin "$EDGE/admin-api/blocks?source=operator" | jcount "b['sourceKey']=='$WRITE_SRC'")"
admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT -H 'Content-Type: application/json' \
-d '{"streakThreshold":7}' "$EDGE/admin-api/policy?zzz=1" >/dev/null
POLICY_AFTER=$(admin "$EDGE/admin-api/policy" | jval streakThreshold)
check 'a policy write with an unknown parameter changes nothing' "$POLICY_BEFORE" "$POLICY_AFTER"
check 'a listing with no paging refuses the paging it never implemented' 'yes' \
"$(admin "$EDGE/admin-api/countries?limit=2" | grep -qi "unknown query parameter 'limit'" && echo yes || echo no)"
check 'the curl-friendly ?token= still works on a write' '200' \
"$(code "$EDGE/admin-api/blocks?token=$OPENWAF_ADMIN_TOKEN&source=operator")"
admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null
echo '- a policy value outside its bounds is refused, and a valid one reaches the wire'
# OPEN-20 measured this on the shipped image: PUT {"engineBlockStatus":1000}
# answered 200, the value was stored, and the next banned visitor got no HTTP
# status at all — curl reported "Unsupported HTTP/1 subversion in response" and
# the connection closed. PUT {"ipv4KeyPrefixLength":0} answered 200 and collapsed
# every IPv4 address onto the literal key "*": one 404 from one address banned
# the next three on their first request. The integration suite proves the guard;
# what is proven here is that the image an operator deploys carries it, and that
# the half nobody tested — a VALID status reaching enforcement — really works.
ENGINE_BEFORE=$(admin "$EDGE/admin-api/policy" | jval engineBlockStatus)
PREFIX_BEFORE=$(admin "$EDGE/admin-api/policy" | jval ipv4KeyPrefixLength)
printf ' info the policy in force before the refused writes: engineBlockStatus=%s ipv4KeyPrefixLength=%s\n' \
"$ENGINE_BEFORE" "$PREFIX_BEFORE"
REFUSED_BODY=$(admin -X PUT -H 'Content-Type: application/json' \
-d '{"engineBlockStatus":1000}' "$EDGE/admin-api/policy")
check 'a policy value outside its bounds is a 400, not a 200 that changed nothing' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT -H 'Content-Type: application/json' \
-d '{"engineBlockStatus":1000}' "$EDGE/admin-api/policy")"
check 'and the refusal names the key and the range it is outside' 'yes' \
"$(printf '%s' "$REFUSED_BODY" | grep -q 'engineBlockStatus must be 400..599; got 1000' && echo yes || echo no)"
check 'the policy it refused is the policy it had before the refusal' "$ENGINE_BEFORE" \
"$(admin "$EDGE/admin-api/policy" | jval engineBlockStatus)"
check 'a second out-of-range key is refused with its own range' 'yes' \
"$(admin -X PUT -H 'Content-Type: application/json' \
-d '{"ipv4KeyPrefixLength":0}' "$EDGE/admin-api/policy" \
| grep -q 'ipv4KeyPrefixLength must be 8..32; got 0' && echo yes || echo no)"
check 'and the granularity in force is the one it had, not the one it was asked for' "$PREFIX_BEFORE" \
"$(admin "$EDGE/admin-api/policy" | jval ipv4KeyPrefixLength)"
# The valid half of the contract, which no gate had ever driven: the operator is
# allowed to choose the status a ban answers with, and the choice has to be what
# the visitor actually receives. Threshold 3 is already in force from the scene
# above, so four refusals from a fresh address is one ban.
admin -X PUT -H 'Content-Type: application/json' -d '{"engineBlockStatus":451}' \
"$EDGE/admin-api/policy" >/dev/null
STATUS_SRC=203.0.113.245
for _ in 1 2 3 4; do code -H "$(xff "$STATUS_SRC")" "$EDGE/no-such-page" >/dev/null; done
BAN_STATUS=000
for _ in $(seq 1 12); do
BAN_STATUS=$(code -H "$(xff "$STATUS_SRC")" "$EDGE/no-such-page")
[ "$BAN_STATUS" = "451" ] && break
sleep 2
done
printf ' info what a banned visitor answers while engineBlockStatus is 451: %s\n' "$BAN_STATUS"
check 'a valid engineBlockStatus reaches enforcement on the wire, from the shipped image' '451' "$BAN_STATUS"
admin -X PUT -H 'Content-Type: application/json' -d "{\"engineBlockStatus\":$ENGINE_BEFORE}" \
"$EDGE/admin-api/policy" >/dev/null
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
check 'and putting the original status back is reflected in the policy read' "$ENGINE_BEFORE" \
"$(admin "$EDGE/admin-api/policy" | jval engineBlockStatus)"
echo '- a provenance nobody means is refused, and the bounds an entry has are enforced'
# OPEN-23 measured on the shipped image before this scene existed: with two operator
# blocks and three engine bans, GET /admin-api/blocks?source=enigne answered 200 with
# the operator list, and DELETE ?source=enigne answered 200 {"deleted":1} and left
# operator=0 engine=3. A typo for "engine" erased the list an operator builds by hand —
# the one thing this API's own comment says it exists to prevent. The bounds are the
# same class of mistake: expiresInMinutes 0 and -5 both meant "never expires" on the
# control that outranks every ban, and a 1 MB reason was accepted with 204 and came
# back as ~1,000,287 bytes of listing.
# The scenes before this one clear the block tables, so the list is empty when the
# scene starts and a "nothing was deleted" assertion would compare 0 with 0. The scene
# therefore writes the list it needs to protect, and says so.
SRC_A=203.0.113.241
SRC_B=203.0.113.242
SRC_OP=203.0.113.231
SRC_TTL=203.0.113.232
SRC_LONG=203.0.113.233
for S in "$SRC_A" "$SRC_B"; do
admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$S\",\"reason\":\"the list this scene protects\"}" "$EDGE/admin-api/blocks" >/dev/null
done
check 'the operator list this scene protects has two rows' '2' \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount "b['source']=='operator'")"
check 'a provenance this endpoint never heard of is a 400' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?live=false&source=enigne")"
BOGUS=$(admin "$EDGE/admin-api/blocks?live=false&source=enigne")
names_set=no
case "$BOGUS" in
*'source must be operator|engine|all'*) names_set=yes ;;
esac
check 'and the refusal names the set it is outside' 'yes' "$names_set"
echoes_value=no
case "$BOGUS" in
*'enigne'*) echoes_value=yes ;;
esac
check 'and echoes back the value it refused' 'yes' "$echoes_value"
check 'a delete with that provenance is refused too' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/blocks?source=enigne")"
check 'and the operator list is still the two rows it was' '2' \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount "b['source']=='operator'")"
check 'both of them by name, not just by count' '2' \
"$(admin "$EDGE/admin-api/blocks?live=false" \
| jcount "b['sourceKey']=='$SRC_A' or b['sourceKey']=='$SRC_B'")"
check 'while the documented filter still answers, spaced and cased' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?live=false&source=%20OPERATOR%20")"
check 'and that filter returns exactly the two rows it means' '2' \
"$(admin "$EDGE/admin-api/blocks?live=false&source=operator" | jcount "b['source']=='operator'")"
check 'a TTL of zero is refused, not read as never' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_OP\",\"note\":\"zero ttl\",\"expiresInMinutes\":0}" "$EDGE/admin-api/allow")"
ZERO_BODY=$(admin -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_OP\",\"note\":\"zero ttl\",\"expiresInMinutes\":0}" "$EDGE/admin-api/allow")
names_range=no
case "$ZERO_BODY" in
*'expiresInMinutes must be 1..5256000'*) names_range=yes ;;
esac
check 'and the refusal names the range it is outside' 'yes' "$names_range"
check 'and the exemption it refused was never written' '0' \
"$(admin "$EDGE/admin-api/allow" | jcount "b['match']=='$SRC_OP'")"
check 'a negative TTL is refused with the same range' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_OP\",\"note\":\"negative ttl\",\"expiresInMinutes\":-5}" "$EDGE/admin-api/allow")"
admin -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_TTL\",\"note\":\"no ttl field\"}" "$EDGE/admin-api/allow" >/dev/null
check 'leaving the field out is still the only way to say never' 'null' \
"$(admin "$EDGE/admin-api/allow" | python3 -c "import json,sys
d=json.load(sys.stdin)
print(','.join('null' if b['expiresAt'] is None else 'set' for b in d if b['match']=='$SRC_TTL'))")"
LONG=$(python3 -c 'print("R"*513)')
REASON_BODY=$(admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$SRC_LONG\",\"reason\":\"$LONG\"}" "$EDGE/admin-api/blocks")
reason_named=no
case "$REASON_BODY" in
*'reason must be at most 512 characters; got 513'*) reason_named=yes ;;
esac
check 'a reason past the column is refused with its length' 'yes' "$reason_named"
check 'and the block it refused was never written' '0' \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount "b['sourceKey']=='$SRC_LONG'")"
NOTE_BODY=$(admin -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_LONG\",\"note\":\"$LONG\"}" "$EDGE/admin-api/allow")
note_named=no
case "$NOTE_BODY" in
*'note must be at most 512 characters; got 513'*) note_named=yes ;;
esac
check 'a note past the column is refused with its length' 'yes' "$note_named"
check 'and the exemption it refused was never written' '0' \
"$(admin "$EDGE/admin-api/allow" | jcount "b['match']=='$SRC_LONG'")"
AT_LIMIT=$(python3 -c 'print("R"*512)')
# Body and status from one request: a second POST for the same match would answer
# 409 and prove nothing about the limit.
AT_RESP=$(admin -w '\n%{http_code}' -X POST -H 'Content-Type: application/json' \
-d "{\"match\":\"$SRC_LONG\",\"note\":\"$AT_LIMIT\"}" "$EDGE/admin-api/allow")
AT_CODE=${AT_RESP##*$'\n'}
printf ' info the note at the limit answered %s: %s\n' "$AT_CODE" "$(printf '%s' "${AT_RESP%$'\n'*}" | head -c 90)"
check 'while a note at the limit is accepted' '204' "$AT_CODE"
# Leave the stack as the scenes after this one expect to find it.
for M in "$SRC_TTL" "$SRC_LONG"; do
AID=$(admin "$EDGE/admin-api/allow" | python3 -c "import json,sys
print(','.join(str(b['id']) for b in json.load(sys.stdin) if b['match']=='$M'))")
for I in ${AID//,/ }; do admin -X DELETE "$EDGE/admin-api/allow/$I" >/dev/null; done
done
for S in "$SRC_A" "$SRC_B"; do
admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$S" >/dev/null
done
printf ' info blocks after the scene: operator=%s engine=%s\n' \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount "b['source']=='operator'")" \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount "b['source']=='engine'")"
echo '- a pillar that stops reading its table says so'
# Measured on the shipped image before this was fixed: with policy_settings
# dropped out from under a running edge, GET /admin-api/policy kept answering the
# operator's own streakThreshold, /admin-api/state reported snapshotAgeSeconds 0
# (the refresh "succeeded" at reading the tables that were still there), /healthz
# and /readyz answered 200, and the whole system produced exactly one log line.
# After a restart the policy was simply gone — a streakThreshold of 2 came back
# as 10 and trustProxyHeaders as false, and four refusals from a fresh source no
# longer matured a ban. Keeping the last good value is the right failure posture;
# keeping it unmentioned is not.
EDGE_CID=$(docker compose ps -q edge)
sidecar() {
# The volume is the edge container's, so a run with no edge container has
# nothing to share — and in the NativeAOT measurement run that was the state
# from the first scene on: EDGE_CID was empty and docker answered `volumes-from
# specification cannot be an empty string`, six times, each one a scene whose
# break never happened reporting a docker usage error. A missing container is
# news about the stack, so it is named as news about the stack.
if [ -z "${EDGE_CID:-}" ] || ! docker inspect -f '{{.State.Status}}' "$EDGE_CID" >/dev/null 2>&1; then
printf ' info the sidecar cannot run: no edge container to share a volume with (the edge reports %s)\n' \
"$(edge_state)" >&2
return 2
fi
docker run --rm -i --volumes-from "$EDGE_CID" python:3.12-slim python -
}
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
c.execute("DROP TABLE policy_settings")
PYSQL
# The refresh runs off the request path on the TTL, so the failure has to be
# allowed to happen at least once before it can be counted.
for _ in $(seq 1 15); do
code "$EDGE/no-such-page" >/dev/null
POLICY_FAILS=$(admin "$EDGE/admin-api/state" | jval policyReloadFailures)
count_moved "${POLICY_FAILS:-0}" && break
sleep 3
done
printf ' info policy reload failures counted after the table went away: %s\n' "${POLICY_FAILS:-0}"
check 'the state counts a policy pillar that cannot read its table' 'yes' \
"$(count_moved "${POLICY_FAILS:-0}" && echo yes || echo no)"
check 'readiness stops saying ready while it cannot' '503' "$(code "$EDGE/readyz")"
# Sampled with a retry, not once. The first Linux rehearsal of this gate failed
# here on a single sample: /state had just reported one reload failure, and the
# very next GET /policy answered with the header at 0 — a reload that succeeded
# in between (a pooled sqlite connection can serve the schema it already
# prepared, which is the same reason chmod 000 on the file never breaks the
# edge). The product was not lying: the header said what the last read did. The
# gate was asserting on one instant. So the header is polled while the table is
# gone, and what was actually seen is printed either way.
POLICY_HDR=""
for _ in $(seq 1 6); do
POLICY_HDR=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/policy" \
| grep -i '^x-policy-reload-failures:' | tr -d '\r')
printf '%s' "$POLICY_HDR" | grep -qi ': [1-9]' && break
code "$EDGE/no-such-page" >/dev/null
sleep 2
done
printf ' info policy provenance header while the table is gone: %s\n' "${POLICY_HDR:-none}"
check 'the policy answer carries its own provenance' 'yes' \
"$(printf '%s' "$POLICY_HDR" | grep -qi '^x-policy-reload-failures: [1-9]' && echo yes || echo no)"
# The two pillars are counted separately on purpose: here the snapshot is still
# refreshing fine and only the policy read is broken, and a single blended
# "storage is unhappy" flag would lose exactly that.
check 'the snapshot pillar is still reported healthy' '0' \
"$(admin "$EDGE/admin-api/state" | jval snapshotRefreshFailures)"
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
c.execute('CREATE TABLE IF NOT EXISTS policy_settings ("Key" TEXT NOT NULL CONSTRAINT "PK_policy_settings" PRIMARY KEY, "Value" TEXT NOT NULL, "UpdatedAt" INTEGER NOT NULL)')
PYSQL
for _ in $(seq 1 15); do
code "$EDGE/no-such-page" >/dev/null
[ "$(code "$EDGE/readyz")" = "200" ] && break
sleep 3
done
check 'putting the table back clears the counters and readiness returns' '200' "$(code "$EDGE/readyz")"
check 'and the policy answer says so again' 'X-Policy-Reload-Failures: 0' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/policy" | grep -i '^x-policy-reload-failures:' | tr -d '\r')"
echo '- a pillar that cannot write says so'
# The read side got its counters first; the write side was still silent, and a
# failed write is worse than a failed read — the row never existed, and no later
# request brings it back. Measured on the shipped image with SQLite triggers
# aborting every INSERT and UPDATE on source_observations and edge_alerts while
# reads stayed working: three new sources refused and a six-request 5xx storm
# later, GET /admin-api/observations answered 200 with the same X-Total-Count it
# had before the break, GET /admin-api/alerts still showed its one row, /healthz
# and /readyz answered 200, /admin-api/state had no write-side field at all, and
# the log carried "ObservationWriter: flush failed, 4 entries dropped." plus two
# "AlertWriter: could not persist…". A trigger, not a dropped table, on purpose:
# a missing table breaks the listing too, and a broken listing is honest about
# being broken. The lie this asserts is the 200 that stays complete-looking.
# State the policy this scene depends on, and prove the source keys it claims
# are real. The read scene above drops policy_settings and recreates it empty,
# which erases the operator's overrides: once the reload succeeds against the
# empty table the policy reverts to the configured defaults, and with
# trustProxyHeaders back to false every "new source" below is the same docker
# bridge address and the scene passes for the wrong reason. Which policy is in
# force after that restore is not deterministic across runs — the first Linux
# rehearsal of the ban scene failed exactly there.
admin -X PUT -H 'Content-Type: application/json' \
-d '{"streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
TOTAL_BEFORE=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1" \
| grep -i '^x-total-count:' | tr -d '\r' | awk '{print $2}')
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for t in ("source_observations", "edge_alerts"):
for op in ("INSERT", "UPDATE"):
c.execute(f'CREATE TRIGGER "gate_{t}_{op}" BEFORE {op} ON "{t}" '
"BEGIN SELECT RAISE(ABORT, 'gate: durable write blocked'); END")
print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
for src in 203.0.113.201 203.0.113.202 203.0.113.203; do
for i in 1 2 3; do code -H "$(xff "$src")" "$EDGE/no-write-$i" >/dev/null; done
done
for i in $(seq 1 6); do code -H "$(xff 203.0.113.210)" "$EDGE/boom" >/dev/null; done
OBS_FAILS=0
for _ in $(seq 1 12); do
OBS_FAILS=$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)
count_moved "${OBS_FAILS:-0}" && break
sleep 3
done
printf ' info observation write failures counted after writes were blocked: %s\n' "${OBS_FAILS:-0}"
check 'the state counts observations this edge could not persist' 'yes' \
"$(count_moved "${OBS_FAILS:-0}" && echo yes || echo no)"
check 'and it says how many rows were lost, not only that something failed' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval observationsLost | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'the alerting pillar counts its lost alerts too' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval alertWriteFailures | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
TOTAL_AFTER=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1" \
| grep -i '^x-total-count:' | tr -d '\r' | awk '{print $2}')
printf ' info X-Total-Count across the break: %s -> %s (three new sources saw, none stored)\n' "$TOTAL_BEFORE" "$TOTAL_AFTER"
check 'the listing still answers with the count it had before the break' "$TOTAL_BEFORE" "$TOTAL_AFTER"
# Not vacuous: the three sources this scene says were seen are in the live
# streak map, so they really were three distinct sources and not one bridge
# address wearing a header nobody trusted.
streaks_fetch; streaks_info
check 'the sources this scene lost were really three distinct sources' '3' \
"$(printf '%s' "$STREAKS_JSON" | streaks_where "b['sourceKey'] in ('203.0.113.201','203.0.113.202','203.0.113.203')")"
check 'the failure it reports is the real reason, not an EF wrapper' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval observationLastWriteError | grep -qi 'durable write blocked' && echo yes || echo no)"
# Reporting-path failures are stated, not gated. The first version of this gate
# asserted 503 here, and the boundary moved after measuring what that cost: one
# lost alert left /readyz at 503 for two idle minutes with the write path already
# healthy, because an alert pillar only writes when an alert happens to be
# raised. An orchestrator would have pulled a working edge out of rotation over a
# reporting side-channel. The enforcement-path failure below is the one that gates.
check 'a reporting-path write failure does not make the edge unready' '200' "$(code "$EDGE/readyz")"
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'")):
c.execute(f'DROP TRIGGER "{r[0]}"')
print("triggers after cleanup:", c.execute("SELECT count(*) FROM sqlite_master WHERE type='trigger'").fetchone()[0])
PYSQL
for src in 203.0.113.221 203.0.113.222; do
for i in 1 2 3; do code -H "$(xff "$src")" "$EDGE/healed-$i" >/dev/null; done
done
for _ in $(seq 1 12); do
[ "$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)" = "0" ] && break
sleep 3
done
check 'the observation pillar heals on its next successful write' '0' \
"$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)"
# The alert pillar has still written nothing since the break, so its counter
# stays exactly where it was: a counter clears on evidence, not on the clock. It
# is reported for as long as it is unproven, and it does not gate.
check 'an unproven alert pillar stays reported without gating readiness' '200' "$(code "$EDGE/readyz")"
# Twelve 502s from a fresh source: the alerting threshold this run set is 3,
# and the escalation alerts at 3 and 6, so this is enough to raise one for sure.
for i in $(seq 1 12); do code -H "$(xff 203.0.113.230)" "$EDGE/boom" >/dev/null; done
check 'the alert counter clears once an alert is actually written' '0' \
"$(admin "$EDGE/admin-api/state" | jval alertWriteFailures)"
echo '- a ban that cannot be written is not enforced, and says so'
# The one durable write on the enforcement path. Measured on the shipped image
# with writes to block_entries aborted and reads left working: five refusals from
# one source at a threshold of 3 answered 404 five times, no ban reached storage
# or /state, /readyz said ready, and the log said "concurrent ban on
# 203.0.113.12; keeping the winner" four times over an inner "SQLite Error 19:
# 'gate: ban write blocked'". Nothing was in force, and the only sentence about
# it in the log said the opposite.
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for op in ("INSERT", "UPDATE"):
c.execute(f'CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" '
"BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END")
print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
admin -X PUT -H 'Content-Type: application/json' \
-d '{"streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
BAN_SRC=203.0.113.241
# Counted before and after, not in total: an earlier scene in this same run may
# legitimately have produced a race line, and a total would blame this scene for
# it.
RACES_BEFORE=$(docker compose logs edge 2>/dev/null | grep -c 'concurrent ban on')
BAN_CODES=""
for i in $(seq 1 5); do BAN_CODES="$BAN_CODES $(code -H "$(xff "$BAN_SRC")" "$EDGE/unbanned-$i")"; done
printf ' info answers from a scanner at threshold 3 while ban writes are blocked:%s\n' "$BAN_CODES"
check 'the scanner is never banned while the ban write fails' '404 404 404 404 404' "${BAN_CODES# }"
streaks_fetch; streaks_info
check 'the scanner really was one source the edge tracked' 'yes' \
"$(printf '%s' "$STREAKS_JSON" | streaks_where "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'and no engine ban for it reached storage' 'yes' \
"$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0==0)?0:1}' && echo yes || echo no)"
# The ban pillar is not updated on the request path: the write attempt and the
# failure to record it land a moment after the refusal that triggered them. Read
# immediately after the fifth refusal, this scene used to see the counters at 0
# and /readyz at 200 while the same run's log already carried two lines saying
# the ban was not persisted (75ee822: /tmp/c25_compose2.log 180/4 and
# /tmp/c25_compose3.log 179/5 — three of the four failures were this read). The
# state is therefore polled, and the raw values are printed as a trajectory:
# "the counter is 0" and "the field is not in the answer" used to be the same
# word in the log, which is where a real regression would hide (OPEN-42).
PILLAR_OK=0; PILLAR_WAIT=0; PILLAR_TRAIL=''; PILLAR_READY=''; PILLAR_WHY=''
BAN_FAILS=0; NOT_WRITTEN=0
for _ in $(seq 1 10); do
STATE_JSON=$(admin "$EDGE/admin-api/state")
BAN_FAILS=$(printf '%s' "$STATE_JSON" | jval banWriteFailures)
NOT_WRITTEN=$(printf '%s' "$STATE_JSON" | jval bansNotWritten)
PILLAR_WHY=$(printf '%s' "$STATE_JSON" | jval banLastWriteError)
PILLAR_READY=$(code "$EDGE/readyz")
PILLAR_TRAIL="$PILLAR_TRAIL ${BAN_FAILS:-?}/${NOT_WRITTEN:-?}"
if count_ge "${BAN_FAILS:-}" 1 && [ "$PILLAR_READY" = "503" ]; then
PILLAR_OK=1; break
fi
PILLAR_WAIT=$((PILLAR_WAIT+2)); sleep 2
done
printf ' info ban pillar after %s s of waiting — failures/notWritten:%s\n' "$PILLAR_WAIT" "$PILLAR_TRAIL"
printf ' info readyz at that moment: %s; the reason quoted: %s\n' "${PILLAR_READY:-none}" "${PILLAR_WHY:-(none)}"
check 'the ban pillar reached its failure state within the wait budget' '1' "$PILLAR_OK"
check 'the state counts the ban write that failed' 'yes' \
"$(count_ge "${BAN_FAILS:-0}" 1 && echo yes || echo no)"
check 'and says how many bans were never written' 'yes' \
"$(count_ge "${NOT_WRITTEN:-0}" 1 && echo yes || echo no)"
check 'readiness names the ban writes, because this is the enforcement path' '503' "$PILLAR_READY"
check 'the reason it quotes is the storage error, not a concurrency race' 'yes' \
"$(printf '%s' "$PILLAR_WHY" | grep -qi 'ban write blocked' && echo yes || echo no)"
# Counted after the wait, so both numbers describe the same moment: the scene
# has demonstrably produced its log lines, and none of them is the race sentence.
BAN_LOG_LINES=$(log_wait_for 'could not persist a ban for')
RACES_AFTER=$(log_count 'concurrent ban on')
printf ' info lines calling a ban write a race, before/after this scene: %s/%s\n' "$RACES_BEFORE" "$RACES_AFTER"
printf ' info lines saying the ban was not persisted and nothing is enforcing it: %s\n' "$BAN_LOG_LINES"
check 'the log no longer calls a storage failure a race' "$RACES_BEFORE" "$RACES_AFTER"
check 'and the log says what actually happened' 'yes' \
"$(count_ge "${BAN_LOG_LINES:-0}" 1 && echo yes || echo no)"
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'")):
c.execute(f'DROP TRIGGER "{r[0]}"')
print("triggers after cleanup:", c.execute("SELECT count(*) FROM sqlite_master WHERE type='trigger'").fetchone()[0])
PYSQL
for i in $(seq 1 3); do code -H "$(xff "$BAN_SRC")" "$EDGE/retried-$i" >/dev/null; done
for _ in $(seq 1 10); do
[ "$(code "$EDGE/readyz")" = "200" ] && break
sleep 3
done
check 'the ban lands on a later refusal once the write path heals' 'yes' \
"$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'and readiness returns on that write, not on a timer' '200' "$(code "$EDGE/readyz")"
echo '- a ban that failed to write is retried without waiting for the attacker'
# The consequence of the fix above, measured before it existed: with the ban
# write path broken and then REPAIRED (triggers dropped, zero triggers left) and
# no further traffic from the source, /readyz answered 503 at t+30, t+60, t+90
# and t+120 s with banWriteFailures and bansNotWritten unmoved. The only event
# that cleared the ban pillar was a successful ban write, and the only thing
# that produced one was the source crossing the threshold again — so the signal
# an orchestrator uses to keep an edge in rotation was coupled to attack
# traffic, and the quieter the site, the longer a healed edge sat out of service.
RETRY_SRC=203.0.113.242
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for op in ("INSERT", "UPDATE"):
c.execute(f'CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" '
"BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END")
print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
admin -X PUT -H 'Content-Type: application/json' \
-d '{"streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
for i in $(seq 1 5); do code -H "$(xff "$RETRY_SRC")" "$EDGE/retry-$i" >/dev/null; done
PENDING=0
for _ in $(seq 1 10); do
PENDING=$(admin "$EDGE/admin-api/state" | jval bansPendingRetry)
count_moved "${PENDING:-0}" && break
sleep 3
done
printf ' info bans queued for retry while storage refuses them: %s\n' "$PENDING"
check 'the failed ban is queued for retry rather than left to the next attack' 'yes' \
"$(count_ge "${PENDING:-0}" 1 && echo yes || echo no)"
# Repair the storage failure. Nothing else is sent from this source: that is the
# whole point of the scene.
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'")):
c.execute(f'DROP TRIGGER "{r[0]}"')
print("triggers after repair:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
RETRY_READY=000
for _ in $(seq 1 20); do
RETRY_READY=$(code "$EDGE/readyz")
[ "$RETRY_READY" = "200" ] && break
sleep 3
done
printf ' info readiness after the repair, with no further request from that source: %s\n' "$RETRY_READY"
check 'readiness returns on the retry, not on attacker traffic' '200' "$RETRY_READY"
check 'and the ban the edge decided hours of polling ago is now in storage' 'yes' \
"$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$RETRY_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'the pending queue is empty again' '0' "$(admin "$EDGE/admin-api/state" | jval bansPendingRetry)"
check 'and the source that was never banned during the break is banned on the wire' '403' \
"$(code -H "$(xff "$RETRY_SRC")" "$EDGE/retry-6")"
echo '- a listing says which part of itself it is'
# OPEN-24, measured on the shipped image before the fix: with 1103 recorded
# sources GET /admin-api/observations?limit=100000 answered 200 with 1000 rows,
# no X-Total-Count and no X-Truncated — 103 sources were unreachable and the
# answer still read as a complete one; ?limit=0 and ?limit=-1 each answered 200
# with a single row. /streaks carried the opposite defect: the flag was counted
# from the size of the streak map, so two standing streaks plus one reset source
# answered X-Truncated: true for a listing that had cut nothing.
#
# The in-process suites have covered the fixed behaviour since; what was missing
# is the same sentence measured over a socket on the image that ships it. Until
# this scene, the image-level gate asserted the paging headers for /allow only.
TMPH=$(mktemp); TMPB=$(mktemp)
# The response's own arithmetic: does X-Truncated agree with X-Total-Count, the
# offset that was asked for, and the rows that actually came back? Written once
# so every listing in this scene is held to the same rule, and so a header that
# is simply absent can never be read as "not truncated".
truth() {
python3 - "$TMPH" "$TMPB" "$1" <<'PY'
import json, sys
hdrs = {}
for line in open(sys.argv[1]):
if ':' in line:
k, v = line.split(':', 1)
hdrs[k.strip().lower()] = v.strip()
try:
d = json.load(open(sys.argv[2]))
except Exception:
print('unparseable-body')
raise SystemExit(0)
rows = d.get('streaks', []) if isinstance(d, dict) else d
total = hdrs.get('x-total-count')
if total is None and isinstance(d, dict):
total = d.get('standingStreaks')
trunc = hdrs.get('x-truncated')
if total is None or trunc is None:
print('no-header')
else:
want = str(bool(int(sys.argv[3]) + len(rows) < int(total))).lower()
print('yes' if trunc == want else 'no')
PY
}
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","streakThreshold":5,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null
# Five sources, one second apart, so the listing's own ordering (newest first)
# is reproducible: five rows sharing one timestamp can be returned in any order
# and the pagination assertions would then be comparing noise.
for n in 1 2 3 4 5; do
code -H "$(xff "203.0.113.18$n")" "$EDGE/page-$n" >/dev/null
sleep 1
done
SEEN5=0
for _ in $(seq 1 12); do
SEEN5=$(admin "$EDGE/admin-api/observations?limit=5" | python3 -c "import json,sys
d=json.load(sys.stdin)
print(sum(1 for o in d if o['sourceKey'].startswith('203.0.113.18')))")
[ "${SEEN5:-0}" = "5" ] && break
sleep 3
done
printf ' info this run seeded five sources 1 s apart; the newest five rows hold %s of them\n' "$SEEN5"
check 'the five sources this scene just created are all listable' '5' "${SEEN5:-0}"
PAGE_KEYS=''; PAGE_TOTALS=''
# Accumulated space-separated and split per line below: the count of unique
# keys is the assertion, so the leading empty field has to be dropped rather
# than counted as a sixth source.
for off in 0 1 2 3 4; do
admin -D "$TMPH" -o "$TMPB" "$EDGE/admin-api/observations?limit=1&offset=$off"
PAGE_KEYS="$PAGE_KEYS $(jget "True" "sourceKey" < "$TMPB")"
PAGE_TOTALS="$PAGE_TOTALS $(grep -i '^x-total-count:' "$TMPH" | tr -cd '0-9')"
done
printf ' info the five single-row pages showed:%s (totals:%s)\n' "$PAGE_KEYS" "$PAGE_TOTALS"
check 'five single-row pages show five different sources' '5' \
"$(tr ' ' '\n' <<<"$PAGE_KEYS" | grep . | sort -u | grep -c .)"
check 'and those five are exactly the first five rows of the whole listing' 'yes' \
"$([ "$(tr ' ' '\n' <<<"$PAGE_KEYS" | grep . | sort)" = "$(admin "$EDGE/admin-api/observations?limit=5" | python3 -c "import json,sys
print('\n'.join(sorted(o['sourceKey'] for o in json.load(sys.stdin))))")" ] && echo yes || echo no)"
check 'every page names the same total, not the size of its own page' '1' \
"$(tr ' ' '\n' <<<"$PAGE_TOTALS" | grep . | sort -u | grep -c .)"
check 'a one-row page says it cut the list' 'X-Truncated: true' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1" | grep -i '^x-truncated:' | tr -d '\r')"
check 'and the flag agrees with the total and the row count it shipped' 'yes' \
"$(admin -D "$TMPH" -o "$TMPB" "$EDGE/admin-api/observations?limit=1&offset=1"; truth 1)"
check 'a page that reaches the end says nothing was cut' 'X-Truncated: false' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1000" | grep -i '^x-truncated:' | tr -d '\r')"
check 'the alert listing carries both headers' 'yes' \
"$(admin -D "$TMPH" -o "$TMPB" "$EDGE/admin-api/alerts?limit=1"; grep -qi '^x-total-count:' "$TMPH" && grep -qi '^x-truncated:' "$TMPH" && echo yes || echo no)"
check 'and its flag agrees with its own arithmetic' 'yes' \
"$(admin -D "$TMPH" -o "$TMPB" "$EDGE/admin-api/alerts?limit=1&offset=1"; truth 1)"
# The flag arithmetic above says a cut happened; it does not say the cut moved the
# window. That gap was OPEN-45's third item: for observations and blocks the image
# proves offset shows a different row, for alerts it proved only the header.
alert_row() { admin "$EDGE/admin-api/alerts?limit=1&offset=$1" \
| python3 -c 'import json,sys; print(json.dumps(json.load(sys.stdin)[0], sort_keys=True))'; }
ALERT0=$(alert_row 0); ALERT1=$(alert_row 1)
printf ' info alert rows at offset 0 and 1 differ: %s\n' \
"$([ "$ALERT0" != "$ALERT1" ] && echo yes || echo no)"
check 'an offset on the alert listing shows a different alert, not the same row again' 'yes' \
"$([ "$ALERT0" != "$ALERT1" ] && echo yes || echo no)"
# The block listing gets exact numbers, because this scene owns the whole
# filtered set: two operator rows and nothing else under source=operator.
admin -X POST -H 'Content-Type: application/json' -d '{"ip":"203.0.113.181","note":"paging-1"}' "$EDGE/admin-api/blocks" >/dev/null
admin -X POST -H 'Content-Type: application/json' -d '{"ip":"203.0.113.182","note":"paging-2"}' "$EDGE/admin-api/blocks" >/dev/null
check 'the operator listing counts exactly what this scene wrote' 'X-Total-Count: 2' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?source=operator" | grep -i '^x-total-count:' | tr -d '\r')"
check 'and says it cut the list at one row' 'X-Truncated: true' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?source=operator&limit=1" | grep -i '^x-truncated:' | tr -d '\r')"
check 'the second page is the other block, not the first again' 'yes' \
"$([ "$(admin "$EDGE/admin-api/blocks?source=operator&limit=1" | jget "True" "sourceKey")" != "$(admin "$EDGE/admin-api/blocks?source=operator&limit=1&offset=1" | jget "True" "sourceKey")" ] && echo yes || echo no)"
check 'a page past the end returns no rows' '0' \
"$(admin "$EDGE/admin-api/blocks?source=operator&limit=1&offset=2" | jcount "True")"
check 'and does not claim a cut that did not happen' 'X-Truncated: false' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?source=operator&limit=1&offset=2" | grep -i '^x-truncated:' | tr -d '\r')"
# Bounds, on the wire: a limit nobody meant used to be answered with one row.
check 'a limit of zero is refused, not served as one row' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=0")"
check 'and the refusal names the range and the value' 'limit must be 1..1000; got 0' \
"$(admin "$EDGE/admin-api/observations?limit=0" | jval error)"
check 'a limit above the ceiling is refused too' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=100000")"
check 'naming the ceiling it hit' 'limit must be 1..1000; got 100000' \
"$(admin "$EDGE/admin-api/observations?limit=100000" | jval error)"
check 'the alert listing refuses both ends the same way' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/alerts?limit=0") $(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/alerts?limit=100000")"
check 'the streak map refuses them the same way' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?limit=0") $(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?limit=100000")"
check 'the block listing quotes its own, wider, ceiling' 'limit must be 1..2000; got 0' \
"$(admin "$EDGE/admin-api/blocks?limit=0" | jval error)"
check 'a negative offset is refused rather than read as zero' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?offset=-1")"
check 'and says which parameter it means' 'offset must be 0 or more; got -1' \
"$(admin "$EDGE/admin-api/observations?offset=-1" | jval error)"
check 'the same negative offset on the block listing' 'offset must be 0 or more; got -1' \
"$(admin "$EDGE/admin-api/blocks?offset=-1" | jval error)"
check 'and on the alert listing' 'offset must be 0 or more; got -1' \
"$(admin "$EDGE/admin-api/alerts?offset=-1" | jval error)"
# The three bounds OPEN-45 found proven only in-process, now proven on the wire.
# Each one is a case where the answer used to be a row rather than a refusal, and
# the in-process test could pass while the shipped image still served the row: the
# block listing's ceiling at its UPPER end (only the lower end was on the image),
# a negative offset on the streak map (checked on observations, blocks and alerts
# but never here), and — below, in the paging scene — that an offset on the alert
# listing moves to a different row rather than only changing the flag arithmetic.
check 'the block listing refuses a limit above its own ceiling' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/blocks?limit=2001")"
check 'naming its own, wider, range and the value it refused' 'limit must be 1..2000; got 2001' \
"$(admin "$EDGE/admin-api/blocks?limit=2001" | jval error)"
check 'the streak map refuses a negative offset as well' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?offset=-1")"
check 'and names the parameter it means there too' 'offset must be 0 or more; got -1' \
"$(admin "$EDGE/admin-api/streaks?offset=-1" | jval error)"
# The streak map, with the two counts deliberately different: two sources with
# something standing, one whose run ended on a clean answer and therefore stays
# in the map while the listing leaves it out. That gap is what makes the flag
# testable — with the two numbers equal, counting the map instead of the listing
# answers correctly by accident.
code -H "$(xff 203.0.113.186)" "$EDGE/streak-a" >/dev/null
code -H "$(xff 203.0.113.186)" "$EDGE/streak-a2" >/dev/null
code -H "$(xff 203.0.113.187)" "$EDGE/streak-b" >/dev/null
code -H "$(xff 203.0.113.188)" "$EDGE/streak-c" >/dev/null
code -H "$(xff 203.0.113.188)" "$EDGE/streak-c2" >/dev/null
CLEAN_CODE=$(code -H "$(xff 203.0.113.188)" "$EDGE/")
printf ' info the clean answer that ends a streak, from the upstream root: %s\n' "$CLEAN_CODE"
check 'a clean answer is available to end a streak with' '200' "$CLEAN_CODE"
streaks_fetch; streaks_info
check 'the map holds more sources than it has streaks to list' 'yes' \
"$(printf '%s' "$STREAKS_JSON" | python3 -c "import json,sys
d=json.load(sys.stdin); print('yes' if d['trackedSources']>d['standingStreaks'] and d['standingStreaks']>=2 else 'no')")"
check 'a listing that returned every standing streak says so' 'X-Truncated: false' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?limit=1000" | grep -i '^x-truncated:' | tr -d '\r')"
check 'the body names both counts side by side' 'yes' \
"$(printf '%s' "$STREAKS_JSON" | python3 -c "import json,sys
d=json.load(sys.stdin)
print('yes' if d['standingStreaks']==len(d['streaks']) and d['trackedSources']>d['standingStreaks'] else 'no')")"
check 'a one-row streak page says it cut the list' 'X-Truncated: true' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?limit=1" | grep -i '^x-truncated:' | tr -d '\r')"
check 'the second streak page is a different source' 'yes' \
"$([ "$(printf '%s' "$STREAKS_JSON" | python3 -c "import json,sys; print(json.load(sys.stdin)['streaks'][0]['sourceKey'])")" != "$(admin "$EDGE/admin-api/streaks?limit=1&offset=1" | python3 -c "import json,sys; print(json.load(sys.stdin)['streaks'][0]['sourceKey'])")" ] && echo yes || echo no)"
check 'a filtered streak answer is not reported as a cut' 'X-Truncated: false' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.186" | grep -i '^x-truncated:' | tr -d '\r')"
check 'and its flag is computed from the filtered count' 'yes' \
"$(admin -D "$TMPH" -o "$TMPB" "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.186"; truth 0)"
admin -X DELETE "$EDGE/admin-api/blocks?source=operator" >/dev/null
rm -f "$TMPH" "$TMPB"
echo '- a country rule is a rule, not a string'
# OPEN-25, measured on the shipped image before the fix (openwaf:ci at 5394751):
# PUT /admin-api/countries/12?allowed=false answered 204, PUT /countries/U.
# answered 204, and both were then listed to the operator as a denial — while a
# source in a real country still reached the upstream with 404, because the
# engine matches two-letter codes and these were not codes. Only length was
# checked, so /countries/USA was the one case refused. And there was no way
# back: DELETE /admin-api/countries/{code} did not exist, so the two junk rows
# stayed in the named volume and survived `compose down` — an operator's
# country table with permanent litter in it.
#
# The in-process suite has covered the fixed behaviour since; what was missing
# is the same sentence measured over a socket on the image that ships it.
printf ' info the country this run resolves for %s: %s\n' "$GEO_IP" "${COUNTRY:-unknown}"
check 'the geo lookup gives this scene a real country to reason about' 'yes' \
"$([ -n "${COUNTRY:-}" ] && echo yes || echo no)"
JUNK_BEFORE=$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='12' or b['code']=='U.' or b['code']=='USA'")
printf ' info junk rows in the country table before this scene: %s\n' "$JUNK_BEFORE"
check 'no two-character junk is sitting in the country table already' '0' "$JUNK_BEFORE"
check 'a two-character non-code is refused, not stored' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT "$EDGE/admin-api/countries/12?allowed=false")"
check 'and the refusal names the rule and the value' 'code must be a two-letter ISO country code; got "12"' \
"$(admin -X PUT "$EDGE/admin-api/countries/12?allowed=false" | jval error)"
check 'punctuation of the right length is refused too' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT "$EDGE/admin-api/countries/U.?allowed=false")"
check 'and so is a question mark, sent as a path and not as a query' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT "$EDGE/admin-api/countries/%3F%3F?allowed=false")"
check 'a three-letter code is refused by the same sentence, not by its length' 'two-letter ISO country code' \
"$(admin -X PUT "$EDGE/admin-api/countries/USA?allowed=false" | jval error | grep -o 'two-letter ISO country code')"
check 'and none of the four wrote a row' '0' \
"$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='12' or b['code']=='U.' or b['code']=='??' or b['code']=='USA'")"
# A refused write must not disturb the rule that is already there: the answer
# has to be about the code that was typed, not about whatever the table held.
admin -X PUT "$EDGE/admin-api/countries/$COUNTRY?allowed=false" >/dev/null
admin -X PUT -H 'Content-Type: application/json' -d '{"geo":"DenyList","trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page" >/dev/null
check 'a refused write leaves the rule that was already there alone' '1' \
"$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='$COUNTRY' and b['isAllowed'] is False")"
check 'lower case on the wire becomes the rule, not a second row' '204' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X PUT "$EDGE/admin-api/countries/$(printf '%s' "$COUNTRY" | tr '[:upper:]' '[:lower:]')?allowed=false")"
check 'and the table holds the upper-case code, never the one typed' 'yes' \
"$([ "$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='$COUNTRY'")" = "1" ] && [ "$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='$(printf '%s' "$COUNTRY" | tr '[:upper:]' '[:lower:]')'")" = "0" ] && echo yes || echo no)"
check 'the normalised rule is the one the engine enforces' '451' \
"$(code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page")"
check 'removing the rule answers 204' '204' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/countries/$COUNTRY")"
check 'and the table no longer lists it' '0' \
"$(admin "$EDGE/admin-api/countries" | jcount "b['code']=='$COUNTRY'")"
# The delete has to reach the decision, not only the table: a rule removed from
# storage while the snapshot still carries it is a denial the operator can
# neither see nor switch off.
check 'the next request is decided without the removed rule' '404' \
"$(code -H "$(xff "$GEO_IP")" "$EDGE/no-such-page")"
check 'deleting a rule that was never written says so, naming the code' '404' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/countries/ZZ")"
check 'and the sentence is about that code' 'no country rule for "ZZ"' \
"$(admin -X DELETE "$EDGE/admin-api/countries/ZZ" | jval error)"
check 'a lower-case delete finds the same answer' '404' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/countries/zz")"
# A delete of a code that was never a code. The handler validates the same way the
# write does, but nothing on the image had ever asked (OPEN-49): the four PUT
# refusals above were proven, the DELETE path was not, so a delete that skipped
# validation and answered 404 for "12" — or worse, 204 for a row that never existed
# — would have gone unnoticed. The sentence has to be the write's sentence, because
# an operator who mistyped a code gets it from whichever half they tried.
check 'a delete of a code that was never a code is refused, not run' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/countries/12")"
check 'with the same sentence the write refuses' 'yes' \
"$(admin -X DELETE "$EDGE/admin-api/countries/12" | jval error | grep -q 'two-letter ISO country code' && echo yes || echo no)"
check 'and a three-letter delete is refused by the same rule' '400' \
"$(admin_write -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -X DELETE "$EDGE/admin-api/countries/USA")"
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' \
"$(admin_write -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' \
"$(admin_write -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' \
"$(admin_write -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' \
"$([ "$(admin_write -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' \
"$(admin_write -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")
count_moved "${OPEN26_SNAP_FAILS:-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' \
"$(count_moved "${OPEN26_SNAP_FAILS:-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 '- a database that predates a table gains it when the edge restarts'
# OPEN-55. The default schema step is EnsureCreated: it creates a missing
# database and changes nothing about an existing one. So an operator who
# upgrades keeps a database with every table except the new ones, and the pillar
# those tables back answers as if there were nothing to see. This stack is that
# state by construction — its data volume outlives `compose down`, which is how
# the gap was first noticed here. The table is dropped from the volume, the edge
# restarts, and the question is whether the pillar works afterwards.
EDGE_CID=$(docker compose ps -q edge)
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
c.execute("DROP TABLE request_rules")
c.execute("DROP TABLE source_streaks")
# OPEN-60 added a table. A volume written by the previous release is exactly the
# state an upgrading operator is in, so the queue table goes too: the edge has to
# put it back by itself, with no operator migration step.
c.execute("DROP TABLE alert_pushes")
print("dropped; tables now:", sorted(r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")))
PYSQL
docker compose restart edge >/dev/null 2>&1
OPEN55_READY='000'
for _ in $(seq 1 12); do
code "$EDGE/no-such-page" >/dev/null
OPEN55_READY=$(code "$EDGE/readyz")
[ "$OPEN55_READY" = "200" ] && break
sleep 3
done
check 'the restarted edge is ready again' '200' "$OPEN55_READY"
OPEN55_STATE=$(admin "$EDGE/admin-api/state")
OPEN55_ADDED=$(printf '%s' "$OPEN55_STATE" | jval schemaTablesAdded)
printf ' info tables this start had to create: %s\n' "${OPEN55_ADDED:-none}"
check 'the state names the tables it had to add' 'yes' \
"$(count_ge "${OPEN55_ADDED:-0}" 3 && echo yes || echo no)"
# The table the durable push queue (OPEN-60) lives in, added by the edge to a
# database that predates it. A restart is the only thing that ran between the
# drop and this read.
OPEN55_PUSH_TABLE=$(sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
print("yes" if c.execute(
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='alert_pushes'"
).fetchone()[0] else "no")
PYSQL
)
check 'the push queue table was added to a database that predates it' 'yes' "$OPEN55_PUSH_TABLE"
check 'and the state counts the queue it now keeps' '0 0 0' \
"$(printf '%s' "$OPEN55_STATE" | jval alertPushPending) \
$(printf '%s' "$OPEN55_STATE" | jval alertPushDelivered) \
$(printf '%s' "$OPEN55_STATE" | jval alertPushGivenUp)"
check 'and says nothing the build needs is missing now' '[]' \
"$(printf '%s' "$OPEN55_STATE" | jval schemaMissingTables)"
check 'the rules pillar is reading again' 'true' \
"$(printf '%s' "$OPEN55_STATE" | jval requestRulesAvailable)"
# A table that exists is worth nothing unless the pillar behind it answers. The
# rule is written after the upgrade, so it can only work if the table it lands in
# is the one the guard reads.
OPEN55_IP="203.0.113.$(( 60 + RANDOM % 30 ))"
OPEN55_RULE_WRITE=$(admin -X POST -H 'Content-Type: application/json' \
-d "{\"pattern\":\"/upgrade-check*\",\"action\":\"block\",\"note\":\"compose: written after the upgrade\"}" \
-w '\nCODE%{http_code}' "$EDGE/admin-api/rules")
OPEN55_RULE_CODE=$(printf '%s' "$OPEN55_RULE_WRITE" | sed -n 's/.*CODE//p')
printf ' info the rule write answered: %s %s\n' "$OPEN55_RULE_CODE" \
"$(printf '%s' "$OPEN55_RULE_WRITE" | sed -n '1s/.*/&/p' | cut -c1-120)"
check 'a rule can be written into the table that was added' '204' "$OPEN55_RULE_CODE"
check 'and it refuses the path on the restarted edge' '403' \
"$(code -H "X-Forwarded-For: $OPEN55_IP" "$EDGE/upgrade-check")"
OPEN55_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/upgrade-check*'" id)
check 'and the rule is removable again, so the volume is left clean' '204' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/rules/$OPEN55_RULE")"
echo "- the edge's own numbers leave in Prometheus format"
# OPEN-58. The smoke gate proves the endpoint against a process built from this
# tree; this proves it against the shipped image, where the thing that could go
# wrong is the deployment: the always-pass prefix, the token, and the body
# staying aggregate on a stack that has real refusals and a real schema upgrade
# behind it.
check 'the metrics surface is closed without the token' '401' "$(code "$EDGE/metrics")"
OPEN58_TYPE=$(curl -s -m 10 -o /dev/null -w '%{content_type}' \
-H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/metrics")
check 'metrics answers in the Prometheus exposition format' 'text/plain; version=0.0.4; charset=utf-8' \
"$OPEN58_TYPE"
OPEN58_BODY=$(admin "$EDGE/metrics")
msample() { printf '%s\n' "$OPEN58_BODY" | awk -v p="$1" 'index($0,p)==1 { print $NF; exit }'; }
check 'the verdict counter counts the rule refusal this stack just made' 'yes' \
"$(count_gt "$(msample 'openwaf_requests_total{verdict="block_rule"} ')" 0 && echo yes || echo no)"
check 'the schema gauge says nothing the build needs is missing' '0' \
"$(msample 'openwaf_schema_missing_tables ')"
check 'the push queue is published as gauges on the shipped image' '0 0 0 0' \
"$(msample 'openwaf_alert_push_pending ') $(msample 'openwaf_alert_push_delivered_total ') \
$(msample 'openwaf_alert_push_given_up_total ') $(msample 'openwaf_alert_push_attempts_total ')"
check 'the write counters are published even on a healthy stack' '0' \
"$(msample 'openwaf_write_failures_total{pillar="bans"} ')"
check 'the body names no address from the scene above' 'yes' \
"$(printf '%s\n' "$OPEN58_BODY" | grep -qF "$OPEN55_IP" && echo no || echo yes)"
check 'and no per-source label exists anywhere in it' 'yes' \
"$(printf '%s\n' "$OPEN58_BODY" | grep -Eq '(^|,)(ip|path|user_agent)=' && echo no || echo yes)"
echo "- asking the shipped edge what it would answer (OPEN-59)"
# The same dry run against the image an operator would actually deploy. The scene
# above already wrote and removed a rule, so this writes one it can ask about and
# removes it again, leaving the volume as it found it.
OPEN59_IP="203.0.113.$(( 100 + RANDOM % 40 ))"
OPEN59_WRITE=$(admin -X POST -H 'Content-Type: application/json' \
-d '{"pattern":"/preview-only*","action":"block","note":"compose: asked, not sent"}' \
-w '\nCODE%{http_code}' "$EDGE/admin-api/rules")
check 'a rule can be written to be asked about' '204' "$(printf '%s' "$OPEN59_WRITE" | sed -n 's/.*CODE//p')"
OPEN59_DECIDE=$(admin "$EDGE/admin-api/decide?ip=$OPEN59_IP&path=/preview-only")
check 'the preview answers with the verdict the wire would give' block_rule \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')"
check 'and names the pillar that spoke' requestRule \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next((r["pillar"] for r in p if r["outcome"]=="answered"), "no-pillar"))')"
check 'and echoes the rule it matched, pattern and all' '/preview-only*' \
"$(printf '%s' "$OPEN59_DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["rule"]["pattern"])')"
check 'and refuses an address that is not an address rather than answering pass' '400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/decide?ip=203.0.113&path=/preview-only")"
OPEN59_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/preview-only*'" id)
check 'and the rule is removable again, so the volume is left clean' '204' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/rules/$OPEN59_RULE")"
echo "- the operator's config leaves the shipped edge as one document (OPEN-61)"
# The transfer on the image an operator would deploy. The in-process suite proves
# the round trip between two fixtures; what could go wrong here is the deployment:
# the route being behind the token, the document surviving the wire, and the
# imported row being enforced by the guard rather than only written to the table.
OPEN61_IP="203.0.113.$(( 150 + RANDOM % 20 ))"
admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$OPEN61_IP\",\"reason\":\"compose: written for the transfer\"}" \
"$EDGE/admin-api/blocks" >/dev/null
check 'the block the transfer scene needs is in force on the image' '301' \
"$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")"
OPEN61_DOC=$(admin "$EDGE/admin-api/export")
check 'the shipped export names the version this build reads' '1' \
"$(printf '%s' "$OPEN61_DOC" | jval version)"
check 'and counts the sections it carries' 'yes' \
"$(printf '%s' "$OPEN61_DOC" | python3 -c 'import sys,json;c=json.load(sys.stdin)["counts"];print("yes" if all(k in c for k in ("blocks","allow","rules","countries")) else "no")')"
check 'and says how many engine bans it deliberately left out' 'yes' \
"$(printf '%s' "$OPEN61_DOC" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("engineBlocksLeftBehind"), int) else "no")')"
admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$OPEN61_IP" >/dev/null
check 'deleting the block takes it off the wire' '404' \
"$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")"
OPEN61_IMPORT=$(admin -X POST -H 'Content-Type: application/json' --data-binary "$OPEN61_DOC" "$EDGE/admin-api/import")
check 'importing the document lands the block again' '1' \
"$(printf '%s' "$OPEN61_IMPORT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')"
check 'and the guard enforces the imported row, not only the table' '301' \
"$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")"
check 'importing the same document again adds nothing' '0' \
"$(admin -X POST -H 'Content-Type: application/json' --data-binary "$OPEN61_DOC" "$EDGE/admin-api/import" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')"
check 'a document from another version is refused naming the version' 'yes' \
"$(admin -X POST -H 'Content-Type: application/json' -d '{"version":999,"blocks":[]}' "$EDGE/admin-api/import" \
| grep -q '999' && echo yes || echo no)"
check 'and the closed surface stays closed over it' '401' \
"$(admin_write -X POST -H 'Content-Type: application/json' -d '{"version":1}' "$EDGE/admin-api/import")"
check 'the transfer row is removable again, so the volume is left clean' '200' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
"$EDGE/admin-api/blocks?source=operator&key=$OPEN61_IP")"
echo '- a second token that can look but not change'
# The read-only token (OPEN-62) against the shipped image. The 200s are the easy
# half; what the gate is really for is the shape of the refusal — a known token
# without the right answers 403 and names the key that would grant it, while an
# unknown token answers 401 — and the fact that the shipped image refuses to
# start when the two tokens are the same value.
check 'the shipped state says a second token exists' 'true' \
"$(admin "$EDGE/admin-api/state" | jval readOnlyTokenConfigured)"
check 'the read-only token reads the shipped state' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/state")"
check 'the read-only token reads the shipped block list' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/blocks")"
check 'the read-only token can scrape the shipped numbers' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/metrics")"
RO_WRITE=$(body -X POST -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" \
-H 'Content-Type: application/json' -d '{"ip":"203.0.113.181","reason":"must not land"}' \
"$EDGE/admin-api/blocks")
check 'a read-only token cannot write a block on the shipped image' '403' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.181","reason":"must not land"}' "$EDGE/admin-api/blocks")"
check 'the refusal says the token is read-only, not unknown' 'yes' \
"$(printf '%s' "$RO_WRITE" | grep -q 'read-only' && echo yes || echo no)"
check 'and it names the key that would grant the write' 'yes' \
"$(printf '%s' "$RO_WRITE" | grep -q 'OpenWaf__Admin__Token' && echo yes || echo no)"
check 'the refused write left no row behind' '0' \
"$(admin "$EDGE/admin-api/blocks?live=false" | jcount 'b["sourceKey"]=="203.0.113.181"')"
check 'a read-only token cannot change the shipped policy' '403' \
"$(admin_write -X PUT -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" -H 'Content-Type: application/json' \
-d '{"mode":"Off"}' "$EDGE/admin-api/policy")"
check 'a read-only token cannot read the shipped export' '403' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/export")"
check 'and the refusal says the document is a capability' 'yes' \
"$(curl -s -m 10 -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/export" \
| grep -q 'capability' && echo yes || echo no)"
check 'a read-only token cannot import a document' '403' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" -H 'Content-Type: application/json' \
-d '{"version":1,"blocks":[]}' "$EDGE/admin-api/import")"
check 'the admin token still writes on the shipped image' '204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.182","reason":"written by the admin token"}' "$EDGE/admin-api/blocks")"
check 'and that row is removable again, so the volume stays clean' '200' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
"$EDGE/admin-api/blocks?source=operator&key=203.0.113.182")"
check 'an unknown token is still 401 on the shipped image' '401' \
"$(code -H "X-Admin-Token: not-a-token" "$EDGE/admin-api/state")"
# The configuration the shipped image refuses to start with, run as a container.
# Asserted against the image rather than only the source, because "refused at
# startup" is a claim about what an operator who configures this actually gets.
BAD_LOG=/tmp/openwaf-compose-bad-$$.log
# Started detached and polled, not waited on: the assertion is that the process
# LEAVES. A refusal that prints its reason and then keeps running is a container
# that sits at full CPU forever with no exit code for the supervisor to react
# to, and a gate that blocks on it cannot tell that apart from a slow run.
BAD_NAME="openwaf-bad-token-$$"
docker compose run -d --name "$BAD_NAME" -e OPENWAF_READ_ONLY_TOKEN="$OPENWAF_ADMIN_TOKEN" edge >/dev/null 2>&1
BAD_RC=''
for _ in $(seq 1 30); do
if [ "$(docker inspect -f '{{.State.Status}}' "$BAD_NAME" 2>/dev/null)" = exited ]; then
BAD_RC=$(docker inspect -f '{{.State.ExitCode}}' "$BAD_NAME" 2>/dev/null)
break
fi
sleep 1
done
docker logs "$BAD_NAME" >"$BAD_LOG" 2>&1
docker rm -f "$BAD_NAME" >/dev/null 2>&1
check 'the shipped image leaves rather than sits there with a bad token pair' 'yes' \
"$([ -n "$BAD_RC" ] && [ "$BAD_RC" -ne 0 ] && echo yes || echo no)"
check 'it names both keys in the reason' 'yes' \
"$(grep -q 'OpenWaf__Admin__ReadOnlyToken' "$BAD_LOG" && grep -q 'OpenWaf__Admin__Token' "$BAD_LOG" && echo yes || echo no)"
check 'and it never prints the secret' 'yes' \
"$(grep -q "$OPENWAF_ADMIN_TOKEN" "$BAD_LOG" && echo no || echo yes)"
rm -f "$BAD_LOG"
echo '- every startup refusal leaves the container, it does not sit there'
# The same claim as the scene above, over the bounds this build refuses to run
# with. Each is raised by the type that owns it - the TTL during host start, the
# retention window through the policy, the alert bounds in the entry point - so
# the gate is what keeps the convention from rotting back into a printed
# complaint and a container that burns a core forever.
for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \
'OpenWaf__Policy__ObservationRetentionDays=0' \
'OpenWaf__Alerts__MaxPushAttempts=0'; do
key=${bad%%=*}
# The validators name the key in the appsettings spelling (OpenWaf:State:...),
# not the environment spelling, so the grep converts it before asking.
msg_key=${bad%%=*}
msg_key=${msg_key//__/:}
bad_name="openwaf-refused-$$"
docker compose run -d --name "$bad_name" -e "$bad" edge >/dev/null 2>&1
bad_rc=''
for _ in $(seq 1 30); do
if [ "$(docker inspect -f '{{.State.Status}}' "$bad_name" 2>/dev/null)" = exited ]; then
bad_rc=$(docker inspect -f '{{.State.ExitCode}}' "$bad_name" 2>/dev/null)
break
fi
sleep 1
done
docker logs "$bad_name" >"$BAD_LOG" 2>&1
docker rm -f "$bad_name" >/dev/null 2>&1
check "a bad $key leaves the shipped image with code 1" '1' "$bad_rc"
check " and the reason names the key" 'yes' \
"$(grep -q "$msg_key" "$BAD_LOG" && echo yes || echo no)"
done
rm -f "$BAD_LOG"
echo '- the record of a config change on the shipped image'
# The change log (OPEN-64) against the deployed image: what an operator reads at
# 03:00 is this surface, so the claim is asserted here and not only in a test.
CH_IP="203.0.113.$(( 170 + RANDOM % 20 ))"
admin -X POST -H 'Content-Type: application/json' -d "{\"ip\":\"$CH_IP\",\"reason\":\"shipped image record\"}" \
"$EDGE/admin-api/blocks" >/dev/null
CHANGES=$(admin "$EDGE/admin-api/changes?section=block")
check 'an operator block lands a record naming the address' 'yes' \
"$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print('yes' if any(c['target']=='$CH_IP' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")"
check 'the record carries the operator sentence' 'yes' \
"$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print('yes' if any('shipped image record' in (c.get('detail') or '') for c in json.load(sys.stdin)) else 'no')")"
check 'it names the surface, never a person' 'operator' \
"$(printf '%s' "$CHANGES" | python3 -c "import sys,json;print(next((c['actor'] for c in json.load(sys.stdin) if c['target']=='$CH_IP'), 'no-record'))")"
check 'no record claims to come from the engine' '0' \
"$(admin "$EDGE/admin-api/changes" | python3 -c 'import sys,json;print(len([c for c in json.load(sys.stdin) if c["actor"]=="engine"]))')"
check 'the read-only token can read the log' '200' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/changes")"
check 'the state counts the records' 'yes' \
"$(admin "$EDGE/admin-api/state" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("configChanges"), int) else "no")')"
CH_IMPORT=$(admin -X POST -H 'Content-Type: application/json' -d '{"version":1,"countries":[{"code":"fr","allowed":false}]}' "$EDGE/admin-api/import")
check 'the import report says one country landed' '1' \
"$(printf '%s' "$CH_IMPORT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["countries"]["added"])')"
# The newest imported record for the section, not a count: the transfer scene
# above imported documents more than once, and each import leaves one record per
# section it carried — which is exactly the ruling being asserted.
check 'an import is recorded per section, not per row' 'yes' \
"$(admin "$EDGE/admin-api/changes?section=country" | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print("yes" if d and "added" in (d[0].get("detail") or "") and len(d[0]["target"]) <= 16 else "no")')"
check 'and the import record says so' 'import' \
"$(admin "$EDGE/admin-api/changes?section=country" | python3 -c 'import sys,json;d=[c for c in json.load(sys.stdin) if c["action"]=="imported"];print(d[0]["actor"] if d else "none")')"
check 'a removal is recorded as a removal' 'yes' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
"$EDGE/admin-api/blocks?source=operator&key=$CH_IP" >/dev/null; \
admin "$EDGE/admin-api/changes?section=block" | python3 -c "import sys,json;print('yes' if any(c['target']=='$CH_IP' and c['action']=='removed' for c in json.load(sys.stdin)) else 'no')")"
check 'the country rule the import wrote is removable, so the volume stays clean' '204' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/countries/fr")"
echo '- an operator bans a range on the shipped image'
# The same feature on the deployed image (OPEN-66): the operator's block control
# takes a netblock, and the guard enforces it by containment. Aligned base, chosen
# per run, so a row left in the data volume by an earlier run cannot answer for
# this one.
RANGE_BASE=$(( 96 + (RANDOM % 4) * 8 ))
RANGE_NET="203.0.113.$RANGE_BASE/29"
RANGE_INSIDE="203.0.113.$(( RANGE_BASE + 3 ))"
RANGE_OUTSIDE="203.0.113.$(( RANGE_BASE + 8 ))"
# Same rule as the payloads at the top of this file: the body is built in a
# variable, not with escaped quotes inside a command substitution.
RANGE_JSON="{\"ip\":\"$RANGE_NET\",\"reason\":\"shipped netblock\"}"
check 'the shipped edge takes a CIDR as a block' '204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RANGE_JSON" "$EDGE/admin-api/blocks")"
check 'a source inside the range is refused on the wire' '301' \
"$(code -H "X-Forwarded-For: $RANGE_INSIDE" "$EDGE/anything")"
check 'a source one address past its end is served' '404' \
"$(code -H "X-Forwarded-For: $RANGE_OUTSIDE" "$EDGE/anything")"
check 'the shipped listing says which shape the row is' 'range' \
"$(admin "$EDGE/admin-api/blocks" | python3 -c "import sys,json;print(next((c['kind'] for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET'), 'no-such-row'))")"
check 'a range over every address is refused on the shipped image' '400' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"0.0.0.0/0","reason":"shutdown"}' "$EDGE/admin-api/blocks")"
check 'the shipped state counts ranges apart' 'yes' \
"$(admin "$EDGE/admin-api/state" | python3 -c "import sys,json;print('yes' if json.load(sys.stdin).get('operatorRanges') == 1 else 'no')")"
check 'the range is removable by its name, so the volume stays clean' '404' \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
"$EDGE/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \
code -H "X-Forwarded-For: $RANGE_INSIDE" "$EDGE/anything")"
echo '- the shipped edge notices a netblock behind its bans'
# The watch (OPEN-67) on the deployed image: the edge groups its own live engine
# bans into the block they sit under and offers that block, and taking the offer
# is the same call as any other block. Aligned base chosen per run, so a row the
# named volume kept from an earlier run cannot answer for this one.
NET_BASE=$(( 192 + (RANDOM % 4) * 4 ))
NET_A="203.0.113.$NET_BASE"
NET_B="203.0.113.$(( NET_BASE + 1 ))"
NET_FRESH="203.0.113.$(( NET_BASE + 2 ))"
NET_RANGE="203.0.113.0/24"
NET_ON_JSON="{\"streakThreshold\":2,\"netblockCandidateBans\":2}"
NET_OFF_JSON="{\"streakThreshold\":10,\"netblockCandidateBans\":0}"
NET_RANGE_JSON="{\"ip\":\"$NET_RANGE\",\"reason\":\"the netblock the shipped edge noticed\"}"
check 'the watch threshold is a policy key on the shipped image' '2' \
"$(admin -X PUT -H 'Content-Type: application/json' --data-binary "$NET_ON_JSON" \
"$EDGE/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["netblockCandidateBans"])')"
# The named volume outlives the run, and an engine ban an earlier scene wrote
# inside this /24 would be counted by the watch as evidence. Clearing the
# engine's list first is what makes the count below this scene's own.
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
for src in "$NET_A" "$NET_B"; do
code -H "X-Forwarded-For: $src" "$EDGE/anything" >/dev/null
code -H "X-Forwarded-For: $src" "$EDGE/anything" >/dev/null
done
check 'the shipped edge offers the block its bans sit inside' "$NET_RANGE" \
"$(admin "$EDGE/admin-api/netblocks" | python3 -c "import sys,json;print(next((n['match'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'), 'none'))")"
check 'the offer counts only the bans inside that block' '2' \
"$(admin "$EDGE/admin-api/netblocks" | python3 -c "import sys,json;print(next(n['bans'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE'))")"
check 'an offer is not a ban: a fresh source inside it is served' '404' \
"$(code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")"
check 'the shipped edge takes the offer with the block form' '204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary "$NET_RANGE_JSON" "$EDGE/admin-api/blocks")"
check 'the taken range refuses a source the engine never saw' '301' \
"$(code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")"
check 'the shipped state says what the watch is running on' 'yes' \
"$(admin "$EDGE/admin-api/state" | python3 -c "import sys,json;d=json.load(sys.stdin);print('yes' if d.get('netblockCandidateBans')==2 and d.get('netblockPrefixV4')==24 and d.get('netblockScanError') is None else 'no')")"
check 'the range and the bans that produced it are cleaned, so the volume stays clean' '404' \
"$(admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$NET_RANGE" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null; \
admin -X PUT -H 'Content-Type: application/json' --data-binary "$NET_OFF_JSON" \
"$EDGE/admin-api/policy" >/dev/null; \
code -H "X-Forwarded-For: $NET_FRESH" "$EDGE/anything")"
# A request budget for one path (OPEN-68), on the image an operator would
# actually ship. The scene is short because the claim is short: the pause covers
# the path it names, writes no ban, and stops the moment the row is gone.
echo '- the shipped edge holds a request budget for one path'
PATH_BUDGET_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
PATH_BUDGET_JSON='{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":120,"note":"compose scene"}'
PATH_BUDGET_IP=198.51.100.91
# The engine's list is cleared first: a path budget must not be judged against a
# ban some earlier scene left on this source.
admin -X DELETE "$EDGE/admin-api/blocks?source=engine" >/dev/null
admin -X PUT -H 'Content-Type: application/json' --data-binary "$PATH_BUDGET_ON_JSON" \
"$EDGE/admin-api/policy" >/dev/null
check 'the shipped edge takes a path budget' '204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_JSON" "$EDGE/admin-api/rate-rules")"
check 'the first two requests on that path are proxied' '404 404' \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted") $(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")"
check 'the third crosses the budget and the edge answers it' '429' \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")"
check 'the rest of the site stays open to that source' '404' \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/anything")"
check 'the shipped state counts the budgets it is enforcing' '1 yes' \
"$(admin "$EDGE/admin-api/state" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("rateRules"), "yes" if d.get("rateRulesAvailable") and d.get("rateRulesError") is None else "no")')"
check 'the shipped listing says who is over the budget now' '1' \
"$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["overBudgetNow"])')"
PATH_BUDGET_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
check 'removing the budget reopens the path, and the volume is left as it was' '404' \
"$(admin -X DELETE "$EDGE/admin-api/rate-rules/$PATH_BUDGET_ID" >/dev/null; \
admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \
"$EDGE/admin-api/policy" >/dev/null; \
code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$EDGE/budgeted")"
# The dry run answers the volume pillar (OPEN-69), on the shipped image: the
# preview used to answer every pillar and stay silent about the one whose number
# the operator is choosing.
echo '- the shipped dry run answers the volume pillar'
DRY_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
DRY_RULE_JSON='{"pattern":"/dryrun*","limitPerWindow":2,"windowSeconds":120}'
DRY_IP=198.51.100.92
admin -X PUT -H 'Content-Type: application/json' --data-binary "$DRY_ON_JSON" \
"$EDGE/admin-api/policy" >/dev/null
admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary "$DRY_RULE_JSON" "$EDGE/admin-api/rate-rules" >/dev/null
check 'the shipped preview answers the volume pillar for a source with nothing counted' 'yes' \
"$(admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" | python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["verdict"]=="would_be_counted" and v["edgeBudget"] is None and v["pathBudgets"][0]["counted"] is False else "no")')"
for _ in 1 2 3; do code -H "X-Forwarded-For: $DRY_IP" "$EDGE/dryrun" >/dev/null; done
check 'the shipped preview says this source is over that budget now' 'yes' \
"$(admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" | python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];b=v["pathBudgets"][0];print("yes" if v["verdict"]=="refused_now" and b["count"]==3 and b["overBudget"] else "no")')"
check 'six shipped previews leave the counters exactly where they were' '1 1' \
"$(for _ in 1 2 3 4 5 6; do admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" >/dev/null; done; \
admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])')"
DRY_RULE_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
check 'the scene cleans itself, so the volume is left as it was found' 'not_counted' \
"$(admin -X DELETE "$EDGE/admin-api/rate-rules/$DRY_RULE_ID" >/dev/null; \
admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \
"$EDGE/admin-api/policy" >/dev/null; \
admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["volume"]["verdict"])')"
# One address, one answer (OPEN-70), on the shipped image. The point is the join:
# an address the operator blocked on its own key, and an address a banned range
# covers without any row naming it. The second is the one every single-table
# listing answered "nothing".
echo '- the shipped edge answers one address in one call'
DOS_IP=198.51.100.141
DOS_NET=198.51.100.144/29 # .144 - .151
DOS_INSIDE=198.51.100.147
DOS_OUTSIDE=198.51.100.152
check 'the shipped edge takes an address block and a range block' '204 204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_IP"'","reason":"dossier scene"}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_NET"'","reason":"dossier range"}' "$EDGE/admin-api/blocks")"
check 'the shipped dossier answers on the key and names the row behind it' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and d["sourceKey"]=="'"$DOS_IP"'" and b and not b["cameFromRange"] and b["live"] else "no")')"
check 'the shipped dossier finds the range that covers an address no row names' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_INSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and b and b["cameFromRange"] and b["match"]=="'"$DOS_NET"'" else "no")')"
check 'the shipped dossier says none for a source it knows nothing about' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_OUTSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["verdict"]=="none" and not d["operatorBlock"] and not d["allow"] and not d["engineBan"] else "no")')"
check 'the shipped dossier refuses a question it cannot answer' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/source?ip=198.51.100") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/source")"
check 'asking it six times wrote nothing to the operator list' 2 \
"$(for _ in 1 2 3 4 5 6; do admin "$EDGE/admin-api/source?ip=$DOS_IP" >/dev/null; done; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$DOS_IP"'","'"$DOS_NET"'")]))')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$DOS_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=${DOS_NET//\//%2F}" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$DOS_IP"'","'"$DOS_NET"'")]))')"
# Who a path budget is pausing (OPEN-71), on the shipped image: the listing has
# named three numbers per budget and no source, so the only lever for one paused
# source was to take the budget off every source on the site.
echo '- the shipped budget says who it is pausing'
BUD_IP=198.51.100.161
BUD_IP2=198.51.100.162
admin -X PUT -H 'Content-Type: application/json' --data-binary "$DRY_ON_JSON" \
"$EDGE/admin-api/policy" >/dev/null
admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":300,"note":"who scene"}' \
"$EDGE/admin-api/rate-rules" >/dev/null
BUD_RULE_ID="$(admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/budgeted*"][0])')"
for _ in 1 2 3 4; do code -H "X-Forwarded-For: $BUD_IP" "$EDGE/budgeted" >/dev/null; done
for _ in 1 2 3 4; do code -H "X-Forwarded-For: $BUD_IP2" "$EDGE/budgeted" >/dev/null; done
check 'the shipped budget names both sources and says both are over' yes \
"$(admin "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources" | python3 -c 'import sys,json;d=json.load(sys.stdin);r=d["sources"];print("yes" if d["total"]==2 and len(r)==2 and all(x["overBudget"] for x in r) and d["scope"]=="this-process" else "no")')"
check 'the shipped names and the shipped counters are the same state' yes \
"$(admin "$EDGE/admin-api/rate-rules" -o /tmp/cbud_row.json; \
admin "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources" -o /tmp/cbud_src.json; \
python3 -c "import json;row=[x for x in json.load(open('/tmp/cbud_row.json')) if x['id']==$BUD_RULE_ID][0];d=json.load(open('/tmp/cbud_src.json'));print('yes' if row['liveWindows']==d['total'] and row['overBudgetNow']==sum(1 for x in d['sources'] if x['overBudget']) else 'no')")"
check 'the shipped edge lets one source out and calls it a reset, not an exemption' yes \
"$(admin -X DELETE "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources?source=$BUD_IP" \
| python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["cleared"] and "not an exemption" in d["note"] else "no")')"
check 'the let-out source is served again, the neighbour is still paused' '404 429' \
"$(code -H "X-Forwarded-For: $BUD_IP" "$EDGE/budgeted") \
$(code -H "X-Forwarded-For: $BUD_IP2" "$EDGE/budgeted")"
check 'the shipped read-only token reads the list and cannot clear it' '200 403' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources") \
$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" \
"$EDGE/admin-api/rate-rules/$BUD_RULE_ID/sources?source=$BUD_IP2")"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/rate-rules/$BUD_RULE_ID" >/dev/null; \
admin -X PUT -H 'Content-Type: application/json' --data-binary '{"rateMode":"Off"}' \
"$EDGE/admin-api/policy" >/dev/null; \
admin "$EDGE/admin-api/rate-rules" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
# What stops being enforced soon (OPEN-72), on the shipped image: the horizon is
# read from the database, so it has to answer the same way through the container
# as through the process, and the prediction it makes has to hold on the wire.
echo '- the shipped edge says what stops answering soon'
HOR_IP=198.51.100.171
HOR_NET=198.51.100.176/29 # .176 - .183
HOR_INSIDE=198.51.100.179
check 'the shipped edge takes a block, a range and an allow that all expire today' '204 204 204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HOR_IP"'","reason":"horizon block","expiresInMinutes":45}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HOR_NET"'","reason":"horizon range","expiresInMinutes":20}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$HOR_INSIDE"'","note":"horizon allow","expiresInMinutes":60}' "$EDGE/admin-api/allow")"
check 'the shipped horizon lists them nearest first and says the range refuses once the allow ages out' yes \
"$(admin "$EDGE/admin-api/expiring?within=90" | python3 -c '
import sys,json
d=json.load(sys.stdin)
rows=[r for r in d["expiring"] if r["match"] in ("'"$HOR_IP"'","'"$HOR_NET"'","'"$HOR_INSIDE"'")]
order=[r["match"] for r in rows]
a=[r for r in rows if r["kind"]=="allow"]
t=a[0]["thenAnswers"] if a else None
print("yes" if d["scope"]=="database" and order==["'"$HOR_NET"'","'"$HOR_IP"'","'"$HOR_INSIDE"'"] and t and t["verdict"]=="block_operator" and t["by"]=="'"$HOR_NET"'" else "no")')"
check 'the shipped horizon says a block with nothing underneath leaves the source free' yes \
"$(admin "$EDGE/admin-api/expiring?within=90" | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="block" and r["match"]=="'"$HOR_IP"'"]
t=rows[0]["thenAnswers"] if rows else None
print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] else "no")')"
check 'the shipped horizon refuses a window of zero minutes or of more than a day' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/expiring?within=0") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/expiring?within=1441")"
check 'the shipped read-only token reads the horizon, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/expiring?within=90") \
$(code "$EDGE/admin-api/expiring?within=90")"
HOR_ALLOW_ID="$(admin "$EDGE/admin-api/allow?live=false" | python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$HOR_INSIDE"'"][0])')"
check 'the shipped prediction holds: with the allow gone the wire refuses that address' block_operator \
"$(admin -X DELETE "$EDGE/admin-api/allow/$HOR_ALLOW_ID" >/dev/null; \
admin "$EDGE/admin-api/decide?ip=$HOR_INSIDE&path=/" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$HOR_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=${HOR_NET//\//%2F}" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$HOR_IP"'","'"$HOR_NET"'")]))')"
# One source through time (OPEN-73), on the shipped image: the join runs against
# the database the container holds, so the story has to be assembled there too.
echo '- the shipped edge tells one source story in order'
HIS_IP=198.51.100.187
HIS_NET=198.51.100.184/29 # .184 - .191
HIS_NONE=192.31.196.7 # outside every range this run writes
check 'the shipped edge bans the network, the address inside it, then exempts it' '204 204 204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_NET"'","reason":"history netblock"}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_IP"'","reason":"history address"}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$HIS_IP"'","note":"history allow","expiresInMinutes":60}' "$EDGE/admin-api/allow")"
check 'the shipped story names the block, the covering range and the exemption, oldest first' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_IP" | python3 -c '
import sys,json
d=json.load(sys.stdin)
k=[e["kind"] for e in d["events"]]
stamps=[e["at"] for e in d["events"]]
print("yes" if d["sourceKey"]=="'"$HIS_IP"'" and d["scope"]=="database"
and all(x in k for x in ("range ban","operator block","allow entry","config change"))
and stamps == sorted(stamps) else "no")')"
check 'the shipped story says the range is there because it covers the address' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_IP" | python3 -c '
import sys,json
e=[x for x in json.load(sys.stdin)["events"] if x["kind"]=="range ban"]
r=e[0] if e else None
print("yes" if r and r["match"]=="'"$HIS_NET"'" and r["inForce"]
and "covers this address" in r["what"] else "no")')"
check 'the shipped story answers an address with nothing recorded in words' yes \
"$(admin "$EDGE/admin-api/history?ip=$HIS_NONE" | python3 -c '
import sys,json
d=json.load(sys.stdin); s=d["searched"]
print("yes" if d["count"]==0 and not any(s.values()) and "nothing recorded" in d["note"] else "no")')"
check 'the shipped history refuses a window of zero minutes and a bare address' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/history?ip=$HIS_IP&within=0") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/history?ip=198.51.100")"
check 'the shipped read-only token reads a story, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/history?ip=$HIS_IP") \
$(code "$EDGE/admin-api/history?ip=$HIS_IP")"
HIS_ALLOW_ID="$(admin "$EDGE/admin-api/allow?live=false" | python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$HIS_IP"'"][0])')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$HIS_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=${HIS_NET//\//%2F}" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/allow/$HIS_ALLOW_ID" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$HIS_IP"'","'"$HIS_NET"'")]))')"
# Where does this appear? (OPEN-74), on the shipped image: one query across the
# stores the operator's decisions live in, including the rows that cover an
# address rather than name it.
echo '- the shipped edge searches every store at once'
FND_IP=198.51.100.195
FND_NET=198.51.100.192/29 # .192 - .199
findq() { admin "$EDGE/admin-api/find?q=$1${2:+&$2}"; }
check 'the shipped edge writes the same phrase into three stores' '204 204 204' \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$FND_IP"'","reason":"ticket 441 closed"}' "$EDGE/admin-api/blocks") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$FND_NET"'","note":"ticket 441 window"}' "$EDGE/admin-api/allow") \
$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-gate*","action":"block","note":"ticket 441 path"}' "$EDGE/admin-api/rules")"
check 'the shipped query comes back from every store that holds it' '1 1 1' \
"$(findq 'ticket%20441' | python3 -c '
import sys,json
c=json.load(sys.stdin)["counts"]
print(c["block"], c["allow"], c["pathRule"])')"
check 'the shipped search treats "100%" as text, not as LIKE grammar' yes \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"198.51.100.196","reason":"100% sure"}' "$EDGE/admin-api/blocks" >/dev/null; \
findq '100%25' | python3 -c '
import sys,json
d=json.load(sys.stdin)
print("yes" if d["counts"]["block"]==1 and all("100%" in (r["text"] or "") for r in d["results"])
else "no")')"
check 'the shipped search finds the entry that covers an address and says so' yes \
"$(findq "$FND_IP" | python3 -c '
import sys,json
d=json.load(sys.stdin)
by=[r for r in d["results"] if r["store"]=="allow"]
print("yes" if d["asAddress"]["sourceKey"]=="'"$FND_IP"'" and len(by)==1
and by[0]["match"]=="'"$FND_NET"'" and "covers '"$FND_IP"'" in by[0]["why"] else "no")')"
check 'the shipped search answers an empty query with all eight stores counted' yes \
"$(findq 'nothing%20like%20this' | python3 -c '
import sys,json
d=json.load(sys.stdin); c=d["counts"]
print("yes" if d["matched"]==0 and len(c)==8 and not any(c.values()) else "no")')"
check 'the shipped search refuses a one-character query and an unknown parameter' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/find?q=x") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/find?q=ticket&store=block")"
check 'the shipped read-only token searches, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/find?q=ticket%20441") \
$(code "$EDGE/admin-api/find?q=ticket%20441")"
FND_ALLOW_ID="$(admin "$EDGE/admin-api/allow?live=false" | python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$FND_NET"'"][0])')"
FND_RULE_ID="$(admin "$EDGE/admin-api/rules" | python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-gate*"][0])')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$FND_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=198.51.100.196" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/allow/$FND_ALLOW_ID" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/rules/$FND_RULE_ID" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$FND_IP"'","'"$FND_NET"'","198.51.100.196")]))')"
# What would this ban touch? (OPEN-75), on the shipped image: the preview runs
# against the snapshot and the observations this container actually holds, so the
# answer is about the sources this edge is watching, not about a table the test
# wrote.
echo '- the shipped edge previews what a ban would touch'
IMP_NET=198.51.100.200/29 # .200 - .207
IMP_NET_Q=198.51.100.200%2F29
IMP_A=198.51.100.201
IMP_B=198.51.100.202
impactq() { admin "$EDGE/admin-api/impact?match=$1${2:+&$2}"; }
imp_seen() {
# The observation writer is a pillar on its own timer, and the preview probes
# the sources the edge has actually recorded.
for _ in $(seq 1 45); do
n=$(admin "$EDGE/admin-api/observations?limit=1000" | python3 -c '
import json,sys
print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))')
if [ "$n" -ge 2 ]; then return 0; fi
sleep 1
done
return 0
}
check 'the shipped edge has seen two sources inside the range' '404 404' \
"$(code -H "X-Forwarded-For: $IMP_A" "$EDGE/imp-a") $(code -H "X-Forwarded-For: $IMP_B" "$EDGE/imp-b")"
check 'the shipped edge has recorded them as observations' 2 \
"$(imp_seen; admin "$EDGE/admin-api/observations?limit=1000" | python3 -c '
import json,sys
print(sum(1 for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$IMP_A"'","'"$IMP_B"'")))')"
check 'the shipped preview names three sources the range would newly refuse' '3 0 0' \
"$(impactq "$IMP_NET_Q" | python3 -c '
import json,sys
c=json.load(sys.stdin)["counts"]
print(c["newlyRefused"], c["alreadyRefused"], c["stillPassing"])')"
check 'the shipped preview answers about the row the write would create' yes \
"$(impactq '198.51.100.205%2F29' | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["match"]=="198.51.100.200/29" and d["kind"]=="range" else "no")')"
check 'the shipped preview refuses a /0 in the writes words' yes \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/impact?match=198.51.100.0/0" >/dev/null; \
admin "$EDGE/admin-api/impact?match=198.51.100.0/0" \
| python3 -c 'import json,sys;print("yes" if "shutdown, not a ban" in json.load(sys.stdin)["error"] else "no")')"
check 'the shipped preview says an exemption over the whole match makes the ban refuse nobody' yes \
"$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$IMP_NET"'","note":"the block is exempt"}' "$EDGE/admin-api/allow" >/dev/null; \
impactq "$IMP_NET_Q" | python3 -c '
import json,sys
d=json.load(sys.stdin)
out=[a["match"] for a in d["outrankedBy"]]
print("yes" if d["changesNothing"] and not d["wouldRefuse"] and out==["198.51.100.200/29"]
else "no")')"
check 'the shipped preview is a read: the wire still answers the upstream' 404 \
"$(code -H "X-Forwarded-For: $IMP_A" "$EDGE/imp-c")"
check 'the scene cleans itself' 0 \
"$(admin_write -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
"$EDGE/admin-api/allow/$(admin "$EDGE/admin-api/allow?live=false" \
| python3 -c 'import sys,json;print(next((a["id"] for a in json.load(sys.stdin) if a["match"]=="'"$IMP_NET"'"), 0))')" >/dev/null; \
admin "$EDGE/admin-api/allow?live=false" \
| python3 -c 'import json,sys;print(len([a for a in json.load(sys.stdin) if a["match"].startswith("198.51.100.20")]))')"
check 'the shipped read-only token previews, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $OPENWAF_READ_ONLY_TOKEN" "$EDGE/admin-api/impact?match=$IMP_NET_Q") \
$(code "$EDGE/admin-api/impact?match=$IMP_NET_Q")"
echo '- a redirect target that arrived by a route the API refuses is still never sent'
# OPEN-40. The write-side guard is proven above. The read-side guard — the one
# that re-checks RedirectTarget.IsSendable on every request, in
# DecisionEngine.BlockResponse — had never been shown on the shipped image,
# because the API cannot be asked to store a target it refuses, and no other
# route writes one. The row that guard exists for is a row that got there another
# way: a restored backup, a hand edit, an import from a release that had no
# guard. So the gate writes a good row through the API, rewrites the stored
# column underneath a running edge, and asks what the edge sends now.
BADRED_SRC=203.0.113.248
BADRED_NET_SRC=203.0.113.249
for S in $BADRED_SRC $BADRED_NET_SRC; do
admin -X POST -H 'Content-Type: application/json' \
-d "{\"ip\":\"$S\",\"reason\":\"good target\",\"redirectTo\":\"https://honeypot.example.org/good\"}" \
"$EDGE/admin-api/blocks" >/dev/null
done
check 'a sendable target is sent while it is sendable' 'https://honeypot.example.org/good' \
"$(hdr -H "$(xff "$BADRED_SRC")" "$EDGE/any/path" | sed -n 's/^[Ll]ocation: //p')"
EDGE_CID=$(docker compose ps -q edge)
# The column is looked up in the schema rather than typed here: this scene is
# about the value, and a scene that goes red because a column was renamed stops
# proving anything about the guard.
sidecar <<PYSQL
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
cols = [r[1] for r in c.execute("PRAGMA table_info(block_entries)")]
col = next(n for n in cols if n.lower() == "redirectto")
for src, val in (("$BADRED_SRC", "javascript:alert(1)"),
("$BADRED_NET_SRC", "http://x.invalid/\\r\\nX-Injected: 1")):
n = c.execute("UPDATE block_entries SET %s = ? WHERE SourceKey = ?" % col, (val, src)).rowcount
print(" info rewrote %s stored row(s) for %s to %r" % (n, src, val))
PYSQL
# The guard reads the snapshot, and the snapshot is rebuilt on the TTL, so the
# rewritten row has to be allowed to arrive before it can be judged.
BADRED_CODE=''
BADRED_LOC=''
for _ in $(seq 1 14); do
BADRED_HDR=$(hdr -H "$(xff "$BADRED_SRC")" "$EDGE/any/path")
BADRED_CODE=$(printf '%s' "$BADRED_HDR" | sed -n 's|^HTTP/[0-9.]* \([0-9]\{3\}\).*|\1|p')
BADRED_LOC=$(printf '%s' "$BADRED_HDR" | sed -n 's/^[Ll]ocation: //p')
[ "$BADRED_LOC" != "https://honeypot.example.org/good" ] && break
sleep 3
done
printf ' info with a javascript: target in the stored row: %s, Location %s\n' \
"${BADRED_CODE:-none}" "${BADRED_LOC:-none}"
# Not inside $( ): a case pattern ending in `*)` closes an enclosing command
# substitution, so the first version of this assertion compared the literal text
# `echo no ;; *) echo yes ;; esac)` and went red about a Location that was fine.
# The same trap this file already names for the CRLF refusal above it.
BADRED_LEAKS=no
case "$BADRED_LOC" in
*javascript:*) BADRED_LEAKS=yes ;;
esac
check 'the stored javascript: target is never sent as a Location' 'no' "$BADRED_LEAKS"
check 'and the request is still a block, not a server error' '301' "$BADRED_CODE"
check 'and it falls back to the policy default target' 'https://www.iana.org/help/example-domains' \
"$BADRED_LOC"
BADRED2_HDR=$(hdr -H "$(xff "$BADRED_NET_SRC")" "$EDGE/any/path")
BADRED2_CODE=$(printf '%s' "$BADRED2_HDR" | sed -n 's|^HTTP/[0-9.]* \([0-9]\{3\}\).*|\1|p')
printf ' info with a CRLF-bearing target in the stored row: %s\n' "${BADRED2_CODE:-none}"
check 'a stored CRLF target does not turn the block into a 500' '301' "$BADRED2_CODE"
check 'and it injects no header on the way out' 'yes' \
"$(printf '%s' "$BADRED2_HDR" | grep -qi 'X-Injected' && echo no || echo yes)"
for S in $BADRED_SRC $BADRED_NET_SRC; do
admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$S" >/dev/null
done
check 'the scene leaves no block behind' '404 404' \
"$(code -H "$(xff "$BADRED_SRC")" "$EDGE/any/path") $(code -H "$(xff "$BADRED_NET_SRC")" "$EDGE/any/path")"
echo '- the gate tells a dead edge from a slow one'
# OPEN-39. A 000 from curl is the gate failing to reach the edge, and until now
# the log carried the number and nothing else, so "the edge hung" and "the edge
# died" produced the same red line. The helper now samples the container with
# every 000; this proves the distinction end to end by making the dead case
# happen on purpose, which is the only way to show the diagnosis names it.
DEAD_CODES_BEFORE=$(dead_codes)
docker compose stop edge >/dev/null 2>&1
DEAD_CODE=$(code "$EDGE/any/path")
DEAD_STATE=$(edge_state)
printf ' info with the container stopped: curl answered %s and the container reports %s\n' \
"$DEAD_CODE" "$DEAD_STATE"
check 'a stopped edge answers no http code at all' '000' "$DEAD_CODE"
check 'and the gate names the container state that goes with it' 'exited' \
"$(printf '%s' "$DEAD_STATE" | cut -d/ -f1)"
check 'and the 000 was counted as an unreachable answer' 'yes' \
"$(count_gt "$(dead_codes)" "$DEAD_CODES_BEFORE" && echo yes || echo no)"
# The gate's own instruments, asked while the edge is dead. This is the state the
# NativeAOT measurement run of 2026-10-06 sat in for its whole length, and what
# it produced there was 125 Python tracebacks and 32 `integer expression
# expected` shell errors — the gate describing its own failure in the same breath
# as the product's, and in two places (`!= 0` on a counter that was never read)
# describing it as a pass. Asserted against a container that is really stopped,
# not against a canned string: the read is the same read every scene above makes.
DEAD_READS=$(mktemp "${TMPDIR:-/tmp}/openwaf-dead-reads.XXXXXX")
# The redirection goes on the *pipeline*, not on its last command: `a | b 2>f`
# captures only b's stderr, and the first version of this scene wrote the nine
# diagnosis lines to the terminal and read back an empty file. The diagnosis is
# printed by the first command, so the group is what has to be redirected.
DEAD_JVAL=$( { admin "$EDGE/admin-api/state" | jval banWriteFailures; } 2>"$DEAD_READS")
DEAD_JCOUNT=$( { admin "$EDGE/admin-api/blocks" | jcount "True"; } 2>>"$DEAD_READS")
DEAD_JGET=$( { admin "$EDGE/admin-api/blocks" | jget "True" "sourceKey"; } 2>>"$DEAD_READS")
DEAD_CMP=no
if count_ge "$DEAD_JVAL" 1 || count_gt "$DEAD_JCOUNT" 0; then DEAD_CMP=yes; fi
check 'a dead edge reads as no body, not as a traceback' 'NO_JSON_BODY' "$DEAD_JVAL"
check 'a dead edge counts as -1, the sentinel streaks_where already used' '-1' "$DEAD_JCOUNT"
check 'and the list-field read says the same thing in the other helper' 'NO_JSON_BODY' "$DEAD_JGET"
check 'a comparison on a value that was never read answers no' 'no' "$DEAD_CMP"
# The sentinel says the body is missing; it never said the request did not happen.
# That distinction is OPEN-39's whole point, and the body-returning helper did not
# carry it. With the edge stopped these three reads now print nine lines — three
# attempts each, each naming the container state it sampled — and not one
# traceback. The assertion that used to sit here demanded *silence* on stderr,
# which is the gate agreeing to be blind: the diagnosis it now prints is the
# thing that made the 2026-10-06 flake readable at all.
check 'a read that reached the dead edge says so out loud, three retries each' '9' \
"$(grep -c 'the request reached nothing' "$DEAD_READS")"
check 'and every one of those lines names the container state it sampled' '9' \
"$(grep -c 'the edge reports exited' "$DEAD_READS")"
check 'and not one of them is a traceback' '0' "$(grep -c Traceback "$DEAD_READS")"
# A write aimed at that same stopped edge, so the retry rule above is a measured
# behaviour and not a comment: three retries, said out loud, and the answer the
# scene gets is still the honest 000 rather than a code that would let the rest
# of a scene read as if its seed had landed.
DEAD_WRITE_ERR=$(mktemp "${TMPDIR:-/tmp}/openwaf-dead-write.XXXXXX")
DEAD_WRITE=$(admin_write -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.253","reason":"a write that cannot land"}' \
"$EDGE/admin-api/blocks" 2>"$DEAD_WRITE_ERR")
check 'a write aimed at a dead edge is retried and still answers nothing' '000' "$DEAD_WRITE"
check 'and the retries are said out loud, three of them' '3' \
"$(grep -c 'the write reached nothing' "$DEAD_WRITE_ERR")"
rm -f "$DEAD_WRITE_ERR"
docker compose start edge >/dev/null 2>&1
ALIVE_STATE='none'
for _ in $(seq 1 90); do
ALIVE_STATE=$(edge_state)
[ "$ALIVE_STATE" = "running/healthy" ] && break
sleep 1
done
printf ' info the container came back as %s\n' "$ALIVE_STATE"
check 'the edge is running and healthy again' 'running/healthy' "$ALIVE_STATE"
check 'and the stack answers the upstream again' '404' "$(code "$EDGE/no-such-page")"
echo "- the gate's own writes all answer through the retry helper"
# a8f440b wrote that every admin write in this gate goes through the retry
# helper. Measured against this file the same day: 34 of its 60 writes that do not
# go through `admin` did, 25 still answered through the un-retried status helper
# and one went straight to curl. So the sentence was a claim about the gate, and nothing in the
# gate could tell anyone it was false — the same defect this file keeps naming one
# level down. The gate now counts its own bypassing write sites by reading its own
# source, which is the only way the rule survives the next write someone adds.
SELF_PATH=${BASH_SOURCE[0]}
if [ -r "$SELF_PATH" ]; then
BYPASS_CODE=$(grep -cE '(^|[^_[:alnum:]])code[[:space:]]+[^|]*-X[[:space:]]+(POST|PUT|DELETE)' "$SELF_PATH")
BYPASS_CURL=$(grep -cE '(^|[^_[:alnum:]])curl[[:space:]][^|]*-X[[:space:]]+(POST|PUT|DELETE)' "$SELF_PATH")
else
# Fails closed: an unreadable self is a red assertion, not a vacuous pass.
BYPASS_CODE=cannot-read-the-gate-source
BYPASS_CURL=cannot-read-the-gate-source
fi
printf ' info write sites in this file that bypass the retry helper: %s via the status helper, %s via raw curl\n' \
"$BYPASS_CODE" "$BYPASS_CURL"
check 'no admin write in this gate answers through the un-retried status helper' '0' "$BYPASS_CODE"
check 'and none of its writes goes straight to curl' '0' "$BYPASS_CURL"
echo
# The total is printed for the reader, and written where
# scripts/ci-gates.sh readme-counts can compare it with the number the README
# claims for this gate (OPEN-46: the README said 229 while this file was
# printing 356, and nothing anywhere could tell).
if [ -n "${GATE_TOTALS_DIR:-}" ]; then
mkdir -p "$GATE_TOTALS_DIR"
printf 'scripts/compose-smoke.sh %d %d\n' "$PASS" "$FAIL" > "$GATE_TOTALS_DIR/scripts_compose-smoke.sh.txt"
fi
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]