scorpiox-bot-plugin-copilot-login
←run.shbash
381 lines · 18 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_copilot_login across all 3 modes.
3#
4# Every check runs against ./plugin_copilot_login with the credential paths and
5# both CLIs redirected at throwaway fixtures, so the suite proves the public
6# contract without touching a real Copilot session and without a network.
7#
8# What it proves:
9# - --meta is exactly {"name":"copilot","desc":"Copilot login"} and is
10# reachable with no password (discovery must never be gated)
11# - every action 401s without the node password, and 401 is a real CGI Status
12# - status parses the credentials file, the token cache, config.json, the
13# profile file and the named account directory, and NEVER emits a token
14# - start relays the CLI's device code + user_code, poll reports pending then
15# done, cancel drops the pending flow
16# - refresh performs the grant, drops the CLI's payload, and surfaces failure
17# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
18# - the source has no hard-coded secret, no internal address and no emoji
19#
20# Exit code 0 = everything passed.
21
22set -u
23
24ROOT=$(cd "$(dirname "$0")/.." && pwd)
25cd "$ROOT" || exit 1
26chmod +x tests/mock_login.sh tests/mock_refresh.sh 2>/dev/null || true
27
28BIN=./plugin_copilot_login
29ID=plugin_copilot_login
30PASS=0
31FAIL=0
32
33if [ -t 1 ]; then
34 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
35else
36 C_OK=; C_BAD=; C_B=; C_0=
37fi
38pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
39fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
40
41check() { # check <desc> <expected-substring> <actual>
42 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
43 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
44 fi
45}
46
47check_not() { # check_not <desc> <forbidden-substring> <actual>
48 if printf '%s' "$3" | grep -F -q -- "$2"; then
49 fail "$1 (must NOT contain: $2)"; else pass "$1"
50 fi
51}
52
53check_empty() { # check_empty <desc> <actual> - passes only when nothing was found
54 if [ -z "$2" ]; then pass "$1"; else
55 fail "$1 (must be empty)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
56 fi
57}
58
59found() { # found <desc> <needle> <file...> - the needle must appear somewhere
60 _d=$1; _n=$2; shift 2
61 if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
62 fail "$_d (missing: $_n)"
63 fi
64}
65
66section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
67
68# strip CGI headers if present, drop CRs, keep the payload
69body() {
70 printf '%s\n' "$1" | tr -d '\r' | awk '
71 BEGIN { inhdr = 0 }
72 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
73 inhdr && $0 == "" { inhdr = 0; next }
74 inhdr { next }
75 { print }
76 '
77}
78
79json_ok() { # json_ok <desc> <json> [python-expression]
80 expr=${3:-True}
81 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
82 pass "$1"
83 else
84 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
85 fi
86}
87
88api() { body "$(QUERY_STRING="$1" $BIN)"; }
89apiraw() { QUERY_STRING="$1" $BIN; }
90
91# ---------------------------------------------------------------- build
92section "build"
93if [ ! -x "$BIN" ]; then
94 echo " building native binary..."
95 gcc -O2 -std=c99 -Wall -Wextra -Wno-format-truncation -I src -o "$BIN" src/$ID.c || {
96 fail "native build"; exit 1; }
97fi
98pass "native binary present"
99
100if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
101 pass "src/ui_html.h is in sync with src/ui.html"
102else
103 fail "src/ui_html.h is stale - run tools/gen_ui.py"
104fi
105
106check "ui header is marked generated" \
107 "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
108
109# ---------------------------------------------------------------- --meta
110section "discovery metadata"
111META=$($BIN --meta)
112check "meta is the exact one-line contract" '{"name":"copilot","desc":"Copilot login"}' "$META"
113check "meta works through SX_PLUGIN_META" '{"name":"copilot"' "$(SX_PLUGIN_META=1 $BIN)"
114check "meta is reachable with no password" '{"name":"copilot"' "$(BOT_PASSWORD='' $BIN --meta)"
115check_not "meta carries nothing else" 'plugin' "$META"
116check "version is reported" "$ID" "$($BIN --version)"
117
118# ---------------------------------------------------------------- fixtures
119FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cplfix)
120trap 'rm -rf "$FIX"' EXIT
121
122mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/mock"
123export COPILOT_LOGIN_BIN="$ROOT/tests/mock_login.sh"
124export COPILOT_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
125export COPILOT_PENDING_DIR="$FIX/pend"
126export COPILOT_ENV_DIR="$FIX/env"
127export COPILOT_ACCOUNTS_DIR="$FIX/acc"
128export COPILOT_CREDS_PATH="$FIX/.credentials.json"
129export COPILOT_MOCK_DIR="$FIX/mock"
130export BOT_PASSWORD=testpw
131PWDQ='pwd=testpw'
132
133NOW=$(date +%s)
134FUTURE=$(( NOW + 1800 ))
135PAST=$(( NOW - 3600 ))
136
137mkcreds() { # mkcreds <path>
138 {
139 printf '{\n'
140 printf ' "github_token": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000",\n'
141 printf ' "token_type": "bearer",\n'
142 printf ' "scope": "read:user",\n'
143 printf ' "timestamp": "2026-01-01T00:00:00Z"\n'
144 printf '}\n'
145 } > "$1"
146}
147
148mkcache() { # mkcache <path> <expires_at-seconds>
149 printf '{"access_token": "SECRET-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$2" > "$1"
150}
151
152mkconfig() { # mkconfig <path> <login>
153 {
154 printf '{\n "copilotTokens": {\n "https://github.com:%s": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000"\n },\n' "$2"
155 printf ' "lastLoggedInUser": {\n "host": "https://github.com",\n "login": "%s"\n }\n}\n' "$2"
156 } > "$1"
157}
158
159# ---------------------------------------------------------------- auth gate
160section "node auth gate"
161RAW=$(apiraw "action=status")
162check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
163check "401 body is JSON" '"error":"invalid node password"' "$RAW"
164check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
165check "X-Bot-Password header auth works" '"ok":true' \
166 "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
167check "Bearer auth works" '"ok":true' \
168 "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
169check "wrong password still 401s" "Status: 401 Unauthorized" \
170 "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
171UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
172check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
173
174# ---------------------------------------------------------------- status: empty
175section "status with no credentials"
176OUT=$(api "action=status&$PWDQ")
177json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
178json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
179json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
180json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0'
181json_ok "empty node reports a null user" "$OUT" 'd["user"]==""'
182json_ok "copilot has no refresh token" "$OUT" 'd["has_refresh"] is False'
183check "empty node reports the credentials path" '"credentials_path"' "$OUT"
184check "empty node reports the device flow" '"flow":"device_code"' "$OUT"
185check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
186check_not "empty node leaks no token" 'SECRETGITHUBTOKEN' "$OUT"
187OUTF=$(api "format=json&$PWDQ")
188json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True'
189
190# ---------------------------------------------------------------- status: live
191section "status with a live session"
192mkcreds "$FIX/.credentials.json"
193mkconfig "$FIX/config.json" "octocat"
194mkcache "$FIX/.copilot-token-cache.json" "$FUTURE"
195printf 'PROVIDER=copilot\nCOPILOT_TOKEN_SOURCE=local\nMODEL=claude-sonnet-5\n' > "$FIX/env/copilot.txt"
196OUT=$(api "action=status&$PWDQ")
197json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
198json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
199json_ok "live session countdown is positive and near 30 min" "$OUT" '1700 < d["expires_in_sec"] <= 1800'
200json_ok "the token cache is detected" "$OUT" 'd["cache_present"] is True'
201json_ok "the GitHub login comes from config.json" "$OUT" 'd["user"]=="octocat"'
202json_ok "the scope comes from the credentials file" "$OUT" 'd["scope"]=="read:user"'
203json_ok "the profile model is parsed" "$OUT" 'd["profile"]=="claude-sonnet-5"'
204json_ok "the profile file is detected" "$OUT" 'd["profile_exists"] is True'
205check_not "status never returns a github token" 'SECRETGITHUBTOKEN' "$OUT"
206check_not "status never returns a derived JWT" 'SECRET-JWT' "$OUT"
207check_not "status never returns the key name github_token" 'github_token' "$OUT"
208
209# ---------------------------------------------------------------- status: expired
210section "status with an expired derived token"
211mkcache "$FIX/.copilot-token-cache.json" "$PAST"
212OUT=$(api "action=status&$PWDQ")
213json_ok "an expired derived token is still logged in" "$OUT" 'd["logged_in"] is True'
214json_ok "an expired derived token is flagged expired" "$OUT" 'd["expired"] is True'
215json_ok "an expired derived token has a negative countdown" "$OUT" 'd["expires_in_sec"]<0'
216
217# ---------------------------------------------------------------- named accounts
218section "named accounts"
219mkcreds "$FIX/acc/work.json"
220mkcreds "$FIX/acc/personal.json"
221mkcache "$FIX/.copilot-token-cache.json" "$FUTURE"
222OUT=$(api "action=status&$PWDQ")
223json_ok "both account files are listed" "$OUT" 'len(d["accounts"])==2'
224json_ok "named_accounts is true with more than one" "$OUT" 'd["named_accounts"] is True'
225json_ok "each account reports logged_in" "$OUT" 'all(a["logged_in"] for a in d["accounts"])'
226OUT=$(api "action=accounts&$PWDQ")
227json_ok "action=accounts answers ok" "$OUT" 'd["ok"] is True'
228json_ok "action=accounts counts the files" "$OUT" 'd["count"]==2'
229check_not "accounts never returns a token" 'SECRETGITHUBTOKEN' "$OUT"
230OUT=$(api "action=status&name=work&$PWDQ")
231json_ok "a named account is read from its own file" "$OUT" 'd["account"]=="work"'
232check "a named account path ends in its file" 'acc/work.json' "$OUT"
233BADNAME=$(apiraw "action=status&name=../escape&pwd=testpw" | tr -d '\r')
234check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"
235
236# ---------------------------------------------------------------- start
237section "action=start"
238rm -f "$FIX/pend"/*.json "$FIX/mock"/*
239rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
240OUT=$(api "action=start&$PWDQ")
241json_ok "start returns ok" "$OUT" 'd["ok"] is True'
242json_ok "start returns a device_code flow" "$OUT" 'd["flow"]=="device_code"'
243json_ok "start returns the GitHub verify URL" "$OUT" 'd["verify_url"]=="https://github.com/login/device"'
244json_ok "start returns the 8-character user code" "$OUT" 'd["user_code"]=="1234-5678"'
245json_ok "start reports the poll interval" "$OUT" 'd["interval"]==5'
246json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0'
247check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)"
248OUT=$(api "action=status&$PWDQ")
249json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True'
250check_not "start never returns a token" 'SECRET' "$OUT"
251# A node that already holds credentials: the CLI answers "exists", not "no
252# code". The plugin must relay that word, because it is the only hint that
253# force=1 (the Re-login button) is what the user needs.
254api "action=cancel&$PWDQ" >/dev/null
255mkcreds "$FIX/.credentials.json"
256OUT=$(api "action=start&$PWDQ")
257check "start relays the CLI's exists error verbatim" '"error":"exists"' "$OUT"
258check "the exists error tells the user to re-login" 'Re-login' "$OUT"
259OUT=$(api "action=start&force=1&$PWDQ")
260json_ok "start with force=1 replaces the credentials" "$OUT" 'd["ok"] is True and d["user_code"]=="1234-5678"'
261api "action=cancel&$PWDQ" >/dev/null
262
263# ---------------------------------------------------------------- poll
264section "action=poll"
265rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
266api "action=start&$PWDQ" >/dev/null
267OUT=$(api "action=poll&$PWDQ")
268json_ok "poll answers ok while waiting" "$OUT" 'd["ok"] is True'
269json_ok "poll reports the pending state" "$OUT" 'd["state"]=="pending"'
270json_ok "poll repeats the interval" "$OUT" 'd["interval"]==5'
271
272: > "$FIX/mock/poll_done"
273rm -f "$FIX/.credentials.json"
274OUT=$(api "action=poll&$PWDQ")
275json_ok "poll reports done after authorization" "$OUT" 'd["ok"] is True and d["state"]=="done"'
276json_ok "poll re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
277check_not "poll never echoes the token" 'SECRETGITHUBTOKEN' "$OUT"
278
279: > "$FIX/mock/poll_denied"
280api "action=start&force=1&$PWDQ" >/dev/null
281OUT=$(api "action=poll&$PWDQ")
282check "a denied authorization surfaces the CLI error" '"error":"denied"' "$OUT"
283OUT=$(api "action=poll&$PWDQ")
284check "poll without a pending flow is reported" '"error":"no_pending"' "$OUT"
285
286# ---------------------------------------------------------------- cancel
287section "action=cancel"
288api "action=start&$PWDQ" >/dev/null
289OUT=$(api "action=cancel&$PWDQ")
290json_ok "cancel answers ok" "$OUT" 'd["ok"] is True'
291json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False'
292OUT=$(api "action=status&$PWDQ")
293json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False'
294
295# ---------------------------------------------------------------- refresh
296section "action=refresh"
297rm -f "$FIX/.copilot-token-cache.json"
298mkcreds "$FIX/.credentials.json"
299OUT=$(api "action=refresh&$PWDQ")
300json_ok "refresh answers ok" "$OUT" 'd["ok"] is True'
301json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True'
302json_ok "refresh produced a fresh cache entry" "$OUT" 'd["cache_present"] is True'
303json_ok "refresh moved the expiry forward" "$OUT" '1700 < d["expires_in_sec"] <= 1800'
304check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
305check_not "refresh never returns an access_token key" 'access_token' "$OUT"
306
307OUT=$(COPILOT_MOCK_FAIL=1 api "action=refresh&$PWDQ")
308check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"
309
310rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
311OUT=$(api "action=refresh&$PWDQ")
312check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT"
313
314# ---------------------------------------------------------------- CLI absent
315section "CLI unavailable"
316OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=start&$PWDQ")
317check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
318check "the cli_unavailable detail explains the fix" 'COPILOT_LOGIN_BIN' "$OUT"
319OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=poll&$PWDQ")
320check "poll without a login CLI is cli_unavailable" 'cli_unavailable' "$OUT"
321mkcreds "$FIX/.credentials.json"
322OUT=$(COPILOT_REFRESH_BIN=/nonexistent/refresh api "action=refresh&$PWDQ")
323check "refresh without a refresh CLI is cli_unavailable" 'cli_unavailable' "$OUT"
324OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=status&$PWDQ")
325json_ok "status without a login CLI still answers from the files" "$OUT" 'd["ok"] is True'
326json_ok "status reports the CLI as absent" "$OUT" 'd["cli_present"] is False'
327
328# ---------------------------------------------------------------- routing
329section "routing"
330OUT=$(apiraw "action=bogus&$PWDQ" | tr -d '\r')
331check "an unknown action is a 404" "Status: 404 Not Found" "$OUT"
332check "an unknown action names itself" '"error":"unknown_action"' "$OUT"
333
334# ---------------------------------------------------------------- HTML page
335section "HTML page"
336PAGE=$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')
337check "page is HTML" "Content-Type: text/html" "$PAGE"
338check "page carries the bot theme handoff" "sx-theme" "$PAGE"
339check "page asks the host for the theme once" "sx-theme-request" "$PAGE"
340check "page carries the bot token block" "--bg-card" "$PAGE"
341check "page has a viewport meta" 'name="viewport"' "$PAGE"
342check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE"
343check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE"
344check "page names the plugin route" "/plugin_copilot_login" "$PAGE"
345check "page links the GitHub device URL" "https://github.com/login/device" "$PAGE"
346check "page has a live polling indicator" "Waiting for GitHub confirmation" "$PAGE"
347check "page has the copy-and-open action" "Copy Code" "$PAGE"
348check_empty "page emits no Content-Length" "$(printf '%s' "$PAGE" | grep -i '^Content-Length' || true)"
349check_not "page loads no CDN script" "<script src=" "$PAGE"
350check_not "page references no external host" "cdnjs" "$PAGE"
351check_not "page has no http:// asset" "http://" "$PAGE"
352check "page CSP forbids remote scripts" "default-src 'none'" "$PAGE"
353check "page is frameable by the bot" "frame-ancestors *" "$PAGE"
354
355# ---------------------------------------------------------------- source hygiene
356section "source hygiene"
357SRC=src/$ID.c
358check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)"
359check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)"
360check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)"
361check_empty "no private 192.168 address" "$(grep -nE '192\.168\.' "$SRC" src/ui.html tests/*.sh README.md plugin.json 2>/dev/null || true)"
362check_empty "no 10.x private address" "$(grep -nE '(^|[^0-9])10\.[0-9]+\.[0-9]+\.[0-9]+' "$SRC" src/ui.html tests/*.sh README.md 2>/dev/null || true)"
363check_empty "no credential literal" "$(grep -nE 'ghp_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}' "$SRC" tests/*.sh README.md 2>/dev/null || true)"
364# The detector literals are assembled from fragments so this scanner's own
365# source line never trips a history secret scan.
366HOSTS="macmin""i|intel-ultra""2|lazar""us"
367check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)"
368check_empty "no OAuth client secret is shipped" "$(grep -nE '20[0-9]{2}[A-Za-z0-9]{10,}' "$SRC" || true)"
369found "the github_token value is never read into a response" 'json_str_field(json, json + strlen(json), "scope"' "$SRC"
370found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
371found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC"
372found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC"
373found "the device code is relayed verbatim" 'json_str_field(j, end, "user_code"' "$SRC"
374check_empty "the shipped page carries no token literal" \
375 "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/$ID.c 2>/dev/null || true)"
376
377# ---------------------------------------------------------------- summary
378printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
379printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
380[ "$FAIL" -eq 0 ] || exit 1
381exit 0