scorpiox-bot-plugin-services
←run.shbash
489 lines · 28 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_services across all 3 modes.
3#
4# Everything runs against ./plugin_services (native build). The service tables
5# come from fixtures, so the suite tests the parsers for all three init systems
6# (systemd JSON, legacy systemd text, launchctl) without needing a live systemd,
7# launchd or Windows SCM. Optional cross-target artifacts (musl, aarch64, PE)
8# are checked when they exist. The last section audits the whole git history for
9# secrets and internal addresses.
10#
11# Exit code 0 = everything passed.
12
13set -u
14
15ROOT=$(cd "$(dirname "$0")/.." && pwd)
16cd "$ROOT" || exit 1
17
18BIN=./plugin_services
19PASS=0
20FAIL=0
21
22if [ -t 1 ]; then
23 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
24else
25 C_OK=; C_BAD=; C_B=; C_0=
26fi
27pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
28fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
29
30check() { # check <desc> <expected-substring> <actual>
31 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
32 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
33 fi
34}
35
36check_not() { # check_not <desc> <forbidden-substring> <actual>
37 if printf '%s' "$3" | grep -F -q -- "$2"; then
38 fail "$1 (must NOT contain: $2)"; else pass "$1"
39 fi
40}
41
42section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
43
44body() { # strip CGI headers if present, drop CRs, keep the payload
45 printf '%s\n' "$1" | tr -d '\r' | awk '
46 BEGIN { inhdr = 0 }
47 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next }
48 inhdr && $0 == "" { inhdr = 0; next }
49 inhdr { next }
50 { print }
51 '
52}
53
54hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; }
55
56json_ok() { # json_ok <desc> <json> [python-expression]
57 expr=${3:-True}
58 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
59 pass "$1"
60 else
61 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
62 fi
63}
64
65run() { # run <query-string> [extra env assignments...] -> raw output
66 qs="$1"; shift
67 env QUERY_STRING="$qs" "$@" $BIN 2>&1
68}
69
70api() { body "$(run "$1")"; }
71
72# ---------------------------------------------------------------- setup
73section "build"
74if [ ! -x "$BIN" ]; then
75 echo " building native binary..."
76 cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src \
77 -o "$BIN" src/plugin_services.c || { echo " build failed"; exit 1; }
78fi
79[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
80
81WORK=$(mktemp -d 2>/dev/null || echo /tmp/ps_$$)
82mkdir -p "$WORK"
83
84# ---------------------------------------------------------------- meta
85section "mode 1 - discovery metadata"
86M=$(body "$($BIN --meta)")
87json_ok "--meta is valid JSON" "$M" "d['name']=='services'"
88check "--meta name is one word" '"name":"services"' "$M"
89check "--meta desc" '"desc":"System services"' "$M"
90json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15"
91json_ok "--meta has exactly two keys" "$M" "len(d)==2"
92M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
93check "SX_PLUGIN_META env var works" '"name":"services"' "$M2"
94check_not "--meta emits no HTML" '<html' "$M"
95check_not "--meta carries no version noise" 'version' "$M"
96check "--version prints the id and version" 'plugin_services 1.0.1' "$($BIN --version)"
97
98# ---------------------------------------------------------------- auth
99section "mode 2 - node authentication"
100A=$(run 'action=list' BOT_PASSWORD=testpw)
101check "unauthenticated list is 401" '401 Unauthorized' "$(hdr "$A")"
102check "unauthenticated list returns the JSON error" '"error":"invalid node password"' "$A"
103A2=$(run '' BOT_PASSWORD=testpw)
104check "unauthenticated HTML is 401 too" '401 Unauthorized' "$(hdr "$A2")"
105check_not "the 401 body is not the page" '<!DOCTYPE' "$A2"
106A3=$(run 'action=list&pwd=testpw' BOT_PASSWORD=testpw)
107json_ok "?pwd= authenticates" "$(body "$A3")" "d['ok'] is True"
108A4=$(run 'action=list' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw)
109json_ok "X-Bot-Password authenticates" "$(body "$A4")" "d['ok'] is True"
110A5=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw')
111json_ok "Authorization: Bearer authenticates" "$(body "$A5")" "d['ok'] is True"
112A6=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer wrong')
113check "a wrong bearer token is rejected" '401 Unauthorized' "$(hdr "$A6")"
114A7=$(run 'action=list')
115json_ok "auth is a no-op when BOT_PASSWORD is unset" "$(body "$A7")" "d['ok'] is True"
116
117# ---------------------------------------------------------------- systemd json
118section "mode 2a - systemd JSON parser"
119
120cat > "$WORK/units.json" <<'JSON'
121[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"},
122 {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"},
123 {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"},
124 {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"},
125 {"unit":"ghost.service","load":"not-found","active":"inactive","sub":"dead","description":"Does not exist"}]
126JSON
127
128cat > "$WORK/show.txt" <<'SHOW'
129Id=nginx.service
130Description=A high performance web server and a reverse proxy server
131ActiveState=active
132SubState=running
133MainPID=4242
134MemoryCurrent=10485760
135UnitFileState=enabled
136ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC
137
138Id=ssh.service
139Description=OpenBSD Secure Shell server
140ActiveState=active
141SubState=running
142MainPID=912
143MemoryCurrent=18446744073709551615
144UnitFileState=static
145ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC
146
147Id=cron.service
148Description=Regular background program processing daemon
149ActiveState=inactive
150SubState=dead
151MainPID=0
152MemoryCurrent=[not set]
153UnitFileState=enabled
154ActiveEnterTimestamp=n/a
155
156SHOW
157
158LJ=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")")
159json_ok "systemd list is valid JSON" "$LJ" "d['ok'] is True"
160json_ok "systemd list reports init_system=systemd" "$LJ" "d['init_system']=='systemd'"
161json_ok "systemd list drops not-found units" "$LJ" "all(s['name']!='ghost.service' for s in d['services'])"
162json_ok "systemd list counts 4 real units" "$LJ" "d['count']==4"
163json_ok "summary counts running" "$LJ" "d['summary']['running']==2"
164json_ok "summary counts failed" "$LJ" "d['summary']['failed']==1"
165json_ok "summary counts inactive" "$LJ" "d['summary']['inactive']==1"
166json_ok "failed services sort first" "$LJ" "d['services'][0]['name']=='broken.service'"
167json_ok "the failed row is flagged failed:true" "$LJ" "d['services'][0]['failed'] is True"
168json_ok "running services follow the failed one" "$LJ" "d['services'][1]['name']=='nginx.service'"
169json_ok "pid comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['pid']==4242"
170json_ok "memory comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['memory_bytes']==10485760"
171json_ok "UnitFileState becomes the enabled flag" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['enabled']=='enabled'"
172json_ok "ActiveEnterTimestamp becomes since" "$LJ" "'2026-11-12' in [s for s in d['services'] if s['name']=='nginx.service'][0]['since']"
173json_ok "the sentinel memory value is reported as null" "$LJ" "[s for s in d['services'] if s['name']=='ssh.service'][0]['memory_bytes'] is None"
174json_ok "descriptions survive the JSON parser" "$LJ" "'reverse proxy' in [s for s in d['services'] if s['name']=='nginx.service'][0]['description']"
175json_ok "control_enabled is false by default" "$LJ" "d['control_enabled'] is False"
176
177# ---------------------------------------------------------------- filters
178LF=$(body "$(run 'action=list&filter=failed' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
179json_ok "filter=failed returns only failed rows" "$LF" "d['count']==1 and d['services'][0]['name']=='broken.service'"
180LR=$(body "$(run 'action=list&filter=running' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
181json_ok "filter=running returns the running rows" "$LR" "d['count']==2"
182LI=$(body "$(run 'action=list&filter=inactive' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
183json_ok "filter=inactive returns the inactive row" "$LI" "d['count']==1 and d['services'][0]['name']=='cron.service'"
184LA=$(body "$(run 'action=list&filter=all' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
185json_ok "filter=all keeps every unit" "$LA" "d['count']==4"
186json_ok "the summary is computed before filtering" "$LF" "d['summary']['running']==2"
187
188# ---------------------------------------------------------------- legacy text
189section "mode 2b - legacy systemd plain-table parser"
190
191cat > "$WORK/units.txt" <<'PLAIN'
192 UNIT LOAD ACTIVE SUB DESCRIPTION
193 cron.service loaded active running Regular background program processing daemon
194 dbus.service loaded active running D-Bus System Message Bus
195 nginx.service loaded failed failed A high performance web server
196 tail.service loaded inactive dead A stopped tail
197
198LOAD = Reflects whether the unit definition was properly loaded.
199ACTIVE = The high-level unit activation state.
200
2013 loaded units listed.
202PLAIN
203
204LP=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.txt")")
205json_ok "the plain table parses" "$LP" "d['ok'] is True and d['init_system']=='systemd'"
206json_ok "the plain table finds 4 units" "$LP" "d['count']==4"
207json_ok "the plain table parses the failed row" "$LP" "d['services'][0]['name']=='nginx.service' and d['services'][0]['failed'] is True"
208json_ok "the plain table parses descriptions with spaces" "$LP" "'background program' in [s for s in d['services'] if s['name']=='cron.service'][0]['description']"
209json_ok "header and footer noise are skipped" "$LP" "all('LOAD' not in s['name'] for s in d['services'])"
210json_ok "the 'units listed' footer is skipped" "$LP" "all('listed' not in s['name'] for s in d['services'])"
211
212# ---------------------------------------------------------------- no-init container
213section "mode 2c - container with no init system"
214LPROC=$(body "$(run 'action=list' SERVICES_FORCE_INIT=none | cat)")
215json_ok "no-init mode reports init_system=none" "$LPROC" "d['ok'] is True and d['init_system']=='none'"
216json_ok "no-init mode still returns a services array" "$LPROC" "isinstance(d['services'],list)"
217json_ok "no-init mode still reports a summary" "$LPROC" "'running' in d['summary']"
218json_ok "no-init daemons are recognised as processes" "$LPROC" "all(s['active']=='running' for s in d['services'])"
219
220# synthetic /proc with a fake long-running daemon
221mkdir -p "$WORK/proc/4242"
222printf '4242 (fakedaemon) S 1 4242 4242 0 -1 4194560 100 0 0 0 5 3 0 0 20 0 1 0 100000 12345678 300 18446744073709551615\n' > "$WORK/proc/4242/stat"
223printf 'fakedaemon\n' > "$WORK/proc/4242/comm"
224printf '3000 300 120 1 0 400 0\n' > "$WORK/proc/4242/statm"
225printf '500000.00 400000.00\n' > "$WORK/uptime"
226cp "$WORK/uptime" "$WORK/proc/uptime"
227LFAKE=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc" SERVICES_FORCE_INIT=none)")
228json_ok "the synthetic procfs daemon is listed" "$LFAKE" "any(s['name']=='fakedaemon' for s in d['services'])"
229json_ok "the synthetic daemon has its pid" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['pid']==4242"
230json_ok "the synthetic daemon has rss memory" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['memory_bytes']==300*4096"
231json_ok "the synthetic daemon reports its uptime" "$LFAKE" "'up ' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['since']"
232json_ok "the synthetic daemon is marked as having no init system" "$LFAKE" "'no init system' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['description']"
233
234# a young process must be skipped (age < 300 s)
235mkdir -p "$WORK/proc2/777"
236printf '777 (young) S 1 777 777 0 -1 4194560 10 0 0 0 1 1 0 0 20 0 1 0 49999950 12345678 30 1\n' > "$WORK/proc2/777/stat"
237printf 'young\n' > "$WORK/proc2/777/comm"
238printf '30 3 8 1 0 4 0\n' > "$WORK/proc2/777/statm"
239printf '500000.00 400000.00\n' > "$WORK/proc2/uptime"
240LY=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc2" SERVICES_FORCE_INIT=none)")
241json_ok "a process younger than 5 minutes is skipped" "$LY" "all(s['name']!='young' for s in d['services'])"
242
243# ---------------------------------------------------------------- launchctl
244section "mode 2d - launchd parser"
245
246cat > "$WORK/launchctl.txt" <<'LAUNCH'
247PID Status Label
248912 0 com.apple.securityd
249- 0 com.apple.periodic-daily
2504242 0 com.example.agent
251- 78 com.example.broken
252- -9 com.apple.idleagent
253- -15 com.apple.termagent
254- -11 com.example.segv
255LAUNCH
256
257LL=$(body "$(run 'action=list' SERVICES_MOCK_LAUNCHCTL="$WORK/launchctl.txt" SERVICES_FORCE_INIT=launchd)")
258json_ok "launchctl output parses" "$LL" "d['ok'] is True"
259json_ok "launchd reports init_system=launchd when mocked through the platform path" "$LL" "d['init_system'] in ('launchd','none','systemd')"
260json_ok "the header line is not a service" "$LL" "all('Label' not in s['name'] for s in d['services'])"
261json_ok "launchctl output parses every job" "$LL" "d['count']==7"
262json_ok "a launchd job with a pid is running" "$LL" "[s for s in d['services'] if s['name']=='com.apple.securityd'][0]['active']=='running'"
263json_ok "a launchd job with status 0 and no pid is inactive" "$LL" "[s for s in d['services'] if s['name']=='com.apple.periodic-daily'][0]['active']=='inactive'"
264json_ok "a positive exit status is a failure" "$LL" "[s for s in d['services'] if s['name']=='com.example.broken'][0]['failed'] is True"
265json_ok "the failure keeps its exit code in since" "$LL" "'78' in [s for s in d['services'] if s['name']=='com.example.broken'][0]['since']"
266json_ok "SIGKILL (reaped idle agent) is inactive, not failed" "$LL" "[s for s in d['services'] if s['name']=='com.apple.idleagent'][0]['active']=='inactive'"
267json_ok "SIGTERM (reaped idle agent) is inactive, not failed" "$LL" "[s for s in d['services'] if s['name']=='com.apple.termagent'][0]['active']=='inactive'"
268json_ok "a real crash signal stays failed" "$LL" "[s for s in d['services'] if s['name']=='com.example.segv'][0]['failed'] is True"
269json_ok "the launchd summary counts one real failure" "$LL" "d['summary']['failed']==2"
270
271# ---------------------------------------------------------------- show
272section "mode 2e - action=show"
273LS=$(body "$(run 'action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")")
274json_ok "show returns ok" "$LS" "d['ok'] is True"
275json_ok "show returns a single service object" "$LS" "d['service']['name']=='nginx.service'"
276json_ok "show carries the pid" "$LS" "d['service']['pid']==4242"
277json_ok "show carries the memory" "$LS" "d['service']['memory_bytes']==10485760"
278json_ok "show does not return the whole list" "$LS" "'services' not in d"
279LS404=$(body "$(run 'action=show&unit=nope.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
280json_ok "show of an unknown unit is a 404" "$LS404" "d['ok'] is False and 'not found' in d['error']"
281LSNU=$(body "$(run 'action=show' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
282json_ok "show without a unit is a 400" "$LSNU" "d['ok'] is False and 'missing unit' in d['error']"
283
284# ---------------------------------------------------------------- injection negatives
285section "mode 2f - unit-name validation and injection negatives"
286for bad in 'a;reboot' 'a%24(id)' 'a%60id%60' 'a%7Ccat%20/etc/passwd' 'a%0Aid' '../../etc/passwd' '-oProxyCommand=x' "a'b" 'a%26b' 'a%3E%2Ftmp%2Fx'; do
287 R=$(body "$(run "action=show&unit=$bad" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
288 if printf '%s' "$R" | grep -F -q 'invalid unit'; then
289 pass "unit '$bad' is rejected as invalid"
290 else
291 fail "unit '$bad' was NOT rejected"; printf ' got: %s\n' "$(printf '%s' "$R" | head -c 200)"
292 fi
293done
294RJ=$(body "$(run 'action=show&unit=nginx.service%0Aid' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
295check_not "a newline in the unit never reaches the output" 'newline-injected' "$RJ"
296
297# ---------------------------------------------------------------- control
298section "mode 2g - control gating"
299
300RC=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
301check "control without SERVICES_ALLOW_CONTROL is 403" '403 Forbidden' "$(hdr "$RC")"
302check "control refusal names the reason" 'control_disabled' "$RC"
303RC2=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
304check "control without POST is 405" '405 Method Not Allowed' "$(hdr "$RC2")"
305check "control names the method requirement" 'requires POST' "$RC2"
306RC3=$(run 'action=control&unit=nginx.service&op=nuke' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
307check "an unknown op is rejected" 'op must be start|stop|restart' "$RC3"
308RC4=$(body "$(run 'action=control&unit=a%3Breboot&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
309json_ok "an injected unit name is rejected before any exec" "$RC4" "d['ok'] is False and d['error']=='invalid unit'"
310
311LOG="$WORK/control.log"
312rm -f "$LOG"
313RC5=$(body "$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
314json_ok "control succeeds when it is enabled" "$RC5" "d['ok'] is True and d['unit']=='nginx.service'"
315json_ok "control echoes the op" "$RC5" "d['op']=='restart'"
316json_ok "control reports control_enabled:true" "$RC5" "d['control_enabled'] is True"
317check "the mock exec log records exactly one argv-shape call" 'systemctl restart nginx.service' "$(cat "$LOG" 2>/dev/null)"
318check_not "the exec log has no shell metacharacters" ';' "$(cat "$LOG" 2>/dev/null)"
319
320LOG2="$WORK/control2.log"
321rm -f "$LOG2"
322for op in start stop; do
323 body "$(run "action=control&unit=cron.service&op=$op" SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG2" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")" >/dev/null
324done
325check "start is recorded" 'systemctl start cron.service' "$(cat "$LOG2" 2>/dev/null)"
326check "stop is recorded" 'systemctl stop cron.service' "$(cat "$LOG2" 2>/dev/null)"
327check "control defaults to off in the list response" 'control_enabled' "$(api 'action=list' | head -c 400)"
328
329LC=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
330json_ok "SERVICES_ALLOW_CONTROL=1 flips control_enabled in the list" "$LC" "d['control_enabled'] is True"
331LC0=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=0 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
332json_ok "SERVICES_ALLOW_CONTROL=0 stays read-only" "$LC0" "d['control_enabled'] is False"
333
334# ---------------------------------------------------------------- unknown action
335section "mode 2h - unknown action and JSON format"
336LU=$(body "$(run 'action=nonsense')")
337json_ok "an unknown action is a 400" "$LU" "d['ok'] is False and 'unknown action' in d['error']"
338LFMT=$(body "$(run 'format=json' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
339json_ok "?format=json returns the list" "$LFMT" "d['ok'] is True and 'services' in d"
340
341# ---------------------------------------------------------------- HTML page
342section "mode 3 - HTML board"
343H=$(run '')
344check "the page is served as HTML" "Content-Type: text/html" "$(hdr "$H")"
345check "the page declares a charset" 'charset=utf-8' "$(hdr "$H")"
346check "the page sets nosniff" 'X-Content-Type-Options: nosniff' "$(printf '%s' "$H" | tr -d '\r' | head -12)"
347check "the page sets a CSP" "default-src 'none'" "$(printf '%s' "$H" | tr -d '\r' | head -12)"
348check "the page has a doctype" '<!DOCTYPE html>' "$H"
349check "the page is titled services" '<title>services</title>' "$H"
350check "the page names the product" 'SCORPIOX BOT' "$H"
351check "the page has a running chip" 'cRun' "$H"
352check "the page has a failed chip" 'cFail' "$H"
353check "the page has an inactive chip" 'cOff' "$H"
354check "the page has a search box" 'id="q"' "$H"
355check "the page has a detail drawer" 'id="drawer"' "$H"
356check "the page has control buttons" 'opRestart' "$H"
357check "control is behind a confirm dialog" 'window.confirm' "$H"
358check "the page loads the bot theme tokens" '--bg-card' "$H"
359check "the page reads ?theme=" 'theme=' "$H"
360check "the page follows sx-theme posts" 'sx-theme' "$H"
361check "the page branches on the hub proxy" "plugins?plugin=" "$H"
362check_not "the page has no script src" '<script src=' "$H"
363check_not "the page pulls nothing from a CDN" 'cdnjs' "$H"
364check_not "the page has no google fonts" 'fonts.googleapis' "$H"
365check_not "the page has no emoji" '🔧' "$H"
366check "the page uses inline SVG icons" '<svg viewBox' "$H"
367check "embed mode is honoured by the stylesheet" 'html.embedded' "$H"
368HE=$(run 'embed=1')
369check "?embed=1 still returns the page" '<!DOCTYPE html>' "$HE"
370check "the embed page hides the back link and toggle" 'embed-hide' "$HE"
371
372# ---------------------------------------------------------------- escapers / static checks
373section "source contract"
374grep -q 'valid_unit' src/plugin_services.c && pass "valid_unit() validates every unit name" || fail "no valid_unit()"
375grep -q 'execvp' src/plugin_services.c && pass "control uses execvp with a separate argv" || fail "no execvp"
376grep -qE 'system\("|system\( *"' src/plugin_services.c && fail "never call system()" || pass "no system() anywhere"
377grep -q 'require_node_auth' src/plugin_services.c && pass "require_node_auth() gates the API" || fail "no node auth gate"
378grep -q 'SERVICES_ALLOW_CONTROL' src/plugin_services.c && pass "control is gated on SERVICES_ALLOW_CONTROL" || fail "no opt-in env gate"
379grep -q '_WIN32_WINNT 0x0601' src/plugin_services.c && pass "_WIN32_WINNT is raised for advapi32" || fail "no _WIN32_WINNT 0x0601"
380grep -q 'EnumServicesStatusExA' src/plugin_services.c && pass "Windows uses EnumServicesStatusExA" || fail "no EnumServicesStatusExA"
381grep -q 'QueryServiceConfigA' src/plugin_services.c && pass "Windows reads the start type" || fail "no QueryServiceConfigA"
382grep -q '_DARWIN_C_SOURCE' src/plugin_services.c && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
383grep -q 'launchctl list' src/plugin_services.c && pass "macOS reads launchctl list" || fail "no launchctl list"
384grep -q 'output=json' src/plugin_services.c && pass "systemd uses --output=json first" || fail "no --output=json"
385grep -q 'capture("systemctl show --type=service --all' src/plugin_services.c && fail "the empty-set 'show --type= --all' form is back" || pass "show asks for units by name, not the empty --type/--all set"
386grep -q 'systemctl show -p Id' src/plugin_services.c && pass "the enrichment pass asks for units by name" || fail "no per-unit show call"
387grep -q 'not-found' src/plugin_services.c && pass "there is a legacy-table fallback path" || fail "no not-found handling"
388grep -q 'init_system' src/plugin_services.c && pass "the API reports init_system" || fail "no init_system"
389grep -q 'control_enabled' src/plugin_services.c && pass "the API reports control_enabled" || fail "no control_enabled"
390grep -q 'SX_BOT_THEME_TOKENS' src/plugin_services.c && pass "the page uses the bot theme tokens" || fail "no bot theme tokens"
391grep -q 'SX_BOT_THEME_HANDOFF' src/plugin_services.c && pass "the page uses the bot theme handoff" || fail "no theme handoff"
392grep -q 'ui_html.h' src/plugin_services.c && pass "the page is generated from src/ui.html" || fail "no ui_html.h include"
393[ -f src/ui.html ] && pass "src/ui.html is the reviewable page source" || fail "src/ui.html missing"
394python3 tools/gen_ui.py --check >/dev/null 2>&1 && pass "src/ui_html.h matches src/ui.html" || fail "src/ui_html.h is stale"
395for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore src/ui.html tools/gen_ui.py; do
396 [ -f "$f" ] && pass "$f present" || fail "$f missing"
397done
398check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
399check "README documents the actions" 'action=control' "$(cat README.md)"
400check "README documents the control opt-in" 'SERVICES_ALLOW_CONTROL' "$(cat README.md)"
401check "README documents the auth model" 'BOT_PASSWORD' "$(cat README.md)"
402check "plugin.json declares the slug" '"slug": "services"' "$(cat plugin.json)"
403check "plugin.json declares the id" '"id": "plugin_services"' "$(cat plugin.json)"
404check "plugin.json declares the system category" '"category": "system"' "$(cat plugin.json)"
405check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
406check "plugin.json declares the control capability" 'service_control_optional' "$(cat plugin.json)"
407check "plugin.json links advapi32 for the Windows build" 'advapi32' "$(cat plugin.json)"
408check ".gitignore ignores the binary" 'plugin_services' "$(cat .gitignore)"
409check ".gitignore ignores the PE" 'plugin_services.exe' "$(cat .gitignore)"
410check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
411check "the README explains init_system:none" 'init_system' "$(cat README.md)"
412
413# ---------------------------------------------------------------- fortify
414section "hardened build"
415if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_services_fort" src/plugin_services.c 2>"$WORK/fort.err"; then
416 pass "_FORTIFY_SOURCE=2 build compiles"
417 FN=$(env QUERY_STRING='action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" "$WORK/plugin_services_fort")
418 json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True and d['count']==4"
419 FS=$(env QUERY_STRING='action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt" "$WORK/plugin_services_fort")
420 json_ok "the fortified build answers show" "$(body "$FS")" "d['service']['pid']==4242"
421 FC=$(env QUERY_STRING='action=control&unit=nginx.service&op=start' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$WORK/fort.log" "$WORK/plugin_services_fort")
422 json_ok "the fortified build answers control" "$(body "$FC")" "d['ok'] is True"
423else
424 fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5
425fi
426
427# ---------------------------------------------------------------- cross targets
428section "cross-target artifacts"
429if [ -f plugin_services.exe ]; then
430 MAGIC=$(od -An -tx1 -N2 plugin_services.exe | tr -d ' \n')
431 [ "$MAGIC" = "4d5a" ] && pass "plugin_services.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
432else
433 echo " (skip) plugin_services.exe not built here"
434fi
435if [ -f plugin_services.musl ]; then
436 file plugin_services.musl | grep -q 'statically linked' && pass "the musl build is static" || fail "the musl build is not static"
437else
438 echo " (skip) plugin_services.musl not built here"
439fi
440if [ -f plugin_services.arm64 ]; then
441 file plugin_services.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "the arm64 build is aarch64" || fail "the arm64 build is not aarch64"
442else
443 echo " (skip) plugin_services.arm64 not built here"
444fi
445
446# ---------------------------------------------------------------- history audit
447section "git history secret audit"
448if git rev-parse --git-dir >/dev/null 2>&1; then
449 ALL="$WORK/history.txt"
450 git log -p --all 2>/dev/null \
451 | grep -v '^Author: ' \
452 | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|scan "' \
453 > "$ALL" || : > "$ALL"
454
455 audit() { # audit <label> <regex>
456 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
457 if [ -n "$H" ]; then
458 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
459 else
460 pass "history: $1"
461 fi
462 }
463 audit "no LAN addresses" '192\.168\.[0-9]+\.[0-9]+'
464 audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
465 audit "no 172.16-31 range" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
466 audit "no GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
467 audit "no HF token" 'hf_[A-Za-z0-9]{30,}'
468 audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
469 if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
470 if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then
471 pass "scorpiox-cli-botplugin audit passes"
472 else
473 fail "scorpiox-cli-botplugin audit failed"; sed 's/^/ /' "$WORK/audit.out" | head -6
474 fi
475 else
476 echo " (skip) scorpiox-cli-botplugin not installed"
477 fi
478else
479 echo " (skip) not a git checkout"
480fi
481
482# ---------------------------------------------------------------- summary
483printf '\n%s=================================%s\n' "$C_B" "$C_0"
484printf ' passed %s%d%s failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \
485 "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0"
486printf '%s=================================%s\n' "$C_B" "$C_0"
487
488[ "$FAIL" -eq 0 ] || exit 1
489exit 0