Files
openwaf/scripts/smoke.sh
T
Pavlo Ratushnyi 4e303cd0ad
ci / build the image and smoke it (push) Failing after 57s
ci / lint the workflow and the shell (push) Successful in 12s
ci / build, test, smoke (push) Successful in 2m39s
ci / the operator page in a real browser (push) Failing after 1m38s
the two docker jobs install the CLI the runner image never shipped
First real run of this workflow: Gitea Actions run 2316 on 6f92d37. Three jobs
red, each with a cause that names itself in the log:

  lint    — shellcheck 0.11.0: 2x SC2086 in scripts/smoke.sh (835, 837)
  image   — ./scripts/ci-gates.sh:44: docker: command not found (exit 127)
  console — - starting the stack / compose up failed (exit 7)
  source  — success, 1m53s

The runner's job image ships no docker CLI while /var/run/docker.sock is mounted
from the host, so the image and console jobs now install docker-ce-cli and
docker-compose-plugin themselves and then fail loudly, at that step, if the
socket is not there — an infrastructure answer should read as infrastructure
rather than as a broken product three steps later. Same install the
neemle-landing pipeline on this instance already uses.

The two SC2086 findings are the string-concatenation trick inside a single-quoted
python -c: '$EDGE_PORT' expands unquoted. Now '"$EDGE_PORT"', which is what
shellcheck proposed and what the scene was already meaning.

