scorpiox-bot-plugin-sysmon
←run.shbash
345 lines · 16 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_sysmon across all 3 modes.
3#
4# Runs against ./plugin_sysmon (native build) on the live machine, so the
5# metrics assertions use this node's real /proc (or mach / Win32) counters.
6# If a musl static build or a Windows PE (plugin_sysmon.exe) is present they are
7# checked too. The whole git history is finally audited for secrets and LAN IPs.
8#
9# Exit code 0 = everything passed.
10
11set -u
12
13ROOT=$(cd "$(dirname "$0")/.." && pwd)
14cd "$ROOT" || exit 1
15
16BIN=./plugin_sysmon
17PASS=0
18FAIL=0
19
20if [ -t 1 ]; then
21 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
22else
23 C_OK=; C_BAD=; C_B=; C_0=
24fi
25pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
26fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
27
28check() { # check <desc> <expected-substring> <actual>
29 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
30 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
31 fi
32}
33
34check_not() { # check_not <desc> <forbidden-substring> <actual>
35 if printf '%s' "$3" | grep -F -q -- "$2"; then
36 fail "$1 (must NOT contain: $2)"; else pass "$1"
37 fi
38}
39
40section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
41
42body() { printf '%s' "$1" | sed '1,/^\r$/d'; }
43
44# ---------------------------------------------------------------- build
45section "build"
46if [ ! -x "$BIN" ]; then
47 echo " building native binary..."
48 cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_sysmon.c || { echo " build failed"; exit 1; }
49fi
50[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
51
52# ---------------------------------------------------------------- meta mode
53section "mode 1 --meta (must work without auth - discovery)"
54META=$("$BIN" --meta)
55check "meta emits name sysmon" '"name":"sysmon"' "$META"
56check "meta emits desc CPU & memory" '"desc":"CPU & memory"' "$META"
57METAENV=$(SX_PLUGIN_META=1 "$BIN")
58check "SX_PLUGIN_META=1 yields same meta" '"name":"sysmon"' "$METAENV"
59LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
60[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
61printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
62 && pass "meta is valid JSON" || fail "meta is not valid JSON"
63DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
64[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
65NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
66[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
67check "--version prints version" '1.0.2' "$("$BIN" --version)"
68check "--help is available" 'usage:' "$("$BIN" --help)"
69META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
70check "meta still works when BOT_PASSWORD is set" '"name":"sysmon"' "$META_AUTH"
71
72# ---------------------------------------------------------------- auth
73section "node auth"
74AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN")
75check "no credentials -> 401" 'Status: 401' "$AUTHNONE"
76check "401 body is json" 'invalid node password' "$AUTHNONE"
77AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN")
78check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")"
79AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=metrics' "$BIN")
80check "Authorization Bearer accepted" '"ok":true' "$(body "$AUTHB")"
81AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=testpw' "$BIN")
82check "?pwd= accepted (plugin iframe)" '"ok":true' "$(body "$AUTHQ")"
83AUTHBAD=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=wrong' "$BIN")
84check "wrong ?pwd= rejected" 'Status: 401' "$AUTHBAD"
85AUTHHTML=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
86check "html also requires auth" 'Status: 401' "$AUTHHTML"
87
88# ---------------------------------------------------------------- metrics
89section "mode 2 action=metrics (live counters)"
90RAW=$(QUERY_STRING='action=metrics' "$BIN")
91MB=$(body "$RAW")
92check_not "metrics has no Content-Length" 'Content-Length' "$RAW"
93check "metrics content-type json" 'Content-Type: application/json' "$RAW"
94check "metrics ok:true" '"ok":true' "$MB"
95check "metrics action echoed" '"action":"metrics"' "$MB"
96check "metrics has cpu_pct" '"cpu_pct":' "$MB"
97check "metrics has ncores" '"ncores":' "$MB"
98check "metrics has mem block" '"mem":{"total_kb":' "$MB"
99check "metrics has swap block" '"swap":{"total_kb":' "$MB"
100check "metrics has uptime" '"uptime_sec":' "$MB"
101check "metrics has load block" '"load":{"available":' "$MB"
102check "metrics has processes" '"processes":[' "$MB"
103check "metrics has host" '"host":' "$MB"
104check "metrics has cpu_model" '"cpu_model":' "$MB"
105check "metrics has utc" '"utc":"20' "$MB"
106check "metrics top defaults to min(25, proc_count)" '"top":' "$MB"
107printf '%s' "$MB" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
108 && pass "metrics body is valid JSON" || fail "metrics body JSON invalid"
109
110# real, non-zero assertions - these are what prove the sampler works
111MJ=/tmp/sysmon_metrics_$$.json
112printf '%s' "$MB" > "$MJ"
113python3 - "$MJ" <<'PY' && pass "live counters are non-zero and in range" || fail "live counters wrong"
114import json,sys
115d=json.load(open(sys.argv[1]))
116assert d["mem"]["total_kb"] > 0, "mem_total must be > 0"
117assert d["mem"]["used_kb"] > 0, "mem_used must be > 0"
118assert 0 <= d["mem"]["pct"] <= 100
119assert 0 <= d["cpu_pct"] <= 100
120assert d["ncores"] >= 1
121assert len(d["cores"]) == d["ncores"]
122for c in d["cores"]:
123 assert 0 <= c["pct"] <= 100
124assert d["uptime_sec"] > 0, "uptime must be > 0"
125assert d["proc_count"] > 0, "proc_count must be > 0"
126assert len(d["processes"]) == d["top"]
127assert d["top"] <= d["proc_count"]
128assert d["swap"]["total_kb"] >= 0
129PY
130
131python3 - "$MJ" <<'PY' && pass "process rows carry pid, name, cpu, rss" || fail "process rows malformed"
132import json,sys
133d=json.load(open(sys.argv[1]))
134assert len(d["processes"]) > 0
135for p in d["processes"]:
136 assert isinstance(p["pid"], int) and p["pid"] > 0
137 assert isinstance(p["name"], str) and p["name"]
138 assert p["cpu"] >= 0
139 assert isinstance(p["rss_kb"], int) and p["rss_kb"] >= 0
140PY
141
142python3 - "$MJ" <<'PY' && pass "cpu percentages are sorted descending" || fail "cpu sort wrong"
143import json,sys
144d=json.load(open(sys.argv[1]))
145vals=[p["cpu"] for p in d["processes"]]
146assert vals == sorted(vals, reverse=True), vals
147PY
148rm -f "$MJ"
149
150section "mode 2 sorting, limits and unknown actions"
151MEMF=/tmp/sysmon_mem_$$.json
152MEM=$(body "$(QUERY_STRING='action=metrics&sort=mem&top=5' "$BIN")")
153printf '%s' "$MEM" > "$MEMF"
154check "sort=mem echoed" '"sort":"mem"' "$MEM"
155check "top=5 honoured" '"top":5' "$MEM"
156python3 - "$MEMF" <<'PY' && pass "memory sort is descending" || fail "mem sort wrong"
157import json,sys
158d=json.load(open(sys.argv[1]))
159v=[p["rss_kb"] for p in d["processes"]]
160assert v == sorted(v, reverse=True), v
161assert len(v) <= 5
162PY
163rm -f "$MEMF"
164TOP1=$(body "$(QUERY_STRING='action=metrics&top=1' "$BIN")")
165check "top=1 honoured" '"top":1' "$TOP1"
166UNK=$(QUERY_STRING='action=bogus' "$BIN")
167check "unknown action rejected" 'unknown_action' "$(body "$UNK")"
168check "unknown action lists supported" '"supported":["metrics","info"]' "$(body "$UNK")"
169check "unknown action echoes request" '"requested":"bogus"' "$(body "$UNK")"
170BIGTOP=$(body "$(QUERY_STRING='action=metrics&top=99999' "$BIN")")
171check "absurd top still returns a valid snapshot" '"ok":true' "$BIGTOP"
172check "absurd top is capped" '"top":' "$BIGTOP"
173
174section "mode 2 action=info"
175INFO=$(QUERY_STRING='action=info' "$BIN")
176IBODY=$(body "$INFO")
177check "info ok:true" '"ok":true' "$IBODY"
178check "info action info" '"action":"info"' "$IBODY"
179check "info pid present" '"pid":' "$IBODY"
180check "info utc present" '"utc":"20' "$IBODY"
181check "info zero_network declared" '"zero_network":true' "$IBODY"
182check "info sample window declared" '"samples_cpu_delta_ms":80' "$IBODY"
183check "info node_auth false when unset" '"node_auth":false' "$IBODY"
184INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")")
185check "info node_auth true when set" '"node_auth":true' "$INFOAUTH"
186printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
187 && pass "info body is valid JSON" || fail "info body JSON invalid"
188check "format=json works as alias" '"action":"metrics"' "$(body "$(QUERY_STRING='format=json&top=2' "$BIN")")"
189
190# ---------------------------------------------------------------- html
191section "mode 3 HTML"
192HTML=$(QUERY_STRING='' "$BIN")
193check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML"
194check_not "html has no Content-Length" 'Content-Length' "$HTML"
195check "html has viewport meta" 'width=device-width' "$HTML"
196check "html title sysmon" '<title>sysmon</title>' "$HTML"
197check "html back-link present" 'Back to Bot' "$HTML"
198check "html theme switch hook" 'bot_theme' "$HTML"
199
200# ---- theme handoff (bot_theme_plugin.h) ----
201# the bot owns the theme: ?theme= before first paint, sx-theme after it
202check "html reads ?theme= before paint" 'theme=(light|dark)' "$HTML"
203check "html listens for sx-theme" "d.type==='sx-theme'" "$HTML"
204check "html asks the host for the theme" "sx-theme-request" "$HTML"
205check "html uses bot token --bg-card" "--bg-card" "$HTML"
206check "html uses bot token --surface-2" "--surface-2" "$HTML"
207check "html uses bot token --text-2" "--text-2" "$HTML"
208check "html hides its toggle when embedded" "embed-hide" "$HTML"
209check_not "html no retired brand casing" 'Scorpio'"X Bot" "$HTML"
210check_not "html no private palette 0b0b0e" '0b0b0e' "$HTML"
211check_not "html no private palette 141419" '141419' "$HTML"
212check_not "html no private palette f2f2f6" 'f2f2f6' "$HTML"
213THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
214check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ"
215# ---- end theme handoff ----
216
217check "html per-core host" "id='cores'" "$HTML"
218check "html history sparkline" "id='spark'" "$HTML"
219check "html memory gauge" "memFill" "$HTML"
220check "html swap gauge" "swapFill" "$HTML"
221check "html process table host" "id='rows'" "$HTML"
222check "html process filter input" "id='q'" "$HTML"
223check "html rate segmented control" 'data-ms=' "$HTML"
224check "html sort segmented control" 'data-sort=' "$HTML"
225check "html calls the metrics action" 'action=metrics' "$HTML"
226check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML"
227check "html falls back to /plugin_sysmon" "/plugin_sysmon" "$HTML"
228check "html closes document" '</html>' "$HTML"
229check "html declares zero network" 'zero outbound network' "$HTML"
230EMB=$(QUERY_STRING='embed=1' "$BIN")
231check_not "embed=1 strips the back-link" 'Back to Bot' "$EMB"
232check "embed=1 still renders the UI" "id='cores'" "$EMB"
233EMBT=$(QUERY_STRING='embed=true' "$BIN")
234check_not "embed=true also strips back-link" 'Back to Bot' "$EMBT"
235
236ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c '
237import sys
238s = sys.stdin.read()
239bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)]
240print(len(bad))
241')
242[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)"
243PK="pico""bot"
244check_not "html has no internal fleet paths" "$PK" "$HTML"
245check_not "html has no private IPs" "192.168." "$HTML"
246check_not "html has no ssh/sshpass" "sshpass" "$HTML"
247check_not "html has no popen of shell" "child_process" "$HTML"
248
249section "responsive markup"
250check "html has a 640px breakpoint" '@media(max-width:640px)' "$HTML"
251check "html hides columns on mobile" 'hide-sm' "$HTML"
252check "html grids use auto-fill" 'auto-fill,minmax' "$HTML"
253check "html sparkline scales" "preserveAspectRatio='none'" "$HTML"
254
255section "no shell, no sockets"
256SRCCAT=$(cat src/plugin_sysmon.c)
257check_not "linux/mac code has no popen of user input" 'popen(\"ps' "$SRCCAT"
258check_not "source opens no sockets" 'socket(' "$SRCCAT"
259check_not "source has no curl or wget" 'wget' "$SRCCAT"
260check_not "source has no ssh invocation" 'ssh ' "$SRCCAT"
261check_not "source has no sshpass" 'sshpass' "$SRCCAT"
262
263# ---------------------------------------------------------------- optional targets
264section "optional cross builds"
265if [ -f plugin_sysmon.musl ]; then
266 M=$(./plugin_sysmon.musl --meta)
267 check "musl build --meta" '"name":"sysmon"' "$M"
268 case $(head -c 4 plugin_sysmon.musl | od -An -tx1 | tr -d ' \n') in
269 7f454c46) pass "musl artifact is ELF" ;;
270 *) fail "musl artifact is not ELF" ;;
271 esac
272else
273 echo " skip musl (not built)"
274fi
275if [ -f plugin_sysmon.exe ]; then
276 MAGIC=$(head -c 2 plugin_sysmon.exe)
277 [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
278 SZ=$(wc -c < plugin_sysmon.exe | tr -d ' ')
279 [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
280else
281 echo " skip windows PE (not built)"
282fi
283if [ -f plugin_sysmon.macos-arm64 ]; then
284 MF=$(head -c 4 plugin_sysmon.macos-arm64 | od -An -tx1 | tr -d ' \n')
285 case "$MF" in
286 cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-arm64 artifact is Mach-O" ;;
287 *) fail "macos-arm64 artifact is not Mach-O ($MF)" ;;
288 esac
289else
290 echo " skip macos-arm64 (not built)"
291fi
292if [ -f plugin_sysmon.macos-x86_64 ]; then
293 MF=$(head -c 4 plugin_sysmon.macos-x86_64 | od -An -tx1 | tr -d ' \n')
294 case "$MF" in
295 cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-x86_64 artifact is Mach-O" ;;
296 *) fail "macos-x86_64 artifact is not Mach-O ($MF)" ;;
297 esac
298else
299 echo " skip macos-x86_64 (not built)"
300fi
301
302# ---------------------------------------------------------------- history audit
303section "git history secret & LAN audit"
304if git rev-parse --git-dir >/dev/null 2>&1; then
305 ALL=$(mktemp 2>/dev/null || echo /tmp/sysmon_hist_$$)
306 # Bookkeeping lines of this audit are excluded so the detector cannot flag itself.
307 git log -p --all 2>/dev/null \
308 | grep -v '^Author: ' \
309 | grep -vE 'audit "|HITS=|grep -E|scan "' \
310 > "$ALL" || : > "$ALL"
311
312 audit() { # audit <label> <regex>
313 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
314 if [ -n "$H" ]; then
315 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
316 else
317 pass "history clean: $1"
318 fi
319 }
320 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
321 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
322 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
323 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
324 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
325 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
326 # the literal is split so this file never contains the string it hunts
327 audit "bare host password" 'Xbo''xone0909|xbo''xone'
328 audit "hard-coded ssh password" 'sshpass -p [^"]$'
329 PK="pico""bot"; WT=".work""trees"
330 audit "fleet path" "/codebases/${PK}|${WT}/"
331 rm -f "$ALL"
332else
333 echo " skip history audit (not a git checkout)"
334fi
335
336# ---------------------------------------------------------------- summary
337printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
338printf ' passed: %d\n' "$PASS"
339printf ' failed: %d\n' "$FAIL"
340if [ "$FAIL" -ne 0 ]; then
341 printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
342 exit 1
343fi
344printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0"
345exit 0