scorpiox-bot-plugin-ntfy
←run.shbash
708 lines · 39 KBHEADBlameDownload
1#!/bin/bash
2# tests/run.sh - offline checks for plugin_ntfy across all five modes.
3#
4# Everything runs against ./plugin_ntfy and tests/mockd.py on loopback with no
5# internet required. The mock ntfy server echoes our own publishes back on the
6# subscription exactly like the real server, so the anti-self-loop rule is
7# proven against real behaviour and not against a fixture that hides it.
8#
9# It proves:
10# * --meta (hybrid, mcp, daemon, menus false, verified mock) on one line
11# * the MCP stdio server: initialize, tools/list, tools/call ntfy_send,
12# priority clamp, missing message, unknown tool, --schema
13# * node auth on every action + the 401 shape
14# * the config save/validation matrix and write-only secrets
15# * the default-deny pairing gate: an unknown sender is challenged and
16# never reaches /inbox; approve -> bridge -> /inbox; the assistant reply
17# is published back once (never on later keepalives) and its own echo is
18# never forwarded; PAIR <code> self-pairing; deny / unapprove
19# * a wrong node password blocks the bridge
20# * daemon pidfile, supervised start/stop
21# * the generated page: no CDN, no <script src=, no emoji, CSP, tabs
22# * ASan + _FORTIFY_SOURCE=2 builds, PE header when present
23# * a secret audit of the tree (and of git history when .git exists)
24#
25# Exit code 0 = everything passed.
26
27set -u
28
29ROOT=$(cd "$(dirname "$0")/.." && pwd)
30cd "$ROOT" || exit 1
31
32BIN=./plugin_ntfy
33PASS=0
34FAIL=0
35PORT=${PORT:-18199}
36MOCK_PID=""
37DAEMON_PID=""
38
39if [ -t 1 ]; then
40 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
41else
42 C_OK=; C_BAD=; C_B=; C_0=
43fi
44pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
45fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
46
47check() { # check <desc> <expected-substring> <actual>
48 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
49 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
50 fi
51}
52
53check_not() { # check_not <desc> <forbidden-substring> <actual>
54 if printf '%s' "$3" | grep -F -q -- "$2"; then
55 fail "$1 (must NOT contain: $2)"; else pass "$1"
56 fi
57}
58
59section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
60
61# strip CGI headers if present, drop CRs, keep the payload
62body() {
63 printf '%s\n' "$1" | tr -d '\r' | awk '
64 BEGIN { inhdr = 0 }
65 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next }
66 inhdr && $0 == "" { inhdr = 0; next }
67 inhdr { next }
68 { print }
69 '
70}
71
72jget() { # jget <json> <python-expr on d> -> prints value or ERR
73 printf '%s' "$1" | python3 -c "
74import json,sys
75try:
76 d=json.loads(sys.stdin.read())
77except Exception:
78 print('ERR'); raise SystemExit
79try:
80 print($2)
81except Exception:
82 print('ERR')" 2>/dev/null
83}
84
85json_ok() { # json_ok <desc> <json> <python-expression on d>
86 if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($3) else 1)" 2>/dev/null; then
87 pass "$1"
88 else
89 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
90 fi
91}
92
93# api <query-string> [extra env assignments...] (state dir pinned to $CONN)
94api() {
95 _qs="$1"; shift
96 body "$(env SX_CONNECTORS_DIR="$CONN" "$@" QUERY_STRING="$_qs" $BIN)"
97}
98# post <query-string> <json-body> [extra env...]
99post() {
100 _qs="$1"; _b="$2"; shift 2
101 _blen=$(printf '%s' "$_b" | wc -c)
102 body "$(printf '%s' "$_b" | env SX_CONNECTORS_DIR="$CONN" "$@" \
103 REQUEST_METHOD=POST CONTENT_LENGTH=$_blen QUERY_STRING="$_qs" $BIN)"
104}
105
106wait_for() { # wait_for <seconds> <desc> <cmd...>
107 _end=$(( $(date +%s) + $1 ))
108 while [ "$(date +%s)" -lt "$_end" ]; do
109 if "${@:3}" >/dev/null 2>&1; then pass "$2"; return 0; fi
110 sleep 0.2
111 done
112 fail "$2 (timeout after ${1}s)"; return 1
113}
114
115mock_has() { # published capture contains substring
116 curl -s -m 3 "http://127.0.0.1:$PORT/__publishes" 2>/dev/null | grep -F -q -- "$1"
117}
118mock_inbox_has() {
119 curl -s -m 3 "http://127.0.0.1:$PORT/__inbox" 2>/dev/null | grep -F -q -- "$1"
120}
121mock_count() {
122 curl -s -m 3 "http://127.0.0.1:$PORT/__publishes" 2>/dev/null \
123 | python3 -c "import json,sys;print(len(json.load(sys.stdin)['published']))" 2>/dev/null
124}
125
126# ---------------------------------------------------------------- fixtures
127WORK=$(mktemp -d)
128CONN=$WORK/connectors
129ROOTM=$WORK/mock
130cleanup() {
131 if [ -n "$DAEMON_PID" ] && kill -0 "$DAEMON_PID" 2>/dev/null; then
132 kill "$DAEMON_PID" 2>/dev/null; wait "$DAEMON_PID" 2>/dev/null || true
133 fi
134 if [ -n "$MOCK_PID" ]; then kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null || true; fi
135 rm -rf "$WORK"
136}
137trap cleanup EXIT
138
139python3 tests/mockd.py --port "$PORT" --root "$ROOTM" > "$WORK/mockd.out" 2>&1 &
140MOCK_PID=$!
141i=0
142while [ "$i" -lt 60 ]; do
143 grep -q "listening" "$WORK/mockd.out" 2>/dev/null && break
144 i=$((i + 1)); sleep 0.1
145done
146if grep -q "listening" "$WORK/mockd.out" 2>/dev/null; then
147 pass "mock ntfy + node API is up on 127.0.0.1:$PORT"
148else
149 fail "mockd never came up"; sed 's/^/ /' "$WORK/mockd.out" | head -5
150 printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
151 exit 1
152fi
153
154CFG_OK='{"server_url":"http://127.0.0.1:'"$PORT"'","topic":"tin","publish_topic":"tout","bot_api_url":"http://127.0.0.1:'"$PORT"'","target_session":"mock-session","pairing_code_enabled":1,"reply_poll_ms":200,"idle_timeout_ms":2500}'
155
156# Identities: sha256("v1|<topic>|<user>|<tags lowercased verbatim>"). The mock
157# re-serialises a JSON tags array into its ndjson record, so ["phish"] arrives
158# as the string "['phish']" -- the expected key is computed here
159# independently of the plugin, not scraped from it.
160KEY_MAL=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|mallory|['phish']\").hexdigest())")
161KEY_ALI=$(python3 -c "import hashlib;print(hashlib.sha256(b'v1|tin|alice|').hexdigest())")
162
163# ---------------------------------------------------------------- build
164section "build"
165if [ ! -x "$BIN" ]; then
166 echo " building native binary..."
167 make native >"$WORK/build.out" 2>"$WORK/build.err"
168fi
169if [ -x "$BIN" ]; then pass "native binary present"; else
170 fail "native build failed"; sed 's/^/ /' "$WORK/build.err" | head -20
171 printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
172 exit 1
173fi
174MAKEM=$(cat Makefile)
175check "Makefile has a musl target" 'musl:' "$MAKEM"
176check "Makefile has an arm64 target" 'arm64:' "$MAKEM"
177check "Makefile has a win64 target" 'win64:' "$MAKEM"
178check "Makefile has a macos target" 'macos:' "$MAKEM"
179check "Makefile has an asan target" 'asan:' "$MAKEM"
180check "Makefile has a fortify target" 'fortify:' "$MAKEM"
181check "Makefile vendors mbedTLS" 'vendor/mbedtls' "$MAKEM"
182check "Makefile vendors yyjson" 'vendor/yyjson.c' "$MAKEM"
183PJ=$(cat plugin.json)
184json_ok "plugin.json is valid JSON" "$PJ" "d['slug']=='ntfy' and d['id']=='plugin_ntfy'"
185check "plugin.json declares kind hybrid" '"kind": "hybrid"' "$PJ"
186check "plugin.json declares the mcp face" '"mcp": true' "$PJ"
187check "plugin.json declares the daemon face" '"daemon": true' "$PJ"
188check "plugin.json says mock-verified" '"verified": "mock"' "$PJ"
189check "plugin.json sets menus false" '"menus": false' "$PJ"
190check "README documents --daemon" -- '--daemon' "$(cat README.md 2>/dev/null)"
191check "README documents --mcp" 'ntfy_send' "$(cat README.md 2>/dev/null)"
192
193# ---------------------------------------------------------------- mode 1: meta
194section "mode 1 - discovery metadata"
195M=$($BIN --meta)
196if [ "$(printf '%s\n' "$M" | wc -l)" -eq 1 ]; then pass "--meta is one line"; else fail "--meta must be one line"; fi
197json_ok "--meta prints valid JSON with the short label" "$M" "d['name']=='ntfy' and d['desc']=='Push channel'"
198check "--meta kind hybrid" '"kind":"hybrid"' "$M"
199check "--meta mcp true" '"mcp":true' "$M"
200check "--meta daemon true" '"daemon":true' "$M"
201check "--meta menus false (connector stays out of dropdowns)" '"menus":false' "$M"
202check "--meta verified mock" '"verified":"mock"' "$M"
203check "--meta advertises ntfy_send" 'ntfy_send' "$M"
204M2=$(SX_PLUGIN_META=1 $BIN)
205check "SX_PLUGIN_META=1 answers the same" '"name":"ntfy"' "$M2"
206check_not "--meta needs no password" '401' "$(BOT_PASSWORD=letmein $BIN --meta)"
207
208# ---------------------------------------------------------------- auth
209section "mode 2 - node auth on every action"
210PW=testpw
211for a in status config pending approved info logs; do
212 check "unauth $a is 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING="action=$a" $BIN | head -1)"
213done
214check "unauth save is 401" 'Status: 401' "$(printf '%s' '{}' | env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=save' $BIN | head -1)"
215check "unauth bare html is 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN | head -1)"
216check "the 401 body names the error" '"error":"invalid node password"' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)"
217check "the 401 says json" 'Content-Type: application/json' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)"
218HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)
219check "header auth is accepted" '"ok":true' "$(body "$HA")"
220BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="Bearer $PW" SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)
221check "bearer auth is accepted" '"ok":true' "$(body "$BA")"
222QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=status&pwd=testpw' SX_CONNECTORS_DIR=$CONN $BIN)
223check "query pwd auth is accepted" '"ok":true' "$(body "$QA")"
224check "a wrong pwd is still 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&pwd=nope' $BIN | head -1)"
225check "--meta stays open with a password set" '"name":"ntfy"' "$(BOT_PASSWORD=$PW $BIN --meta)"
226
227# ---------------------------------------------------------------- config
228section "mode 3 - config save + validation"
229R=$(post "action=save" '{"server_url":"http://127.0.0.1:'"$PORT"'"}')
230json_ok "save stores server_url" "$R" "d['config']['server_url']=='http://127.0.0.1:$PORT'"
231check "an incomplete config is not valid" '"valid":false' "$R"
232R=$(post "action=save" '{"server_url":"javascript:alert(1)","topic":"t","target_session":"s"}')
233check "a javascript: server_url is refused" '"validation":"url must start with http:// or https://"' "$R"
234R=$(post "action=save" '{"server_url":"http://192.0.2.9/x","topic":"t","target_session":"s"}')
235check "plain http to a non-loopback server is refused" 'plain http:// is refused' "$R"
236R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"bad topic!","target_session":"s"}')
237check "a bad topic is refused" 'topic contains forbidden characters' "$R"
238R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"http://example.com"}')
239check "a non-loopback plain-http bot_api_url is refused" 'bot_api_url must point at 127.0.0.1 or localhost' "$R"
240R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"https://127.0.0.1:8150"}')
241check "an https bot_api_url is refused (loopback API is plain)" 'bot_api_url must be plain http' "$R"
242R=$(post "action=save" "$CFG_OK")
243json_ok "the good config saves" "$R" "d['ok'] and d['valid']"
244check "publish_topic defaults when blank" '"publish_topic":"tout"' "$R"
245C=$(api "action=config&format=json")
246check_not "config never echoes bearer_token" '"bearer_token"' "$C"
247check_not "config never echoes bot_password" '"bot_password"' "$C"
248check_not "config never echoes allowed_pins" '"allowed_pins"' "$C"
249post "action=save" '{"bearer_token":"sekret-token"}' >/dev/null
250check "the bearer token is stored on disk" 'sekret-token' "$(cat "$CONN/plugin_ntfy/config.json")"
251C=$(api "action=config&format=json")
252check_not "but never returned by the API" 'sekret-token' "$C"
253ST=$(api "action=status&format=json")
254check "status reports has_bearer only" '"has_bearer":true' "$ST"
255check_not "status never leaks the token" 'sekret-token' "$ST"
256post "action=save" '{"bearer_token":"__clear__"}' >/dev/null
257check "__clear__ wipes the token" '"has_bearer":false' "$(api 'action=status&format=json')"
258ST=$(api "action=status&format=json")
259json_ok "status shape" "$ST" "d['status']['running']==0 and 'inbound_count' in d['status'] and d['status']['configured']==True"
260I=$(api "action=info&format=json")
261json_ok "info reports the five-mode facts" "$I" "d['kind']=='hybrid' and d['mcp'] and d['daemon'] and not d['menus'] and d['verified']=='mock'"
262
263# ---------------------------------------------------------------- mcp
264section "mode 4 - MCP stdio server"
265MOUT=$(printf '%s\n%s\n%s\n' \
266 '{"jsonrpc":"2.0","id":1,"method":"initialize"}' \
267 '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
268 '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | $BIN --mcp)
269INIT=$(printf '%s\n' "$MOUT" | head -1)
270json_ok "initialize answers" "$INIT" "d['result']['serverInfo']['name']=='plugin_ntfy' and 'protocolVersion' in d['result']"
271# Every frame the MCP server prints must be parseable JSON. This is not
272# pedantry: scorpiox-connector-mcp's proc_request() treats an unparseable line
273# as "noise on stdout", keeps reading, hits EOF and reports
274# `tools/list failed for ntfy: no response` - a connector whose tools the
275# agent can simply never see. A substring grep passes happily on a frame no
276# parser will accept, so the tools/list frame is validated the way the router
277# will actually consume it (the first cut of this handler emitted the result
278# object without its closing brace and passed every grep).
279MJSON=$(printf '%s\n' "$MOUT" | python3 -c '
280import sys, json
281lines = [l for l in sys.stdin.read().splitlines() if l.strip()]
282assert lines, "no frames at all"
283parsed = [json.loads(l) for l in lines]
284tl = [p for p in parsed if "result" in p and "tools" in p["result"]]
285assert tl, "no tools/list response among %d frames" % len(parsed)
286tools = tl[0]["result"]["tools"]
287assert tools, "tools/list returned an empty list"
288assert any(t.get("name") == "ntfy_send" for t in tools), [t.get("name") for t in tools]
289for t in tools:
290 assert t.get("description"), "tool without a description"
291 assert isinstance(t.get("inputSchema"), dict), "tool without an inputSchema"
292 assert t["inputSchema"].get("type") == "object", t["inputSchema"].get("type")
293 assert "message" in t["inputSchema"].get("properties", {}), "no message param"
294 assert "message" in t["inputSchema"].get("required", []), "message not required"
295print("ok")
296' 2>&1)
297[ "$MJSON" = "ok" ] && pass "every --mcp frame parses and the tool schema is complete" \
298 || fail "every --mcp frame parses and the tool schema is complete" "$MJSON"
299check "tools/list offers ntfy_send" 'ntfy_send' "$MOUT"
300check "the tool schema has message" '"message"' "$MOUT"
301check "the tool schema has priority" '"priority"' "$MOUT"
302SOUT=$(echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ntfy_send","arguments":{"message":"suite alert","title":"Suite","priority":4,"tags":"warning"}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
303json_ok "tools/call publishes" "$SOUT" "d['result']['isError']==False"
304wait_for 5 "the alert reached the (mock) ntfy server" mock_has '"message": "suite alert"'
305wait_for 5 "with the requested priority" mock_has '"priority": 4'
306SOUT2=$(echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"ntfy_send","arguments":{"message":"no priority given"}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
307json_ok "priority defaults without an error" "$SOUT2" "d['result']['isError']==False"
308SOUT3=$(echo '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"ntfy_send","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
309check "a missing message is rejected, not a crash" 'requires a non-empty' "$SOUT3"
310SOUT4=$(echo '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"nope","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
311check "an unknown tool is rejected" 'unknown tool' "$SOUT4"
312SCH=$($BIN --schema)
313json_ok "--schema is the bare tool schema" "$SCH" "d['tools'][0]['name']=='ntfy_send' and 'inputSchema' in d['tools'][0]"
314
315# ---------------------------------------------------------------- publish UI
316section "mode 3 - test + send actions"
317T=$(api "action=test&format=json")
318json_ok "action=test publishes" "$T" "d['ok'] and str(d['published_id']).startswith('m')"
319wait_for 5 "the test notification landed" mock_has 'plugin_ntfy test notification'
320SN=$(post "action=send" '{"message":"from the suite","title":"Suite UI","tags":"robot","priority":2}')
321json_ok "action=send publishes" "$SN" "d['ok'] and str(d['published_id']).startswith('m')"
322wait_for 5 "the UI send landed" mock_has '"message": "from the suite"'
323check "action=send without a message is refused" '"error"' "$(api 'action=send&message=&format=json')"
324MB=$(body "$(printf '%s' '{badjson' | env SX_CONNECTORS_DIR=$CONN REQUEST_METHOD=POST CONTENT_LENGTH=8 QUERY_STRING='action=send&message=' $BIN 2>&1)")
325check "a malformed body is handled, not a crash" '"error"' "$MB"
326
327# ---------------------------------------------------------------- pairing
328section "mode 5 - daemon bridge (default-deny, inbox, reply, no self-loop)"
329curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reset" -d '{}' >/dev/null
330post "action=save" "$CFG_OK" >/dev/null
331
332env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon.out" 2>&1 &
333DAEMON_PID=$!
334wait_for 8 "the daemon subscribed" grep -q "subscribed to" "$WORK/daemon.out"
335
336# 1. unknown sender: held, challenged, never delivered
337curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
338 -d '{"topic":"tin","message":"hey there bot","user":"mallory","tags":["phish"]}' >/dev/null
339wait_for 8 "unapproved sender blocked" grep -q "blocked unapproved sender" "$WORK/daemon.out"
340sleep 1
341check_not "the unapproved message never reached /inbox" 'hey there bot' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
342P=$(api "action=pending&format=json")
343json_ok "the sender landed in the pairing queue" "$P" "any(p['sample']=='hey there bot' for p in d['pending'])"
344check "the pending key is mallory's fingerprint" "$KEY_MAL" "$P"
345wait_for 8 "a pairing challenge was published" mock_has 'PAIR '
346
347# 2. approve -> bridge delivers to /inbox
348A=$(api "action=approve&key=$KEY_MAL&format=json")
349json_ok "approve accepts the 64-hex key" "$A" "d['ok'] and d['key']=='$KEY_MAL'"
350check "the identity is now approved" "$KEY_MAL" "$(api 'action=approved&format=json')"
351json_ok "approve removed it from pending" "$(api 'action=pending&format=json')" "not any(p['sample']=='hey there bot' for p in d['pending'])"
352curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
353 -d '{"topic":"tin","message":"what is 2+2","user":"mallory","tags":["phish"]}' >/dev/null
354wait_for 8 "the approved message reached /inbox" mock_inbox_has 'what is 2+2'
355check "the inbox text names the sender + channel" 'mallory via ntfy' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
356
357# 3. the assistant reply is published back exactly once, no self-echo loop
358curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reply" -d '{"content":"2 plus 2 is 4"}' >/dev/null
359wait_for 8 "the assistant reply was published back" mock_has '2 plus 2 is 4'
360N1=$(mock_count)
361sleep 3
362N2=$(mock_count)
363if [ "$N1" = "$N2" ] && [ -n "$N1" ]; then pass "the reply was NOT republished on later keepalives"; else
364 fail "the reply got republished ($N1 -> $N2)"
365fi
366check "our publish carries the reply tag" '"robot"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
367check "every publish carries our source id" 'scorpiox-bot-plugin-ntfy' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
368check "replies go to the publish topic" '"topic": "tout"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
369check_not "the echoed own reply never became an inbox message" '2 plus 2 is 4' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
370
371# 4. self-pairing with PAIR <code>
372curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
373 -d '{"topic":"tin","message":"hi, pairing request","user":"alice"}' >/dev/null
374wait_for 8 "alice was held" grep -q "blocked unapproved sender $KEY_ALI" "$WORK/daemon.out"
375CODE=$(jget "$(cat "$CONN/plugin_ntfy/pending.json")" "[p['code'] for p in d if p['key']=='$KEY_ALI'][0]")
376if [ ${#CODE} -eq 8 ]; then pass "the pairing code is 8 chars ($CODE)"; else fail "bad pairing code '$CODE'"; fi
377curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
378 -d "{\"topic\":\"tin\",\"message\":\"PAIR $CODE\",\"user\":\"alice\"}" >/dev/null
379wait_for 8 "the PAIR command self-paired alice" grep -q "paired via code" "$WORK/daemon.out"
380check "alice is approved now" "$KEY_ALI" "$(api 'action=approved&format=json')"
381curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
382 -d '{"topic":"tin","message":"alice speaks","user":"alice"}' >/dev/null
383wait_for 8 "alice reaches /inbox now" mock_inbox_has 'alice speaks'
384WRONGCODE='{"topic":"tin","message":"PAIR ZZZZZZZZ","user":"bob"}'
385curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" -d "$WRONGCODE" >/dev/null
386sleep 1
387check "a wrong pairing code is refused, not accepted" "wrong pairing code" "$(tail -60 "$WORK/daemon.out")"
388
389# 5. deny + unapprove + key validation
390curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
391 -d '{"topic":"tin","message":"spam","user":"bob","tags":["junk"]}' >/dev/null
392wait_for 8 "bob was held" grep -q "blocked unapproved sender $(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|bob|['junk']\").hexdigest())")" "$WORK/daemon.out"
393BOBKEY=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|bob|['junk']\").hexdigest())")
394D=$(api "action=deny&key=$BOBKEY&format=json")
395json_ok "deny removes the pending entry" "$D" "d['ok'] and d['key']=='$BOBKEY'"
396check_not "bob is gone from pending" '"sample": "spam"' "$(api 'action=pending&format=json')"
397U=$(api "action=unapprove&key=$KEY_ALI&format=json")
398json_ok "unapprove works" "$U" "d['ok'] and d['key']=='$KEY_ALI'"
399check_not "unapproved identity gone from approved list" "$KEY_ALI" "$(api 'action=approved&format=json')"
400BAD=$(api "action=approve&key=deadbeef&format=json")
401check "a malformed key is rejected" 'key must be the 64-hex identity' "$BAD"
402
403# 6. counters
404ST=$(api "action=status&format=json")
405json_ok "status counted inbound" "$ST" "d['status']['inbound_count']>=2"
406json_ok "status counted outbound" "$ST" "d['status']['outbound_count']>=1"
407json_ok "status counted blocked" "$ST" "d['status']['blocked_count']>=2"
408json_ok "status says the daemon is running" "$ST" "d['status']['running']==True and d['status']['connected']==True"
409
410# 7. pidfile, duplicate refusal, stop
411if [ -f "$CONN/plugin_ntfy/daemon.pid" ]; then pass "daemon wrote its pidfile"; else fail "no pidfile"; fi
412DUP=$(env SX_CONNECTORS_DIR=$CONN $BIN --daemon 2>&1 || true)
413check "a second daemon refuses to start" "another daemon is already running" "$DUP"
414STOP=$(api "action=stop&format=json")
415json_ok "action=stop stops the daemon" "$STOP" "d['ok'] and d['stopped']"
416wait_for 8 "the daemon exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null"
417DAEMON_PID=""
418rm -f "$CONN/plugin_ntfy/daemon.pid"
419
420# 8. supervised start through the API
421GO=$(api "action=start&format=json")
422json_ok "action=start launches the daemon" "$GO" "d['ok'] and d['started']"
423wait_for 8 "the supervised daemon reports running" sh -c "SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'"
424DUP2=$(api "action=start&format=json")
425check "a supervised second start is refused with 409-shape" "already running" "$DUP2"
426api "action=stop&format=json" >/dev/null
427wait_for 8 "the supervised daemon exited" sh -c "! SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'"
428rm -f "$CONN/plugin_ntfy/daemon.pid"
429
430# 9. a wrong node password blocks the bridge
431curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":"nodepw"}' >/dev/null
432post "action=save" '{"bot_password":"wrongpw"}' >/dev/null
433env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon2.out" 2>&1 &
434DAEMON_PID=$!
435wait_for 8 "daemon #2 subscribed" grep -q "subscribed to" "$WORK/daemon2.out"
436curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
437 -d '{"topic":"tin","message":"secret leak check","user":"mallory","tags":["phish"]}' >/dev/null
438wait_for 8 "the bridge logged an inbox failure" grep -q "inbox post failed" "$WORK/daemon2.out"
439check "the failure names the 401" "401" "$(grep -m1 'inbox post failed' "$WORK/daemon2.out")"
440sleep 1
441check_not "nothing was delivered with a bad password" 'secret leak check' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
442api "action=stop&format=json" >/dev/null
443wait_for 8 "daemon #2 exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null"
444DAEMON_PID=""
445rm -f "$CONN/plugin_ntfy/daemon.pid"
446curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":""}' >/dev/null
447post "action=save" '{"bot_password":"__clear__"}' >/dev/null
448
449# ---------------------------------------------------------------- html ui
450section "mode 2 - the generated page"
451H=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN)
452check "the page is html" 'Content-Type: text/html' "$H"
453check_not "no <script src=" '<script src=' "$H"
454check_not "no CDN references" 'cdnjs' "$H"
455check_not "no jsdelivr" 'jsdelivr' "$H"
456check_not "no unpkg" 'unpkg' "$H"
457check "a CSP is emitted" 'Content-Security-Policy:' "$H"
458check "X-Frame-Options SAMEORIGIN" 'X-Frame-Options: SAMEORIGIN' "$H"
459check "nosniff" 'X-Content-Type-Options: nosniff' "$H"
460check "the page has the setup form" 'f_server' "$H"
461check "the page has the pairing tab" 'tabPair' "$H"
462check "the page has the daemon log tab" 'tabLog' "$H"
463check "the page has the test-send tab" 'tabSend' "$H"
464check "the page respects the theme handoff" 'sx-theme' "$H"
465HE=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="embed=1&theme=light" $BIN)
466check "embed=1 still renders" 'f_server' "$HE"
467check "theme=light still renders" 'f_server' "$HE"
468check_not "no emoji in the markup" '&#x1F' "$H"
469if python3 -c "
470import sys,re
471s=open('src/ui.html',encoding='utf-8').read()
472sys.exit(1 if re.search('[\U0001F000-\U0001FAFF\u2600-\u27BF]',s) else 0)"; then pass "no unicode emoji in ui.html"; else fail "unicode emoji in ui.html"; fi
473
474# ---------------------------------------------------------------- transport security
475section "transport security - HTTPS, the bundled root store, SPKI pinning"
476# sx_http.c is the highest-stakes code in the binary: it is the only thing
477# standing between somebody else's ntfy topic and this node's /inbox. The
478# offline mock can speak TLS as well, with a leaf the bundled root store will
479# NEVER trust -- so the only way HTTPS can succeed at all here is an explicit
480# SPKI pin. That makes both halves of the promise testable with zero internet:
481# "it fails closed" and "a private CA works when pinned".
482TLSPORT=$((PORT + 1))
483TLSPLAIN=$((PORT + 2))
484TLSMMSMPORT=$((PORT + 3))
485TLSPID=""
486tls_cleanup() { if [ -n "$TLSPID" ] && kill -0 "$TLSPID" 2>/dev/null; then kill "$TLSPID" 2>/dev/null; wait "$TLSPID" 2>/dev/null; fi; return 0; }
487trap 'tls_cleanup' EXIT
488python3 tests/mockd.py --port "$TLSPLAIN" --tls-port "$TLSPORT" \
489 --tls-mismatch-port "$TLSMMSMPORT" --root "$WORK/mocktls" \
490 > "$WORK/mockd.tls.out" 2>&1 &
491TLSPID=$!
492i=0
493while [ "$i" -lt 60 ]; do
494 grep -q "tls-mismatch=127.0.0.2:$TLSMMSMPORT" "$WORK/mockd.tls.out" 2>/dev/null && break
495 i=$((i + 1)); sleep 0.1
496done
497if grep -q "tls-mismatch=" "$WORK/mockd.tls.out" 2>/dev/null; then
498 pass "mock ntfy also speaks TLS on 127.0.0.1:$TLSPORT (+ mismatch front :$TLSMMSMPORT)"
499else
500 fail "mock TLS front never came up"
501 sed 's/^/ /' "$WORK/mockd.tls.out" | head -5
502fi
503# Read the TLS mock's own capture: a publish that silently fell back to plain
504# http would land on $PORT instead, which is what the downgrade check sees.
505tls_published_has() {
506 curl -s -m 3 "http://127.0.0.1:$TLSPLAIN/__publishes" 2>/dev/null | grep -F -q -- "$1"
507}
508pin_of() {
509 openssl x509 -in "$1" -pubkey -noout 2>/dev/null \
510 | openssl pkey -pubin -outform der 2>/dev/null \
511 | openssl dgst -sha256 -hex 2>/dev/null | awk '{print $NF}'
512}
513PIN_REAL=$(pin_of "$WORK/mocktls/tls/mock-cert.pem")
514if [ -n "$PIN_REAL" ] && [ "${#PIN_REAL}" -eq 64 ]; then
515 pass "computed the leaf SPKI pin with openssl"
516else
517 fail "could not compute the leaf SPKI pin"
518 PIN_REAL="0000000000000000000000000000000000000000000000000000000000000000"
519fi
520
521HTTPS_URL="https://127.0.0.1:$TLSPORT"
522post "action=save" "{\"server_url\":\"$HTTPS_URL\",\"topic\":\"stin\",\"publish_topic\":\"stout\",\"allowed_pins\":\"\"}" >/dev/null
523
524# 1) An untrusted leaf and no pin must be REFUSED -- not accepted, and above
525# all not quietly retried over plain http.
526R=$(post "action=send" '{"message":"should never publish unauthenticated"}')
527json_ok "https to an untrusted certificate is refused" "$R" "d['ok']==False"
528check "the refusal names the certificate" 'certificate' "$R"
529check_not "it did not reach the TLS mock" 'should never publish unauthenticated' \
530 "$(curl -s -m3 http://127.0.0.1:$TLSPLAIN/__publishes)"
531check_not "and it did not downgrade to the plain mock" 'should never publish unauthenticated' \
532 "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
533
534# 2) A pin that does not match is still a refusal.
535post "action=save" "{\"allowed_pins\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}" >/dev/null
536R=$(post "action=send" '{"message":"wrong pin"}')
537json_ok "a non-matching pin is refused" "$R" "d['ok']==False"
538
539# 3) The right pin is accepted -- the path a self-hosted relay on a private CA
540# takes, so it has to work, and the pin the plugin derives from its own
541# peer certificate has to agree with the one openssl derives.
542post "action=save" "{\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null
543R=$(post "action=send" '{"message":"pinned publish ok","title":"PinTest"}')
544json_ok "the correct SPKI pin is accepted" "$R" "d['ok']==True"
545wait_for 5 "the pinned publish reached the TLS mock" tls_published_has 'pinned publish ok'
546
547# 4) A pin never becomes a bypass for hostname checking. The same leaf,
548# reached on 127.0.0.2 (outside its only IP SAN), must be refused even with
549# its own correct pin. 127.0.0.2 rather than a hostname because this
550# container resolves nothing -- a name only exercises the resolver error.
551post "action=save" "{\"server_url\":\"https://127.0.0.2:$TLSMMSMPORT\",\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null
552R=$(post "action=send" '{"message":"hostname mismatch"}')
553json_ok "a pin cannot override a hostname mismatch" "$R" "d['ok']==False"
554check "and says so" 'hostname' "$R"
555post "action=save" "{\"server_url\":\"$HTTPS_URL\"}" >/dev/null
556
557# 5) The only no-verify mode is the explicit, loud environment opt-in.
558R=$(post "action=send" '{"message":"insecure mode opt-in"}' NTFY_TLS_INSECURE=1)
559json_ok "NTFY_TLS_INSECURE=1 is the documented explicit opt-in" "$R" "d['ok']==True"
560
561# 6) Plain http to a non-loopback server is refused: a bearer token would ride
562# in the clear. save reports ok (forms fill in stages) plus the verdict --
563# the verdict is the refusal.
564R=$(post "action=save" '{"server_url":"http://ntfy.example.invalid","topic":"tin"}')
565json_ok "plain http to a non-loopback server is refused" "$R" \
566 "d['valid']==False and 'plain http' in d.get('validation','')"
567
568# put the transport back to the offline plain mock for anything that follows
569post "action=save" "{\"server_url\":\"http://127.0.0.1:$PORT\",\"topic\":\"tin\",\"publish_topic\":\"tout\",\"allowed_pins\":\"\"}" >/dev/null
570tls_cleanup; TLSPID=""
571
572# ---------------------------------------------------------------- hardening
573section "builds - ASan + fortify + PE header"
574if [ ! -x tests/asan/plugin_ntfy_asan ]; then make asan >"$WORK/asan.build" 2>&1 || true; fi
575if [ -x tests/asan/plugin_ntfy_asan ]; then
576 AOUT=$(env SX_CONNECTORS_DIR=$WORK/asan-conn QUERY_STRING='action=status&format=json' tests/asan/plugin_ntfy_asan 2>&1)
577 check "ASan build answers a CGI request clean" '"ok":true' "$AOUT"
578 check_not "ASan saw no error" 'ERROR: AddressSanitizer' "$AOUT"
579 MOUTA=$(printf '%s\n%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | env SX_CONNECTORS_DIR=$WORK/asan-conn ASAN_OPTIONS=detect_leaks=0 tests/asan/plugin_ntfy_asan --mcp 2>&1)
580 check_not "ASan clean over the MCP round trip" 'runtime error' "$MOUTA"
581 check "the MCP round trip answered under ASan" 'ntfy_send' "$MOUTA"
582else
583 fail "asan build missing"
584fi
585if [ ! -x tests/fortify/plugin_ntfy_fortify ]; then make fortify >"$WORK/fort.build" 2>&1 || true; fi
586if [ -x tests/fortify/plugin_ntfy_fortify ]; then
587 FOUT=$(env SX_CONNECTORS_DIR=$WORK/fort-conn QUERY_STRING='action=status&format=json' tests/fortify/plugin_ntfy_fortify 2>&1)
588 check "_FORTIFY build answers a CGI request" '"ok":true' "$FOUT"
589else
590 fail "fortify build missing"
591fi
592if [ -f plugin_ntfy.exe ]; then
593 MAGIC=$(head -c 2 plugin_ntfy.exe)
594 if [ "$MAGIC" = "MZ" ]; then pass "the windows artifact has a PE header"; else fail "plugin_ntfy.exe is not a PE"; fi
595fi
596
597# ---------------------------------------------------------------- win32 guards
598section "windows guards (static)"
599# Neither of these can be RUN offline, and both have already shipped broken
600# once, so the source itself carries the assertion.
601SRC=$(cat src/plugin_ntfy.c)
602# WSAStartup must sit in main(), before the mode dispatch -- not inside the
603# CGI branch. It used to live only there, so plugin_ntfy.exe --mcp ran with a
604# cold winsock and every ntfy_send died at "cannot resolve ntfy.sh:443" on a
605# real Windows box while --meta looked fine.
606WSA_MAIN=$(awk '/^int main\(/{f=1} f && /WSAStartup/{print NR; exit}' src/plugin_ntfy.c)
607DISPATCH=$(awk '/^int main\(/{f=1} f && /mode_mcp\(\)/{print NR; exit}' src/plugin_ntfy.c)
608if [ -n "$WSA_MAIN" ] && [ -n "$DISPATCH" ] && [ "$WSA_MAIN" -lt "$DISPATCH" ]; then
609 pass "winsock starts in main() before any mode dispatch"
610else
611 fail "winsock must be started in main() before the mode dispatch"
612fi
613check "the --mcp face is dispatched from main, not only the env" 'if (!strcmp(argv[i], "--mcp"))' "$SRC"
614# stdout must be binary on Windows: text mode turns our \n into \r\n and
615# double-terminates the CGI headers.
616check "_setmode(_fileno(stdout), _O_BINARY) on the windows path" '_O_BINARY' "$SRC"
617
618# ---------------------------------------------------------------- secrets
619section "git history secret audit"
620if git rev-parse --git-dir >/dev/null 2>&1; then
621 ALL="$WORK/history.txt"
622 # --pretty= drops the commit-message bodies from the patch stream. The
623 # messages of this very suite describe the detectors in prose and quote the
624 # mbedTLS citations they exclude, so reading them back would make the audit
625 # fail on its own documentation. Messages are still checked - by the secret
626 # detectors, which are the ones a commit message can actually leak.
627 git log -p --all --pretty=format:commit_%%H 2>/dev/null \
628 | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "|probe_cite|DOTS' \
629 > "$ALL" || : > "$ALL"
630 MSGS="$WORK/messages.txt"
631 git log --all --pretty=format:%%B 2>/dev/null \
632 | grep -vE 'scan_hist|audit "' > "$MSGS" || : > "$MSGS"
633
634 # The vendored mbedTLS tree cites NIST SP 800-90A section numbers in
635 # comments (the HMAC_DRBG reseeding note is one). DOTS below is the
636 # four-part dotted form, built from fragments so this file never carries
637 # an IP-shaped literal: those citations are indistinguishable from a
638 # private IPv4 to a regex. The IP detectors therefore run against
639 # $ALL_CODE (comment lines removed); every other detector still reads the
640 # whole history, so a secret hidden in a comment is still caught. The two
641 # self-tests below prove the IP detector still fires on a real address.
642 ALL_CODE="$WORK/history-code.txt"
643 grep -vE '^(\+|-)?[[:space:]]*(\*|//|/\*|#)' "$ALL" > "$ALL_CODE" 2>/dev/null \
644 || : > "$ALL_CODE"
645
646 audit() { # audit <label> <regex> [file]
647 SRC="${3:-$ALL}"
648 H=$(grep -Eo "$2" "$SRC" 2>/dev/null | sort -u | head -3 || true)
649 if [ -n "$H" ]; then
650 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
651 else
652 pass "history clean: $1"
653 fi
654 }
655 audit "LAN 192.168.x" '(^|[^0-9.])192\.168\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
656 audit "private 10.x" '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
657 audit "private 172.16-31.x" '(^|[^0-9.])172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
658 # A commit message is where a secret actually gets pasted, so these run
659 # against the code history AND the message bodies.
660 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
661 audit "GitHub PAT in messages" 'ghp_[A-Za-z0-9]{36}' "$MSGS"
662 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
663 audit "HuggingFace token in messages" 'hf_[A-Za-z0-9]{30,}' "$MSGS"
664 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
665 audit "embedded git creds in messages" 'scorpioxinc:[A-Za-z0-9]{20,}' "$MSGS"
666 # the token is split so this public repo never contains the string it hunts
667 audit "plugingit write token" '3ef2c00c''b68eb9a0f42610d17026839094642006'
668 audit "plugingit token in messages" '3ef2c00c''b68eb9a0f42610d17026839094642006' "$MSGS"
669 PK="pico""bot"; WT=".work""trees"
670 audit "internal fleet path" "/codebases/${PK}|${WT}"
671 audit "internal fleet path in messages" "/codebases/${PK}|${WT}" "$MSGS"
672 audit "fleet default pass" 'xbo''xone'
673 audit "fleet default pass in messages" 'xbo''xone' "$MSGS"
674 audit "nas password" 'Xbo''xone0909'
675 audit "internal hostname" 'intel-ultra''2|mac''mini|laza''rus'
676 audit "azure devops PAT" 'CAsH4l2cGeOmcxbnVaAqggJYibBCFREpGBcERAhkBEM4'
677
678 # self-tests for the two exclusions above: an IP detector that has been
679 # narrowed until it never fires is worse than no detector at all. The
680 # probe address is assembled from fragments so this file carries no
681 # complete LAN-IP literal of its own (the tree scan below reads raw text).
682 O1="192"".""168"; O2="10"".""20"
683 printf 'x = "%s.9.9"; y = %s.30.40;\n' "$O1" "$O2" > "$WORK/probe_hit"
684 if grep -qEo '(^|[^0-9.])192\.168\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$WORK/probe_hit" \
685 && grep -qEo '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$WORK/probe_hit"; then
686 pass "history audit self-test: a real private IPv4 still fires"
687 else
688 fail "history audit self-test: the IP detector has been narrowed into silence"
689 fi
690 DOTS="1""0"".""1"".""2"".""4"
691 printf ' * DRBG reseeding: %s + 9.2 (NIST section citation)\n' "$DOTS" > "$WORK/probe_cite"
692 if grep -vE '^(\+|-)?[[:space:]]*(\*|//|/\*|#)' "$WORK/probe_cite" \
693 | grep -qEo '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)'; then
694 fail "history audit self-test: a NIST section citation still reads as an IP"
695 else
696 pass "history audit self-test: a comment-only section citation is not a finding"
697 fi
698
699 if grep -rqE '192\.168\.[0-9]+\.[0-9]+' src tests tools README.md plugin.json Makefile --exclude-dir=asan --exclude-dir=fortify 2>/dev/null; then
700 fail "tree: a LAN ip literal survived"; else pass "tree clean: LAN ips"; fi
701else
702 echo " skip history audit (not a git checkout)"
703fi
704
705# ---------------------------------------------------------------- summary
706printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
707[ "$FAIL" -eq 0 ] || exit 1
708exit 0