Gate evidence on this tree: shellcheck 0.11.0 (the pinned version, same command
as the gate: shellcheck -s bash scripts/*.sh) clean; scripts/smoke.sh 256 passed
/ 0 failed on EDGE_PORT=18411. build and unit were green at ddddfc8 and nothing
here touches C# — integration was not re-run locally, its two host-specific
races are OPEN-47 and OPEN-76.

The header comments that said this file had never executed on a runner are now
wrong and say what happened instead.
2026-10-05 20:46:22 +02:00

1458 lines
96 KiB
Bash
Executable File

#!/usr/bin/env bash
# End-to-end smoke test against a real edge and a real upstream.
#
# The integration tests prove the decision logic in isolation; this proves the
# deployed shape: the binary starts, proxies to an upstream it knows nothing
# about, bans a source that drew enough refusals, answers the way the design
# says it should, and healthchecks itself the way a shell-less distroless image
# needs.
#
# Sources are simulated with X-Forwarded-For and TrustProxyHeaders=on. That is
# not a shortcut: it is the only way to exercise "this source is banned, that
# one is not" over a loopback connection, and it doubles as a check that the
# trusted-proxy path is wired.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
EDGE_PORT=${EDGE_PORT:-18088}
UP_PORT=${UP_PORT:-18900}
DB=/tmp/openwaf-smoke-$$.db
TOKEN=smoketoken
RO_TOKEN=smokereadonly
BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Release/net10.0/OpenWaf.Edge.dll"
[ -f "$BIN" ] || BIN="$ROOT/dotnet/OpenWaf.Edge/bin/Debug/net10.0/OpenWaf.Edge.dll"
# The content root is the directory that holds appsettings.json, and ASP.NET
# Core takes it from the current directory — which here is the repository root,
# where there is no appsettings.json. Measured: started this way the edge loaded
# no ReverseProxy section at all, logged "Request reached the end of the
# middleware pipeline without being handled by application code" for every
# request, and answered 404 for a path the upstream was serving with 200. Every
# smoke assertion below expects 404 or a refusal, so the gate kept passing on an
# edge that never proxied anything. Naming the content root is what makes the
# first line of this file's comment — "proxies to a real upstream" — true.
BIN_DIR="$(dirname "$BIN")"
export HEALTHCHECK_PORT="$EDGE_PORT"
SCANNER=203.0.113.66
OFFICER=198.51.100.7
Bystander=198.51.100.99
# Payloads live in single-quoted variables: embedding them in the command
# substitutions below with escaped quotes is exactly the kind of thing that
# silently truncates a body.
BLOCK_JSON='{"ip":"198.51.100.7","reason":"confirmed scraper","redirectTo":"https://honeypot.example.org/"}'
ALLOW_JSON='{"match":"198.51.100.0/24","note":"office"}'
POLICY_OFF_JSON='{"mode":"Off"}'
# The volume pillar (OPEN-56). A window long enough that the scene below cannot
# race it, and a budget small enough to cross in three requests.
RATE_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":2,"rateWindowSeconds":120}'
RATE_OFF_JSON='{"rateMode":"Off"}'
RATE_BAD_JSON='{"rateLimitPerWindow":0}'
cleanup() {
[ -n "${EDGE_PID:-}" ] && kill "$EDGE_PID" 2>/dev/null
[ -n "${UP_PID:-}" ] && kill "$UP_PID" 2>/dev/null
rm -f "$DB" "$DB-shm" "$DB-wal"
}
trap cleanup EXIT
mkdir -p /tmp/openwaf-upstream
python3 -m http.server "$UP_PORT" --bind 127.0.0.1 -d /tmp/openwaf-upstream >/dev/null 2>&1 &
UP_PID=$!
rm -f "$DB"
ASPNETCORE_URLS="http://127.0.0.1:$EDGE_PORT" \
OPENWAF_ADMIN_TOKEN="$TOKEN" \
OPENWAF_READ_ONLY_TOKEN="$RO_TOKEN" \
ConnectionStrings__OpenWaf="Data Source=$DB" \
OpenWaf__Policy__StreakThreshold=3 \
OpenWaf__Policy__Mode=Enforce \
OpenWaf__Policy__BanDuration="00:00:06" \
OpenWaf__Policy__TrustProxyHeaders=true \
ReverseProxy__Clusters__upstream__Destinations__upstream1__Address="http://127.0.0.1:$UP_PORT/" \
dotnet "$BIN" --contentRoot "$BIN_DIR" >/tmp/openwaf-smoke.log 2>&1 &
EDGE_PID=$!
for _ in $(seq 1 60); do
curl -fsS "http://127.0.0.1:$EDGE_PORT/healthz" >/dev/null 2>&1 && break
sleep 0.25
done
pass=0; fail=0
check() {
if [ "$2" = "$3" ]; then pass=$((pass+1)); printf ' ok %-56s %s\n' "$1" "$3"
else fail=$((fail+1)); printf ' FAIL %-56s expected %s, got %s\n' "$1" "$2" "$3"; fi
}
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
from() { printf 'http://127.0.0.1:%s/%s' "$EDGE_PORT" "$1"; } # usage: from path + -H "X-Forwarded-For: ip"
# A startup refusal has to leave a process that is GONE. Measured on the shipped
# image (OPEN-63): an unhandled exception at startup prints the reason and then
# the process sits at 100% CPU inside the runtime's crash path, so the container
# stays Up forever and the supervisor restarts nothing. This starts the edge with
# one bad value, waits for it to leave on its own, and answers its exit code - or
# "hung" if it is still there after 20 seconds. A gate that simply waited on the
# process could not tell the two apart.
refused_rc() { # $1 = KEY=VALUE to override, $2 = where to put the output
local override="$1" log="$2"
local db="/tmp/openwaf-smoke-refused-$$.db"
rm -f "$db"
env ASPNETCORE_URLS="http://127.0.0.1:$((EDGE_PORT+9))" \
OPENWAF_ADMIN_TOKEN="$TOKEN" \
ConnectionStrings__OpenWaf="Data Source=$db" \
"$override" \
dotnet "$BIN" --contentRoot "$BIN_DIR" >"$log" 2>&1 &
local pid=$! rc=''
for _ in $(seq 1 40); do
if ! kill -0 "$pid" 2>/dev/null; then
wait "$pid" 2>/dev/null
rc=$?
break
fi
sleep 0.5
done
if [ -z "$rc" ]; then
kill "$pid" 2>/dev/null
wait "$pid" 2>/dev/null
rc=hung
fi
rm -f "$db" "$db-shm" "$db-wal"
printf '%s' "$rc"
}
echo "edge :$EDGE_PORT upstream :$UP_PORT db $DB"
echo '- streak ban'
for i in 1 2 3; do
check "probe $i from the scanner reaches the upstream" 404 \
"$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")"
done
# The ban is written out of band, after the response that proved it has been
# sent, and the snapshot the guard reads is refreshed by that write. So the
# gate has to wait for the row to exist before it asks the wire whether the ban
# is enforced — otherwise it is racing a durable write and the answer depends on
# how busy the disk is. The wait is bounded, and a timeout leaves the ban
# missing, which is exactly what the assertion below then reports.
for _ in $(seq 1 40); do
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
| grep -q "$SCANNER" && break
sleep 0.25
done
check '4th request from the scanner is refused by the edge' 403 \
"$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")"
check 'a bystander is untouched' 404 \
"$(code -H "X-Forwarded-For: $Bystander" "$(from anything)")"
check 'the refusal explains itself' blocked_by_policy \
"$(curl -s -H "X-Forwarded-For: $SCANNER" "$(from anything)" | python3 -c 'import sys,json;print(json.load(sys.stdin)["error"])')"
# The refusal in the visitor's language (OPEN-57). A browser named text/html, so
# it gets sentences; the same refusal stays JSON for the client that did not ask.
check 'a browser gets a page it can read, not a JSON blob' 'text/html; charset=utf-8' \
"$(curl -s -o /dev/null -w '%{content_type}' -H 'Accept: text/html,*/*' \
-H "X-Forwarded-For: $SCANNER" "$(from anything)")"
check 'the page carries the reference an operator can look up' yes \
"$(curl -s -H 'Accept: text/html' -H "X-Forwarded-For: $SCANNER" "$(from anything)" \
| grep -q 'Reference:' && echo yes || echo no)"
check 'and the same refusal is still JSON for a client that parses it' blocked_by_policy \
"$(curl -s -H 'Accept: */*' -H "X-Forwarded-For: $SCANNER" "$(from anything)" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["error"])')"
check 'the ban carries a Retry-After' yes \
"$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $SCANNER" "$(from anything)" | grep -qi '^retry-after:' && echo yes || echo no)"
echo '- metrics (OPEN-58)'
# The pull surface. The integration tests hold the format; this holds the
# deployed shape — the content type a scraper negotiates on, the token that
# closes it, and the one property the whole feature exists for: an edge that is
# refusing a source can still be watched by that source's operator.
check 'the metrics surface is closed without the token' 401 \
"$(code "http://127.0.0.1:$EDGE_PORT/metrics")"
check 'metrics answers in the Prometheus exposition format' 'text/plain; version=0.0.4; charset=utf-8' \
"$(curl -s -o /dev/null -w '%{content_type}' -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/metrics")"
METRICS=$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/metrics")
msample() { printf '%s\n' "$METRICS" | awk -v p="$1" 'index($0,p)==1 { print $NF; exit }'; }
check 'the body declares a type for every family it samples' yes \
"$([ "$(printf '%s\n' "$METRICS" | grep -c '^# TYPE ')" -ge 20 ] && echo yes || echo no)"
check 'no value in the body is NaN or Inf' yes \
"$(printf '%s\n' "$METRICS" | grep -Eq 'NaN|Inf' && echo no || echo yes)"
BLOCK_ENGINE=$(msample 'openwaf_requests_total{verdict="block_engine"} ')
check 'the verdict counter counts the ban this scene just made' yes \
"$([ "${BLOCK_ENGINE:-0}" -gt 0 ] 2>/dev/null && echo yes || echo no)"
check 'the live blocks gauge counts the engine ban' 1 \
"$(msample 'openwaf_blocks_live{source="engine"} ')"
# The push queue (OPEN-60) is a table, so its numbers are publishable the same
# way. No endpoint is configured in this scene, so the honest answer is three
# zeros — and a gauge that is missing is a different failure from a gauge that
# says 0, which is why msample's empty answer fails the check.
check 'the push queue is published as gauges as well' '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 ')"
# The aggregate-only invariant, asserted over the whole body with the markers
# from the scene above actually in the database behind it.
check 'the body names no address, no path and no operator note' yes \
"$(printf '%s\n' "$METRICS" | grep -Eq "$SCANNER|wp-admin|confirmed scraper" && echo no || echo yes)"
check 'a source the edge is refusing can still be watched' 200 \
"$(code -H "X-Admin-Token: $TOKEN" -H "X-Forwarded-For: $SCANNER" "http://127.0.0.1:$EDGE_PORT/metrics")"
echo '- asking the edge what it would answer (OPEN-59)'
# The dry run. The assertion that matters is not the verdict — the scene above
# already proved the ban is enforced — it is that the preview answers about the
# named address and says which pillar spoke, including the ones that never got
# asked.
DECIDE=$(curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$SCANNER&path=/anything")
check 'the preview answers with the verdict the wire gives' block_engine \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;print(json.load(sys.stdin)["verdict"])')"
check 'and names the pillar that spoke' engineBan \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next(r["pillar"] for r in p if r["outcome"]=="answered"))')"
check 'and says the geo pillar was never asked in this configuration' not_enforced_in_this_mode \
"$(printf '%s' "$DECIDE" | python3 -c 'import sys,json;p=json.load(sys.stdin)["pillars"];print(next(r["outcome"] for r in p if r["pillar"]=="geo"))')"
check 'a typo in the address is refused rather than answered with pass' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=203.0.113&path=/anything")"
check 'a parameter this surface never read is refused before it is ignored' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$SCANNER&path=/anything&source=engine")"
echo '- operator list'
check 'add an operator block' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$BLOCK_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'an operator block answers 301 with Location' https://honeypot.example.org/ \
"$(curl -s -o /dev/null -w '%{redirect_url}' -H "X-Forwarded-For: $OFFICER" "$(from anything)")"
echo '- allowlist outranks everything'
check 'allow the office range' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$ALLOW_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow")"
check 'the blocked office address gets through' 404 \
"$(code -H "X-Forwarded-For: $OFFICER" "$(from anything)")"
check 'the scanner outside that range stays banned' 403 \
"$(code -H "X-Forwarded-For: $SCANNER" "$(from anything)")"
# The exemption listing used to be the only listing with no ceiling: every paging
# parameter was ignored and the response said nothing about how many rows there
# were. Measured on the shipped image: 1101 rows, 130,386 bytes, no X-Total-Count,
# and ?limit=10 answered all 1101.
check 'the allow listing says how many rows there are' yes \
"$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow" | grep -qi '^x-total-count:' && echo yes || echo no)"
check 'the allow listing refuses a limit nobody meant' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?limit=0")"
check 'a page of one is a page of one' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow?limit=1" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
# A path rule is the one pillar about the request rather than about what the
# upstream answered, so the smoke run asks the question the feature exists to
# answer: does a refused path reach the origin or not.
# Not $Bystander: the allowlist scene above exempted 198.51.100.0/24, and an
# exempt address is the one answer a path rule must not override.
RULE_IP=203.0.113.77
RULE_JSON='{"pattern":"/gate-blocked*","action":"block","note":"smoke: the request itself"}'
BAD_RULE_JSON='{"pattern":"gate-blocked","action":"block"}'
echo '- a path rule refuses the request itself'
check 'add a blocking path rule' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RULE_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules")"
check 'the path is refused rather than proxied' 403 \
"$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")"
check 'a browser gets the same refusal in sentences' yes \
"$(curl -s -H 'Accept: text/html' -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)" \
| grep -q 'This path is refused on this site.' && echo yes || echo no)"
check 'the refusal names the rule and not the pattern' yes \
"$(curl -s -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)" | grep -q blocked_by_rule && echo yes || echo no)"
check 'a pattern that could never match is refused' 400 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$BAD_RULE_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules")"
check 'the rules listing holds the rule' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
check 'the rule can be removed by id' 204 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules/$RULE_ID")"
check 'and the path flows again once it is gone' 404 \
"$(code -H "X-Forwarded-For: $RULE_IP" "$(from gate-blocked)")"
# The volume pillar, and the one claim it exists to make: the origin is happy to
# serve this traffic, so no streak, no rule and no list says anything about it —
# only the count does. index.html is the 200 this upstream will give.
echo 'openwaf smoke' > /tmp/openwaf-upstream/index.html
RATE_IP=203.0.113.88
echo '- the operator config leaves the edge as one document (OPEN-61)'
# The transfer. A block is written, the whole config is exported, the block is
# deleted, and the exported document is imported back. The assertions are on the
# wire, not on the JSON: the document has to be enough to rebuild what the edge
# enforces, including the redirect the operator typed.
TRANSFER_IP=203.0.113.151
TRANSFER_JSON='{"ip":"203.0.113.151","reason":"written for the transfer","redirectTo":"https://honeypot.example.org/seen"}'
check 'the block this scene starts with is in force' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$TRANSFER_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'and the wire says so' 301 "$(code -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)")"
EXPORT_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export")"
check 'the export names the version this build reads' 1 \
"$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["version"])')"
check 'the export counts its sections' yes \
"$(printf '%s' "$EXPORT_JSON" | 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' "$EXPORT_JSON" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("engineBlocksLeftBehind"), int) else "no")')"
check 'the exported document carries no engine ban' yes \
"$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;print("yes" if all("203.0.113.66" != b["ip"] for b in json.load(sys.stdin)["blocks"]) else "no")')"
check 'deleting the block takes it off the wire' 200 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$TRANSFER_IP")"
check 'and the path flows again' 404 "$(code -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)")"
IMPORT_JSON="$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$EXPORT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/import")"
check 'importing the document lands the block again' 1 \
"$(printf '%s' "$IMPORT_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')"
check 'and the wire enforces it, redirect and all' yes \
"$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)" \
| tr -d '\r' | grep -qi '^location: https://honeypot.example.org/seen' && echo yes || echo no)"
check 'importing the same document again adds nothing' '0 0' \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$EXPORT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/import" \
| python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["blocks"]["added"], d["rules"]["added"])')"
BEFORE_IMPORT_BLOCKS="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
check 'a document from another version is refused naming the version' yes \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"version":999,"blocks":[{"ip":"203.0.113.152"}]}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/import" | grep -q '999' && echo yes || echo no)"
check 'and it wrote nothing' "$BEFORE_IMPORT_BLOCKS" \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
check 'the transfer row is removable again, so the run ends clean' 200 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$TRANSFER_IP")"
echo '- a second token that can look but not change'
# The read-only token (OPEN-62). The interesting assertions are not the 200s —
# a read is a read — but the shape of the refusal: a known token that lacks the
# right answers 403 and names the key that would grant it, while an unknown
# token still answers 401. Those two sentences are the feature; collapsing them
# is what would make an operator debug the wrong thing.
check 'the state says a second token exists on this edge' True \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["readOnlyTokenConfigured"])')"
check 'the read-only token reads the state' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")"
check 'the read-only token reads the block list' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the read-only token reads the path rules' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules")"
check 'the read-only token reads the policy' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/policy")"
check 'the read-only token can watch /metrics' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/metrics")"
check 'a read-only token presented in the query string is served' 200 \
"$(code "http://127.0.0.1:$EDGE_PORT/admin-api/observations?token=$RO_TOKEN")"
RO_WRITE="$(curl -s -X POST -H "X-Admin-Token: $RO_TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.155","reason":"must not land"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'a read-only token cannot write a block' 403 \
"$(code -X POST -H "X-Admin-Token: $RO_TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.155","reason":"must not land"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the refusal says the token is read-only, not unknown' yes \
"$(printf '%s' "$RO_WRITE" | python3 -c 'import sys,json;print("yes" if "read-only" in json.load(sys.stdin)["error"] else "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 write really did not land' 0 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([b for b in json.load(sys.stdin) if b["sourceKey"]=="203.0.113.155"]))')"
check 'a read-only token cannot change the policy' 403 \
"$(code -X PUT -H "X-Admin-Token: $RO_TOKEN" -H 'Content-Type: application/json' --data-binary "$POLICY_OFF_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy")"
check 'a read-only token cannot delete a block' 403 \
"$(code -X DELETE -H "X-Admin-Token: $RO_TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator")"
check 'a read-only token cannot import a document' 403 \
"$(code -X POST -H "X-Admin-Token: $RO_TOKEN" -H 'Content-Type: application/json' \
-d '{"version":1,"blocks":[]}' "http://127.0.0.1:$EDGE_PORT/admin-api/import")"
check 'the export is not readable by the read-only token' 403 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export")"
check 'and the refusal says the document is a capability' yes \
"$(curl -s -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export" \
| grep -q 'capability' && echo yes || echo no)"
check 'the admin token still writes what the other one cannot' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.156","reason":"written by the admin token"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
# Cleaned up straight away: the later sections count operator rows, and a row
# left behind by this scene would be read as one of theirs.
check 'and the admin-token row is removable again' 200 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=203.0.113.156")"
check 'an unknown token is still 401, not 403' 401 \
"$(code -H "X-Admin-Token: not-a-token" "http://127.0.0.1:$EDGE_PORT/admin-api/state")"
check 'and an unknown token cannot write either' 401 \
"$(code -X POST -H "X-Admin-Token: not-a-token" -H 'Content-Type: application/json' \
-d '{"ip":"203.0.113.157"}' "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
# The configuration this build refuses to start with: a read-only token that is
# also the admin token. Started for real, on its own port and its own database,
# because "refused at startup" is only worth claiming if a process that is
# actually configured that way fails to come up. The message has to name both
# keys and must not repeat the secret — startup output is where secrets leak.
BAD_DB=/tmp/openwaf-smoke-bad-$$.db
BAD_LOG=/tmp/openwaf-smoke-bad-$$.log
rm -f "$BAD_DB"
ASPNETCORE_URLS="http://127.0.0.1:$((EDGE_PORT+7))" \
OPENWAF_ADMIN_TOKEN="$TOKEN" \
OPENWAF_READ_ONLY_TOKEN="$TOKEN" \
ConnectionStrings__OpenWaf="Data Source=$BAD_DB" \
dotnet "$BIN" --contentRoot "$BIN_DIR" >"$BAD_LOG" 2>&1
BAD_RC=$?
check 'an edge whose read-only token is also its admin token does not start' yes \
"$([ "$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 "$TOKEN" "$BAD_LOG" && echo no || echo yes)"
rm -f "$BAD_DB" "$BAD_DB-shm" "$BAD_DB-wal" "$BAD_LOG"
echo '- a startup refusal leaves, it does not sit there'
# Every bound this build refuses to run with, asserted the same way: the process
# goes away by itself with code 1 and the reason names the key. These are the
# refusals that are NOT written in one place - each is raised by the type that
# owns the bound - so the assertion is what keeps the convention from rotting.
for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \
'OpenWaf__Policy__ObservationRetentionDays=0' \
'OpenWaf__Alerts__MaxPushAttempts=0' \
'OpenWaf__Alerts__PushRetrySeconds=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//__/:}
refused_log="/tmp/openwaf-smoke-refused-$$.log"
refused_code=$(refused_rc "$bad" "$refused_log")
check "a bad $key exits instead of spinning" 1 "$refused_code"
check " and the reason names the key" yes \
"$(grep -q "$msg_key" "$refused_log" && echo yes || echo no)"
done
rm -f "$refused_log"
echo '- the record of a config change'
# The change log (OPEN-64). The assertions are on the surface an operator reads
# at 03:00, and the interesting one is the ruling the log could quietly get
# wrong: an engine ban is not a decision somebody made, so it is not in here.
check 'the state counts the records the edge holds' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \
| python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("configChanges"), int) else "no")')"
check 'an engine ban is not a change record' 0 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \
| python3 -c 'import sys,json;print(len([c for c in json.load(sys.stdin) if c["target"]=="203.0.113.66"]))')"
check 'the read-only token can read the log' 200 \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes")"
check 'an unknown section is answered by the vocabulary' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=traffic")"
LOG_IP="203.0.113.$(( 160 + RANDOM % 20 ))"
curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d "{\"ip\":\"$LOG_IP\",\"reason\":\"written to be remembered\"}" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null
CHANGES_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block")"
check 'the write added exactly one record' 1 \
"$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['target']=='$LOG_IP']))")"
check 'an operator block lands a record naming the address' yes \
"$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print('yes' if any(c['target']=='$LOG_IP' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")"
check 'and the record carries the operator sentence' yes \
"$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print('yes' if any('remembered' in (c.get('detail') or '') for c in json.load(sys.stdin)) else 'no')")"
check 'and it names the surface, not a person' operator \
"$(printf '%s' "$CHANGES_JSON" | python3 -c "import sys,json;print(next(c['actor'] for c in json.load(sys.stdin) if c['target']=='$LOG_IP'))")"
curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$LOG_IP" >/dev/null
check 'a removal is recorded as a removal' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \
| python3 -c "import sys,json;print('yes' if any(c['target']=='$LOG_IP' and c['action']=='removed' for c in json.load(sys.stdin)) else 'no')")"
# A policy write of our own, so the assertion is about this scene and not about
# whether an earlier one happened to move a field.
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"streakThreshold":4}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
check 'a policy write records what moved' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=policy" \
| python3 -c 'import sys,json;print("yes" if any("streakThreshold 3->4" in (c.get("detail") or "") for c in json.load(sys.stdin)) else "no")')"
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"streakThreshold":3}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
# One record per import per section, whatever the document carried: the transfer
# scene above imported twice, so the newest imported row is the one to read.
check 'an import is recorded per section, not per row' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \
| 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 "ip" not in (d[0].get("target") or "") else "no")')"
check 'and that record names the import as the surface' import \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \
| 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 'the log is newest first' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \
| python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d==sorted(d,key=lambda c:-c["id"]) else "no")')"
check 'and a page says when it is truncated' yes \
"$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?limit=1" \
| tr -d '\r' | grep -qi '^X-Truncated: true' && echo yes || echo no)"
echo '- volume budget'
STATE0_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")"
check 'the budget is off until an operator writes one' Off \
"$(printf '%s' "$STATE0_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
check 'a written budget is live without a restart' Enforce \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RATE_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
check 'a budget outside its range is refused by name' 400 \
"$(code -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RATE_BAD_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy")"
check 'the first request inside the budget is proxied' 200 \
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
check 'so is the second' 200 \
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
check 'the third crosses the budget and is answered by the edge' 429 \
"$(code -H "X-Forwarded-For: $RATE_IP" "$(from index.html)")"
check 'the refusal says when the pause ends' yes \
"$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $RATE_IP" "$(from index.html)" \
| grep -qi '^retry-after:' && echo yes || echo no)"
check 'the breach wrote an engine ban the operator can see' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
| python3 -c "import sys,json;print(len([b for b in json.load(sys.stdin) if b['sourceKey']=='$RATE_IP']))")"
check 'and the ban says volume, not refusals' rate \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
| python3 -c "import sys,json;print('rate' if any('rate policy' in (b.get('reason') or '') for b in json.load(sys.stdin) if b['sourceKey']=='$RATE_IP') else 'none')")"
check 'the listing says what the limiter counted' 3 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate?source=$RATE_IP" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["sources"][0]["count"])')"
check 'the operator can clear the ban the breach wrote' '{"deleted":1}' \
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine&key=$RATE_IP" | tr -d ' ')"
check 'the budget can be switched off again' Off \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
rm -f /tmp/openwaf-upstream/index.html
echo '- expiry and clearing'
sleep 7
check 'the engine ban lifted itself' 404 "$(code -H "X-Forwarded-For: $SCANNER" "$(from wp-admin)")"
check 'clearing engine bans leaves operator rows' '{"deleted":1}' \
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" | tr -d ' ')"
check 'an operator row survives it' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator" | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
# This scene clears the engine's list wholesale, so it runs after the scenes
# that live off an engine row of their own; a range is not in that list, but
# the clear is not scoped to it.
echo '- an operator bans a range'
# A netblock, not one address (OPEN-66). The block API answered "not an IP
# address" for a CIDR while the allowlist accepted one, so a scanner rotating
# inside one /29 cost one write and one row per address — and the export of an
# edge's decisions could not carry the range either. The base is aligned to the
# prefix and chosen per run, so a leftover row in the database cannot satisfy the
# assertions.
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 ))"
# The bodies live in single-quoted-safe variables: an escaped-quote body
# written straight inside a command substitution is the thing this file has
# been bitten by before (see the payloads at the top).
RANGE_JSON="{\"ip\":\"$RANGE_NET\",\"reason\":\"netblock scanning\"}"
RANGE_SLOPPY_JSON="{\"ip\":\"203.0.113.$(( RANGE_BASE + 5 ))/29\",\"reason\":\"typed sloppily\"}"
check 'a CIDR is a block, not a rejected input' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RANGE_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'every address inside the range is refused' 301 \
"$(code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")"
check 'the address one past its end is served' 404 \
"$(code -H "X-Forwarded-For: $RANGE_OUTSIDE" "$(from anything)")"
check 'the listing says which shape the row is' range \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \
| python3 -c "import sys,json;print(next(c['kind'] for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET'))")"
check 'one range is one row however it is spelled' 1 \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RANGE_SLOPPY_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \
| python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['sourceKey']=='$RANGE_NET']))")"
check 'a range over every address is refused and says why' yes \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"ip":"0.0.0.0/0","reason":"shutdown dressed as a ban"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks" \
| grep -q 'every address' && echo yes || echo no)"
check 'the range is recorded under the name the row is stored under' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes?section=block" \
| python3 -c "import sys,json;print('yes' if any(c['target']=='$RANGE_NET' and c['action']=='added' for c in json.load(sys.stdin)) else 'no')")"
check 'the state counts ranges apart from address blocks' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \
| python3 -c "import sys,json;print('yes' if json.load(sys.stdin).get('operatorRanges') == 1 else 'no')")"
# Provenance is part of a clear: the engine's list is not the operator's, and a
# /29 the operator wrote is not in it.
check 'clearing the engine bans leaves the range in force' 301 \
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" >/dev/null; \
code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")"
check 'and the range is removable by its name' 404 \
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$RANGE_NET" >/dev/null; \
code -H "X-Forwarded-For: $RANGE_INSIDE" "$(from anything)")"
echo '- the edge notices a netblock behind its bans'
# The watch (OPEN-67): the edge groups its own live engine bans into the block
# they sit under and offers that block to the operator. The bans are produced the
# only way they can be produced — by traffic — and the ban window is widened for
# the scene, because this edge runs a six-second sentence and a scan that arrives
# after it would be reading rows that are no longer live.
NET_A=203.0.113.201
NET_B=203.0.113.202
NET_FRESH=203.0.113.203
NET_RANGE=203.0.113.0/24
NET_ON_JSON='{"streakThreshold":2,"netblockCandidateBans":2,"banDurationMinutes":5}'
NET_OFF_JSON='{"streakThreshold":3,"netblockCandidateBans":0,"banDurationMinutes":0.01}'
NET_RANGE_JSON='{"ip":"203.0.113.0/24","reason":"the netblock the edge noticed"}'
check 'the watch threshold is a policy key' 2 \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$NET_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["netblockCandidateBans"])')"
check 'a netblock prefix outside its bounds is refused by name' yes \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
-d '{"netblockPrefixV4":33}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| grep -q 'netblockPrefixV4 must be 8..31' && echo yes || echo no)"
for src in "$NET_A" "$NET_B"; do
code -H "X-Forwarded-For: $src" "$(from wp-admin)" >/dev/null
code -H "X-Forwarded-For: $src" "$(from wp-admin)" >/dev/null
done
check 'the two bans the edge wrote are inside one block' 2 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
| python3 -c "import sys,json;print(len([b for b in json.load(sys.stdin) if b['sourceKey'].startswith('203.0.113.2')]))")"
check 'the edge offers that block as a range' "$NET_RANGE" \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/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'))")"
check 'and it says how many bans sit inside it' 2 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/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 address inside it is served' 404 \
"$(code -H "X-Forwarded-For: $NET_FRESH" "$(from wp-admin)")"
check 'the operator takes the offer with the same call as any other block' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$NET_RANGE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the offer is then marked taken rather than repeated' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \
| python3 -c "import sys,json;print('yes' if next(n['alreadyBanned'] for n in json.load(sys.stdin)['netblocks'] if n['match']=='$NET_RANGE') else 'no')")"
check 'the taken range refuses a source the engine never saw' 301 \
"$(code -H "X-Forwarded-For: $NET_FRESH" "$(from wp-admin)")"
check 'and it answers ahead of the engine ban it replaces' 301 \
"$(code -H "X-Forwarded-For: $NET_A" "$(from wp-admin)")"
check 'the state says the watch ran and what it saw' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \
| python3 -c "import sys,json;d=json.load(sys.stdin);print('yes' if d['netblockCandidateBans']==2 and d['netblockPrefixV4']==24 and d['netblockScanError'] is None else 'no')")"
# Clean up: the range, the bans that produced it, and the policy the rest of the
# gate runs on.
curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$NET_RANGE" >/dev/null
curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" >/dev/null
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$NET_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
check 'the watch is off again and offers nothing' 0 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/netblocks" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)["netblocks"]))')"
# A request budget for one path (OPEN-68). The edge-wide budget above is one
# number for the whole site; this is the same switch with a path on it, and the
# claim worth testing is the narrow one: the pause covers the path it names and
# nothing else, and it writes no ban.
echo '- a request budget for one path'
echo 'path budget' > /tmp/openwaf-upstream/login.txt
PATH_BUDGET_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
PATH_BUDGET_JSON='{"pattern":"/login*","limitPerWindow":2,"windowSeconds":120,"note":"smoke scene"}'
PATH_BUDGET_CLASH_JSON='{"pattern":"/login*","limitPerWindow":50}'
PATH_BUDGET_BADPATTERN_JSON='{"pattern":"login*","limitPerWindow":2}'
PATH_BUDGET_ZEROLIMIT_JSON='{"pattern":"/login*","limitPerWindow":0}'
PATH_BUDGET_BADWINDOW_JSON='{"pattern":"/login*","windowSeconds":99999}'
# TEST-NET-1, and deliberately not 198.51.100.0/24: an earlier scene allowlists
# that whole range, and an allowlisted source never reaches the counter — which
# would make this scene measure nothing and still print 200s.
PATH_BUDGET_IP=192.0.2.77
PATH_BUDGET_OTHER=192.0.2.78
check 'the path budgets hang off the same volume switch' Enforce \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
check 'a pattern with no leading slash is refused by name' yes \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_BADPATTERN_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| grep -q 'must start with /' && echo yes || echo no)"
check 'a budget of zero is refused by name' yes \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_ZEROLIMIT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| grep -q 'limitPerWindow must be 1..100000' && echo yes || echo no)"
check 'a window outside its bounds is refused by name' yes \
"$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_BADWINDOW_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| grep -q 'windowSeconds must be 1..3600' && echo yes || echo no)"
check 'a written budget is live without a restart' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
check 'a second live budget for one path is refused, not resolved by accident' 409 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$PATH_BUDGET_CLASH_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
check 'the first request inside the path budget is proxied' 200 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")"
check 'so is the second' 200 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")"
check 'the third crosses it and is answered by the edge' 429 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")"
check 'the refusal says when the pause ends' yes \
"$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)" \
| grep -qi '^retry-after:' && echo yes || echo no)"
check 'the refusal names the budget it crossed' yes \
"$(curl -s -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)" \
| grep -q 'rate_rule_' && echo yes || echo no)"
check 'the rest of the site stays open to the same source' 404 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from wp-admin)")"
check 'and the pause wrote no ban' 0 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=engine" \
| python3 -c "import sys,json;print(len([b for b in json.load(sys.stdin) if b['sourceKey']=='$PATH_BUDGET_IP']))")"
check 'a second source has its own window on the same path' 200 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_OTHER" "$(from login.txt)")"
check 'the listing says what the budget counted and who is over it' '2 1' \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])')"
check 'the state says the budgets are being read' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state" \
| python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["rateRules"]==1 and d["rateRulesAvailable"] and d["rateRulesError"] is None else "no")')"
check 'the budget travels in an exported document' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)["rateRules"]))')"
PATH_BUDGET_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
check 'removing it stops enforcing on the next request' 204 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$PATH_BUDGET_ID")"
check 'the same source is proxied again' 200 \
"$(code -H "X-Forwarded-For: $PATH_BUDGET_IP" "$(from login.txt)")"
check 'and the listing is empty again' 0 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
rm -f /tmp/openwaf-upstream/login.txt
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
# The dry run answers the volume pillar (OPEN-69). The preview used to answer
# every pillar and stay silent about the one whose number the operator is choosing;
# the claim worth testing on the wire is that it answers it without spending it.
echo '- the dry run answers the volume pillar'
echo 'dry run' > /tmp/openwaf-upstream/dryrun.txt
DRY_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":120}'
DRY_RULE_JSON='{"pattern":"/dryrun*","limitPerWindow":2,"windowSeconds":120}'
DRY_IP=192.0.2.88
decide() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$1&path=$2"; }
check 'the volume switch is on for this scene' Enforce \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$DRY_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["rateMode"])')"
check 'a source with no running window is answered as nothing counted, not as zero of the limit' yes \
"$(decide "$DRY_IP" /dryrun.txt \
| 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"]==[] else "no")')"
check 'a written path budget appears in the preview for its path' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$DRY_RULE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
check 'and it says so before it has counted anything for this source' yes \
"$(decide "$DRY_IP" /dryrun.txt \
| python3 -c 'import sys,json;b=json.load(sys.stdin)["volume"]["pathBudgets"][0];print("yes" if b["pattern"]=="/dryrun*" and not b["counted"] and b["count"] is None else "no")')"
check 'the first two requests on that path are proxied' '200 200' \
"$(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)") $(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)")"
check 'the third crosses the budget' 429 \
"$(code -H "X-Forwarded-For: $DRY_IP" "$(from dryrun.txt)")"
check 'the preview now says this source is over that budget' yes \
"$(decide "$DRY_IP" /dryrun.txt \
| 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"] and b["secondsLeft"]>=1 else "no")')"
check 'a path the budget does not name is answered without it' yes \
"$(decide "$DRY_IP" /wp-admin \
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["pathBudgets"]==[] and v["verdict"]=="would_be_counted" else "no")')"
# The counters of the listing are the same counters the preview reads, so the pair
# is compared before and after: a preview that answered by counting its own
# question would move them, and the next real request would be refused because
# somebody pressed a button.
BUDGET_COUNTERS='import sys,json;r=json.load(sys.stdin)[0];print(r["trackedSources"], r["overBudgetNow"])'
check 'the listing says one source is over that budget' '1 1' \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c "$BUDGET_COUNTERS")"
check 'six previews leave those counters exactly where they were' '1 1' \
"$(for _ in 1 2 3 4 5 6; do decide "$DRY_IP" /dryrun.txt >/dev/null; done; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c "$BUDGET_COUNTERS")"
check 'the pillar row that used to be a silence names the volume section' yes \
"$(decide "$DRY_IP" /dryrun.txt \
| python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if any("volume" in (p.get("note") or "") for p in d["pillars"] if p["pillar"]=="rate") else "no")')"
check 'with the pillar off the preview says nothing is counted' yes \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$RATE_OFF_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null; \
decide "$DRY_IP" /dryrun.txt \
| python3 -c 'import sys,json;v=json.load(sys.stdin)["volume"];print("yes" if v["verdict"]=="not_counted" and v["edgeBudget"] is None else "no")')"
DRY_RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')"
check 'the scene cleans itself, so the rest of the gate runs on the stack it expects' 0 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$DRY_RULE_ID" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
rm -f /tmp/openwaf-upstream/dryrun.txt
# One address, one answer (OPEN-70). Every other listing here answers one table;
# an operator investigating one source had to open six and hold the join in their
# head. The two shapes this scene checks are the two that join got wrong: a block
# written on the address itself, and a block written on a network that contains
# the address - the second is invisible to anything that compares keys.
echo '- one address, one answer'
DOS_IP=192.0.2.121
DOS_NET=192.0.2.128/29 # .128 - .135
DOS_INSIDE=192.0.2.131
DOS_OUTSIDE=192.0.2.136
dossier() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=$1${2:+&path=$2}"; }
check 'the operator writes an address and a range' '204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"192.0.2.121","reason":"dossier scene"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_NET"'","reason":"dossier range"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the dossier answers on the key, and names the rule that made it' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["sourceKey"]=="192.0.2.121" and d["keyRule"]["ipv4PrefixLength"]==32 else "no")')"
check 'an address the operator blocked on its own key is answered by that row' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and b and not b["cameFromRange"] and b["live"] and b["reason"]=="dossier scene" else "no")')"
check 'an address inside a banned range is answered by that range, not by a row that does not exist' yes \
"$(dossier "$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"]=="192.0.2.128/29" else "no")')"
check 'an address on no list is answered as none, with nothing invented for it' yes \
"$(dossier "$DOS_OUTSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["verdict"]=="none" and d["operatorBlock"] is None and d["allow"] is None and d["engineBan"] is None and d["streak"] is None else "no")')"
check 'the answer says which store each part came from' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["operatorBlock"]["scope"]=="database" and d["volume"]["scope"]=="this-process" and "allow" in d["scope"]["database"] else "no")')"
check 'with a path the dossier and the dry run give the same verdict' yes \
"$(python3 -c '
import json,subprocess
d=json.loads(subprocess.run(["curl","-s","-H","X-Admin-Token: '$TOKEN'",
"http://127.0.0.1:'"$EDGE_PORT"'/admin-api/source?ip='$DOS_INSIDE'&path=/wp-admin"],capture_output=True,text=True).stdout)
p=json.loads(subprocess.run(["curl","-s","-H","X-Admin-Token: '$TOKEN'",
"http://127.0.0.1:'"$EDGE_PORT"'/admin-api/decide?ip='$DOS_INSIDE'&path=/wp-admin"],capture_output=True,text=True).stdout)
print("yes" if d["wouldAnswer"]["verdict"]==p["verdict"]==d["verdict"]=="block_operator" else "no")')"
check 'a question it cannot answer is refused by name' '400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=192.0.2") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/source")"
check 'asking it six times wrote nothing: the operator list still holds those two rows' 2 \
"$(for _ in 1 2 3 4 5 6; do dossier "$DOS_IP" >/dev/null; dossier "$DOS_INSIDE" >/dev/null; done; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')"
# Who a path budget is pausing (OPEN-71). The listing has carried three numbers
# per budget since OPEN-68 and no name, so "2 over budget" was the half an
# operator could not act on: the only lever for one of those two was to take the
# budget off every source on the site.
echo '- a budget says who it is pausing, and one source can be let out'
BUD_IP=192.0.2.141
BUD_IP2=192.0.2.142
BUD_ON_JSON='{"rateMode":"enforce","rateLimitPerWindow":1000,"rateWindowSeconds":300}'
BUD_RULE_JSON='{"pattern":"/budgeted*","limitPerWindow":2,"windowSeconds":300,"note":"who scene"}'
echo 'budgeted' > /tmp/openwaf-upstream/budgeted.txt
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$BUD_ON_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null
check 'a budget is written for one path' 204 \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary "$BUD_RULE_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
BUD_RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/budgeted*"][0])')"
check 'two sources cross it' '429 429' \
"$(for _ in 1 2 3; do code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)" >/dev/null; done; \
for _ in 1 2 3; do code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)" >/dev/null; done; \
code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)") \
$(code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)")"
check 'the budget names both sources, busiest first, with what each has spent' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/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 r[0]["count"]>=4 and d["scope"]=="this-process" and d["keyRule"]["ipv4PrefixLength"]==32 else "no")')"
# The invariant that keeps this from being a second ledger: the names come from
# the same state as the three numbers the operator already reads.
check 'the names and the three counters are the same state' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
-o /tmp/bud_row.json; \
curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources" \
-o /tmp/bud_src.json; \
python3 -c "import json;row=[x for x in json.load(open('/tmp/bud_row.json')) if x['id']==$BUD_RULE_ID][0];d=json.load(open('/tmp/bud_src.json'));print('yes' if row['liveWindows']==d['total'] and row['overBudgetNow']==sum(1 for x in d['sources'] if x['overBudget']) and row['trackedSources']>=d['total'] else 'no')")"
check 'one source is let out, and the answer says it is a reset and not an exemption' yes \
"$(curl -s -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/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 d["sourceKey"]=="'"$BUD_IP"'" and "not an exemption" in d["note"] else "no")')"
check 'the let-out source is served again on that path, the neighbour is still paused' '200 429' \
"$(code -H "X-Forwarded-For: $BUD_IP" "$(from budgeted.txt)") \
$(code -H "X-Forwarded-For: $BUD_IP2" "$(from budgeted.txt)")"
check 'and the list now shows the let-out source counting from one, not exempt' yes \
"$(curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources" \
| python3 -c "import sys,json;d=json.load(sys.stdin);m=[x for x in d['sources'] if x['sourceKey']=='$BUD_IP'];print('yes' if len(m)==1 and m[0]['count']==1 and not m[0]['overBudget'] else 'no')")"
check 'an unknown budget is a 404 and a missing source is a 400' '404 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/999999/sources") \
$(code -X DELETE -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID/sources")"
check 'the clearing left a record of itself' 1 \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/changes" \
| python3 -c "import sys,json;print(len([c for c in json.load(sys.stdin) if c['section']=='rate rule' and c['action']=='changed' and c['target']=='$BUD_RULE_ID']))")"
check 'the scene cleans itself' 0 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$BUD_RULE_ID" >/dev/null; \
curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"rateMode":"Off"}' "http://127.0.0.1:$EDGE_PORT/admin-api/policy" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
rm -f /tmp/openwaf-upstream/budgeted.txt
check 'the scene cleans itself' 0 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.121" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${DOS_NET//\//%2F}" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')"
# What stops being enforced soon (OPEN-72). A list of expiry dates tells an
# operator nothing about what the site will be doing tomorrow: the row has to
# carry the answer that takes over when the entry ages out, or "expires at 06:00"
# is a timestamp to interpret by hand at 05:55.
echo '- the enforcement horizon'
HOR_IP=192.0.2.151
HOR_NET=192.0.2.152/29 # .152 - .159
HOR_INSIDE=192.0.2.155
horizon() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=${1:-30}"; }
check 'the operator writes a block, a range, an allow and a path rule that all expire today' '204 204 204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HOR_IP"'","reason":"horizon block","expiresInMinutes":45}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HOR_NET"'","reason":"horizon range","expiresInMinutes":20}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"192.0.2.155","note":"horizon allow","expiresInMinutes":60}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/horizon-gate*","action":"block","note":"horizon rule","expiresInMinutes":25}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules")"
check 'the horizon lists them nearest first, from the database' yes \
"$(horizon 90 | python3 -c '
import sys,json
d=json.load(sys.stdin)
rows=[r for r in d["expiring"] if r["match"] in ("192.0.2.151","192.0.2.152/29","192.0.2.155") or r["pattern"]=="/horizon-gate*"]
order=[r["match"] or r["pattern"] for r in rows]
print("yes" if d["scope"]=="database" and d["count"]>=4 and order==["192.0.2.152/29","/horizon-gate*","192.0.2.151","192.0.2.155"] else "no")')"
check 'the allow says which range refuses its address once it ages out' yes \
"$(horizon 90 | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="allow" and r["match"]=="192.0.2.155"]
t=rows[0]["thenAnswers"] if rows else None
print("yes" if t and t["verdict"]=="block_operator" and t["wouldBeRefused"] and t["by"]=="192.0.2.152/29" else "no")')"
check 'a block with nothing underneath says the source goes free' yes \
"$(horizon 90 | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="block" and r["match"]=="192.0.2.151"]
t=rows[0]["thenAnswers"] if rows else None
print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] and "nothing else refuses" in t["note"] else "no")')"
check 'a range answers for its own network address, not for the notation' yes \
"$(horizon 90 | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if r["kind"]=="range" and r["match"]=="192.0.2.152/29"]
t=rows[0]["thenAnswers"] if rows else None
print("yes" if t and t["verdict"]=="pass" and not t["wouldBeRefused"] else "no")')"
check 'a path rule says why it has no single answer and points at the dry run' yes \
"$(horizon 90 | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if r["pattern"]=="/horizon-gate*"]
r=rows[0] if rows else None
print("yes" if r and r["thenAnswers"] is None and "/admin-api/decide?ip=&path=" in (r["whyNoAnswer"] or "") else "no")')"
check 'every row counts down in whole minutes from now' yes \
"$(horizon 90 | python3 -c '
import sys,json
rows=[r for r in json.load(sys.stdin)["expiring"] if (r["match"] or r["pattern"]) in ("192.0.2.151","192.0.2.152/29","192.0.2.155","/horizon-gate*")]
print("yes" if len(rows)==4 and all(0 < r["minutesLeft"] <= 60 for r in rows) else "no")')"
check 'the answer separates "nothing expires soon" from "nothing is dated"' yes \
"$(horizon 1 | python3 -c '
import sys,json
d=json.load(sys.stdin)
mine=[r for r in d["expiring"] if (r["match"] or r["pattern"]) in ("192.0.2.151","192.0.2.152/29","192.0.2.155","/horizon-gate*")]
print("yes" if not mine and d["withinMinutes"]==1 and all(k in d["alreadyExpired"] for k in ("block","range","engineBan","allow","pathRule","pathBudget")) else "no")')"
check 'no window asked is answered with the default, and it says so' '30 200' \
"$(horizon | python3 -c 'import sys,json;print(json.load(sys.stdin)["withinMinutes"])') \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring")"
check 'a window of zero minutes or of more than a day is refused by name' '400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=1441")"
check 'a question it cannot answer is refused by name' 400 \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=30&nonsense=1")"
check 'the read-only token reads the horizon, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=90") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/expiring?within=90")"
check 'asking it six times wrote nothing: the dated rows are still the four it was shown' '2 1' \
"$(for _ in 1 2 3 4 5 6; do horizon 90 >/dev/null; done; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/hor-blocks.json; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/hor-allow.json; \
python3 -c '
import json
b=json.load(open("/tmp/hor-blocks.json")); a=json.load(open("/tmp/hor-allow.json"))
print(len([r for r in b if r["sourceKey"] in ("192.0.2.151","192.0.2.152/29")]),
len([r for r in a if r["match"]=="192.0.2.155"]))')"
# The prediction has to be true, not plausible: take the allow away for real and
# ask the wire the same question the horizon answered.
HOR_ALLOW_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" \
| python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="192.0.2.155"][0])')"
check 'the horizon was right: with the allow gone the wire refuses that address' 'block_operator 192.0.2.152/29' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$HOR_ALLOW_ID" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/decide?ip=$HOR_INSIDE&path=/" -o /tmp/hor_decide.json; \
curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=$HOR_INSIDE" -o /tmp/hor_dossier.json; \
python3 -c '
import json
d=json.load(open("/tmp/hor_decide.json")); e=json.load(open("/tmp/hor_dossier.json"))["operatorBlock"]
print(d["verdict"], e["match"] if e and e["cameFromRange"] else None)')"
check 'the scene cleans itself' '0 0' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$HOR_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${HOR_NET//\//%2F}" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules?live=false" -o /tmp/hor-rules.json; \
HOR_RULE_ID="$(python3 -c 'import json;print([r["id"] for r in json.load(open("/tmp/hor-rules.json")) if r["pattern"]=="/horizon-gate*"][0])')"; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules/$HOR_RULE_ID" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/hor-blocks2.json; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules?live=false" -o /tmp/hor-rules2.json; \
python3 -c '
import json
b=json.load(open("/tmp/hor-blocks2.json")); r=json.load(open("/tmp/hor-rules2.json"))
print(len([x for x in b if x["sourceKey"] in ("192.0.2.151","192.0.2.152/29")]),
len([x for x in r if x["pattern"]=="/horizon-gate*"]))')"
# One source through time (OPEN-73). Every record is dated and every one is in
# this database — the range, the block, the exemption, the change records, the
# alerts — but they sit in six tables, so an operator rebuilding the story gets
# whichever listing they opened last. The order is the answer: "the exemption,
# then the ban" and "the ban, then the exemption" are different incidents.
echo '- one source through time'
HIS_IP=192.0.2.171
HIS_NET=192.0.2.168/29 # .168 - .175
HIS_NONE=192.31.196.7 # outside every range this run writes
history() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$1${2:+&$2}"; }
hist_counts() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/his-blocks.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/his-allow.json
python3 -c '
import json
b=json.load(open("/tmp/his-blocks.json")); a=json.load(open("/tmp/his-allow.json"))
print(len(b), len(a))'
}
check 'the operator bans the network, then the address inside it, then exempts it' '204 204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_NET"'","reason":"history netblock"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$HIS_IP"'","reason":"history address"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$HIS_IP"'","note":"history allow","expiresInMinutes":60}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow")"
check 'the story names the block, the range covering the address and the exemption' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
k=[e["kind"] for e in d["events"]]
print("yes" if d["sourceKey"]=="192.0.2.171" and d["scope"]=="database"
and all(x in k for x in ("range ban","operator block","allow entry","config change"))
else "no")')"
check 'the story is told oldest first, whatever order the rows were written in' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
stamps=[e["at"] for e in json.load(sys.stdin)["events"]]
print("yes" if len(stamps) >= 6 and stamps == sorted(stamps) else "no")')"
check 'the range is in the story because it covers the address, and says so' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
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"]=="192.0.2.168/29" and r["inForce"]
and "covers this address" in r["what"] and r["detail"]=="history netblock" else "no")')"
check 'the exemption says it outranks every ban and until when it stops' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
e=[x for x in json.load(sys.stdin)["events"] if x["kind"]=="allow entry"]
r=e[0] if e else None
print("yes" if r and r["inForce"] and r["expiresAt"] and r["detail"]=="history allow"
and "outranks every ban" in r["what"] else "no")')"
check 'a change to the range that covers this address is part of this address story' yes \
"$(history "$HIS_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
ch=[x for x in d["events"] if x["kind"]=="config change"]
print("yes" if any(x["match"]=="192.0.2.168/29" for x in ch)
and d["searched"]["change"] >= 2 else "no")')"
check 'the answer counts what it searched, not only what it found' '1 1 1' \
"$(history "$HIS_IP" | python3 -c '
import json,sys
s=json.load(sys.stdin)["searched"]
print(s["block"], s["range"], s["allow"])')"
check 'a limit says how much it left out' yes \
"$(history "$HIS_IP" "limit=2" | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["shown"]==2 and len(d["events"])==2 and d["truncated"] and d["count"]>2 else "no")')"
check 'an address with nothing recorded is answered in words, with the counts beside it' yes \
"$(history "$HIS_NONE" | python3 -c '
import json,sys
d=json.load(sys.stdin)
s=d["searched"]
print("yes" if d["count"]==0 and not d["events"] and not any(s.values())
and "nothing recorded" in d["note"] else "no")')"
check 'a window or a limit it cannot answer with is refused by name' '400 400 400 400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&within=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&limit=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=192.0.2") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?within=60") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP&nonsense=1")"
check 'the read-only token reads a story, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/history?ip=$HIS_IP")"
check 'asking it six times wrote nothing: the listings hold the same rows' \
"$(hist_counts)" \
"$(for _ in 1 2 3 4 5 6; do history "$HIS_IP" >/dev/null; history "$HIS_NONE" >/dev/null; done; hist_counts)"
HIS_ALLOW_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" \
| python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="192.0.2.171"][0])')"
check 'the scene cleans itself' '0 0' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$HIS_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${HIS_NET//\//%2F}" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$HIS_ALLOW_ID" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/his-blocks2.json; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/his-allow2.json; \
python3 -c '
import json
b=json.load(open("/tmp/his-blocks2.json")); a=json.load(open("/tmp/his-allow2.json"))
print(len([r for r in b if r["sourceKey"] in ("192.0.2.171","192.0.2.168/29")]),
len([r for r in a if r["match"]=="192.0.2.171"]))')"
# Where does this appear? (OPEN-74). The words an operator remembers are not a
# field any listing filters on: the same phrase sits in a block's reason, an
# exemption's note, a path rule's note and a path budget's note, and asking it
# means opening eight listings. One call asks all eight at once — and an address
# query returns the rows that cover the address rather than name it, which is the
# answer a text match cannot give.
echo '- one search across every store'
FND_IP=192.0.2.181
FND_NET=192.0.2.176/29 # .176 - .183
FND_PHRASE='ticket%20441'
FND_NONE='nothing%20like%20this'
findq() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$1${2:+&$2}"; }
find_rows() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/fnd-b.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/fnd-a.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" -o /tmp/fnd-r.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" -o /tmp/fnd-t.json
python3 -c '
import json
b=json.load(open("/tmp/fnd-b.json")); a=json.load(open("/tmp/fnd-a.json"))
r=json.load(open("/tmp/fnd-r.json")); t=json.load(open("/tmp/fnd-t.json"))
print(sum(1 for x in b if "ticket 441" in (x.get("reason") or "")),
sum(1 for x in a if "ticket 441" in (x.get("note") or "")),
sum(1 for x in r if "ticket 441" in (x.get("note") or "")),
sum(1 for x in t if "ticket 441" in (x.get("note") or "")))'
}
check 'the same phrase is written into four different stores' '204 204 204 204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$FND_IP"'","reason":"ticket 441 closed"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"192.0.2.182","reason":"100% sure about this one"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$FND_NET"'","note":"ticket 441 a_b window"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-gate*","action":"block","note":"ticket 441 path"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"pattern":"/find-login*","limitPerWindow":3,"windowSeconds":120,"note":"ticket 441 budget"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules")"
check 'one query comes back from every store that holds it, and counts each' '1 0 1 1 1 4 8' \
"$(findq "$FND_PHRASE" | python3 -c '
import json,sys
d=json.load(sys.stdin); c=d["counts"]
print(c["block"], c["range"], c["allow"], c["pathRule"], c["pathBudget"], c["change"], d["matched"])')"
check 'every row names its store and the field that carried the text' yes \
"$(findq "$FND_PHRASE" | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if all(k in by for k in ("block","allow","pathRule","pathBudget","change"))
and by["block"]["why"]=="text matched reason" and by["block"]["match"]=="192.0.2.181"
and by["allow"]["why"]=="text matched note" and by["allow"]["match"]=="192.0.2.176/29"
and by["pathRule"]["why"]=="text matched note" and by["pathRule"]["pattern"]=="/find-gate*"
and by["pathBudget"]["pattern"]=="/find-login*"
and by["change"]["why"]=="text matched detail"
else "no")')"
check 'the query is data and not LIKE grammar: "100%" finds the percent' yes \
"$(findq '100%25' | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if d["counts"]["block"]==1 and by["block"]["text"]=="100% sure about this one"
and all("100%" in (r["text"] or "") for r in d["results"])
and d["matching"]["wildcardsEscaped"] else "no")')"
check 'and an underscore is an underscore, not any one character' yes \
"$(findq 'a_b' | python3 -c '
import json,sys
d=json.load(sys.stdin)
by={r["store"]:r for r in d["results"]}
print("yes" if d["counts"]["allow"]==1 and by["allow"]["text"]=="ticket 441 a_b window"
and all("a_b" in (r["text"] or "") for r in d["results"]) else "no")')"
check 'an address query finds the entry that covers it and says that is why' yes \
"$(findq "$FND_IP" | python3 -c '
import json,sys
d=json.load(sys.stdin)
by=[r for r in d["results"] if r["store"]=="allow"]
print("yes" if d["asAddress"]["sourceKey"]=="192.0.2.181" and len(by)==1
and by[0]["match"]=="192.0.2.176/29" and "covers 192.0.2.181" in by[0]["why"]
and d["counts"]["allow"]==1 and d["counts"]["block"]==1 else "no")')"
check 'an address outside the range is not told it is inside it' yes \
"$(findq '192.0.2.190' | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["counts"]["range"]==0 and not d["results"] else "no")')"
check 'an empty answer names all eight stores it searched' yes \
"$(findq "$FND_NONE" | python3 -c '
import json,sys
d=json.load(sys.stdin); c=d["counts"]
print("yes" if d["matched"]==0 and not d["results"] and len(c)==8 and not any(c.values())
and "counts" in d["note"] else "no")')"
check 'a limit says how much it left out' '8 1 1' \
"$(findq "$FND_PHRASE" 'limit=1' | python3 -c '
import json,sys
d=json.load(sys.stdin)
print(d["matched"], d["shown"], 1 if d["truncated"] else 0)')"
check 'a query it cannot answer with is refused by name' '400 400 400 400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=x") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE&store=block") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE&limit=0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=%20%20")"
check 'the read-only token searches, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/find?q=$FND_PHRASE")"
check 'asking it eight times wrote nothing: the stores hold the same rows' \
"$(find_rows)" \
"$(for _ in 1 2 3 4; do findq "$FND_PHRASE" >/dev/null; findq "$FND_IP" >/dev/null; done; find_rows)"
FND_ALLOW_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" \
| python3 -c 'import sys,json;print([a["id"] for a in json.load(sys.stdin) if a["match"]=="192.0.2.176/29"][0])')"
FND_RULE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rules" \
| python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-gate*"][0])')"
FND_RATE_ID="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules" \
| python3 -c 'import sys,json;print([r["id"] for r in json.load(sys.stdin) if r["pattern"]=="/find-login*"][0])')"
check 'the scene cleans itself' '0 0 0 0' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$FND_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=$FND_IP" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.182" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$FND_ALLOW_ID" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rules/$FND_RULE_ID" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/rate-rules/$FND_RATE_ID" >/dev/null; \
find_rows)"
# What would this ban touch? (OPEN-75). The dry run answers one named request and
# the horizon answers what stops soon; neither answers the question asked BEFORE
# the write. Both failures are silent: a range written over an office block
# refuses people who were never the target, and a range written under an existing
# exemption refuses nobody at all — the operator sees 204 and moves on.
echo '- what a ban would touch, before it is written'
IMP_NET=192.0.2.192/29 # .192 - .199
IMP_NET_Q=192.0.2.192%2F29
IMP_A=192.0.2.193
IMP_B=192.0.2.194
IMP_FREE=192.0.2.195
IMP_OUT=192.0.2.201
impactq() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$1${2:+&$2}"; }
impact_rows() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/imp-b.json
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/imp-a.json
python3 -c '
import json
print(len(json.load(open("/tmp/imp-b.json"))), len(json.load(open("/tmp/imp-a.json"))))'
}
imp_seen() {
# The observation writer is a pillar on its own timer, and the preview probes
# the sources the edge has actually recorded — so the scene has to wait for the
# rows its own traffic earned to land before it asks what a ban would touch.
# The flush interval is fifteen seconds,
# every fifteen seconds, so the wait is longer than one interval.
for _ in $(seq 1 45); do
n=$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/observations" \
| 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
# Not found. The scene does not fail here: the check that asked prints what it
# actually saw, and a wait that ends without the rows is a slower failure, not
# a hidden one.
return 0
}
allow_id_by_match() {
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" \
| python3 -c 'import sys,json;print(next((a["id"] for a in json.load(sys.stdin) if a["match"]==sys.argv[1]), 0))' "$1"
}
check 'the edge has seen sources inside the range and one outside it' '404 404 404' \
"$(code -H "X-Forwarded-For: $IMP_A" "$(from imp-a)") \
$(code -H "X-Forwarded-For: $IMP_B" "$(from imp-b)") \
$(code -H "X-Forwarded-For: $IMP_OUT" "$(from imp-c)")"
check 'the edge has recorded the sources inside the range it is about to be asked about' 2 \
"$(imp_seen; curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/observations" \
| 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 preview names the sources inside the range it 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 'it probes the watched sources and the ranges own address, not the one outside' yes \
"$(impactq "$IMP_NET_Q" | python3 -c '
import json,sys
d=json.load(sys.stdin)
src={r["source"] for r in d["sources"]}
print("yes" if {"192.0.2.193","192.0.2.194","192.0.2.192"} <= src and "192.0.2.201" not in src
and all(r["change"]=="newly refused" for r in d["sources"])
and all(r["after"]=="block_operator" and r["afterBy"]=="192.0.2.192/29" for r in d["sources"])
else "no")')"
check 'a bare address is previewed under the key this edge files it under' yes \
"$(impactq "$IMP_A" | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("yes" if d["kind"]=="address" and d["filedUnder"]=="192.0.2.193"
and d["probed"]==1 and d["wouldRefuse"] else "no")')"
check 'the preview is a promise, not a write: the wire still answers the upstream' '404 404' \
"$(code -H "X-Forwarded-For: $IMP_A" "$(from imp-d)") \
$(code -H "X-Forwarded-For: 192.0.2.197" "$(from imp-e)")"
check 'an exemption inside the range is named as inside, and the ban will not reach it' yes \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$IMP_FREE"'","note":"the office inside"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow" >/dev/null; \
impactq "$IMP_NET_Q" | python3 -c '
import json,sys
d=json.load(sys.stdin)
ex=[a["match"] for a in d["exemptionsInside"]]
print("yes" if ex==["192.0.2.195"] and d["counts"]["stillPassing"]==0
and d["wouldRefuse"] else "no")')"
check 'an exemption that covers the whole match makes the ban refuse nobody' yes \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"match":"'"$IMP_NET"'","note":"the block is exempt"}' \
"http://127.0.0.1:$EDGE_PORT/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 d["counts"]["newlyRefused"]==0
and out==["192.0.2.192/29"] and d["counts"]["stillPassing"]>=3 else "no")')"
check 'a range already covered by a live one is named as a write that changes nothing' yes \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$(allow_id_by_match '192.0.2.192/29')" >/dev/null; \
code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"192.0.2.192/28","reason":"the whole netblock"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks" >/dev/null; \
impactq "$IMP_NET_Q" | python3 -c '
import json,sys
d=json.load(sys.stdin)
cov=d["alreadyCoveredBy"]
print("yes" if d["changesNothing"] and cov and cov["verdict"]=="block_operator"
and cov["by"]=="192.0.2.192/28" and d["counts"]["alreadyRefused"]>=3 else "no")')"
check 'a match the write would refuse is refused here in the writes words' '400 400 400 400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=192.0.2.0/0") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=192.0.2") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q&path=wp-login") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q&limit=0")"
check 'the read-only token previews, no token does not' '200 401' \
"$(code -H "X-Admin-Token: $RO_TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q") \
$(code "http://127.0.0.1:$EDGE_PORT/admin-api/impact?match=$IMP_NET_Q")"
check 'previewing it six times wrote nothing: the stores hold the same rows' \
"$(impact_rows)" \
"$(for _ in 1 2 3; do impactq "$IMP_NET_Q" >/dev/null; impactq "$IMP_A" >/dev/null; done; impact_rows)"
check 'the scene cleans itself' '0 0' \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.192%2F28" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/allow/$(allow_id_by_match '192.0.2.195')" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" -o /tmp/imp-b2.json; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/allow?live=false" -o /tmp/imp-a2.json; \
python3 -c '
import json
b=json.load(open("/tmp/imp-b2.json")); a=json.load(open("/tmp/imp-a2.json"))
print(len([r for r in b if r["sourceKey"].startswith("192.0.2.19")]),
len([r for r in a if r["match"].startswith("192.0.2.19")]))')"
echo '- admin surface'
check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the policy is readable' Enforce \
"$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')"
# Each pillar keeps its last good value when its own read fails, which is the
# right failure posture and was, until recently, an unmentioned one. The healthy
# case has to be said with numbers too — silence and "0" look the same from
# outside, and only one of them is a claim.
STATE_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")"
check 'the state counts failed pillar reads, and there are none' '0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["snapshotRefreshFailures"], d["policyReloadFailures"])')"
check 'the state says the snapshot is inside its ttl' False \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["snapshotStale"])')"
# Whether a raised alert goes anywhere on its own. Off by default, and the
# surface has to say which of "no alerts" and "no push" it is answering.
check 'the state says alerts are not pushed anywhere by default' False \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["alertWebhookConfigured"])')"
# What the push queue holds (OPEN-60): owed, delivered, given up. The keys are
# asserted before the values, because "0" from a surface that never writes the
# queue is indistinguishable from "0" from one that does.
check 'the state names the push queue it keeps' True \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("alertPushPending","alertPushDelivered","alertPushGivenUp","alertPushLastError","alertPushOldestPendingAt")))')"
check 'and with no endpoint configured it keeps nothing' '0 0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["alertPushPending"], d["alertPushDelivered"], d["alertPushGivenUp"])')"
check 'the policy answer carries its provenance header' 0 \
"$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy" | tr -d '\r' \
| sed -n 's/^[Xx]-[Pp]olicy-[Rr]eload-[Ff]ailures: //p')"
# The write side of the same contract. A failed write is worse than a failed
# read — the row never existed and no later request brings it back — so the
# counters exist even in a clean run, where they read 0 0 0. A surface that
# answers "0" for a field it never publishes is indistinguishable from one that
# publishes it and means it, which is why the keys are asserted too.
check 'the state counts writes it could not persist, and there are none' '0 0 0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["banWriteFailures"], d["observationWriteFailures"], d["alertWriteFailures"], d["retentionPruneFailures"])')"
check 'and it carries what was lost and when a write last landed' True \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("bansNotWritten","banLastWriteAt","observationsLost","alertsLost","observationLastWriteAt","alertLastWriteAt","retentionLastPruneAt")))')"
check 'readiness is ready while the write path is healthy' 200 \
"$(code "http://127.0.0.1:$EDGE_PORT/readyz")"
check 'switching the engine off is accepted' Off \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' --data-binary "$POLICY_OFF_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')"
echo '- healthcheck mode (a shell-less image can only ask the binary)'
dotnet "$BIN" --healthcheck; check 'healthcheck exit code' 0 "$?"
echo
echo "passed $pass, failed $fail"
[ "$fail" -eq 0 ]