Files
openwaf/scripts/compose-smoke.sh
T
Pavlo Ratushnyi b6126c2fd2 Two rules that had only ever been proven inside a test process
`Server errors alert, they never ban` and `Observe mode records the decision and
blocks nothing` are the two claims that protect honest traffic from this WAF: a
bad deploy must not lock out the site's own visitors, and a dry run must be
judgeable before it is allowed to act. Both were proven in-process, against
`FakeUpstream`, in `EdgeBlockingTests`. Neither had ever been proven against the
image users actually run. And `GET /admin-api/alerts` appeared in **zero** gate
scripts — the operator-visible half of the alerting pillar had no gate at all,
which is how the console gate found its first bug: everything below the surface
looks fine while nothing reads it.

`deploy/upstream.conf` is nginx's own default plus one path that answers 502,
mounted read-only into the compose upstream. `scripts/compose-smoke.sh` grew two
sections, 28 → **35 assertions**:

    - server errors alert, and never ban
      a 502 reaches the client through the edge / four 502s did not ban the source
      that saw them / no engine ban written / a server_error_streak alert exists
    - Observe mode records the decision and blocks nothing
      five refusals still reach the upstream / no ban written / the dry run is
      visible as a candidate_ban alert

Numbers: host **35 passed, 0 failed**; the same script in the Linux rehearsal
(`docker:cli` against the host daemon) **35 passed, 0 failed**.

Two lessons about counting, both written into the script:

- The data volume survives `compose down`, so an absolute alert count asserts
  history rather than this run. Alerts are counted as a delta now.
- The alert is written *after* the response is, so a count read the instant the
  last request returns undercounts. The first version of the measurement line
  printed 1 where the settled number is 2. A number that is wrong by a race is
  worse than no number, so the count is taken after a pause.

The measurement itself is the finding: **4 requests past N=3 wrote 2 alert rows**
— one row per response past the threshold, not one per source. A real 5xx storm
therefore writes at request rate. Retention ages alerts out (`BanRetention`), so
they do not accumulate forever, but the write rate is a number an operator should
know before their upstream falls over.

Honest about the fixture: the 502 is nginx returning it directly, not an
application failing behind nginx. The edge's classifier sees a status code on a
socket, which is exactly what the rule is about; the fixture does not simulate a
crashed process, and nothing should read it as if it did.
2026-10-01 16:24:02 +02:00

233 lines
14 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"; }
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"; }
# 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 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'")"
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 '- 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")"
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 1 2 3 4; 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 'four 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)"
# Not an assertion, a measurement. The alert fires on every response *past* the
# threshold, so a 5xx storm writes one row per request rather than one per
# 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 is
# 2, and a number that is wrong by a race is worse than no number. Retention ages
# alerts out (BanRetention), but the write rate is what an operator should see.
sleep 2
ERR_SETTLED=$(alerts_for server_error_streak "$ERR_SRC")
printf ' info alert rows for 4 requests past the threshold: %s (N=3 — one per response past N)\n' \
"$(( ${ERR_SETTLED:-0} - ${BEFORE_ERR:-0} ))"
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 1 2 3 4 5; do code -H "$(xff "$OBS_SRC")" "$EDGE/no-such-page" >/dev/null; done
check 'five 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"
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
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]