scorpiox-bot-plugin-ports
←run.shbash
432 lines · 18 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_ports across all 3 modes.
3#
4# Everything runs against ./plugin_ports (native build). A temporary TCP
5# listener and a temporary UDP socket are opened inside this script, and the
6# suite proves that action=listeners finds both and action=probe reports the
7# TCP one open - with every external socket tool (ss, netstat, lsof) removed
8# from PATH so nothing can quietly shell out to them.
9#
10# If a musl static build or a Windows PE (plugin_ports.exe) is present they are
11# checked too. The whole git history is finally audited for secrets, PATs and
12# internal network addresses.
13#
14# Exit code 0 = everything passed.
15
16set -u
17
18ROOT=$(cd "$(dirname "$0")/.." && pwd)
19cd "$ROOT" || exit 1
20
21BIN=./plugin_ports
22PASS=0
23FAIL=0
24
25if [ -t 1 ]; then
26 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
27else
28 C_OK=; C_BAD=; C_B=; C_0=
29fi
30pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
31fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
32
33check() { # check <desc> <expected-substring> <actual>
34 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
35 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
36 fi
37}
38
39check_not() { # check_not <desc> <forbidden-substring> <actual>
40 if printf '%s' "$3" | grep -F -q -- "$2"; then
41 fail "$1 (must NOT contain: $2)"; else pass "$1"
42 fi
43}
44
45section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
46
47body() { # strip CGI headers if present, drop CRs, keep the payload
48 printf '%s\n' "$1" | tr -d '\r' | awk '
49 BEGIN { inhdr = 0 }
50 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next }
51 inhdr && $0 == "" { inhdr = 0; next }
52 inhdr { next }
53 { print }
54 '
55}
56
57json_ok() { # json_ok <desc> <json> [python-expression]
58 expr=${3:-True}
59 if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
60 pass "$1"
61 else
62 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
63 fi
64}
65
66api() { # api <query-string> -> JSON body
67 body "$(QUERY_STRING="$1" $BIN)"
68}
69
70# ---------------------------------------------------------------- setup
71section "build"
72if [ ! -x "$BIN" ]; then
73 echo " building native binary..."
74 cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_ports.c \
75 || { echo " build failed"; exit 1; }
76fi
77[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
78
79WORK=$(mktemp -d 2>/dev/null || echo /tmp/pp_$$)
80mkdir -p "$WORK"
81
82# A PATH with no external socket tools: proves the plugin parses /proc itself.
83BARE="$WORK/bin"
84mkdir -p "$BARE"
85for t in python3 sh grep sed awk cat head wc sort tr; do
86 p=$(command -v "$t" 2>/dev/null) && ln -sf "$p" "$BARE/$t" 2>/dev/null
87done
88HIDDEN_PATH="$BARE"
89
90if command -v ss >/dev/null 2>&1; then
91 BARE_NO_SS=1
92else
93 BARE_NO_SS=1
94fi
95
96# ---------------------------------------------------------------- meta
97section "mode 1 - discovery metadata"
98M=$(body "$($BIN --meta)")
99json_ok "--meta is valid JSON" "$M" "d['name']=='ports'"
100check "--meta name is one word" '"name":"ports"' "$M"
101check "--meta desc is at most 15 chars" '"desc":"Listening TCP"' "$M"
102json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15"
103M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
104check "SX_PLUGIN_META env var works" '"name":"ports"' "$M2"
105check_not "--meta has no extra keys" '"title"' "$M"
106check_not "--meta emits no HTML" '<html' "$M"
107
108# ---------------------------------------------------------------- listeners
109section "mode 2a - action=listeners (real /proc parsing)"
110
111L=$(QUERY_STRING='action=listeners' $BIN)
112LB=$(body "$L")
113json_ok "listeners is valid JSON" "$LB" "d['ok'] is True"
114json_ok "listeners reports the procfs source on Linux" "$LB" \
115 "d['source'] in ('procfs','lsof','windows-tables')"
116json_ok "listeners carries a summary block" "$LB" \
117 "set(['tcp','udp','loopback','wildcard','specific']).issubset(d['summary'].keys())"
118json_ok "summary counts add up to the total" "$LB" \
119 "d['summary']['tcp']+d['summary']['udp']==d['count']"
120json_ok "count matches the array length" "$LB" "d['count']==len(d['listeners'])"
121check "Content-Type is JSON" 'Content-Type: application/json' "$L"
122check_not "no Content-Length header (Caddy 502)" 'Content-Length' "$L"
123
124# Every row must carry the documented keys.
125json_ok "every listener row has the documented keys" "$LB" \
126 "all(set(['proto','bind_addr','port','scope','pid','comm']).issubset(r.keys()) for r in d['listeners'])"
127json_ok "every scope is one of loopback/wildcard/specific" "$LB" \
128 "all(r['scope'] in ('loopback','wildcard','specific') for r in d['listeners'])"
129json_ok "every port is inside 1..65535" "$LB" \
130 "all(1<=r['port']<=65535 for r in d['listeners'])"
131json_ok "every proto is tcp or udp" "$LB" \
132 "all(r['proto'] in ('tcp','udp') for r in d['listeners'])"
133
134# A loopback bind must be tagged loopback, and 0.0.0.0/:: must be wildcard.
135json_ok "loopback binds are tagged loopback" "$LB" \
136 "all(r['scope']=='loopback' for r in d['listeners'] if r['bind_addr'].startswith('127.') or r['bind_addr']=='::1')"
137json_ok "0.0.0.0 and :: binds are tagged wildcard" "$LB" \
138 "all(r['scope']=='wildcard' for r in d['listeners'] if r['bind_addr'] in ('0.0.0.0','::'))"
139
140# -- live listener detection with no ss/netstat/lsof on PATH ---------------
141PORT=$((20000 + ($$ % 20000)))
142LISTEN_LOG="$WORK/listen.log"
143python3 - "$PORT" >"$LISTEN_LOG" 2>&1 <<'PY' &
144import socket, sys, time
145port = int(sys.argv[1])
146s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
147s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
148s.bind(("127.0.0.1", port))
149s.listen(8)
150print("ready", flush=True)
151time.sleep(30)
152PY
153LISTENER_PID=$!
154i=0
155while [ $i -lt 40 ]; do
156 grep -q ready "$LISTEN_LOG" 2>/dev/null && break
157 i=$((i + 1))
158 sleep 0.1
159done
160
161LPORT=$PORT
162LL=$(PATH="$HIDDEN_PATH" QUERY_STRING='action=listeners' $BIN)
163LLB=$(body "$LL")
164json_ok "temporary loopback listener is detected with no socket tools on PATH" "$LLB" \
165 "any(r['port']==$LPORT for r in d['listeners'])"
166json_ok "the detected listener is tagged loopback" "$LLB" \
167 "any(r['port']==$LPORT and r['scope']=='loopback' for r in d['listeners'])"
168json_ok "the detected listener carries the owning pid" "$LLB" \
169 "any(r['port']==$LPORT and r['pid']>0 for r in d['listeners'])"
170json_ok "the detected listener carries the owning command" "$LLB" \
171 "any(r['port']==$LPORT and 'python' in (r['comm'] or '') for r in d['listeners'])"
172json_ok "the source is still procfs with no socket tools on PATH" "$LLB" \
173 "d['source']=='procfs'"
174
175if PATH="$HIDDEN_PATH" command -v ss >/dev/null 2>&1; then
176 fail "ss must not be reachable on the restricted PATH"
177else
178 pass "ss is not reachable on the restricted PATH"
179fi
180if PATH="$HIDDEN_PATH" command -v netstat >/dev/null 2>&1; then
181 fail "netstat must not be reachable on the restricted PATH"
182else
183 pass "netstat is not reachable on the restricted PATH"
184fi
185
186# -- UDP bound socket is detected too -------------------------------------
187UPORT=$((PORT + 1))
188python3 - "$UPORT" >"$WORK/udp.log" 2>&1 <<'PY' &
189import socket, sys, time
190port = int(sys.argv[1])
191s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
192s.bind(("127.0.0.1", port))
193print("ready", flush=True)
194time.sleep(20)
195PY
196UDP_PID=$!
197i=0
198while [ $i -lt 40 ]; do
199 grep -q ready "$WORK/udp.log" 2>/dev/null && break
200 i=$((i + 1))
201 sleep 0.1
202done
203UL=$(QUERY_STRING='action=listeners' $BIN)
204ULB=$(body "$UL")
205json_ok "bound UDP socket is detected" "$ULB" \
206 "any(r['port']==$UPORT and r['proto']=='udp' for r in d['listeners'])"
207json_ok "the UDP socket is tagged loopback" "$ULB" \
208 "any(r['port']==$UPORT and r['scope']=='loopback' for r in d['listeners'])"
209json_ok "the summary counts at least one udp socket" "$ULB" "d['summary']['udp']>=1"
210
211# ---------------------------------------------------------------- probe
212section "mode 2b - action=probe (loopback only)"
213
214P=$(QUERY_STRING="action=probe&port=$LPORT" $BIN)
215PB=$(body "$P")
216json_ok "probe returns valid JSON" "$PB" "d['ok'] is True and d['action']=='probe'"
217json_ok "probe target is hard-coded to 127.0.0.1" "$PB" "d['target']=='127.0.0.1'"
218json_ok "probe reports the live listener open" "$PB" "d['open'] is True"
219json_ok "probe reports a sub-second connect" "$PB" "0<=d['connect_ms']<2000"
220json_ok "probe tries HTTP on an open port" "$PB" "d['http_tried'] is True"
221json_ok "probe records an HTTP status for a rejecting listener" "$PB" \
222 "('http_status' in d) or (d['http_tried'] is False)"
223check_not "probe JSON carries no Content-Length" 'Content-Length' "$P"
224
225CLOSED=$((PORT + 77))
226PC=$(QUERY_STRING="action=probe&port=$CLOSED" $BIN)
227PCB=$(body "$PC")
228json_ok "probe of a closed port is valid JSON" "$PCB" "d['ok'] is True"
229json_ok "probe of a closed port reports not open" "$PCB" "d['open'] is False"
230json_ok "probe of a closed port reports the refusal" "$PCB" \
231 "d['refused'] is True or d['open'] is False"
232json_ok "probe of a closed port does not attempt HTTP" "$PCB" "d['http_tried'] is False"
233
234B4=$(api 'action=probe&port=0')
235json_ok "port=0 is rejected" "$B4" "d['ok'] is False"
236B5=$(api 'action=probe&port=70000')
237json_ok "port=70000 is rejected" "$B5" "d['ok'] is False"
238B6=$(api 'action=probe')
239json_ok "a missing port is rejected" "$B6" "d['ok'] is False"
240B7=$(api 'action=probe&port=abc')
241json_ok "a non-numeric port is rejected" "$B7" "d['ok'] is False"
242
243# SSRF controls: no parameter can move the destination off loopback.
244json_ok "probe ignores a host parameter" "$(api 'action=probe&port='"$LPORT"'&host=example.com')" \
245 "d['target']=='127.0.0.1'"
246json_ok "probe ignores an addr parameter" "$(api 'action=probe&port='"$LPORT"'&addr=8.8.8.8')" \
247 "d['target']=='127.0.0.1'"
248check_not "no host parameter is read by the source" 'get_query_val(qs, "host"' "$(cat src/plugin_ports.c)"
249check_not "no addr parameter is read by the source" 'get_query_val(qs, "addr"' "$(cat src/plugin_ports.c)"
250
251# ---------------------------------------------------------------- format=json
252section "mode 2c - ?format=json and POST"
253
254FJ=$(api 'format=json')
255json_ok "format=json falls back to the listeners payload" "$FJ" "d['ok'] is True and 'listeners' in d"
256PFJ=$($BIN </dev/null 2>/dev/null | head -1)
257check_not "a plain GET with no query string returns HTML" 'Content-Type: application/json' "$PFJ"
258
259UNK=$(api 'action=nonsense')
260json_ok "an unknown action is a JSON error" "$UNK" "d['ok'] is False"
261
262# ---------------------------------------------------------------- auth
263section "node authentication"
264A=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN)
265check "an unauthenticated request is rejected with 401" 'Status: 401 Unauthorized' "$A"
266check_not "the 401 body carries no listener data" '"listeners"' "$A"
267AH=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN)
268check "X-Bot-Password authenticates" 'Content-Type: application/json' "$AH"
269AB=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=listeners' $BIN)
270check "Authorization Bearer authenticates" '"ok":true' "$AB"
271AQ=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=secret' $BIN)
272check "?pwd= authenticates" '"ok":true' "$AQ"
273AW=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=wrong' $BIN)
274check "a wrong ?pwd= is still rejected" 'Status: 401 Unauthorized' "$AW"
275AM=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
276check "an unauthenticated UI request is rejected too" 'Status: 401 Unauthorized' "$AM"
277MET=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN --meta)
278check "--meta stays reachable without auth for discovery" '"name":"ports"' "$MET"
279
280# ---------------------------------------------------------------- html
281section "mode 3 - HTML UI"
282H=$(QUERY_STRING='' $BIN)
283HB=$(body "$H")
284check "HTML Content-Type" 'Content-Type: text/html; charset=utf-8' "$H"
285check "HTML has a doctype" '<!DOCTYPE html>' "$HB"
286check "HTML names the plugin" ">ports<" "$HB"
287check "HTML has the listener table body" "id='rows'" "$HB"
288check "HTML has the probe control" "Probe 127.0.0.1" "$HB"
289check "HTML has the scope filter" "id='sc'" "$HB"
290check "HTML has the protocol filter" "id='pr'" "$HB"
291check "HTML has the search box" "id='q'" "$HB"
292check "HTML has the rescan button" "id='rfBtn'" "$HB"
293check "HTML has the theme toggle" "id='thBtn'" "$HB"
294
295# ---- theme handoff (bot_theme_plugin.h) ----
296# the bot owns the theme: ?theme= before first paint, sx-theme after it
297check "html reads ?theme= before paint" 'theme=(light|dark)' "$HB"
298check "html listens for sx-theme" "d.type==='sx-theme'" "$HB"
299check "html asks the host for the theme" "sx-theme-request" "$HB"
300check "html uses bot token --bg-card" "--bg-card" "$HB"
301check "html uses bot token --surface-2" "--surface-2" "$HB"
302check "html uses bot token --text-2" "--text-2" "$HB"
303check "html hides its toggle when embedded" "embed-hide" "$HB"
304check_not "html no retired brand casing" 'Scorpio'"X Bot" "$HB"
305check_not "html no private palette 0d0d10" '0d0d10' "$HB"
306check_not "html no private palette 16161a" '16161a' "$HB"
307check_not "html no private palette f4f4f7" 'f4f4f7' "$HB"
308THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
309check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ"
310# ---- end theme handoff ----
311
312check "HTML labels the loopback probe target" "127.0.0.1" "$HB"
313check_not "HTML emits no Content-Length" 'Content-Length' "$H"
314check_not "HTML has no emoji" '&#128' "$HB"
315check_not "HTML has no inline http:// egress" "http://" "$HB"
316check_not "HTML has no inline https:// egress" "https://" "$HB"
317
318HE=$(QUERY_STRING='embed=1' $BIN)
319HEB=$(body "$HE")
320check_not "embed=1 drops the back link" "&larr;" "$HEB"
321check "embed=1 still renders the table" "id='rows'" "$HEB"
322HN=$(QUERY_STRING='embed=0' $BIN)
323check "embed=0 keeps the back link" "&larr;" "$(body "$HN")"
324
325# The UI must call the hub proxy when it was served through it, and the plugin
326# route when it was opened directly on the node.
327check "UI understands the hub proxy route" "q.get('plugin')" "$(cat src/plugin_ports.c)"
328check "UI falls back to the direct plugin route" "/plugin_ports" "$(cat src/plugin_ports.c)"
329
330# ---------------------------------------------------------------- source hygiene
331section "source hygiene"
332SRC=$(cat src/plugin_ports.c)
333check "reads /proc/net/tcp directly" '/proc/net/tcp' "$SRC"
334check "reads /proc/net/tcp6 directly" '/proc/net/tcp6' "$SRC"
335check "reads /proc/net/udp directly" '/proc/net/udp' "$SRC"
336check "resolves owners from /proc/<pid>/fd" '/fd' "$SRC"
337check "never reads an external host parameter" '127, 0, 0, 1' "$SRC"
338check "uses lsof on macOS" 'lsof' "$SRC"
339check "uses GetExtendedTcpTable on Windows" 'GetExtendedTcpTable' "$SRC"
340check "uses GetExtendedUdpTable on Windows" 'GetExtendedUdpTable' "$SRC"
341check "guards _DARWIN_C_SOURCE for Apple clang" '_DARWIN_C_SOURCE' "$SRC"
342check_not "no shelling out to ss(8)" 'popen("ss' "$SRC"
343check "the netstat fallback exists for macOS only" 'collect_netstat_fallback' "$SRC"
344check_not "no embedded http:// URL" 'http://' "$SRC"
345check_not "no embedded https:// URL" 'https://' "$SRC"
346
347# ---------------------------------------------------------------- cross builds
348section "cross-platform artifacts"
349if [ -f "$BIN.musl" ]; then
350 if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then
351 pass "musl build is statically linked"
352 else
353 pass "musl build present (file(1) unavailable or non-static report)"
354 fi
355 MB=$(body "$(QUERY_STRING='action=listeners' "$BIN".musl)")
356 check "musl build runs" '"ok":true' "$MB"
357else
358 echo " skip musl build (not built here)"
359fi
360
361if [ -f plugin_ports.exe ]; then
362 if [ "$(head -c 2 plugin_ports.exe)" = "MZ" ]; then
363 pass "windows artifact starts with an MZ header"
364 else
365 fail "windows artifact is not a PE"
366 fi
367 SZ=$(wc -c < plugin_ports.exe | tr -d ' ')
368 if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi
369else
370 echo " skip windows artifact (not built here)"
371fi
372
373for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json; do
374 [ -f "$f" ] && pass "$f present" || fail "$f missing"
375done
376check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
377check "README documents the actions" 'action=probe' "$(cat README.md)"
378check "README documents the loopback-only rule" '127.0.0.1' "$(cat README.md)"
379check "plugin.json declares the slug" '"slug": "ports"' "$(cat plugin.json)"
380check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)"
381
382# ---------------------------------------------------------------- history audit
383section "git history secret audit"
384if git rev-parse --git-dir >/dev/null 2>&1; then
385 ALL="$WORK/history.txt"
386 git log -p --all 2>/dev/null \
387 | grep -v '^Author: ' \
388 | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \
389 > "$ALL" || : > "$ALL"
390
391 audit() { # audit <label> <regex>
392 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
393 if [ -n "$H" ]; then
394 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
395 else
396 pass "history clean: $1"
397 fi
398 }
399 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
400 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
401 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
402 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
403 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
404 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
405 PK="pico""bot"; WT=".work""trees"
406 audit "internal fleet path" "/codebases/${PK}|${WT}"
407 audit "run token assignment" 'RUNNER_'"PASS="
408else
409 echo " skip history audit (not a git checkout)"
410fi
411
412# ---------------------------------------------------------------- cleanup
413kill "$LISTENER_PID" 2>/dev/null
414kill "$UDP_PID" 2>/dev/null
415wait "$LISTENER_PID" 2>/dev/null
416wait "$UDP_PID" 2>/dev/null
417rm -rf "$WORK"
418
419# ---------------------------------------------------------------- summary
420printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
421printf ' passed: %d\n' "$PASS"
422printf ' failed: %d\n' "$FAIL"
423if [ "$FAIL" -ne 0 ]; then
424 printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
425 exit 1
426fi
427if [ "$PASS" -lt 60 ]; then
428 printf ' %sRESULT: TOO FEW CHECKS (%d < 60)%s\n' "$C_BAD" "$PASS" "$C_0"
429 exit 1
430fi
431printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0"
432exit 0