Files
openwaf/scripts/compose-smoke.sh
T
Pavlo Ratushnyi d871d5791b The redirect target an edge cannot send is now refused by the shipped image, not only by the test host
OPEN-21's validator had never been driven from the image: the compose
gate wrote a valid redirectTo and asserted the 301, and never once sent
a CRLF, a javascript: or a relative target. Six assertions close that —
400 for each shape, the refusal naming the field, zero rows written for
either address, and both addresses still reaching the upstream
afterwards, which is what "no half-blocked visitor" means when the
block list is read by the next request rather than this one.

Two harness traps found on the way and written into the script: under
set -o pipefail, curl | grep -q reports failure because grep exits on
the first match and curl dies of SIGPIPE — the assertion went red about
a body that said exactly the right sentence; and a case pattern ending
in *) closes an enclosing command substitution, so the first rewrite
printed the rest of the line as the value under test.
2026-10-02 18:37:34 +02:00

800 lines
50 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
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
}
admin() { curl -s -m 10 -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; }
# 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.
jcount() { python3 -c "import json,sys
d=json.load(sys.stdin); print(sum(1 for b in d if $1))"; }
jget() { python3 -c "import json,sys
d=json.load(sys.stdin)
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)"
}
code() { curl -s -m 10 -o /dev/null -w '%{http_code}' "$@"; }
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.
jval() { python3 -c "import json,sys
d=json.load(sys.stdin); v=d.get('$1')
print('' if v is None else (json.dumps(v) if isinstance(v,(bool,int,float)) else v))"; }
# 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'"; }
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
}
trap cleanup EXIT
echo '- starting the stack'
docker compose up -d --build >/dev/null 2>&1 || { echo "compose up failed"; exit 1; }
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 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
[ "$(docker inspect --format '{{.State.Health.Status}}' "$CID")" = healthy ] && break
sleep 0.5
done
check 'image HEALTHCHECK reports healthy' 'healthy' "$(docker inspect --format '{{.State.Health.Status}}' "$CID")"
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' \
"$(code -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' \
"$(code -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' \
"$(code -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")
[ "${ACOUNT:-0}" -gt "${BEFORE_ERR:-0}" ] && break
sleep 0.5
done
ERR_DELTA=$(( ${ACOUNT:-0} - ${BEFORE_ERR:-0} ))
check 'a server_error_streak alert was written for that source' 'yes' "$([ "$ERR_DELTA" -ge 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.
sleep 2
ERR_SETTLED=$(alerts_for server_error_streak "$ERR_SRC")
ERR_ROWS=$(( ${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
[ "$(alerts_for candidate_ban "$OBS_SRC")" -gt "${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.
sleep 2
OBS_ROWS=$(( $(alerts_for 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'")
[ "${FILTER_ROWS:-0}" != "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' \
"$(code -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' \
"$(code -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' \
"$(code -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'")"
code -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' \
"$(code -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 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() { 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)
[ "${POLICY_FAILS:-0}" != "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' \
"$([ "${POLICY_FAILS:-0}" != "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)
[ "${OBS_FAILS:-0}" != "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' \
"$([ "${OBS_FAILS:-0}" != "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)"
check 'the state counts the ban write that failed' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval banWriteFailures | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'and says how many bans were never written' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval bansNotWritten | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'readiness names the ban writes, because this is the enforcement path' '503' "$(code "$EDGE/readyz")"
check 'the reason it quotes is the storage error, not a concurrency race' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval banLastWriteError | 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' \
"$([ "${BAN_LOG_LINES:-0}" -ge 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)
[ "${PENDING:-0}" != "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' \
"$([ "${PENDING:-0}" -ge 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
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]