| 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 | |
| 27 | set -u |
| 28 | |
| 29 | ROOT=$(cd "$(dirname "$0")/.." && pwd) |
| 30 | cd "$ROOT" || exit 1 |
| 31 | |
| 32 | BIN=./plugin_ntfy |
| 33 | PASS=0 |
| 34 | FAIL=0 |
| 35 | PORT=${PORT:-18199} |
| 36 | MOCK_PID="" |
| 37 | DAEMON_PID="" |
| 38 | |
| 39 | if [ -t 1 ]; then |
| 40 | C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') |
| 41 | else |
| 42 | C_OK=; C_BAD=; C_B=; C_0= |
| 43 | fi |
| 44 | pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } |
| 45 | fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } |
| 46 | |
| 47 | check() { # 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 | |
| 53 | check_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 | |
| 59 | section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } |
| 60 | |
| 61 | # strip CGI headers if present, drop CRs, keep the payload |
| 62 | body() { |
| 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 | |
| 72 | jget() { # jget <json> <python-expr on d> -> prints value or ERR |
| 73 | printf '%s' "$1" | python3 -c " |
| 74 | import json,sys |
| 75 | try: |
| 76 | d=json.loads(sys.stdin.read()) |
| 77 | except Exception: |
| 78 | print('ERR'); raise SystemExit |
| 79 | try: |
| 80 | print($2) |
| 81 | except Exception: |
| 82 | print('ERR')" 2>/dev/null |
| 83 | } |
| 84 | |
| 85 | json_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) |
| 94 | api() { |
| 95 | _qs="$1"; shift |
| 96 | body "$(env SX_CONNECTORS_DIR="$CONN" "$@" QUERY_STRING="$_qs" $BIN)" |
| 97 | } |
| 98 | # post <query-string> <json-body> [extra env...] |
| 99 | post() { |
| 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 | |
| 106 | wait_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 | |
| 115 | mock_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 | } |
| 118 | mock_inbox_has() { |
| 119 | curl -s -m 3 "http://127.0.0.1:$PORT/__inbox" 2>/dev/null | grep -F -q -- "$1" |
| 120 | } |
| 121 | mock_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 |
| 127 | WORK=$(mktemp -d) |
| 128 | CONN=$WORK/connectors |
| 129 | ROOTM=$WORK/mock |
| 130 | cleanup() { |
| 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 | } |
| 137 | trap cleanup EXIT |
| 138 | |
| 139 | python3 tests/mockd.py --port "$PORT" --root "$ROOTM" > "$WORK/mockd.out" 2>&1 & |
| 140 | MOCK_PID=$! |
| 141 | i=0 |
| 142 | while [ "$i" -lt 60 ]; do |
| 143 | grep -q "listening" "$WORK/mockd.out" 2>/dev/null && break |
| 144 | i=$((i + 1)); sleep 0.1 |
| 145 | done |
| 146 | if grep -q "listening" "$WORK/mockd.out" 2>/dev/null; then |
| 147 | pass "mock ntfy + node API is up on 127.0.0.1:$PORT" |
| 148 | else |
| 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 |
| 152 | fi |
| 153 | |
| 154 | CFG_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. |
| 160 | KEY_MAL=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|mallory|['phish']\").hexdigest())") |
| 161 | KEY_ALI=$(python3 -c "import hashlib;print(hashlib.sha256(b'v1|tin|alice|').hexdigest())") |
| 162 | |
| 163 | # ---------------------------------------------------------------- build |
| 164 | section "build" |
| 165 | if [ ! -x "$BIN" ]; then |
| 166 | echo " building native binary..." |
| 167 | make native >"$WORK/build.out" 2>"$WORK/build.err" |
| 168 | fi |
| 169 | if [ -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 |
| 173 | fi |
| 174 | MAKEM=$(cat Makefile) |
| 175 | check "Makefile has a musl target" 'musl:' "$MAKEM" |
| 176 | check "Makefile has an arm64 target" 'arm64:' "$MAKEM" |
| 177 | check "Makefile has a win64 target" 'win64:' "$MAKEM" |
| 178 | check "Makefile has a macos target" 'macos:' "$MAKEM" |
| 179 | check "Makefile has an asan target" 'asan:' "$MAKEM" |
| 180 | check "Makefile has a fortify target" 'fortify:' "$MAKEM" |
| 181 | check "Makefile vendors mbedTLS" 'vendor/mbedtls' "$MAKEM" |
| 182 | check "Makefile vendors yyjson" 'vendor/yyjson.c' "$MAKEM" |
| 183 | PJ=$(cat plugin.json) |
| 184 | json_ok "plugin.json is valid JSON" "$PJ" "d['slug']=='ntfy' and d['id']=='plugin_ntfy'" |
| 185 | check "plugin.json declares kind hybrid" '"kind": "hybrid"' "$PJ" |
| 186 | check "plugin.json declares the mcp face" '"mcp": true' "$PJ" |
| 187 | check "plugin.json declares the daemon face" '"daemon": true' "$PJ" |
| 188 | check "plugin.json says mock-verified" '"verified": "mock"' "$PJ" |
| 189 | check "plugin.json sets menus false" '"menus": false' "$PJ" |
| 190 | check "README documents --daemon" -- '--daemon' "$(cat README.md 2>/dev/null)" |
| 191 | check "README documents --mcp" 'ntfy_send' "$(cat README.md 2>/dev/null)" |
| 192 | |
| 193 | # ---------------------------------------------------------------- mode 1: meta |
| 194 | section "mode 1 - discovery metadata" |
| 195 | M=$($BIN --meta) |
| 196 | if [ "$(printf '%s\n' "$M" | wc -l)" -eq 1 ]; then pass "--meta is one line"; else fail "--meta must be one line"; fi |
| 197 | json_ok "--meta prints valid JSON with the short label" "$M" "d['name']=='ntfy' and d['desc']=='Push channel'" |
| 198 | check "--meta kind hybrid" '"kind":"hybrid"' "$M" |
| 199 | check "--meta mcp true" '"mcp":true' "$M" |
| 200 | check "--meta daemon true" '"daemon":true' "$M" |
| 201 | check "--meta menus false (connector stays out of dropdowns)" '"menus":false' "$M" |
| 202 | check "--meta verified mock" '"verified":"mock"' "$M" |
| 203 | check "--meta advertises ntfy_send" 'ntfy_send' "$M" |
| 204 | M2=$(SX_PLUGIN_META=1 $BIN) |
| 205 | check "SX_PLUGIN_META=1 answers the same" '"name":"ntfy"' "$M2" |
| 206 | check_not "--meta needs no password" '401' "$(BOT_PASSWORD=letmein $BIN --meta)" |
| 207 | |
| 208 | # ---------------------------------------------------------------- auth |
| 209 | section "mode 2 - node auth on every action" |
| 210 | PW=testpw |
| 211 | for 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)" |
| 213 | done |
| 214 | check "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)" |
| 215 | check "unauth bare html is 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN | head -1)" |
| 216 | check "the 401 body names the error" '"error":"invalid node password"' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)" |
| 217 | check "the 401 says json" 'Content-Type: application/json' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)" |
| 218 | HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN) |
| 219 | check "header auth is accepted" '"ok":true' "$(body "$HA")" |
| 220 | BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="Bearer $PW" SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN) |
| 221 | check "bearer auth is accepted" '"ok":true' "$(body "$BA")" |
| 222 | QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=status&pwd=testpw' SX_CONNECTORS_DIR=$CONN $BIN) |
| 223 | check "query pwd auth is accepted" '"ok":true' "$(body "$QA")" |
| 224 | check "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)" |
| 225 | check "--meta stays open with a password set" '"name":"ntfy"' "$(BOT_PASSWORD=$PW $BIN --meta)" |
| 226 | |
| 227 | # ---------------------------------------------------------------- config |
| 228 | section "mode 3 - config save + validation" |
| 229 | R=$(post "action=save" '{"server_url":"http://127.0.0.1:'"$PORT"'"}') |
| 230 | json_ok "save stores server_url" "$R" "d['config']['server_url']=='http://127.0.0.1:$PORT'" |
| 231 | check "an incomplete config is not valid" '"valid":false' "$R" |
| 232 | R=$(post "action=save" '{"server_url":"javascript:alert(1)","topic":"t","target_session":"s"}') |
| 233 | check "a javascript: server_url is refused" '"validation":"url must start with http:// or https://"' "$R" |
| 234 | R=$(post "action=save" '{"server_url":"http://192.0.2.9/x","topic":"t","target_session":"s"}') |
| 235 | check "plain http to a non-loopback server is refused" 'plain http:// is refused' "$R" |
| 236 | R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"bad topic!","target_session":"s"}') |
| 237 | check "a bad topic is refused" 'topic contains forbidden characters' "$R" |
| 238 | R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"http://example.com"}') |
| 239 | check "a non-loopback plain-http bot_api_url is refused" 'bot_api_url must point at 127.0.0.1 or localhost' "$R" |
| 240 | R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"https://127.0.0.1:8150"}') |
| 241 | check "an https bot_api_url is refused (loopback API is plain)" 'bot_api_url must be plain http' "$R" |
| 242 | R=$(post "action=save" "$CFG_OK") |
| 243 | json_ok "the good config saves" "$R" "d['ok'] and d['valid']" |
| 244 | check "publish_topic defaults when blank" '"publish_topic":"tout"' "$R" |
| 245 | C=$(api "action=config&format=json") |
| 246 | check_not "config never echoes bearer_token" '"bearer_token"' "$C" |
| 247 | check_not "config never echoes bot_password" '"bot_password"' "$C" |
| 248 | check_not "config never echoes allowed_pins" '"allowed_pins"' "$C" |
| 249 | post "action=save" '{"bearer_token":"sekret-token"}' >/dev/null |
| 250 | check "the bearer token is stored on disk" 'sekret-token' "$(cat "$CONN/plugin_ntfy/config.json")" |
| 251 | C=$(api "action=config&format=json") |
| 252 | check_not "but never returned by the API" 'sekret-token' "$C" |
| 253 | ST=$(api "action=status&format=json") |
| 254 | check "status reports has_bearer only" '"has_bearer":true' "$ST" |
| 255 | check_not "status never leaks the token" 'sekret-token' "$ST" |
| 256 | post "action=save" '{"bearer_token":"__clear__"}' >/dev/null |
| 257 | check "__clear__ wipes the token" '"has_bearer":false' "$(api 'action=status&format=json')" |
| 258 | ST=$(api "action=status&format=json") |
| 259 | json_ok "status shape" "$ST" "d['status']['running']==0 and 'inbound_count' in d['status'] and d['status']['configured']==True" |
| 260 | I=$(api "action=info&format=json") |
| 261 | json_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 |
| 264 | section "mode 4 - MCP stdio server" |
| 265 | MOUT=$(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) |
| 269 | INIT=$(printf '%s\n' "$MOUT" | head -1) |
| 270 | json_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). |
| 279 | MJSON=$(printf '%s\n' "$MOUT" | python3 -c ' |
| 280 | import sys, json |
| 281 | lines = [l for l in sys.stdin.read().splitlines() if l.strip()] |
| 282 | assert lines, "no frames at all" |
| 283 | parsed = [json.loads(l) for l in lines] |
| 284 | tl = [p for p in parsed if "result" in p and "tools" in p["result"]] |
| 285 | assert tl, "no tools/list response among %d frames" % len(parsed) |
| 286 | tools = tl[0]["result"]["tools"] |
| 287 | assert tools, "tools/list returned an empty list" |
| 288 | assert any(t.get("name") == "ntfy_send" for t in tools), [t.get("name") for t in tools] |
| 289 | for 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" |
| 295 | print("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" |
| 299 | check "tools/list offers ntfy_send" 'ntfy_send' "$MOUT" |
| 300 | check "the tool schema has message" '"message"' "$MOUT" |
| 301 | check "the tool schema has priority" '"priority"' "$MOUT" |
| 302 | SOUT=$(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) |
| 303 | json_ok "tools/call publishes" "$SOUT" "d['result']['isError']==False" |
| 304 | wait_for 5 "the alert reached the (mock) ntfy server" mock_has '"message": "suite alert"' |
| 305 | wait_for 5 "with the requested priority" mock_has '"priority": 4' |
| 306 | SOUT2=$(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) |
| 307 | json_ok "priority defaults without an error" "$SOUT2" "d['result']['isError']==False" |
| 308 | SOUT3=$(echo '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"ntfy_send","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp) |
| 309 | check "a missing message is rejected, not a crash" 'requires a non-empty' "$SOUT3" |
| 310 | SOUT4=$(echo '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"nope","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp) |
| 311 | check "an unknown tool is rejected" 'unknown tool' "$SOUT4" |
| 312 | SCH=$($BIN --schema) |
| 313 | json_ok "--schema is the bare tool schema" "$SCH" "d['tools'][0]['name']=='ntfy_send' and 'inputSchema' in d['tools'][0]" |
| 314 | |
| 315 | # ---------------------------------------------------------------- publish UI |
| 316 | section "mode 3 - test + send actions" |
| 317 | T=$(api "action=test&format=json") |
| 318 | json_ok "action=test publishes" "$T" "d['ok'] and str(d['published_id']).startswith('m')" |
| 319 | wait_for 5 "the test notification landed" mock_has 'plugin_ntfy test notification' |
| 320 | SN=$(post "action=send" '{"message":"from the suite","title":"Suite UI","tags":"robot","priority":2}') |
| 321 | json_ok "action=send publishes" "$SN" "d['ok'] and str(d['published_id']).startswith('m')" |
| 322 | wait_for 5 "the UI send landed" mock_has '"message": "from the suite"' |
| 323 | check "action=send without a message is refused" '"error"' "$(api 'action=send&message=&format=json')" |
| 324 | MB=$(body "$(printf '%s' '{badjson' | env SX_CONNECTORS_DIR=$CONN REQUEST_METHOD=POST CONTENT_LENGTH=8 QUERY_STRING='action=send&message=' $BIN 2>&1)") |
| 325 | check "a malformed body is handled, not a crash" '"error"' "$MB" |
| 326 | |
| 327 | # ---------------------------------------------------------------- pairing |
| 328 | section "mode 5 - daemon bridge (default-deny, inbox, reply, no self-loop)" |
| 329 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reset" -d '{}' >/dev/null |
| 330 | post "action=save" "$CFG_OK" >/dev/null |
| 331 | |
| 332 | env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon.out" 2>&1 & |
| 333 | DAEMON_PID=$! |
| 334 | wait_for 8 "the daemon subscribed" grep -q "subscribed to" "$WORK/daemon.out" |
| 335 | |
| 336 | # 1. unknown sender: held, challenged, never delivered |
| 337 | curl -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 |
| 339 | wait_for 8 "unapproved sender blocked" grep -q "blocked unapproved sender" "$WORK/daemon.out" |
| 340 | sleep 1 |
| 341 | check_not "the unapproved message never reached /inbox" 'hey there bot' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)" |
| 342 | P=$(api "action=pending&format=json") |
| 343 | json_ok "the sender landed in the pairing queue" "$P" "any(p['sample']=='hey there bot' for p in d['pending'])" |
| 344 | check "the pending key is mallory's fingerprint" "$KEY_MAL" "$P" |
| 345 | wait_for 8 "a pairing challenge was published" mock_has 'PAIR ' |
| 346 | |
| 347 | # 2. approve -> bridge delivers to /inbox |
| 348 | A=$(api "action=approve&key=$KEY_MAL&format=json") |
| 349 | json_ok "approve accepts the 64-hex key" "$A" "d['ok'] and d['key']=='$KEY_MAL'" |
| 350 | check "the identity is now approved" "$KEY_MAL" "$(api 'action=approved&format=json')" |
| 351 | json_ok "approve removed it from pending" "$(api 'action=pending&format=json')" "not any(p['sample']=='hey there bot' for p in d['pending'])" |
| 352 | curl -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 |
| 354 | wait_for 8 "the approved message reached /inbox" mock_inbox_has 'what is 2+2' |
| 355 | check "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 |
| 358 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reply" -d '{"content":"2 plus 2 is 4"}' >/dev/null |
| 359 | wait_for 8 "the assistant reply was published back" mock_has '2 plus 2 is 4' |
| 360 | N1=$(mock_count) |
| 361 | sleep 3 |
| 362 | N2=$(mock_count) |
| 363 | if [ "$N1" = "$N2" ] && [ -n "$N1" ]; then pass "the reply was NOT republished on later keepalives"; else |
| 364 | fail "the reply got republished ($N1 -> $N2)" |
| 365 | fi |
| 366 | check "our publish carries the reply tag" '"robot"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)" |
| 367 | check "every publish carries our source id" 'scorpiox-bot-plugin-ntfy' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)" |
| 368 | check "replies go to the publish topic" '"topic": "tout"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)" |
| 369 | check_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> |
| 372 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \ |
| 373 | -d '{"topic":"tin","message":"hi, pairing request","user":"alice"}' >/dev/null |
| 374 | wait_for 8 "alice was held" grep -q "blocked unapproved sender $KEY_ALI" "$WORK/daemon.out" |
| 375 | CODE=$(jget "$(cat "$CONN/plugin_ntfy/pending.json")" "[p['code'] for p in d if p['key']=='$KEY_ALI'][0]") |
| 376 | if [ ${#CODE} -eq 8 ]; then pass "the pairing code is 8 chars ($CODE)"; else fail "bad pairing code '$CODE'"; fi |
| 377 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \ |
| 378 | -d "{\"topic\":\"tin\",\"message\":\"PAIR $CODE\",\"user\":\"alice\"}" >/dev/null |
| 379 | wait_for 8 "the PAIR command self-paired alice" grep -q "paired via code" "$WORK/daemon.out" |
| 380 | check "alice is approved now" "$KEY_ALI" "$(api 'action=approved&format=json')" |
| 381 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \ |
| 382 | -d '{"topic":"tin","message":"alice speaks","user":"alice"}' >/dev/null |
| 383 | wait_for 8 "alice reaches /inbox now" mock_inbox_has 'alice speaks' |
| 384 | WRONGCODE='{"topic":"tin","message":"PAIR ZZZZZZZZ","user":"bob"}' |
| 385 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" -d "$WRONGCODE" >/dev/null |
| 386 | sleep 1 |
| 387 | check "a wrong pairing code is refused, not accepted" "wrong pairing code" "$(tail -60 "$WORK/daemon.out")" |
| 388 | |
| 389 | # 5. deny + unapprove + key validation |
| 390 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \ |
| 391 | -d '{"topic":"tin","message":"spam","user":"bob","tags":["junk"]}' >/dev/null |
| 392 | wait_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" |
| 393 | BOBKEY=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|bob|['junk']\").hexdigest())") |
| 394 | D=$(api "action=deny&key=$BOBKEY&format=json") |
| 395 | json_ok "deny removes the pending entry" "$D" "d['ok'] and d['key']=='$BOBKEY'" |
| 396 | check_not "bob is gone from pending" '"sample": "spam"' "$(api 'action=pending&format=json')" |
| 397 | U=$(api "action=unapprove&key=$KEY_ALI&format=json") |
| 398 | json_ok "unapprove works" "$U" "d['ok'] and d['key']=='$KEY_ALI'" |
| 399 | check_not "unapproved identity gone from approved list" "$KEY_ALI" "$(api 'action=approved&format=json')" |
| 400 | BAD=$(api "action=approve&key=deadbeef&format=json") |
| 401 | check "a malformed key is rejected" 'key must be the 64-hex identity' "$BAD" |
| 402 | |
| 403 | # 6. counters |
| 404 | ST=$(api "action=status&format=json") |
| 405 | json_ok "status counted inbound" "$ST" "d['status']['inbound_count']>=2" |
| 406 | json_ok "status counted outbound" "$ST" "d['status']['outbound_count']>=1" |
| 407 | json_ok "status counted blocked" "$ST" "d['status']['blocked_count']>=2" |
| 408 | json_ok "status says the daemon is running" "$ST" "d['status']['running']==True and d['status']['connected']==True" |
| 409 | |
| 410 | # 7. pidfile, duplicate refusal, stop |
| 411 | if [ -f "$CONN/plugin_ntfy/daemon.pid" ]; then pass "daemon wrote its pidfile"; else fail "no pidfile"; fi |
| 412 | DUP=$(env SX_CONNECTORS_DIR=$CONN $BIN --daemon 2>&1 || true) |
| 413 | check "a second daemon refuses to start" "another daemon is already running" "$DUP" |
| 414 | STOP=$(api "action=stop&format=json") |
| 415 | json_ok "action=stop stops the daemon" "$STOP" "d['ok'] and d['stopped']" |
| 416 | wait_for 8 "the daemon exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null" |
| 417 | DAEMON_PID="" |
| 418 | rm -f "$CONN/plugin_ntfy/daemon.pid" |
| 419 | |
| 420 | # 8. supervised start through the API |
| 421 | GO=$(api "action=start&format=json") |
| 422 | json_ok "action=start launches the daemon" "$GO" "d['ok'] and d['started']" |
| 423 | wait_for 8 "the supervised daemon reports running" sh -c "SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'" |
| 424 | DUP2=$(api "action=start&format=json") |
| 425 | check "a supervised second start is refused with 409-shape" "already running" "$DUP2" |
| 426 | api "action=stop&format=json" >/dev/null |
| 427 | wait_for 8 "the supervised daemon exited" sh -c "! SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'" |
| 428 | rm -f "$CONN/plugin_ntfy/daemon.pid" |
| 429 | |
| 430 | # 9. a wrong node password blocks the bridge |
| 431 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":"nodepw"}' >/dev/null |
| 432 | post "action=save" '{"bot_password":"wrongpw"}' >/dev/null |
| 433 | env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon2.out" 2>&1 & |
| 434 | DAEMON_PID=$! |
| 435 | wait_for 8 "daemon #2 subscribed" grep -q "subscribed to" "$WORK/daemon2.out" |
| 436 | curl -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 |
| 438 | wait_for 8 "the bridge logged an inbox failure" grep -q "inbox post failed" "$WORK/daemon2.out" |
| 439 | check "the failure names the 401" "401" "$(grep -m1 'inbox post failed' "$WORK/daemon2.out")" |
| 440 | sleep 1 |
| 441 | check_not "nothing was delivered with a bad password" 'secret leak check' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)" |
| 442 | api "action=stop&format=json" >/dev/null |
| 443 | wait_for 8 "daemon #2 exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null" |
| 444 | DAEMON_PID="" |
| 445 | rm -f "$CONN/plugin_ntfy/daemon.pid" |
| 446 | curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":""}' >/dev/null |
| 447 | post "action=save" '{"bot_password":"__clear__"}' >/dev/null |
| 448 | |
| 449 | # ---------------------------------------------------------------- html ui |
| 450 | section "mode 2 - the generated page" |
| 451 | H=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN) |
| 452 | check "the page is html" 'Content-Type: text/html' "$H" |
| 453 | check_not "no <script src=" '<script src=' "$H" |
| 454 | check_not "no CDN references" 'cdnjs' "$H" |
| 455 | check_not "no jsdelivr" 'jsdelivr' "$H" |
| 456 | check_not "no unpkg" 'unpkg' "$H" |
| 457 | check "a CSP is emitted" 'Content-Security-Policy:' "$H" |
| 458 | check "X-Frame-Options SAMEORIGIN" 'X-Frame-Options: SAMEORIGIN' "$H" |
| 459 | check "nosniff" 'X-Content-Type-Options: nosniff' "$H" |
| 460 | check "the page has the setup form" 'f_server' "$H" |
| 461 | check "the page has the pairing tab" 'tabPair' "$H" |
| 462 | check "the page has the daemon log tab" 'tabLog' "$H" |
| 463 | check "the page has the test-send tab" 'tabSend' "$H" |
| 464 | check "the page respects the theme handoff" 'sx-theme' "$H" |
| 465 | HE=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="embed=1&theme=light" $BIN) |
| 466 | check "embed=1 still renders" 'f_server' "$HE" |
| 467 | check "theme=light still renders" 'f_server' "$HE" |
| 468 | check_not "no emoji in the markup" '' "$H" |
| 469 | if python3 -c " |
| 470 | import sys,re |
| 471 | s=open('src/ui.html',encoding='utf-8').read() |
| 472 | sys.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 |
| 475 | section "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". |
| 482 | TLSPORT=$((PORT + 1)) |
| 483 | TLSPLAIN=$((PORT + 2)) |
| 484 | TLSMMSMPORT=$((PORT + 3)) |
| 485 | TLSPID="" |
| 486 | tls_cleanup() { if [ -n "$TLSPID" ] && kill -0 "$TLSPID" 2>/dev/null; then kill "$TLSPID" 2>/dev/null; wait "$TLSPID" 2>/dev/null; fi; return 0; } |
| 487 | trap 'tls_cleanup' EXIT |
| 488 | python3 tests/mockd.py --port "$TLSPLAIN" --tls-port "$TLSPORT" \ |
| 489 | --tls-mismatch-port "$TLSMMSMPORT" --root "$WORK/mocktls" \ |
| 490 | > "$WORK/mockd.tls.out" 2>&1 & |
| 491 | TLSPID=$! |
| 492 | i=0 |
| 493 | while [ "$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 |
| 496 | done |
| 497 | if 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)" |
| 499 | else |
| 500 | fail "mock TLS front never came up" |
| 501 | sed 's/^/ /' "$WORK/mockd.tls.out" | head -5 |
| 502 | fi |
| 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. |
| 505 | tls_published_has() { |
| 506 | curl -s -m 3 "http://127.0.0.1:$TLSPLAIN/__publishes" 2>/dev/null | grep -F -q -- "$1" |
| 507 | } |
| 508 | pin_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 | } |
| 513 | PIN_REAL=$(pin_of "$WORK/mocktls/tls/mock-cert.pem") |
| 514 | if [ -n "$PIN_REAL" ] && [ "${#PIN_REAL}" -eq 64 ]; then |
| 515 | pass "computed the leaf SPKI pin with openssl" |
| 516 | else |
| 517 | fail "could not compute the leaf SPKI pin" |
| 518 | PIN_REAL="0000000000000000000000000000000000000000000000000000000000000000" |
| 519 | fi |
| 520 | |
| 521 | HTTPS_URL="https://127.0.0.1:$TLSPORT" |
| 522 | post "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. |
| 526 | R=$(post "action=send" '{"message":"should never publish unauthenticated"}') |
| 527 | json_ok "https to an untrusted certificate is refused" "$R" "d['ok']==False" |
| 528 | check "the refusal names the certificate" 'certificate' "$R" |
| 529 | check_not "it did not reach the TLS mock" 'should never publish unauthenticated' \ |
| 530 | "$(curl -s -m3 http://127.0.0.1:$TLSPLAIN/__publishes)" |
| 531 | check_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. |
| 535 | post "action=save" "{\"allowed_pins\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}" >/dev/null |
| 536 | R=$(post "action=send" '{"message":"wrong pin"}') |
| 537 | json_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. |
| 542 | post "action=save" "{\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null |
| 543 | R=$(post "action=send" '{"message":"pinned publish ok","title":"PinTest"}') |
| 544 | json_ok "the correct SPKI pin is accepted" "$R" "d['ok']==True" |
| 545 | wait_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. |
| 551 | post "action=save" "{\"server_url\":\"https://127.0.0.2:$TLSMMSMPORT\",\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null |
| 552 | R=$(post "action=send" '{"message":"hostname mismatch"}') |
| 553 | json_ok "a pin cannot override a hostname mismatch" "$R" "d['ok']==False" |
| 554 | check "and says so" 'hostname' "$R" |
| 555 | post "action=save" "{\"server_url\":\"$HTTPS_URL\"}" >/dev/null |
| 556 | |
| 557 | # 5) The only no-verify mode is the explicit, loud environment opt-in. |
| 558 | R=$(post "action=send" '{"message":"insecure mode opt-in"}' NTFY_TLS_INSECURE=1) |
| 559 | json_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. |
| 564 | R=$(post "action=save" '{"server_url":"http://ntfy.example.invalid","topic":"tin"}') |
| 565 | json_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 |
| 569 | post "action=save" "{\"server_url\":\"http://127.0.0.1:$PORT\",\"topic\":\"tin\",\"publish_topic\":\"tout\",\"allowed_pins\":\"\"}" >/dev/null |
| 570 | tls_cleanup; TLSPID="" |
| 571 | |
| 572 | # ---------------------------------------------------------------- hardening |
| 573 | section "builds - ASan + fortify + PE header" |
| 574 | if [ ! -x tests/asan/plugin_ntfy_asan ]; then make asan >"$WORK/asan.build" 2>&1 || true; fi |
| 575 | if [ -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" |
| 582 | else |
| 583 | fail "asan build missing" |
| 584 | fi |
| 585 | if [ ! -x tests/fortify/plugin_ntfy_fortify ]; then make fortify >"$WORK/fort.build" 2>&1 || true; fi |
| 586 | if [ -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" |
| 589 | else |
| 590 | fail "fortify build missing" |
| 591 | fi |
| 592 | if [ -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 |
| 595 | fi |
| 596 | |
| 597 | # ---------------------------------------------------------------- win32 guards |
| 598 | section "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. |
| 601 | SRC=$(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. |
| 606 | WSA_MAIN=$(awk '/^int main\(/{f=1} f && /WSAStartup/{print NR; exit}' src/plugin_ntfy.c) |
| 607 | DISPATCH=$(awk '/^int main\(/{f=1} f && /mode_mcp\(\)/{print NR; exit}' src/plugin_ntfy.c) |
| 608 | if [ -n "$WSA_MAIN" ] && [ -n "$DISPATCH" ] && [ "$WSA_MAIN" -lt "$DISPATCH" ]; then |
| 609 | pass "winsock starts in main() before any mode dispatch" |
| 610 | else |
| 611 | fail "winsock must be started in main() before the mode dispatch" |
| 612 | fi |
| 613 | check "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. |
| 616 | check "_setmode(_fileno(stdout), _O_BINARY) on the windows path" '_O_BINARY' "$SRC" |
| 617 | |
| 618 | # ---------------------------------------------------------------- secrets |
| 619 | section "git history secret audit" |
| 620 | if 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 |
| 701 | else |
| 702 | echo " skip history audit (not a git checkout)" |
| 703 | fi |
| 704 | |
| 705 | # ---------------------------------------------------------------- summary |
| 706 | printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0" |
| 707 | [ "$FAIL" -eq 0 ] || exit 1 |
| 708 | exit 0 |