scorpiox-bot-plugin-sqlite
←run.shbash
503 lines · 25 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_sqlite across all 3 modes.
3#
4# Builds a throwaway SQLite database in a temp directory, points the plugin at
5# it with SQLITE_ALLOWED_ROOT, and proves:
6# * discovery, schema and query all answer with well-formed JSON
7# * the read-only contract holds (INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/
8# CREATE are refused, both by the statement guard and by the authorizer)
9# * path traversal, system paths and SQLite URI filenames are refused
10# * the row cap and the statement time budget actually bite
11# * node auth (401 / X-Bot-Password / Bearer / ?pwd=) behaves
12# * the musl static build and the Windows PE are the right kind of file
13# * the whole git history carries no secret and no LAN IP
14#
15# If musl / arm64 / Win64 artifacts are present they are checked too.
16# Exit code 0 = everything passed.
17
18set -u
19
20ROOT=$(cd "$(dirname "$0")/.." && pwd)
21cd "$ROOT" || exit 1
22
23BIN=./plugin_sqlite
24PASS=0
25FAIL=0
26
27if [ -t 1 ]; then
28 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
29else
30 C_OK=; C_BAD=; C_B=; C_0=
31fi
32pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
33fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
34
35check() { # check <desc> <expected-substring> <actual>
36 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
37 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
38 fi
39}
40
41check_not() { # check_not <desc> <forbidden-substring> <actual>
42 if printf '%s' "$3" | grep -F -q -- "$2"; then
43 fail "$1 (must NOT contain: $2)"; else pass "$1"
44 fi
45}
46
47section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
48
49# Strip the CGI header block, leaving the body.
50body() { printf '%s' "$1" | sed '1,/^\r$/d'; }
51
52[ -x "$BIN" ] || { printf '%smissing %s - run make first%s\n' "$C_BAD" "$BIN" "$C_0" >&2; exit 1; }
53
54TMP=$(mktemp -d 2>/dev/null || echo "/tmp/plugin_sqlite_test.$$")
55mkdir -p "$TMP"
56trap 'rm -rf "$TMP"' EXIT 2>/dev/null || true
57
58# Export so every invocation below sees a narrow, predictable allowlist.
59SQLITE_ALLOWED_ROOT="$TMP"; export SQLITE_ALLOWED_ROOT
60
61# ---------------------------------------------------------------- fixture
62section "fixture"
63if ! command -v python3 >/dev/null 2>&1; then
64 printf '%sFAIL%s python3 is required to build the test database\n' "$C_BAD" "$C_0" >&2
65 exit 1
66fi
67
68python3 - "$TMP" <<'PY' || exit 1
69import sqlite3, sys, os
70tmp = sys.argv[1]
71db = os.path.join(tmp, "shop.sqlite")
72if os.path.exists(db):
73 os.remove(db)
74c = sqlite3.connect(db)
75c.executescript("""
76CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
77CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
78 total REAL, note BLOB, created TEXT);
79CREATE INDEX idx_orders_cust ON orders(customer_id);
80CREATE VIEW big_orders AS SELECT * FROM orders WHERE total > 100;
81INSERT INTO customers(name,email) VALUES ('Ada','ada@example.com'),('Bo',NULL);
82""")
83for i in range(1200):
84 c.execute("INSERT INTO orders(customer_id,total,note,created) VALUES(?,?,?,?)",
85 (1 + (i % 2), (i % 500) + 0.5, b"\x01\x02", "2026-03-%02d" % (i % 28 + 1)))
86c.commit()
87c.close()
88open(os.path.join(tmp, "notes.txt"), "w").write("not a database\n")
89open(os.path.join(tmp, "fake.db"), "w").write("this is definitely not sqlite\n")
90print(" fixture: %s (%d bytes)" % (db, os.path.getsize(db)))
91PY
92[ -f "$TMP/shop.sqlite" ] && pass "test database created" || { fail "test database missing"; exit 1; }
93
94DB="$TMP/shop.sqlite"
95
96# ---------------------------------------------------------------- mode 1
97section "mode 1 --meta"
98META=$("$BIN" --meta)
99check "meta emits name sqlite" '"name":"sqlite"' "$META"
100check "meta emits desc SQLite viewer" '"desc":"SQLite viewer"' "$META"
101METAENV=$(SX_PLUGIN_META=1 "$BIN")
102check "SX_PLUGIN_META=1 yields same meta" '"name":"sqlite"' "$METAENV"
103LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
104[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
105printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
106 && pass "meta is valid JSON" || fail "meta is not valid JSON"
107DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
108[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
109NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
110[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
111check "--version prints version" '1.0.3' "$("$BIN" --version)"
112
113# ------------------------------------------------- CGI framing (Windows trap)
114# MinGW/MSVC CRT stdout defaults to TEXT mode, rewriting every \n into \r\n.
115# A CGI header block must end with exactly CRLF CRLF; text mode yields
116# CR CR LF CR CR LF, scorpiox-server cannot find the header/body separator and
117# the reply comes back mangled. Live-confirmed on a Windows NTFS node
118# (2026-11-12) with the shipped 1.0.2 windows-x86_64 artifact.
119section "CGI header framing (no CR CR LF)"
120FRAMETMP=$(mktemp)
121cgi_hex() { od -An -tx1 "$1" | tr -s ' \t\n' ' '; }
122cgi_frame_check() { # cgi_frame_check <desc> <query>
123 BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="$2" "$BIN" > "$FRAMETMP"
124 H=$(cgi_hex "$FRAMETMP")
125 case " $H " in *" 0d 0d 0a "*) fail "$1: found CR CR LF (text-mode stdout)"; return;; esac
126 case " $H " in *" 0d 0a 0d 0a "*) pass "$1: exact CRLF CRLF header separator";;
127 *) fail "$1: no CRLF CRLF separator found";;
128 esac
129}
130cgi_frame_check "html mode framing" ""
131cgi_frame_check "dbs action framing" "action=dbs"
132cgi_frame_check "info action framing" "action=info"
133rm -f "$FRAMETMP"
134check "--version names the sqlite lib" 'sqlite 3.' "$("$BIN" --version)"
135check "--help is available" 'usage:' "$("$BIN" --help)"
136META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
137check "meta still works when BOT_PASSWORD is set" '"name":"sqlite"' "$META_AUTH"
138
139# ---------------------------------------------------------------- auth
140section "node auth"
141AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
142check "no credentials -> 401" 'Status: 401' "$AUTHNONE"
143check "401 body is json" 'invalid node password' "$AUTHNONE"
144AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
145check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")"
146AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=info' "$BIN")
147check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")"
148AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=info&pwd=testpw' "$BIN")
149check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")"
150AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=info' "$BIN")
151check "wrong password -> 401" 'Status: 401' "$AUTHBAD"
152HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
153check "html mode is also gated" 'Status: 401' "$HTMLAUTH"
154
155# ---------------------------------------------------------------- dbs
156section "mode 2 action=dbs"
157DBS=$(body "$(QUERY_STRING='action=dbs' "$BIN")")
158printf '%s' "$DBS" > "$TMP/dbs.json"
159check "dbs ok:true" '"ok":true' "$DBS"
160check "dbs names the plugin" '"plugin":"plugin_sqlite"' "$DBS"
161check "dbs declares read-only" '"readonly":true' "$DBS"
162check "dbs carries the allowed root" "$TMP" "$DBS"
163check "dbs finds our database" 'shop.sqlite' "$DBS"
164check "dbs reports a count" '"count":' "$DBS"
165check "dbs reports per-root fields" '"scanned_entries":' "$DBS"
166check "dbs declares the scan cap" '"max_scan_entries":' "$DBS"
167printf '%s' "$DBS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
168 && pass "dbs body is valid JSON" || fail "dbs body JSON invalid"
169python3 - "$TMP/dbs.json" <<'PYEOF' && pass "dbs rows are well formed" || fail "dbs rows malformed"
170import json, sys
171d = json.load(open(sys.argv[1]))
172assert d["ok"] is True
173assert d["count"] == len(d["dbs"])
174assert d["count"] >= 1
175names = [x["path"] for x in d["dbs"]]
176assert any(p.endswith("shop.sqlite") for p in names), names
177assert not any(p.endswith("notes.txt") for p in names), names
178for x in d["dbs"]:
179 assert x["bytes"] > 0
180 assert x["root"]
181 assert x["mtime"].endswith("Z")
182for r in d["roots"]:
183 for k in ("label", "path", "exists", "dbs", "scanned_entries", "truncated"):
184 assert k in r, (k, r)
185 assert isinstance(r["dbs"], int) and r["dbs"] >= 0
186 assert isinstance(r["scanned_entries"], int) and r["scanned_entries"] >= 0
187 assert isinstance(r["truncated"], bool)
188assert d["max_scan_entries"] > 0
189PYEOF
190check_not "dbs ignores non-db files" 'notes.txt' "$DBS"
191
192# Every allowlisted root must get its own scan budget. One global counter let a
193# large tree exhaust the allowance before the walk reached $HOME, so a database
194# in the home directory was simply invisible. SQLITE_SCAN_BUDGET shrinks the
195# allowance so a five-directory fixture can prove it.
196BIGDIR="$TMP/bigtree"
197mkdir -p "$BIGDIR"
198for i in 1 2 3 4 5 6 7 8 9; do mkdir -p "$BIGDIR/f$i"; done
199ROOTRUN=$(SQLITE_ALLOWED_ROOT="$BIGDIR" SQLITE_SCAN_BUDGET=4 QUERY_STRING='action=dbs' "$BIN" | sed '1,/^\r$/d')
200check "dbs reports per-root scan counts" '"scanned_entries":' "$ROOTRUN"
201check "dbs flags the truncated root" '"truncated":true' "$ROOTRUN"
202HOMEHIT=$(printf '%s' "$ROOTRUN" | python3 -c '
203import json, sys
204d = json.load(sys.stdin)
205labels = {r["label"]: r for r in d["roots"]}
206assert labels["allowed"]["truncated"] is True, labels["allowed"]
207home = labels.get("home")
208assert home is not None, labels
209if home["exists"]:
210 assert home["scanned_entries"] > 0 or home["dbs"] > 0, home
211 print("home_walked", home["scanned_entries"])
212' 2>/dev/null)
213case "$HOMEHIT" in
214home_walked*) pass "home is still walked after a truncated root" ;;
215*) fail "home was skipped after a truncated root (got: $HOMEHIT)" ;;
216esac
217
218# ---------------------------------------------------------------- schema
219section "mode 2 action=schema"
220SCHEMA=$(body "$(QUERY_STRING="action=schema&db=$DB" "$BIN")")
221printf '%s' "$SCHEMA" > "$TMP/schema.json"
222check "schema ok:true" '"ok":true' "$SCHEMA"
223check "schema names the database" "$DB" "$SCHEMA"
224check "schema lists customers" '"name":"customers"' "$SCHEMA"
225check "schema lists orders" '"name":"orders"' "$SCHEMA"
226check "schema marks the view" '"type":"view"' "$SCHEMA"
227check "schema reports the index" 'idx_orders_cust' "$SCHEMA"
228check "schema has column detail" '"notnull":true' "$SCHEMA"
229python3 - "$TMP/schema.json" <<'PYEOF' && pass "schema rows are well formed" || fail "schema malformed"
230import json, sys
231d = json.load(open(sys.argv[1]))
232assert d["ok"] is True and d["readonly"] is True
233tables = {t["name"]: t for t in d["tables"]}
234assert "customers" in tables and "orders" in tables and "big_orders" in tables
235assert tables["orders"]["rows"] == 1200, tables["orders"]["rows"]
236assert tables["customers"]["rows"] == 2
237cols = {c["name"]: c for c in tables["orders"]["columns"]}
238assert cols["customer_id"]["type"] == "INTEGER"
239assert [i["name"] for i in tables["orders"]["indexes"]] == ["idx_orders_cust"]
240assert tables["customers"]["type"] == "table"
241assert tables["big_orders"]["type"] == "view"
242PYEOF
243SCHEMA_MISS=$(body "$(QUERY_STRING="action=schema&db=$TMP/nope.sqlite" "$BIN")")
244SCHEMA_FAKE=$(body "$(QUERY_STRING="action=schema&db=$TMP/fake.db" "$BIN")")
245check "non-sqlite file -> not_a_database" 'not_a_database' "$SCHEMA_FAKE"
246
247# ---------------------------------------------------------------- query
248section "mode 2 action=query (allowed)"
249Q1=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
250check "count(*) works" '[[1200]]' "$Q1"
251check "query reports row_count" '"row_count":1' "$Q1"
252check "query reports elapsed ms" '"ms":' "$Q1"
253check "query reports column types" '"types":["int"]' "$Q1"
254
255Q2=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+name,email+from+customers+order+by+id" "$BIN")")
256check "text values are quoted" '"Ada"' "$Q2"
257check "NULL becomes json null" 'null' "$Q2"
258
259Q3=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+total,note+from+orders+limit+1" "$BIN")")
260check "real numbers are emitted" '"total"' "$Q3"
261check "blobs become a hex preview" '"blob_bytes":2' "$Q3"
262check "blob hex is the real bytes" '"hex":"0102"' "$Q3"
263
264Q4=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+table_info(orders)" "$BIN")")
265check "read-only pragma runs" '"customer_id"' "$Q4"
266
267Q5=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+integrity_check" "$BIN")")
268check "integrity_check runs" '"ok"' "$Q5"
269
270Q6=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+o+AS+(SELECT+id+FROM+orders)+SELECT+count(*)+FROM+o" "$BIN")")
271check "WITH / CTE select works" '[[1200]]' "$Q6"
272
273Q7=$(body "$(QUERY_STRING="action=query&db=$DB&sql=explain+select+1" "$BIN")")
274check "EXPLAIN works" '"ok":true' "$Q7"
275
276# POST-style body parsing
277printf 'sql=select+42+as+answer' > "$TMP/body.txt"
278Q8=$(body "$(HTTP_BODY_FILE="$TMP/body.txt" QUERY_STRING="action=query&db=$DB" "$BIN")")
279check "POST body sql= is parsed" '[[42]]' "$Q8"
280
281# ---------------------------------------------------------------- row cap
282section "row cap and time budget"
283CAP=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+*+from+orders" "$BIN")")
284check "unbounded select is capped" '"row_count":500' "$CAP"
285check "cap is flagged as truncated" '"truncated":true' "$CAP"
286check "cap declares the limit" '"limit":500' "$CAP"
287printf '%s' "$CAP" | python3 -c '
288import json,sys
289d = json.load(sys.stdin)
290assert len(d["rows"]) == 500, len(d["rows"])
291assert d["row_count"] == 500
292' 2>/dev/null && pass "exactly 500 rows were streamed" || fail "row cap did not produce 500 rows"
293
294BUDGET=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+RECURSIVE+c(i)+AS(SELECT+1+UNION+ALL+SELECT+i%2B1+FROM+c+WHERE+i%3C30000000)+SELECT+count(*)+FROM+c" "$BIN")")
295check "runaway recursion is stopped" '"aborted":true' "$BUDGET"
296
297# ---------------------------------------------------------------- read-only
298section "read-only enforcement"
299deny() { # deny <desc> <sql>
300 local out
301 out=$(body "$(QUERY_STRING="action=query&db=$DB&sql=$2" "$BIN")")
302 case "$out" in
303 *'"ok":false'*) pass "$1 rejected" ;;
304 *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
305 esac
306}
307deny "INSERT" "insert+into+customers(name)+values('x')"
308deny "UPDATE" "update+customers+set+name='x'"
309deny "DELETE" "delete+from+customers"
310deny "DROP TABLE" "drop+table+orders"
311deny "ALTER TABLE" "alter+table+orders+add+column+x+int"
312deny "CREATE TABLE" "create+table+x(a)"
313deny "CREATE VIEW" "create+view+v+as+select+1"
314deny "ATTACH" "attach+%27$TMP%2Fevil.db%27+as+evil"
315deny "DETACH" "detach+main"
316deny "REINDEX" "reindex"
317deny "VACUUM" "vacuum"
318deny "BEGIN" "begin"
319deny "PRAGMA write" "pragma+user_version%3D5"
320deny "stacked stmt" "select+1%3B+drop+table+orders"
321deny "WITH-DELETE" "WITH+x+AS(SELECT+1)+DELETE+FROM+customers"
322
323# Row-count evidence that nothing above actually mutated the file.
324AFTER=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
325check "orders still has 1200 rows" '[[1200]]' "$AFTER"
326AFTER_C=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+customers" "$BIN")")
327check "customers still has 2 rows" '[[2]]' "$AFTER_C"
328[ ! -f "$TMP/evil.db" ] && pass "ATTACH created no file" || fail "ATTACH created $TMP/evil.db"
329
330# The authorizer is the second line of defence; prove it fires directly.
331python3 - "$DB" <<'PY' && pass "on-disk mtime proves no write happened" || fail "database file changed"
332import os, sqlite3, sys, time
333db = sys.argv[1]
334before = os.stat(db).st_mtime
335c = sqlite3.connect(db)
336c.execute("SELECT count(*) FROM orders").fetchone()
337c.close()
338assert os.stat(db).st_mtime == before
339PY
340
341# ---------------------------------------------------------------- paths
342section "path discipline"
343bad_path() { # bad_path <desc> <db-query-value>
344 local out
345 out=$(body "$(QUERY_STRING="action=query&db=$2&sql=select+1" "$BIN")")
346 case "$out" in
347 *forbidden_path*) pass "$1 rejected" ;;
348 *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
349 esac
350}
351bad_path "/etc/passwd" "/etc/passwd"
352bad_path "../ traversal" "$TMP/../../etc/passwd"
353bad_path "encoded traversal" "$TMP/%2e%2e/%2e%2e/etc/passwd"
354bad_path "SQLite URI filename" "file:$DB"
355bad_path "URI with mode=rwc" "file:$DB%3Fmode%3Drwc"
356bad_path "http scheme" "http://example.com/x.db"
357bad_path "non-db suffix" "$TMP/notes.txt"
358bad_path "arbitrary root" "/etc/hosts.db"
359
360MISSING=$(body "$(QUERY_STRING="action=query&db=$TMP/absent.sqlite&sql=select+1" "$BIN")")
361check "allowed location, missing file -> not_found" 'not_found' "$MISSING"
362
363# ---------------------------------------------------------------- misc
364section "mode 2 misc"
365INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
366check "info names the plugin" '"plugin":"plugin_sqlite"' "$INFO"
367check "info names the sqlite version" '"sqlite":"3.' "$INFO"
368check "info declares read-only" '"readonly":true' "$INFO"
369check "info declares zero_network" '"zero_network":true' "$INFO"
370check "info declares no extension load" '"load_extension":false' "$INFO"
371check "info lists the actions" '"dbs","schema","query","info"' "$INFO"
372check "info declares max_rows" '"max_rows":500' "$INFO"
373
374UNK=$(body "$(QUERY_STRING='action=nope' "$BIN")")
375check "unknown action is refused" 'unknown_action' "$UNK"
376JSONF=$(body "$(QUERY_STRING='format=json' "$BIN")")
377check "format=json falls back to dbs" '"action":"dbs"' "$JSONF"
378NOSQL=$(body "$(QUERY_STRING="action=query&db=$DB" "$BIN")")
379check "query without sql -> missing_sql" 'missing_sql' "$NOSQL"
380
381# ---------------------------------------------------------------- mode 3
382section "mode 3 html"
383HTML=$("$BIN")
384check "html content type" 'Content-Type: text/html' "$HTML"
385check "html has a doctype" '<!DOCTYPE html>' "$HTML"
386check "html titles the tool" '<title>sqlite</title>' "$HTML"
387check "html ships the sql editor" "id='sql'" "$HTML"
388check "html ships the db picker" "id='dbsel'" "$HTML"
389check "html shows which roots were walked" "id='rootline'" "$HTML"
390check "html ships the result grid" "id='reswrap'" "$HTML"
391check "html supports ctrl+enter" 'Ctrl' "$HTML"
392check "html offers CSV copy" 'Copy CSV' "$HTML"
393check "html offers JSON copy" 'Copy JSON' "$HTML"
394check "html declares the node route" '/plugin_sqlite?action=' "$HTML"
395check "html declares the hub route" "/plugins?plugin=" "$HTML"
396check "html honours embed" "/plugin_sqlite?action=" "$HTML"
397check "html supports light theme" "data-theme=light" "$HTML"
398
399# ---- theme handoff (bot_theme_plugin.h) ----
400# the bot owns the theme: ?theme= before first paint, sx-theme after it
401check "html reads ?theme= before paint" 'theme=(light|dark)' "$HTML"
402check "html listens for sx-theme" "d.type==='sx-theme'" "$HTML"
403check "html asks the host for the theme" "sx-theme-request" "$HTML"
404check "html uses bot token --bg-card" "--bg-card" "$HTML"
405check "html uses bot token --surface-2" "--surface-2" "$HTML"
406check "html uses bot token --text-2" "--text-2" "$HTML"
407check "html hides its toggle when embedded" "embed-hide" "$HTML"
408check_not "html no retired brand casing" 'Scorpio'"X Bot" "$HTML"
409check_not "html no private palette 0b0b0e" '0b0b0e' "$HTML"
410check_not "html no private palette 141419" '141419' "$HTML"
411check_not "html no private palette f2f2f6" 'f2f2f6' "$HTML"
412THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
413check "?theme=light still renders the UI" 'prefers-color-scheme' "$THEMEQ"
414# ---- end theme handoff ----
415
416check_not "html has no CDN script" '<script src=' "$HTML"
417check_not "html has no cdnjs" 'cdnjs' "$HTML"
418check_not "html emits no Content-Length" 'Content-Length' "$HTML"
419EMBED=$("$BIN" </dev/null 2>/dev/null | head -1)
420EMBEDQ=$(QUERY_STRING='embed=1' "$BIN")
421check_not "embed=1 drops the back link" 'Back to Bot' "$EMBEDQ"
422check "non-embed keeps the back link" 'Back to Bot' "$HTML"
423
424# ---------------------------------------------------------------- artifacts
425section "cross builds"
426if [ -f plugin_sqlite.musl ]; then
427 MAGIC=$(od -An -tx1 -N4 plugin_sqlite.musl | tr -d ' \n')
428 [ "$MAGIC" = "7f454c46" ] && pass "musl artifact is an ELF" || fail "musl artifact is not ELF ($MAGIC)"
429 python3 - plugin_sqlite.musl <<'PY' && pass "musl artifact is x86_64 (EM_X86_64=62)" || fail "musl artifact wrong machine"
430import sys, struct
431d = open(sys.argv[1], "rb").read(20)
432assert d[4] == 2, "not 64-bit"
433assert d[5] == 1, "not little-endian"
434assert struct.unpack("<H", d[18:20])[0] == 62
435PY
436 if command -v readelf >/dev/null 2>&1; then
437 readelf -d plugin_sqlite.musl 2>/dev/null | grep -q NEEDED \
438 && fail "musl artifact is dynamically linked" || pass "musl artifact is fully static"
439 fi
440else
441 printf ' skip musl artifact (not built)\n'
442fi
443
444if [ -f plugin_sqlite.arm64 ]; then
445 python3 - plugin_sqlite.arm64 <<'PY' && pass "arm64 artifact is EM_AARCH64 (183)" || fail "arm64 artifact wrong machine"
446import sys, struct
447d = open(sys.argv[1], "rb").read(20)
448assert d[4] == 2, "not 64-bit"
449assert d[5] == 1, "not little-endian"
450assert struct.unpack("<H", d[18:20])[0] == 183
451PY
452else
453 printf ' skip arm64 artifact (not built)\n'
454fi
455
456if [ -f plugin_sqlite.exe ]; then
457 MZ=$(head -c 2 plugin_sqlite.exe)
458 [ "$MZ" = "MZ" ] && pass "windows artifact starts with MZ" || fail "windows artifact is not a PE"
459 SZ=$(wc -c < plugin_sqlite.exe | tr -d ' ')
460 [ "$SZ" -gt 200000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
461else
462 printf ' skip windows artifact (not built)\n'
463fi
464
465# ---------------------------------------------------------------- history
466section "git history audit"
467if [ -d .git ]; then
468 SCAN="$TMP/history.txt"
469 P_ROOT=$(pwd); P_WT=$(pwd)
470 git log -p --all 2>/dev/null \
471 | grep -v '^Author: ' \
472 | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
473 > "$SCAN" || : > "$SCAN"
474 HITS=0
475 scan() { # scan <label> <regex>
476 out=$(grep -Eo "$2" "$SCAN" 2>/dev/null | sort -u | head -5 || true)
477 if [ -n "$out" ]; then
478 printf ' %sHIT%s %s\n %s\n' "$C_BAD" "$C_0" "$1" "$(printf '%s' "$out" | tr '\n' ' ')"
479 HITS=$((HITS + 1))
480 else
481 pass "no $1 in history"
482 fi
483 }
484 scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
485 scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
486 scan "private 172.16-31.x.x" '\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
487 scan "GitHub tokens" 'ghp_[A-Za-z0-9]{20,}'
488 scan "HuggingFace tokens" 'hf_[A-Za-z0-9]{20,}'
489 scan "AWS access keys" 'AKIA[0-9A-Z]{16}'
490 scan "OpenAI keys" 'sk-[A-Za-z0-9]{32,}'
491 scan "private keys" 'BEGIN (RSA|OPENSSH|EC|PGP) PRIVATE KEY'
492 scan "passwords in source" '(password|passwd|secret)[[:space:]]*=[[:space:]]*"[^"]{4,}"'
493 [ "$HITS" -eq 0 ] && pass "history audit clean (0 hits)" || fail "history audit found $HITS category(ies)"
494else
495 printf ' skip history audit (not a git repo)\n'
496fi
497
498# ---------------------------------------------------------------- summary
499printf '\n%s----------------------------------------%s\n' "$C_B" "$C_0"
500printf ' %spass %d%s %sfail %d%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
501[ "$FAIL" -eq 0 ] && { printf ' %sALL PASS%s\n' "$C_OK" "$C_0"; exit 0; }
502printf ' %sFAILURES%s\n' "$C_BAD" "$C_0"
503exit 1