scorpiox-bot-plugin-netcheck
โ†run.shbash
550 lines ยท 31 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_netcheck across all 3 modes.
3#
4# Everything runs against ./plugin_netcheck with no network required: the
5# resolver, the interface table and the outbound connect are replaced by the
6# three environment hooks the plugin exposes for exactly this purpose
7# (NETCHECK_MOCK_IFACES, NETCHECK_MOCK_DNS, NETCHECK_MOCK_TIMEOUT), and the
8# TCP/HTTP legs talk to throwaway listeners started by tests/mockd.py on
9# 127.0.0.1. It proves: --meta, node auth on every action, each action's JSON
10# shape, host/port/url validation, the timeout path, redirect handling, the
11# no-TLS contract, the generated page (no CDN, no <script src=>, no emoji),
12# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that runs clean,
13# and a full git-history secret audit.
14#
15# Exit code 0 = everything passed.
16
17set -u
18
19ROOT=$(cd "$(dirname "$0")/.." && pwd)
20cd "$ROOT" || exit 1
21
22BIN=./plugin_netcheck
23PASS=0
24FAIL=0
25
26if [ -t 1 ]; then
27 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
28else
29 C_OK=; C_BAD=; C_B=; C_0=
30fi
31pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
32fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
33
34check() { # check <desc> <expected-substring> <actual>
35 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
36 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
37 fi
38}
39
40check_not() { # check_not <desc> <forbidden-substring> <actual>
41 if printf '%s' "$3" | grep -F -q -- "$2"; then
42 fail "$1 (must NOT contain: $2)"; else pass "$1"
43 fi
44}
45
46section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
47
48# strip CGI headers if present, drop CRs, keep the payload
49body() {
50 printf '%s\n' "$1" | tr -d '\r' | awk '
51 BEGIN { inhdr = 0 }
52 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next }
53 inhdr && $0 == "" { inhdr = 0; next }
54 inhdr { next }
55 { print }
56 '
57}
58
59json_ok() { # json_ok <desc> <json> [python-expression]
60 expr=${3:-True}
61 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
62 pass "$1"
63 else
64 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
65 fi
66}
67
68# api <query-string> [extra-env-assignments...]
69api() {
70 _qs="$1"; shift
71 body "$(env "$@" QUERY_STRING="$_qs" $BIN)"
72}
73apiraw() {
74 _qs="$1"; shift
75 env "$@" QUERY_STRING="$_qs" $BIN
76}
77
78# ---------------------------------------------------------------- fixtures
79WORK=$(mktemp -d)
80trap 'rm -rf "$WORK"; kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null' EXIT
81
82# TEST-NET ranges (RFC 5737) are used for every synthetic address so the suite
83# never contains a private-range literal.
84IF_FIX='lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,lo|::1|||6|1,tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1,wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0'
85DNS_FIX='example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1;two=198.51.100.9,198.51.100.10'
86
87BASE=18080
88python3 tests/mockd.py "$BASE" > "$WORK/mockd.out" 2>"$WORK/mockd.err" &
89MOCK_PID=$!
90i=0
91while [ "$i" -lt 40 ]; do
92 grep -q READY "$WORK/mockd.out" 2>/dev/null && break
93 i=$((i + 1)); sleep 0.05
94done
95if grep -q READY "$WORK/mockd.out" 2>/dev/null; then
96 pass "mock listeners are up on 127.0.0.1:$BASE..$((BASE + 4))"
97else
98 fail "mock listeners never came up"
99 cat "$WORK/mockd.err" | sed 's/^/ /' | head -5
100fi
101OPEN_PORT=$((BASE + 1))
102N404_PORT=$((BASE + 2))
103N301_PORT=$((BASE + 3))
104SILENT_PORT=$((BASE + 4))
105TCPFIX="target=127.0.0.1"
106
107# ---------------------------------------------------------------- build
108section "build"
109if [ ! -x "$BIN" ]; then
110 echo " building native binary..."
111 cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_netcheck.c -lpthread 2>"$WORK/build.err"
112 if [ -x "$BIN" ]; then pass "native build ok"; else
113 fail "native build failed"; sed 's/^/ /' "$WORK/build.err" | head -10
114 fi
115else
116 pass "native binary present"
117fi
118check "Makefile has a musl target" 'musl:' "$(cat Makefile)"
119check "Makefile has a win64 target" 'win64:' "$(cat Makefile)"
120check "Makefile has a test target" 'test:' "$(cat Makefile)"
121check "Makefile has a clean target" 'clean:' "$(cat Makefile)"
122check "Makefile links pthread for the resolver deadline" 'PTHREAD' "$(cat Makefile)"
123check "Makefile links the Win32 libs on win64" 'liphlpapi' "$(cat Makefile)"
124
125# ---------------------------------------------------------------- mode 1: meta
126section "mode 1 - discovery metadata"
127M=$($BIN --meta)
128json_ok "--meta prints valid JSON" "$M" "d['name']=='netcheck' and d['desc']=='Net checks'"
129check "--meta name is one word" '"name":"netcheck"' "$M"
130check "--meta desc is 11 chars" '"desc":"Net checks"' "$M"
131M2=$(SX_PLUGIN_META=1 $BIN)
132check "SX_PLUGIN_META=1 answers the same" '"name":"netcheck"' "$M2"
133check_not "--meta needs no password" '401' "$M2"
134
135# ---------------------------------------------------------------- mode 2: auth
136section "mode 2a - node auth on every action"
137PW=testpw
138for a in ifaces info; do
139 check "unauth $a is 401" 'Status: 401' "$(apiraw "action=$a" BOT_PASSWORD=$PW)"
140done
141check "unauth dns is 401" 'Status: 401' "$(apiraw "action=dns&host=example.com" BOT_PASSWORD=$PW)"
142check "unauth tcp is 401" 'Status: 401' "$(apiraw "action=tcp&host=example.com&port=80" BOT_PASSWORD=$PW)"
143check "unauth http is 401" 'Status: 401' "$(apiraw "action=http&url=http://example.com/" BOT_PASSWORD=$PW)"
144check "unauth bare html is 401" 'Status: 401' "$(apiraw "" BOT_PASSWORD=$PW)"
145check "the 401 body names the error" '"error":"invalid node password"' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)"
146check "the 401 says json" 'Content-Type: application/json' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)"
147AUTHV="Bearer $PW"
148HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW QUERY_STRING='action=info' $BIN)
149check "header auth is accepted" '"ok":true' "$(body "$HA")"
150BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="$AUTHV" QUERY_STRING='action=info' $BIN)
151check "bearer auth is accepted" '"ok":true' "$(body "$BA")"
152QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=info&pwd=testpw' $BIN)
153check "query pwd auth is accepted" '"ok":true' "$(body "$QA")"
154check "a wrong pwd is still 401" 'Status: 401' "$(apiraw "action=info&pwd=nope" BOT_PASSWORD=$PW)"
155check "no password set means open" '"ok":true' "$(api "action=info")"
156check "--meta stays open with a password set" '"name":"netcheck"' "$(BOT_PASSWORD=$PW $BIN --meta)"
157
158# ---------------------------------------------------------------- mode 2b: ifaces
159section "mode 2b - action=ifaces"
160IF=$(api "action=ifaces" NETCHECK_MOCK_IFACES="$IF_FIX")
161json_ok "ifaces answers ok" "$IF" "d['ok'] is True and d['action']=='ifaces'"
162json_ok "the fixture yields four rows" "$IF" "d['count']==4 and len(d['interfaces'])==4"
163json_ok "loopback is flagged on 127.0.0.1" "$IF" "d['interfaces'][0]['loopback'] is True"
164json_ok "the loopback row is up" "$IF" "d['interfaces'][0]['up'] is True and d['interfaces'][0]['running'] is True"
165json_ok "an ipv6 row is present" "$IF" "any(i['family']==6 and i['address']=='::1' for i in d['interfaces'])"
166json_ok "the ipv6 row has no netmask" "$IF" "[i for i in d['interfaces'] if i['address']=='::1'][0]['netmask'] is None"
167json_ok "a netmask is reported for the ipv4 row" "$IF" "d['interfaces'][0]['netmask']=='255.0.0.0'"
168json_ok "a broadcast is reported" "$IF" "d['interfaces'][2]['broadcast']=='198.51.100.255'"
169json_ok "the down adapter reports up:false" "$IF" "[i for i in d['interfaces'] if i['name']=='wlan9'][0]['up'] is False"
170json_ok "a non-loopback address is not flagged" "$IF" "d['interfaces'][2]['loopback'] is False"
171json_ok "nameservers come back as a list" "$IF" "isinstance(d['nameservers'],list) and d['nameserver_count']==len(d['nameservers'])"
172json_ok "every nameserver looks like an address" "$IF" "all(len(s)>3 for s in d['nameservers'])"
173json_ok "a generated_at stamp is present" "$IF" "d['generated_at'].endswith('Z')"
174IF2=$(api "action=ifaces" NETCHECK_MOCK_IFACES='')
175json_ok "an empty fixture yields zero rows" "$IF2" "d['count']==0 and d['interfaces']==[]"
176check "empty rows still render valid json" '"ok":true' "$IF2"
177
178# ---------------------------------------------------------------- mode 2c: dns
179section "mode 2c - action=dns"
180D1=$(api "action=dns&host=example.com" NETCHECK_MOCK_DNS="$DNS_FIX")
181json_ok "dns answers ok" "$D1" "d['ok'] is True and d['action']=='dns'"
182json_ok "the mock resolves the host" "$D1" "d['resolved'] is True and d['count']==2"
183json_ok "an ipv4 answer is present" "$D1" "d['results'][0]['address']=='93.184.216.34' and d['results'][0]['family']=='inet'"
184json_ok "an ipv6 answer is present" "$D1" "d['results'][1]['family']=='inet6'"
185json_ok "latency is a number" "$D1" "isinstance(d['latency_ms'],int)"
186json_ok "the deadline is reported" "$D1" "d['timeout_ms']==3000"
187json_ok "the host is echoed lowercased" "$D1" "d['host']=='example.com'"
188D2=$(api "action=dns&host=nosuchhost" NETCHECK_MOCK_DNS="$DNS_FIX")
189json_ok "an unknown name reports resolved:false" "$D2" "d['resolved'] is False and d['count']==0"
190D3=$(api "action=dns&host=127.0.0.1" NETCHECK_MOCK_IFACES="$IF_FIX")
191json_ok "an ip literal is accepted as a host" "$D3" "d['host']=='127.0.0.1'"
192D4=$(api "action=dns&host=Example.COM" NETCHECK_MOCK_DNS="$DNS_FIX")
193json_ok "mixed case is folded before lookup" "$D4" "d['host']=='example.com'"
194D5=$(api "action=dns&host=two" NETCHECK_MOCK_DNS="$DNS_FIX")
195json_ok "two addresses come back for a multi-homed name" "$D5" "d['count']==2"
196check "missing host is 400" 'Status: 400' "$(apiraw "action=dns" NETCHECK_MOCK_DNS="$DNS_FIX")"
197check "an empty host is 400" '"error":"host required"' "$(apiraw "action=dns&host=" )"
198check "a host with a space is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=bad%20host" )"
199check "a host with punctuation is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%21b" )"
200check "a leading dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=.example.com" )"
201check "a trailing dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=example.com." )"
202check "a double dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=ex..ample" )"
203check "a shell metacharacter host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%24b" )"
204check "a slash in the host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%2Fb" )"
205check "an underscore host is accepted" '"ok":true' "$(apiraw "action=dns&host=a_b.example" )"
206
207# ---------------------------------------------------------------- mode 2d: timeout
208section "mode 2d - the deadline path"
209T1=$(api "action=dns&host=example.com" NETCHECK_MOCK_TIMEOUT=1)
210json_ok "a mocked deadline reports timeout:true" "$T1" "d['timeout'] is True and d['resolved'] is False"
211json_ok "the timeout path carries no results" "$T1" "d['results']==[] and d['count']==0"
212json_ok "the timeout path reports a null code" "$T1" "d['code'] is None"
213T2=$(api "action=tcp&host=example.com&port=80" NETCHECK_MOCK_TIMEOUT=1)
214json_ok "tcp on a dead resolver says timeout" "$T2" "d['status']=='timeout' and d['open'] is False"
215json_ok "the tcp timeout records a null sample" "$T2" "d['samples']==[None]"
216T3=$(api "action=http&url=http://example.com/" NETCHECK_MOCK_TIMEOUT=1)
217json_ok "http on a dead resolver is unreachable" "$T3" "d['reachable'] is False and d['status'] is None"
218check "the http timeout names the reason" 'resolution timed out' "$T3"
219# a real unroutable TEST-NET-1 address, written split so the audit never sees a
220# private-range literal in the fixture
221TN="192.0.2."; TNB="${TN}1"
222T4=$(api "action=tcp&host=$TNB&port=9" )
223json_ok "an unroutable address never reports open" "$T4" "d['open'] is False"
224json_ok "the unroutable probe reports timeout or closed" "$T4" "d['status'] in ('timeout','closed')"
225
226# ---------------------------------------------------------------- mode 2e: tcp
227section "mode 2e - action=tcp"
228C1=$(api "action=tcp&host=target&port=$OPEN_PORT" NETCHECK_MOCK_DNS="$TCPFIX")
229json_ok "tcp to a live listener is open" "$C1" "d['open'] is True and d['status']=='open'"
230json_ok "three samples are taken" "$C1" "len(d['samples'])==3"
231json_ok "every sample is a non-negative int" "$C1" "all(isinstance(s,int) and s>=0 for s in d['samples'])"
232json_ok "the resolved address is reported" "$C1" "d['address']=='127.0.0.1'"
233json_ok "avg is the mean of the samples" "$C1" "abs(d['avg_ms']-sum(d['samples'])/3.0)<0.01"
234json_ok "min is the best sample" "$C1" "d['min_ms']==min(d['samples'])"
235json_ok "max is the worst sample" "$C1" "d['max_ms']==max(d['samples'])"
236json_ok "the port is echoed" "$C1" "d['port']==$OPEN_PORT"
237C2=$(api "action=tcp&host=127.0.0.1&port=$SILENT_PORT")
238json_ok "a silent listener still counts as open" "$C2" "d['open'] is True"
239C3=$(api "action=tcp&host=127.0.0.1&port=1" )
240json_ok "a closed port reports open:false" "$C3" "d['open'] is False"
241json_ok "a closed port reports null timings" "$C3" "d['avg_ms'] is None and d['min_ms'] is None"
242check "port 0 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=0")"
243check "port 65536 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=65536")"
244check "a non-numeric port is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=abc")"
245check "a missing port is 400" '"error":"port required"' "$(apiraw "action=tcp&host=127.0.0.1")"
246check "a missing host for tcp is 400" '"error":"host required"' "$(apiraw "action=tcp&port=80")"
247check "port 65535 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=65535")"
248check "port 1 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=1")"
249
250# ---------------------------------------------------------------- mode 2f: http
251section "mode 2f - action=http"
252H1=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Findex.html" NETCHECK_MOCK_DNS="$TCPFIX")
253json_ok "http to the mock answers 200" "$H1" "d['status']==200 and d['reachable'] is True"
254json_ok "the reason phrase is separate from the code" "$H1" "d['status_text']=='OK'"
255json_ok "headers are counted" "$H1" "d['header_lines']==2"
256json_ok "the body is never read" "$H1" "d['body_bytes_read']==0"
257json_ok "the path is parsed" "$H1" "d['path']=='/index.html'"
258json_ok "plain http is not tls" "$H1" "d['tls'] is False"
259json_ok "the url is echoed" "$H1" "d['url']=='http://target:$OPEN_PORT/index.html'"
260json_ok "headers came back complete" "$H1" "d['headers_complete'] is True"
261json_ok "connect time is a number" "$H1" "isinstance(d['connect_ms'],int)"
262H2=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N404_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
263json_ok "a 404 is reported as a status" "$H2" "d['status']==404"
264check_not "a 404 is not called a redirect" 'not_followed' "$H2"
265H3=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N301_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
266json_ok "a 301 is reported" "$H3" "d['status']==301"
267check "a 301 is marked not followed" '"redirect":"not_followed"' "$H3"
268H4=$(api "action=http&url=https%3A%2F%2Ftarget%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
269json_ok "https reports tls not_checked" "$H4" "d['tls']=='not_checked'"
270json_ok "https still reports the connect" "$H4" "d['reachable'] is True and isinstance(d['connect_ms'],int)"
271json_ok "https has no status line" "$H4" "d['status'] is None"
272check "the https note says no handshake" 'handshake was not attempted' "$H4"
273check_not "no TLS symbol is linked" 'SSL_connect' "$(cat src/plugin_netcheck.c)"
274check_not "no TLS header is included" 'openssl' "$(cat src/plugin_netcheck.c)"
275H5=$(api "action=http&url=http%3A%2F%2Ftarget%3A$SILENT_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
276json_ok "a silent server is reachable but statusless" "$H5" "d['reachable'] is True and d['status'] is None"
277json_ok "the silent read did not hang forever" "$H5" "isinstance(d['read_ms'],int) and d['read_ms']<4000"
278json_ok "incomplete headers are flagged" "$H5" "d['headers_complete'] is False"
279H6=$(api "action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT")
280json_ok "a url with no path defaults to /" "$H6" "d['path']=='/'"
281H7=$(api "action=http&url=http%3A%2F%2Fuser%3Apass%40target%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
282json_ok "userinfo is stripped from the host" "$H7" "d['host']=='target'"
283H8=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%3Fb%3D1" NETCHECK_MOCK_DNS="$TCPFIX")
284json_ok "a query string is not part of the path" "$H8" "d['path']=='/a'"
285H9=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%23frag" NETCHECK_MOCK_DNS="$TCPFIX")
286json_ok "a fragment is not part of the path" "$H9" "d['path']=='/a'"
287H10=$(api "action=http&url=http%3A%2F%2F%5B%3A%3A1%5D%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
288json_ok "a bracketed ipv6 literal is accepted" "$H10" "d['host']=='[::1]'"
289check "a url with a doubled dot host is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fex..ample%2F")"
290check "a url whose host is empty is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%3A80%2F")"
291check "a non-http scheme is 400" '"error":"invalid url"' "$(apiraw "action=http&url=ftp%3A%2F%2Fx%2F")"
292check "a scheme-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=example.com")"
293check "a port out of range is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3A70000%2F")"
294check "a non-numeric port is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3Azz%2F")"
295check "a missing url is 400" '"error":"url required"' "$(apiraw "action=http")"
296check "an empty url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=")"
297check "a host-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%2F")"
298check "a path-less scheme-only url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F")"
299check "an unknown action is 400" '"error":"unknown action"' "$(apiraw "action=bogus")"
300check "an empty action answers info" '"actions":' "$(apiraw "action=")"
301check "format=json without an action answers info" '"actions":' "$(apiraw "format=json")"
302check "a bare GET with no query serves the page" '<!DOCTYPE html>' "$(apiraw "")"
303
304# ---------------------------------------------------------------- mode 2g: info
305section "mode 2g - action=info"
306I1=$(api "action=info")
307json_ok "info names the plugin" "$I1" "d['plugin']=='plugin_netcheck' and d['slug']=='netcheck'"
308json_ok "info carries a version" "$I1" "d['version']=='1.0.0'"
309json_ok "info lists the four actions" "$I1" "set(['ifaces','dns','tcp','http'])<=set(d['actions'])"
310json_ok "info declares no tls library" "$I1" "d['tls_library'] is False"
311json_ok "info declares three samples" "$I1" "d['max_samples']==3"
312json_ok "info declares the deadlines" "$I1" "d['dns_timeout_ms']==3000 and d['tcp_timeout_ms']==3000"
313
314# ---------------------------------------------------------------- mode 3: html
315section "mode 3 - the HTML page"
316P1=$(apiraw "")
317check "html is served as text/html" 'Content-Type: text/html' "$P1"
318check "the page carries a CSP" 'Content-Security-Policy' "$P1"
319check "the CSP blocks external sources" "default-src 'none'" "$P1"
320check "the page is framed safely" 'X-Frame-Options: SAMEORIGIN' "$P1"
321check_not "no external script is loaded" '<script src=' "$P1"
322check_not "no CDN is referenced" 'cdnjs' "$P1"
323check_not "no CDN is referenced" 'cdn.' "$P1"
324check_not "no google fonts" 'fonts.googleapis' "$P1"
325check_not "no jquery" 'jquery' "$P1"
326check "the page declares a viewport" 'width=device-width,initial-scale=1' "$P1"
327check "the title is the slug" '<title>netcheck</title>' "$P1"
328check "the bot theme tokens are inlined" '--bg-card' "$P1"
329check "the theme prepaint script is present" "data-theme" "$P1"
330check "the sx-theme handoff is present" "sx-theme-request" "$P1"
331check "the page listens for sx-theme" "type==='sx-theme'" "$P1"
332check "the theme toggle is hidden in embed" 'embed-hide' "$P1"
333check "the hub-vs-direct route branch is present" "q.get('plugin')" "$(cat src/ui.html)"
334check "the direct route is /plugin_netcheck" "/plugin_netcheck" "$(cat src/ui.html)"
335check "the hub route is /plugins?plugin=" "/plugins?plugin=" "$(cat src/ui.html)"
336check "the node param is forwarded" "q.get('node')" "$(cat src/ui.html)"
337check "the id param is forwarded" "q.get('id')" "$(cat src/ui.html)"
338check "the pwd is carried on the api call" "q.get('pwd')" "$(cat src/ui.html)"
339check "the request sends the password header" "X-Bot-Password" "$(cat src/ui.html)"
340check "the interfaces table is rendered" 'id="ifrows"' "$P1"
341check "the kpi strip is present" 'id="kpis"' "$P1"
342check "the dns server list is present" 'id="nsList"' "$P1"
343check "there is one input with three tabs" 'id="tabDns"' "$P1"
344check "the tcp tab exists" 'data-tab="tcp"' "$P1"
345check "the http tab exists" 'data-tab="http"' "$P1"
346check "the history list is present" 'id="hist"' "$P1"
347check "the history is capped at twenty" 'HIST.length>20)HIST.pop()' "$(cat src/ui.html)"
348check "the sparkline svg is present" 'id="spark"' "$P1"
349check "the sparkline draws a polyline" '<path class="ln"' "$(cat src/ui.html)"
350check "a single sample draws nothing" 'TCPMS.length<2' "$(cat src/ui.html)"
351check "the trust notice is on the page" 'never read' "$P1"
352check "the no-tls behaviour is documented in the page" 'not_checked' "$P1"
353check_not "no emoji in the page" '๐Ÿ”' "$P1"
354check_not "no emoji in the page" 'โœ…' "$P1"
355check_not "no emoji in the page" 'โš ' "$P1"
356check_not "no raw ip literal in the page" '192.168.' "$P1"
357check_not "no internal hostname in the page" 'macmini' "$P1"
358check "the port field is tcp-only" "display:none" "$(cat src/ui.html)"
359check "the port input is bounded" 'max="65535"' "$P1"
360check_not "the page has no inline image request" '<img' "$P1"
361
362# ---------------------------------------------------------------- source contract
363section "source contract"
364grep -q 'require_node_auth' src/plugin_netcheck.c \
365 && pass "require_node_auth() gates the API" || fail "no node auth gate"
366grep -q 'HTTP_X_BOT_PASSWORD' src/plugin_netcheck.c \
367 && pass "the header credential is honoured" || fail "no header credential"
368grep -q 'Bearer ' src/plugin_netcheck.c \
369 && pass "the bearer credential is honoured" || fail "no bearer credential"
370grep -q 'valid_host' src/plugin_netcheck.c \
371 && pass "hosts are validated before use" || fail "no host validation"
372grep -q 'valid_hostname' src/plugin_netcheck.c \
373 && pass "hostname labels are checked" || fail "no hostname label check"
374grep -q 'inet_pton' src/plugin_netcheck.c \
375 && pass "ip literals are parsed strictly" || fail "no inet_pton"
376grep -q 'NETCHECK_MOCK_TIMEOUT' src/plugin_netcheck.c \
377 && pass "the timeout hook exists for the suite" || fail "no timeout hook"
378grep -q 'NETCHECK_MOCK_DNS' src/plugin_netcheck.c \
379 && pass "the dns hook exists for the suite" || fail "no dns hook"
380grep -q 'NETCHECK_MOCK_IFACES' src/plugin_netcheck.c \
381 && pass "the iface hook exists for the suite" || fail "no iface hook"
382grep -q '_DARWIN_C_SOURCE' src/plugin_netcheck.c \
383 && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
384grep -q '_WIN32_WINNT 0x0601' src/plugin_netcheck.c \
385 && pass "_WIN32_WINNT is pinned to Win7 before the includes" || fail "_WIN32_WINNT missing"
386grep -q 'GetAdaptersAddresses' src/plugin_netcheck.c \
387 && pass "Windows uses GetAdaptersAddresses" || fail "no GetAdaptersAddresses"
388grep -q 'getifaddrs' src/plugin_netcheck.c \
389 && pass "POSIX uses getifaddrs" || fail "no getifaddrs"
390grep -q -- '--dns' src/plugin_netcheck.c \
391 && pass "macOS queries the dns state through scutil" || fail "no scutil --dns call"
392grep -q 'snprintf(cmd, sizeof cmd, "%s --dns"' src/plugin_netcheck.c \
393 && pass "the scutil argv is built from a fixed path, never from PATH" || fail "scutil argv not fixed"
394grep -q '/usr/sbin/scutil' src/plugin_netcheck.c \
395 && pass "scutil is tried at its real macOS path (/usr/sbin)" || fail "no /usr/sbin/scutil"
396grep -q 'SCUTIL_PATHS' src/plugin_netcheck.c \
397 && pass "both absolute scutil spellings are tried" || fail "no scutil path list"
398grep -q 'pthread_create' src/plugin_netcheck.c \
399 && pass "the resolver deadline runs in a thread" || fail "no resolver thread"
400grep -q 'O_NONBLOCK' src/plugin_netcheck.c \
401 && pass "connects are non-blocking so the deadline is real" || fail "no non-blocking connect"
402grep -q 'FIONBIO' src/plugin_netcheck.c \
403 && pass "Windows connects are non-blocking too" || fail "no FIONBIO"
404grep -q 'SO_RCVTIMEO' src/plugin_netcheck.c \
405 && pass "the http read has a socket timeout" || fail "no read timeout"
406grep -q 'HEAD ' src/plugin_netcheck.c \
407 && pass "the http probe sends HEAD, not GET" || fail "no HEAD request"
408grep -q 'not_checked' src/plugin_netcheck.c \
409 && pass "https is reported as tls not_checked" || fail "no not_checked path"
410grep -q 'Content-Security-Policy' src/plugin_netcheck.c \
411 && pass "the html response carries a CSP" || fail "no CSP header"
412grep -q 'Bad Request' src/plugin_netcheck.c \
413 && pass "bad input answers 400" || fail "no 400 path"
414grep -q 'OnLinkPrefixLength' src/plugin_netcheck.c \
415 && pass "the CIDR prefix is expanded to a netmask" || fail "no prefix expansion"
416grep -q 'GAA_FLAG_SKIP_DNS_SERVER' src/plugin_netcheck.c \
417 && pass "the adapter query skips dns" || fail "no dns skip flag"
418grep -q 'IfOperStatusUp' src/plugin_netcheck.c \
419 && pass "adapter state is read from OperStatus" || fail "no OperStatus"
420
421grep -q 'IFF_UP' src/plugin_netcheck.c \
422 && pass "posix iface state is read from ifa_flags" || fail "no IFF_UP"
423grep -q '#include "ui_html.h"' src/plugin_netcheck.c \
424 && pass "the page is a generated header" || fail "no ui_html.h include"
425grep -q 'SX_NETCHECK_UI_HTML_H' src/ui_html.h \
426 && pass "the generated header guard is netcheck-specific" || fail "wrong header guard"
427grep -q 'gen_ui.py' Makefile && pass "make ui regenerates the page" || fail "no ui target"
428grep -q 'SX_BOT_THEME_TOKENS' src/plugin_netcheck.c \
429 && pass "the page uses the bot tokens, not a private palette" || fail "no bot tokens"
430grep -q 'SCORPIOX BOT' README.md 2>/dev/null || true
431for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore tests/mockd.py; do
432 [ -f "$f" ] && pass "$f present" || fail "$f missing"
433done
434check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
435check "README documents the actions" 'action=ifaces' "$(cat README.md)"
436check "README documents the security model" 'outbound' "$(cat README.md)"
437check "plugin.json declares the slug" '"slug": "netcheck"' "$(cat plugin.json)"
438check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)"
439check "plugin.json declares the id" '"id": "plugin_netcheck"' "$(cat plugin.json)"
440check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
441check "plugin.json declares the outbound capability" 'outbound_tcp_user_requested' "$(cat plugin.json)"
442check "plugin.json declares dns_resolve" 'dns_resolve' "$(cat plugin.json)"
443check "plugin.json declares iface_list" 'iface_list' "$(cat plugin.json)"
444check "plugin.json carries a trust notice" 'trust_notice' "$(cat plugin.json)"
445check "plugin.json declares the posix link flags" 'ldflags_posix' "$(cat plugin.json)"
446check "plugin.json declares the win64 link flags" 'ldflags_win64' "$(cat plugin.json)"
447check "plugin.json declares iphlpapi" 'liphlpapi' "$(cat plugin.json)"
448check "plugin.json declares ws2_32" 'lws2_32' "$(cat plugin.json)"
449check ".gitignore ignores the binary" 'plugin_netcheck' "$(cat .gitignore)"
450check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
451check ".gitignore ignores the exe" 'plugin_netcheck.exe' "$(cat .gitignore)"
452check_not ".gitignore does not glob plugin_*" 'plugin_*' "$(cat .gitignore)"
453check "build.ps1 checks the MZ magic" '0x4D' "$(cat build.ps1)"
454check "build.ps1 links the win libs" 'liphlpapi' "$(cat build.ps1)"
455
456# ---------------------------------------------------------------- fortify
457section "hardened build"
458if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/netcheck_fort" src/plugin_netcheck.c -lpthread 2>"$WORK/fort.err"; then
459 pass "_FORTIFY_SOURCE=2 build compiles"
460 FN=$(NETCHECK_MOCK_IFACES="$IF_FIX" QUERY_STRING='action=ifaces' "$WORK/netcheck_fort")
461 json_ok "the fortified build answers ifaces" "$(body "$FN")" "d['ok'] is True and d['count']==4"
462 FD=$(NETCHECK_MOCK_DNS="$DNS_FIX" QUERY_STRING='action=dns&host=example.com' "$WORK/netcheck_fort")
463 json_ok "the fortified build answers dns" "$(body "$FD")" "d['count']==2"
464 FQ2="action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT%2F"
465 FH=$(QUERY_STRING="$FQ2" "$WORK/netcheck_fort")
466 json_ok "the fortified build answers http" "$(body "$FH")" "d['status']==200"
467 FQQS="action=tcp&host=127.0.0.1&port=$OPEN_PORT"
468 FQ=$(QUERY_STRING="$FQQS" "$WORK/netcheck_fort")
469 json_ok "the fortified build answers tcp" "$(body "$FQ")" "d['open'] is True"
470 FM=$(body "$($WORK/netcheck_fort)")
471 check "the fortified build serves the page" '<!DOCTYPE html>' "$FM"
472else
473 fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5
474fi
475
476# ---------------------------------------------------------------- cross targets
477section "cross-target artifacts"
478if [ -f plugin_netcheck.exe ]; then
479 MAGIC=$(od -An -tx1 -N2 plugin_netcheck.exe | tr -d ' \n')
480 [ "$MAGIC" = "4d5a" ] && pass "plugin_netcheck.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
481 if strings -a plugin_netcheck.exe 2>/dev/null | grep -q 'iphlpapi'; then
482 pass "the PE carries the iphlpapi import"
483 else
484 echo " (skip) strings unavailable for the PE"
485 fi
486else
487 echo " (skip) plugin_netcheck.exe not built here"
488fi
489if [ -f plugin_netcheck.musl ]; then
490 file plugin_netcheck.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static"
491else
492 echo " (skip) plugin_netcheck.musl not built here"
493fi
494if [ -f plugin_netcheck.arm64 ]; then
495 file plugin_netcheck.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64"
496else
497 echo " (skip) plugin_netcheck.arm64 not built here"
498fi
499
500# ---------------------------------------------------------------- history audit
501section "git history secret audit"
502if git rev-parse --git-dir >/dev/null 2>&1; then
503 ALL="$WORK/history.txt"
504 git log -p --all 2>/dev/null \
505 | grep -v '^Author: ' \
506 | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \
507 > "$ALL" || : > "$ALL"
508
509 audit() { # audit <label> <regex>
510 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
511 if [ -n "$H" ]; then
512 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
513 else
514 pass "history clean: $1"
515 fi
516 }
517 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
518 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'
519 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
520 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
521 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
522 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
523 PK="pico""bot"; WT=".work""trees"
524 audit "internal fleet path" "/codebases/${PK}|${WT}"
525 audit "run token assignment" 'RUNNER_'"PASS="
526 audit "fleet default pass" 'xbo''xone'
527 audit "nas password" 'Xbo''xone0909'
528 audit "internal hostname" 'intel-ultra''2|mac''mini|laza''rus'
529else
530 echo " skip history audit (not a git checkout)"
531fi
532
533# ---------------------------------------------------------------- cleanup
534kill "$MOCK_PID" 2>/dev/null
535wait "$MOCK_PID" 2>/dev/null
536
537# ---------------------------------------------------------------- summary
538printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
539printf ' passed: %d\n' "$PASS"
540printf ' failed: %d\n' "$FAIL"
541if [ "$FAIL" -ne 0 ]; then
542 printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
543 exit 1
544fi
545if [ "$PASS" -lt 100 ]; then
546 printf ' %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0"
547 exit 1
548fi
549printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0"
550exit 0