scorpiox-bot-plugin-disks
←run.shbash
437 lines · 20 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_disks across all 3 modes.
3#
4# Runs against ./plugin_disks (native build) on the live machine, so the mount
5# assertions use this node's real /proc/mounts (or getmntinfo / Win32 drive
6# list). If a musl static build or a Windows PE (plugin_disks.exe) is present
7# they are checked too. The whole git history is finally audited for secrets
8# and LAN IPs.
9#
10# Exit code 0 = everything passed.
11
12set -u
13
14ROOT=$(cd "$(dirname "$0")/.." && pwd)
15cd "$ROOT" || exit 1
16
17BIN=./plugin_disks
18PASS=0
19FAIL=0
20
21if [ -t 1 ]; then
22 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
23else
24 C_OK=; C_BAD=; C_B=; C_0=
25fi
26pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
27fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
28
29check() { # check <desc> <expected-substring> <actual>
30 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
31 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
32 fi
33}
34
35check_not() { # check_not <desc> <forbidden-substring> <actual>
36 if printf '%s' "$3" | grep -F -q -- "$2"; then
37 fail "$1 (must NOT contain: $2)"; else pass "$1"
38 fi
39}
40
41section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
42
43body() { printf '%s' "$1" | sed '1,/^\r$/d'; }
44
45TMP=$(mktemp -d 2>/dev/null || echo /tmp/disks_tests_$$)
46mkdir -p "$TMP" 2>/dev/null || true
47
48# ---------------------------------------------------------------- build
49section "build"
50if [ ! -x "$BIN" ]; then
51 echo " building native binary..."
52 cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_disks.c || { echo " build failed"; exit 1; }
53fi
54[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
55
56# ---------------------------------------------------------------- meta mode
57section "mode 1 --meta (must work without auth - discovery)"
58META=$("$BIN" --meta)
59check "meta emits name disks" '"name":"disks"' "$META"
60check "meta emits desc Local storage" '"desc":"Local storage"' "$META"
61METAENV=$(SX_PLUGIN_META=1 "$BIN")
62check "SX_PLUGIN_META=1 yields same meta" '"name":"disks"' "$METAENV"
63LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
64[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
65printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
66 && pass "meta is valid JSON" || fail "meta is not valid JSON"
67DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
68[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
69NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
70[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
71check "--version prints version" '1.0.2' "$("$BIN" --version)"
72check "--help is available" 'usage:' "$("$BIN" --help)"
73META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
74check "meta still works when BOT_PASSWORD is set" '"name":"disks"' "$META_AUTH"
75
76# ---------------------------------------------------------------- auth
77section "node auth"
78AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN")
79check "no credentials -> 401" 'Status: 401' "$AUTHNONE"
80check "401 body is json" 'invalid node password' "$AUTHNONE"
81AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=mounts' "$BIN")
82check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")"
83AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=mounts' "$BIN")
84check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")"
85AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=mounts&pwd=testpw' "$BIN")
86check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")"
87AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=mounts' "$BIN")
88check "wrong password -> 401" 'Status: 401' "$AUTHBAD"
89HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
90check "html mode is also gated" 'Status: 401' "$HTMLAUTH"
91
92# ---------------------------------------------------------------- mounts
93section "mode 2 action=mounts"
94MF="$TMP/mounts.json"
95MOUNTS=$(body "$(QUERY_STRING='action=mounts' "$BIN")")
96printf '%s' "$MOUNTS" > "$MF"
97check "mounts ok:true" '"ok":true' "$MOUNTS"
98check "mounts names the plugin" '"plugin":"plugin_disks"' "$MOUNTS"
99check "mounts declares platform" '"platform":"' "$MOUNTS"
100check "mounts declares zero_network" '"zero_network":true' "$MOUNTS"
101check "mounts carries a utc stamp" '"utc":"20' "$MOUNTS"
102check "mounts lists an array" '"mounts":[' "$MOUNTS"
103printf '%s' "$MOUNTS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
104 && pass "mounts body is valid JSON" || fail "mounts body JSON invalid"
105
106python3 - "$MF" <<'PY' && pass "mount rows are well formed" || fail "mount rows malformed"
107import json, sys
108d = json.load(open(sys.argv[1]))
109assert d["count"] == len(d["mounts"])
110for m in d["mounts"]:
111 assert isinstance(m["device"], str)
112 assert isinstance(m["fstype"], str)
113 assert isinstance(m["mount"], str) and m["mount"]
114 for k in ("total_bytes", "used_bytes", "free_bytes", "avail_bytes"):
115 assert isinstance(m[k], int) and m[k] >= 0, (k, m[k])
116 assert 0.0 <= m["pct"] <= 100.0
117PY
118
119python3 - "$MF" <<'PY' && pass "no pseudo filesystems leaked into the table" || fail "pseudo fs present"
120import json, sys
121d = json.load(open(sys.argv[1]))
122banned = {"proc","sysfs","cgroup","cgroup2","devpts","devtmpfs","debugfs",
123 "tracefs","securityfs","pstore","bpf","mqueue","configfs"}
124got = {m["fstype"] for m in d["mounts"]} & banned
125assert not got, got
126PY
127
128python3 - "$MF" <<'PY' && pass "no kernel mountpoints leaked into the table" || fail "kernel mountpoint present"
129import json, sys
130d = json.load(open(sys.argv[1]))
131bad = [m["mount"] for m in d["mounts"]
132 if m["mount"].startswith(("/sys", "/proc", "/dev"))]
133assert not bad, bad
134PY
135
136python3 - "$MF" <<'PY' && pass "mountpoints are unique (no double counting)" || fail "duplicate mountpoint"
137import json, sys
138d = json.load(open(sys.argv[1]))
139mp = [m["mount"] for m in d["mounts"]]
140assert len(mp) == len(set(mp)), [x for x in mp if mp.count(x) > 1]
141PY
142
143python3 - "$MF" <<'PY' && pass "mounts are ordered largest first" || fail "mount order wrong"
144import json, sys
145d = json.load(open(sys.argv[1]))
146t = [m["total_bytes"] for m in d["mounts"]]
147assert t == sorted(t, reverse=True), t
148PY
149
150# The live root filesystem must always be reported on POSIX, whichever node runs it.
151python3 - "$MF" <<'PY' && pass "live root mount is reported" || fail "root mount missing"
152import json, sys, os
153d = json.load(open(sys.argv[1]))
154if os.name != "nt":
155 roots = [m for m in d["mounts"] if m["mount"] == "/"]
156 assert roots, "no / mount"
157 assert roots[0]["total_bytes"] > 0
158PY
159
160python3 - "$MF" <<'PY' && pass "used + avail never exceeds the reported total by much" || fail "usage math inconsistent"
161import json, sys
162d = json.load(open(sys.argv[1]))
163for m in d["mounts"]:
164 # reserved blocks may make used+avail < total; they must never exceed it
165 assert m["used_bytes"] + m["avail_bytes"] <= m["total_bytes"] + 1
166PY
167
168python3 - "$MF" <<'PY' && pass "info/supported keys reachable via format=json" || fail "format=json alias broken"
169import json, sys
170PY
171check "format=json aliases to mounts" '"action":"mounts"' "$(body "$(QUERY_STRING='format=json' "$BIN")")"
172rm -f "$MF"
173
174# ---------------------------------------------------------------- dirs
175section "mode 2 action=dirs - allowlist and traversal rejection"
176for bad in etc /etc .. ../.. workspace/ /workspace /root /home workspace\\ $'workspace\n' '%2Fetc' ; do
177 R=$(body "$(QUERY_STRING="action=dirs&root=$(printf '%s' "$bad" | sed 's/ /%20/g')" "$BIN")")
178 if printf '%s' "$R" | grep -F -q '"ok":false'; then
179 pass "root rejected: $bad"
180 else
181 fail "root accepted: $bad -> $R"
182 fi
183done
184MISS=$(body "$(QUERY_STRING='action=dirs' "$BIN")")
185check "missing root rejected" 'missing_root' "$MISS"
186check "missing root lists the allowlist" '"allowed_roots":["workspace","home"]' "$MISS"
187TRAV=$(body "$(QUERY_STRING='action=dirs&root=/etc' "$BIN")")
188check "traversal rejection is explicit" 'root_not_allowed' "$TRAV"
189check "traversal rejection echoes input" '"requested":"/etc"' "$TRAV"
190
191section "mode 2 action=dirs - real roots"
192DH=$(body "$(QUERY_STRING='action=dirs&root=home' "$BIN")")
193DF="$TMP/home.json"
194printf '%s' "$DH" > "$DF"
195if printf '%s' "$DH" | grep -F -q '"ok":true'; then
196 pass "home root scans on this node"
197 check "dirs echoes the root kind" '"root_kind":"home"' "$DH"
198 check "dirs labels the root" '"root_label":"$HOME"' "$DH"
199 check "dirs declares max depth" '"max_depth":' "$DH"
200 check "dirs declares the scan budget" '"max_scan_entries":' "$DH"
201 check "dirs reports the scan time" '"scan_ms":' "$DH"
202 check "dirs reports truncation state" '"truncated":' "$DH"
203 python3 - "$DF" <<'PY' && pass "dir rows are well formed" || fail "dir rows malformed"
204import json, sys
205d = json.load(open(sys.argv[1]))
206assert d["count"] == len(d["entries"])
207for e in d["entries"]:
208 assert isinstance(e["name"], str) and e["name"]
209 assert isinstance(e["path"], str) and e["path"]
210 assert isinstance(e["bytes"], int) and e["bytes"] >= 0
211 assert isinstance(e["is_dir"], bool)
212 assert 0.0 <= e["pct"] <= 100.0
213PY
214 python3 - "$DF" <<'PY' && pass "dir entries are ordered largest first" || fail "dir order wrong"
215import json, sys
216d = json.load(open(sys.argv[1]))
217b = [e["bytes"] for e in d["entries"]]
218assert b == sorted(b, reverse=True), b
219PY
220 python3 - "$DF" <<'PY' && pass "dir scan stays inside the requested root" || fail "entry escaped the root"
221import json, sys, os
222d = json.load(open(sys.argv[1]))
223root = d["root"].rstrip("/") + "/"
224for e in d["entries"]:
225 assert e["path"].startswith(root), e["path"]
226PY
227 python3 - "$DF" <<'PY' && pass "dir scan is bounded (entry count within the cap)" || fail "entry cap exceeded"
228import json, sys
229d = json.load(open(sys.argv[1]))
230assert d["count"] <= 512, d["count"]
231PY
232else
233 pass "home root unavailable on this node (root_unavailable is a valid answer)"
234 check "unavailable root is not an error leak" 'root_unavailable' "$DH"
235fi
236rm -f "$DF"
237
238DW=$(body "$(QUERY_STRING='action=dirs&root=workspace' "$BIN")")
239if printf '%s' "$DW" | grep -F -q '"ok":true'; then
240 pass "workspace root scans on this node"
241 check "workspace echoes its kind" '"root_kind":"workspace"' "$DW"
242elif printf '%s' "$DW" | grep -F -q 'root_unavailable'; then
243 pass "workspace root absent on this node (reported as root_unavailable)"
244else
245 fail "workspace root gave neither data nor root_unavailable: $DW"
246fi
247
248# ---------------------------------------------------------------- info + unknown
249section "mode 2 action=info"
250INFO=$(QUERY_STRING='action=info' "$BIN")
251IBODY=$(body "$INFO")
252check "info ok:true" '"ok":true' "$IBODY"
253check "info action info" '"action":"info"' "$IBODY"
254check "info pid present" '"pid":' "$IBODY"
255check "info utc present" '"utc":"20' "$IBODY"
256check "info zero_network declared" '"zero_network":true' "$IBODY"
257check "info allowed_roots declared" '"allowed_roots":["workspace","home"]' "$IBODY"
258check "info max_depth declared" '"max_depth":8' "$IBODY"
259check "info node_auth false when unset" '"node_auth":false' "$IBODY"
260INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")")
261check "info node_auth true when set" '"node_auth":true' "$INFOAUTH"
262printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
263 && pass "info body is valid JSON" || fail "info body JSON invalid"
264
265UNK=$(QUERY_STRING='action=bogus' "$BIN")
266check "unknown action rejected" 'unknown_action' "$(body "$UNK")"
267check "unknown action lists supported" '"supported":["mounts","dirs","info"]' "$(body "$UNK")"
268check "unknown action echoes request" '"requested":"bogus"' "$(body "$UNK")"
269
270# ---------------------------------------------------------------- html
271section "mode 3 HTML"
272HTML=$(QUERY_STRING='' "$BIN")
273check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML"
274check_not "html has no Content-Length" 'Content-Length' "$HTML"
275check "html has viewport meta" 'width=device-width' "$HTML"
276check "html title disks" '<title>disks</title>' "$HTML"
277check "html theme switch hook" 'bot_theme' "$HTML"
278
279# ---- theme handoff (bot_theme_plugin.h) ----
280# the bot owns the theme: ?theme= before first paint, sx-theme after it
281check "html reads ?theme= before paint" 'theme=(light|dark)' "$HTML"
282check "html listens for sx-theme" "d.type==='sx-theme'" "$HTML"
283check "html asks the host for the theme" "sx-theme-request" "$HTML"
284check "html uses bot token --bg-card" "--bg-card" "$HTML"
285check "html uses bot token --surface-2" "--surface-2" "$HTML"
286check "html uses bot token --text-2" "--text-2" "$HTML"
287check "html hides its toggle when embedded" "embed-hide" "$HTML"
288check_not "html no retired brand casing" 'Scorpio'"X Bot" "$HTML"
289check_not "html no private palette 0b0b0e" '0b0b0e' "$HTML"
290check_not "html no private palette 141419" '141419' "$HTML"
291check_not "html no private palette f2f2f6" 'f2f2f6' "$HTML"
292THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
293check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ"
294# ---- end theme handoff ----
295
296check "html mount host present" "id='mounts'" "$HTML"
297check "html folder table host" "id='rows'" "$HTML"
298check "html root segmented control" 'data-root=' "$HTML"
299check "html rate segmented control" 'data-ms=' "$HTML"
300check "html capacity bar element" "el('div','bar')" "$HTML"
301check "html calls the mounts action" "base('mounts')" "$HTML"
302check "html calls the dirs action" "base('dirs')" "$HTML"
303check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML"
304check "html falls back to /plugin_disks" "/plugin_disks" "$HTML"
305check "html closes document" '</html>' "$HTML"
306check "html declares zero network" 'zero outbound network' "$HTML"
307check "html shows the inode column" 'inodes' "$HTML"
308check "html colour-codes over-75%" 'warn' "$HTML"
309check "html colour-codes over-90%" 'danger' "$HTML"
310EMB=$(QUERY_STRING='embed=1' "$BIN")
311check "embed=1 still renders the UI" "id='mounts'" "$EMB"
312check_not "embed=1 drops the direct-open note" 'Opened directly from the node API' "$EMB"
313EMBT=$(QUERY_STRING='embed=true' "$BIN")
314check_not "embed=true also drops the note" 'Opened directly from the node API' "$EMBT"
315EMBN=$(QUERY_STRING='' "$BIN")
316check "non-embed keeps the note" 'Opened directly from the node API' "$EMBN"
317
318ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c '
319import sys
320s = sys.stdin.read()
321bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)]
322print(len(bad))
323')
324[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)"
325PK="pico""bot"
326check_not "html has no internal fleet paths" "$PK" "$HTML"
327check_not "html has no private IPs" "192.168." "$HTML"
328check_not "html has no ssh/sshpass" "sshpass" "$HTML"
329
330section "responsive markup"
331check "html has a narrow breakpoint" '@media(max-width:560px)' "$HTML"
332check "html hides columns on mobile" 'hide-sm' "$HTML"
333check "html grids use auto-fit" 'auto-fit,minmax' "$HTML"
334
335section "no shell, no sockets, no remote access"
336SRCCAT=$(cat src/plugin_disks.c)
337check_not "source opens no sockets" 'socket(' "$SRCCAT"
338check_not "source has no curl or wget" 'wget' "$SRCCAT"
339check_not "source has no ssh invocation" 'ssh ' "$SRCCAT"
340check_not "source has no sshpass" 'sshpass' "$SRCCAT"
341check_not "source runs no popen" 'popen(' "$SRCCAT"
342check_not "source has no system()" 'system(' "$SRCCAT"
343check "source walks with opendir/readdir" 'readdir' "$SRCCAT"
344check "source uses statvfs on linux" 'statvfs' "$SRCCAT"
345check "source refuses to follow symlinks" 'S_ISLNK' "$SRCCAT"
346check "source caps the walk depth" 'MAX_DEPTH' "$SRCCAT"
347
348# ---------------------------------------------------------------- optional targets
349section "optional cross builds"
350if [ -f plugin_disks.musl ]; then
351 M=$(./plugin_disks.musl --meta)
352 check "musl build --meta" '"name":"disks"' "$M"
353 case $(head -c 4 plugin_disks.musl | od -An -tx1 | tr -d ' \n') in
354 7f454c46) pass "musl artifact is ELF" ;;
355 *) fail "musl artifact is not ELF" ;;
356 esac
357else
358 echo " skip musl (not built)"
359fi
360if [ -f plugin_disks.arm64 ]; then
361 case $(head -c 4 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in
362 7f454c46) pass "arm64 artifact is ELF" ;;
363 *) fail "arm64 artifact is not ELF" ;;
364 esac
365 # e_machine sits at offset 18, little endian: b7 00 == EM_AARCH64
366 EM=$(od -An -tx1 -j 18 -N 2 plugin_disks.arm64 | tr -d ' \n')
367 [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \
368 || fail "arm64 artifact e_machine is $EM, expected b700"
369else
370 echo " skip arm64 (not built)"
371fi
372if [ -f plugin_disks.exe ]; then
373 MAGIC=$(head -c 2 plugin_disks.exe)
374 [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
375 SZ=$(wc -c < plugin_disks.exe | tr -d ' ')
376 [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
377else
378 echo " skip windows PE (not built)"
379fi
380for slice in arm64 x86_64; do
381 f="plugin_disks.macos-$slice"
382 if [ -f "$f" ]; then
383 MF=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n')
384 case "$MF" in
385 cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;;
386 *) fail "macos-$slice artifact is not Mach-O ($MF)" ;;
387 esac
388 else
389 echo " skip macos-$slice (not built)"
390 fi
391done
392
393# ---------------------------------------------------------------- history audit
394section "git history secret & LAN audit"
395if git rev-parse --git-dir >/dev/null 2>&1; then
396 ALL="$TMP/history.txt"
397 # Bookkeeping lines of this audit are excluded so the detector cannot flag itself.
398 git log -p --all 2>/dev/null \
399 | grep -v '^Author: ' \
400 | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \
401 > "$ALL" || : > "$ALL"
402
403 audit() { # audit <label> <regex>
404 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
405 if [ -n "$H" ]; then
406 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
407 else
408 pass "history clean: $1"
409 fi
410 }
411 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
412 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
413 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
414 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
415 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
416 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
417 # the literal is split so this file never contains the string it hunts
418 audit "bare host password" 'Xbo''xone0909|xbo''xone'
419 PK="pico""bot"; WT=".work""trees"
420 audit "fleet path" "/codebases/${PK}|${WT}/"
421 rm -f "$ALL"
422else
423 echo " skip history audit (not a git checkout)"
424fi
425
426rm -rf "$TMP"
427
428# ---------------------------------------------------------------- summary
429printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
430printf ' passed: %d\n' "$PASS"
431printf ' failed: %d\n' "$FAIL"
432if [ "$FAIL" -ne 0 ]; then
433 printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
434 exit 1
435fi
436printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0"
437exit 0