scorpiox-bot-plugin-google-quota
←run.shbash
273 lines · 14 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_google_quota across all 3 modes.
3#
4# Runs against ./plugin_google_quota with credential paths and the quota CLI
5# redirected at throwaway fixtures, proving the contract without network access.
6
7set -u
8
9ROOT=$(cd "$(dirname "$0")/.." && pwd)
10cd "$ROOT" || exit 1
11
12BIN=./plugin_google_quota
13PASS=0
14FAIL=0
15
16if [ -t 1 ]; then
17 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
18else
19 C_OK=; C_BAD=; C_B=; C_0=
20fi
21pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
22fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
23
24check() {
25 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
26 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
27 fi
28}
29
30check_not() {
31 if printf '%s' "$3" | grep -F -q -- "$2"; then
32 fail "$1 (must NOT contain: $2)"; else pass "$1"
33 fi
34}
35
36section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
37
38body() {
39 printf '%s\n' "$1" | tr -d '\r' | awk '
40 BEGIN { inhdr = 0 }
41 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next }
42 inhdr && $0 == "" { inhdr = 0; next }
43 inhdr { next }
44 { print }
45 '
46}
47
48json_ok() {
49 expr=${3:-True}
50 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
51 pass "$1"
52 else
53 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
54 fi
55}
56
57api() { body "$(QUERY_STRING="$1" $BIN)"; }
58apiraw() { QUERY_STRING="$1" $BIN; }
59
60# ---------------------------------------------------------------- build
61section "build"
62if [ ! -x "$BIN" ]; then
63 gcc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$BIN" src/plugin_google_quota.c || {
64 fail "native build"; exit 1; }
65fi
66pass "native binary present"
67
68if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
69 pass "src/ui_html.h is in sync with src/ui.html"
70else
71 fail "src/ui_html.h is stale - run tools/gen_ui.py"
72fi
73
74check "ui header is marked generated" "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
75
76# ---------------------------------------------------------------- fixtures
77FIX=$(mktemp -d 2>/dev/null || mktemp -d -t gqfix)
78trap 'rm -rf "$FIX"' EXIT
79
80mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full"
81chmod +x "$ROOT/tests/mock_quota.sh"
82export GOOGLE_QUOTA_BIN="$ROOT/tests/mock_quota.sh"
83export GOOGLE_ACCESS_TOKEN="ya29.INHERITED-TOKEN-MUST-BE-CLEARED"
84export MOCK_RESET_CLAUDE=$(python3 -c "from datetime import datetime,timedelta,timezone; print((datetime.now(timezone.utc)+timedelta(hours=2,minutes=15)).strftime('%Y-%m-%dT%H:%M:%SZ'))")
85export MOCK_RESET_GEMINI=$(python3 -c "from datetime import datetime,timedelta,timezone; print((datetime.now(timezone.utc)+timedelta(hours=144,minutes=30)).strftime('%Y-%m-%dT%H:%M:%SZ'))")
86
87cat > "$FIX/full/antigravity_accounts.json" <<'EOF'
88[
89 {"email": "alpha@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-A"},
90 {"email": "beta@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-B"},
91 {"email": "broken@example.com", "refresh_token": "1//MOCK-REFRESH-TOKEN-MUST-NOT-LEAK-C"}
92]
93EOF
94printf 'beta@example.com\n' > "$FIX/full/selected_account.txt"
95
96# ---------------------------------------------------------------- meta & auth
97section "meta & auth"
98META=$(BOT_PASSWORD=secret-pass $BIN --meta)
99check "--meta returns short name and desc without auth" '{"name":"google quota","desc":"Account quotas"}' "$META"
100
101META_ENV=$(BOT_PASSWORD=secret-pass SX_PLUGIN_META=1 $BIN)
102check "SX_PLUGIN_META=1 works without auth" '{"name":"google quota","desc":"Account quotas"}' "$META_ENV"
103
104VER=$($BIN --version)
105check "--version prints plugin id and version" "plugin_google_quota 1.0.3" "$VER"
106UNAUTH=$(BOT_PASSWORD=secret-pass QUERY_STRING="action=status" $BIN)
107check "missing password returns 401" "Status: 401 Unauthorized" "$UNAUTH"
108
109AUTH_HDR=$(BOT_PASSWORD=secret-pass HTTP_X_BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
110json_ok "X-Bot-Password header authorizes request" "$AUTH_HDR" "d['ok'] is True"
111
112AUTH_BEARER=$(BOT_PASSWORD=secret-pass HTTP_AUTHORIZATION="Bearer secret-pass" GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
113json_ok "Bearer header authorizes request" "$AUTH_BEARER" "d['ok'] is True"
114
115AUTH_QS=$(BOT_PASSWORD=secret-pass GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status&pwd=secret-pass")
116json_ok "?pwd= query param authorizes request" "$AUTH_QS" "d['ok'] is True"
117
118# ---------------------------------------------------------------- status
119section "status"
120ST_NONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/none/antigravity_accounts.json" api "action=status")
121json_ok "missing accounts file returns count 0" "$ST_NONE" "d['ok'] is True and d['count'] == 0 and d['cli_present'] is True"
122
123ST_EMPTY=$(GOOGLE_ACCOUNTS_FILE="$FIX/empty/antigravity_accounts.json" api "action=status")
124json_ok "empty accounts file returns count 0" "$ST_EMPTY" "d['ok'] is True and d['count'] == 0"
125
126ST_FULL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status")
127json_ok "full accounts status lists 3 accounts and selected" "$ST_FULL" \
128 "d['ok'] is True and d['count'] == 3 and d['selected'] == 'beta@example.com' and d['accounts'][1]['selected'] is True and all(a['has_refresh'] for a in d['accounts'])"
129check_not "status never leaks refresh_token" "MOCK-REFRESH-TOKEN" "$ST_FULL"
130
131ST_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=status")
132json_ok "missing CLI sets cli_present false" "$ST_NOCLI" "d['ok'] is True and d['cli_present'] is False"
133
134# ---------------------------------------------------------------- quota
135section "quota"
136Q_ONE=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=alpha@example.com")
137json_ok "single account quota parses gemini, argon, and claude pools and remaining hours" "$Q_ONE" \
138 "d['ok'] is True and d['account']['ok'] is True and abs(d['account']['gemini']['pct'] - 85.5) < 0.01 and abs(d['account']['argon']['pct'] - 100.0) < 0.01 and abs(d['account']['claude']['pct'] - 100.0) < 0.01 and len(d['account']['models']) == 9 and d['account']['gemini']['reset_in_seconds'] > 500000 and d['account']['gemini']['reset_in_hours'] > 140 and 'd ' in d['account']['gemini']['reset_remaining'] and d['account']['claude']['reset_in_seconds'] > 7000 and 'h ' in d['account']['claude']['reset_remaining'] and all('reset_remaining' in m and 'reset_in_hours' in m for m in d['account']['models'])"
139json_ok "single account quota parses both 5-hour and weekly limits" "$Q_ONE" \
140 "abs(d['account']['limits']['gemini']['five_hour']['pct'] - 37.5) < 0.01 and abs(d['account']['limits']['gemini']['weekly']['pct'] - 85.5) < 0.01 and 'd ' in d['account']['limits']['gemini']['weekly']['reset_remaining'] and 'h ' in d['account']['limits']['gemini']['five_hour']['reset_remaining'] and abs(d['account']['limits']['claude']['five_hour']['pct'] - 100.0) < 0.01 and abs(d['account']['limits']['claude']['weekly']['pct'] - 99.0) < 0.01"
141check_not "single quota never leaks token" "MOCK-TOKEN" "$Q_ONE"
142check_not "single quota never leaks refresh token" "MOCK-REFRESH-TOKEN" "$Q_ONE"
143
144Q_EXH=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota&account=beta@example.com")
145json_ok "null/missing remainingFraction marks gemini pool exhausted with reset remaining" "$Q_EXH" \
146 "d['ok'] is True and d['account']['gemini']['exhausted'] is True and d['account']['gemini']['pct'] == 0.0 and abs(d['account']['claude']['pct'] - 42.0) < 0.01 and d['account']['gemini']['reset_in_hours'] > 140 and 'd ' in d['account']['gemini']['reset_remaining']"
147json_ok "free account missing gemini 5h returns null five_hour and exhausted weekly" "$Q_EXH" \
148 "d['account']['limits']['gemini']['five_hour'] is None and d['account']['limits']['gemini']['weekly']['exhausted'] is True and d['account']['limits']['gemini']['weekly']['pct'] == 0.0 and abs(d['account']['limits']['claude']['five_hour']['pct'] - 50.0) < 0.01 and abs(d['account']['limits']['claude']['weekly']['pct'] - 42.0) < 0.01"
149Q_ALL=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota")
150json_ok "all-accounts quota aggregates best_gemini, best_argon, best_claude, and broken account" "$Q_ALL" \
151 "d['ok'] is True and d['count'] == 3 and d['best_gemini'] == 'alpha@example.com' and d['best_argon'] == 'alpha@example.com' and d['best_claude'] == 'alpha@example.com' and d['accounts'][2]['ok'] is False"
152
153Q_FMT=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "format=json")
154json_ok "?format=json returns full quota JSON" "$Q_FMT" "d['ok'] is True and d['count'] == 3 and 'best_gemini' in d"
155
156Q_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=quota&account=nobody@example.com")
157check "unknown account returns 404" "Status: 404 Not Found" "$Q_UNK"
158
159Q_NOCLI=$(GOOGLE_QUOTA_BIN="/nonexistent/scorpiox-google-quota" GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=quota")
160json_ok "missing CLI returns cli_unavailable" "$Q_NOCLI" "d['ok'] is False and d['error'] == 'cli_unavailable'"
161
162# ---------------------------------------------------------------- switch
163section "switch"
164SW_OK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" api "action=switch&account=alpha@example.com")
165json_ok "switch updates selected account" "$SW_OK" "d['ok'] is True and d['selected'] == 'alpha@example.com'"
166check "selected_account.txt persisted" "alpha@example.com" "$(cat "$FIX/full/selected_account.txt")"
167
168printf '{"account":"beta@example.com"}' > "$FIX/post.json"
169SW_PBF=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" POST_BODY_FILE="$FIX/post.json" api "action=switch")
170json_ok "switch accepts POST_BODY_FILE JSON" "$SW_PBF" "d['ok'] is True and d['selected'] == 'beta@example.com'"
171
172SW_BAD=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=bad;rm")
173check "invalid email rejected with 400" "Status: 400 Bad Request" "$SW_BAD"
174
175SW_UNK=$(GOOGLE_ACCOUNTS_FILE="$FIX/full/antigravity_accounts.json" apiraw "action=switch&account=nobody@example.com")
176check "unknown email rejected with 404" "Status: 404 Not Found" "$SW_UNK"
177
178# ---------------------------------------------------------------- HTML UI
179section "HTML UI"
180HTML=$(apiraw "")
181check "HTML emits Content-Type text/html" "Content-Type: text/html" "$HTML"
182check "HTML includes bot theme prepaint" "bot_theme" "$HTML"
183check "HTML includes theme handoff" "sx-theme-request" "$HTML"
184check "HTML uses two-route API helper" "plugin_google_quota" "$HTML"
185check "HTML hub proxy URL uses &action= separator" "'/plugins?plugin='+encodeURIComponent(HUB)+'&'" "$HTML"
186check "HTML formats multi-day remaining resets cleanly" "d+'d '+h+'h'" "$HTML"
187check "HTML renders both 5-hour and weekly limit sections" "5-Hour Limit" "$HTML"
188check "HTML renders weekly limit label" "Weekly Limit" "$HTML"
189check "HTML renders per-model reset remaining hours" "fmtResetShort" "$HTML"
190check "HTML includes live reset countdown attributes" "data-reset" "$HTML"
191check_not "HTML loads no CDN script" "<script src=" "$HTML"
192check_not "HTML references no external host script" "cdnjs" "$HTML"
193check_not "HTML makes no outbound fetch to googleapis" "googleapis.com" "$HTML"
194printf '%s' "$HTML" > "$FIX/page.html"
195if python3 - "$FIX/page.html" <<'PY'
196import re, sys
197html = open(sys.argv[1], encoding='utf-8').read()
198ids = set(re.findall(r'id="([^"]+)"', html))
199missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids]
200if missing:
201 print("missing ids:", missing)
202 sys.exit(1)
203PY
204then pass "every JS element id exists in the markup"
205else fail "JS references missing element id"; fi
206
207# ---------------------------------------------------------------- source hygiene
208section "source hygiene"
209check_not "source has no OAuth client secret" "GOCSPX" "$(cat src/plugin_google_quota.c)"
210check_not "source has no Google API key" "AIza" "$(cat src/plugin_google_quota.c)"
211check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_google_quota.c)"
212check_not "source has no internal 192.168 address" "192.168." "$(cat src/plugin_google_quota.c src/ui.html)"
213check_not "source has no internal 10.0 address" "10.0." "$(cat src/plugin_google_quota.c src/ui.html)"
214check_not "source has no internal 172.16 address" "172.16" "$(cat src/plugin_google_quota.c src/ui.html)"
215
216if python3 - src/plugin_google_quota.c src/ui.html src/bot_theme_plugin.h <<'PY'
217import sys, unicodedata
218bad = []
219for path in sys.argv[1:]:
220 for n, line in enumerate(open(path, encoding='utf-8'), 1):
221 for ch in line:
222 o = ord(ch)
223 if o < 0x2000:
224 continue
225 if 0x2190 <= o <= 0x21FF:
226 continue
227 if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF:
228 bad.append('%s:%d %r' % (path, n, ch))
229if bad:
230 print('\n'.join(bad[:10]))
231 sys.exit(1)
232PY
233then pass "no emoji in source, page or theme header"
234else fail "emoji found in shipped sources"; fi
235
236# ---------------------------------------------------------------- cross-target builds
237section "cross-target builds"
238if command -v musl-gcc >/dev/null 2>&1; then
239 if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_google_quota.c 2>/dev/null; then
240 pass "static musl build"
241 check "musl binary reports --meta" '"name":"google quota"' "$("$FIX/musl-bin" --meta)"
242 else fail "static musl build"; fi
243else
244 echo " skip musl-gcc not installed"
245fi
246
247if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
248 if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_google_quota.c 2>/dev/null; then
249 pass "MinGW-w64 build"
250 if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
251 pass "Windows build has PE header"
252 else fail "Windows build missing MZ header"; fi
253 else fail "MinGW-w64 build"; fi
254else
255 echo " skip x86_64-w64-mingw32-gcc not installed"
256fi
257
258if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
259 if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_google_quota.c 2>/dev/null; then
260 pass "static arm64 build"
261 else fail "static arm64 build"; fi
262else
263 echo " skip aarch64-linux-gnu-gcc not installed"
264fi
265
266if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_google_quota.c 2>/dev/null; then
267 pass "_FORTIFY_SOURCE=2 build"
268else
269 fail "_FORTIFY_SOURCE=2 build"
270fi
271
272printf '\n%sSummary:%s %d passed, %d failed\n' "$C_B" "$C_0" "$PASS" "$FAIL"
273[ "$FAIL" -eq 0 ]