scorpiox-bot-plugin-webhook
←run.shbash
574 lines · 31 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_webhook across every mode.
3#
4# No network beyond a loopback receiver the suite starts itself (tests/
5# mockrecv.py), which records the method, path, query and EVERY header of each
6# request it gets. That is the point of the suite: it asserts that the request
7# the plugin actually put on the wire matches the hook definition - method,
8# path, custom headers, HMAC signature over the exact body bytes - instead of
9# merely asserting that something returned 200.
10#
11# --meta / --schema the discovery contract the node and the router read
12# --mcp a full JSON-RPC session: handshake, both tools, every
13# documented refusal, and the router's two-write framing
14# CGI JSON API CRUD, secret redaction, the 0600 store, delivery log
15# HTML the page: bot theme, no <script src=>, embed, ?theme=
16# SSRF loopback refused by default, allowed with the opt-in
17# signatures github / gitlab / v2, verified against python hmac
18# robustness 4xx, redirect, chunked, oversized body, truncation
19# safety no popen/system, ASan+UBSan+fortify clean, no secret,
20# no private address, no internal hostname in git history
21#
22# Exit 0 = everything passed.
23
24set -u
25
26ROOT=$(cd "$(dirname "$0")/.." && pwd)
27cd "$ROOT" || exit 1
28
29BIN=./plugin_webhook
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 500)"
44 fi
45}
46check_not() { # check_not <desc> <forbidden-substring> <actual>
47 if printf '%s' "$3" | grep -F -q -- "$2"; then
48 fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
49 else pass "$1"; fi
50}
51section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
52
53# strip CGI headers, drop CRs, keep the payload
54body() {
55 printf '%s\n' "$1" | tr -d '\r' | awk '
56 BEGIN { inhdr = 0 }
57 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Referrer-Policy|Content-Security-Policy|X-Frame-Options):/) { inhdr = 1; next }
58 inhdr && $0 == "" { inhdr = 0; next }
59 inhdr { next }
60 { print }
61 '
62}
63
64json_ok() { # json_ok <desc> <json> [python-expression]
65 expr=${3:-True}
66 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
67 pass "$1"
68 else
69 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 500)"
70 fi
71}
72
73api() { body "$(QUERY_STRING="$1" $BIN)"; }
74apiraw() { QUERY_STRING="$1" $BIN; }
75
76# api_post <query-string> <json-payload>
77api_post() {
78 _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
79 body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
80}
81
82# mcp <lines...> - one JSON reply per line
83mcp() {
84 printf '%s\n' "$@" | $BIN --mcp
85}
86
87# mcp_two_write <line> - the connector router's proc_send() shape: the body and
88# the terminating newline arrive as two separate writes. A reader that uses
89# fread() blocks forever here, so this is the assertion that the MCP loop reads
90# with read(2).
91mcp_two_write() {
92 { printf '%s' "$1"; sleep 0.15; printf '\n'; } | $BIN --mcp
93}
94
95tmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t wh)
96trap 'rm -rf "$tmpdir"; [ -n "${RECV_PID:-}" ] && kill "$RECV_PID" 2>/dev/null' EXIT INT TERM
97
98export WEBHOOK_STORE_PATH="$tmpdir/hooks.json"
99export BOT_PASSWORD="suite-password-not-a-real-secret"
100unset WEBHOOK_ALLOW_PRIVATE
101
102# =====================================================================
103section "discovery (--meta / --schema)"
104# =====================================================================
105meta=$($BIN --meta)
106json_ok "--meta is one JSON object" "$meta"
107json_ok "--meta name is webhook" "$meta" 'd["name"]=="webhook"'
108json_ok "--meta desc is short (<=15)" "$meta" 'len(d["desc"])<=15'
109json_ok "--meta kind is mcp" "$meta" 'd["kind"]=="mcp"'
110json_ok "--meta mcp true" "$meta" 'd["mcp"] is True'
111json_ok "--meta daemon false" "$meta" 'd["daemon"] is False'
112json_ok "--meta menus false" "$meta" 'd["menus"] is False'
113json_ok "--meta verified live" "$meta" 'd["verified"]=="live"'
114json_ok "--meta version matches plugin.json" "$meta" 'd["version"]=="1.0.3"'
115check "--meta is a single line" "1" "$($BIN --meta | wc -l | tr -d ' ')"
116
117schema=$($BIN --schema)
118json_ok "--schema lists tools" "$schema" 'len(d["tools"])==2'
119json_ok "--schema has webhook_list" "$schema" '[t["name"] for t in d["tools"]]==["webhook_list","webhook_trigger"]'
120json_ok "--schema tool has an input schema" "$schema" 'd["tools"][1]["inputSchema"]["required"]==["name"]'
121check "SX_PLUGIN_META env also emits metadata" '"kind":"mcp"' "$(SX_PLUGIN_META=1 $BIN)"
122
123# =====================================================================
124section "--mcp session"
125# =====================================================================
126mcp_out=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"suite","version":"1"}}}')
127json_ok "initialize returns a result" "$mcp_out" 'd["result"]["protocolVersion"]=="2024-11-05"'
128json_ok "initialize names the server" "$mcp_out" 'd["result"]["serverInfo"]["name"]=="plugin_webhook"'
129json_ok "initialize advertises tools" "$mcp_out" '"tools" in d["result"]["capabilities"]'
130
131tl=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}')
132json_ok "tools/list returns two tools" "$tl" 'len(d["result"]["tools"])==2'
133json_ok "webhook_list has a description" "$tl" 'len(d["result"]["tools"][0]["description"])>40'
134
135pl=$(mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}')
136json_ok "webhook_list on an empty store succeeds" "$pl" 'd["result"].get("isError") is not True'
137check "webhook_list says nothing is configured" "No webhooks are configured" "$pl"
138
139ping=$(mcp '{"jsonrpc":"2.0","id":4,"method":"ping"}')
140json_ok "ping answers" "$ping" 'd["result"]=={}'
141
142note=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}')
143if [ -z "$(printf '%s' "$note" | tr -d '\n')" ]; then
144 pass "a notification produces no reply"
145else
146 fail "a notification produced a reply"; printf ' got: %s\n' "$note"
147fi
148
149bad=$(mcp 'not json at all')
150json_ok "a parse error answers -32700 with a null id" "$bad" 'd["error"]["code"]==-32700 and d["id"] is None'
151
152unk=$(mcp '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}')
153json_ok "an unknown tool answers -32602" "$unk" 'd["error"]["code"]==-32602'
154
155none=$(mcp '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"arguments":{}}}')
156json_ok "a call with no tool name answers -32602" "$none" 'd["error"]["code"]==-32602'
157
158meth=$(mcp '{"jsonrpc":"2.0","id":7,"method":"no/such/method"}')
159json_ok "an unknown method answers -32601" "$meth" 'd["error"]["code"]==-32601'
160
161tw=$(mcp_two_write '{"jsonrpc":"2.0","id":8,"method":"tools/list"}')
162json_ok "two-write framing (router proc_send shape) is read, not hung" "$tw" 'len(d["result"]["tools"])==2'
163
164# =====================================================================
165section "HTML page"
166# =====================================================================
167page=$(apiraw "")
168check_not "an unauthenticated page is refused" "<!DOCTYPE" "$page"
169check "an unauthenticated page answers 401" "Status: 401" "$page"
170json_ok "the 401 body is JSON" "$(body "$page")" 'd["ok"] is False'
171
172apage=$(apiraw "pwd=suite-password-not-a-real-secret")
173check "the authenticated page is HTML" "Content-Type: text/html" "$apage"
174check_not "the page has no <script src=>" "<script src=" "$apage"
175check_not "the page pulls nothing from a CDN" "cdnjs" "$apage"
176check_not "the page has no http:// asset reference" "http://cdn" "$apage"
177check "the page carries the bot theme tokens" "--bg-card" "$apage"
178check "the page carries the prepaint script" "bot_theme" "$apage"
179check "the page carries the theme handoff" "sx-theme-request" "$apage"
180check "the page hides its chrome when embedded" "html.embedded" "$apage"
181check "the page names the light theme rule" "data-theme" "$apage"
182check "the page shows the hook table" "Recent deliveries" "$apage"
183check "the page mentions both tools" "webhook_trigger" "$apage"
184
185embed=$(apiraw "pwd=suite-password-not-a-real-secret&embed=1")
186check "?embed=1 is accepted" "Content-Type: text/html" "$embed"
187light=$(apiraw "pwd=suite-password-not-a-real-secret&theme=light")
188check "?theme=light sets data-theme before paint" "setAttribute('data-theme','light')" "$light"
189
190json_ok "an unauthenticated action is refused" "$(body "$(apiraw 'action=list')")" 'd["ok"] is False'
191
192# =====================================================================
193section "store CRUD, secrets, and the 0600 file"
194# =====================================================================
195P="pwd=suite-password-not-a-real-secret"
196lst=$(api "action=list&$P")
197json_ok "an empty store lists zero hooks" "$lst" 'd["count"]==0 and d["hooks"]==[] and d["log"]==[]'
198json_ok "the list reports the SSRF policy" "$lst" 'd["allow_private"] is False'
199
200saved=$(api_post "action=save&$P" '{"name":"demo","url":"http://127.0.0.1:1/hook","method":"POST","desc":"Suite demo","sig":"github","secret":"s3cr3t-value","headers":[{"name":"Authorization","value":"Bearer abc123"},{"name":"X-Custom","value":"one"}]}')
201json_ok "save creates a hook" "$saved" 'd["ok"] is True and d["saved"]=="demo"'
202
203lst=$(api "action=list&$P")
204json_ok "the hook is listed" "$lst" 'd["count"]==1 and d["hooks"][0]["name"]=="demo"'
205check_not "the list does not leak the header value" "Bearer abc123" "$lst"
206check_not "the list does not leak the HMAC secret" "s3cr3t-value" "$lst"
207json_ok "the header is reported as a secret presence only" "$lst" 'd["hooks"][0]["headers"][0]=={"name":"Authorization","has_secret":True}'
208json_ok "the hook reports it has an HMAC secret" "$lst" 'd["hooks"][0]["has_secret"] is True'
209json_ok "the signature scheme is reported" "$lst" 'd["hooks"][0]["sig"]=="github"'
210json_ok "the query string of a stored url is redacted in the list" \
211 "$(api_post "action=save&$P" '{"name":"qtoken","url":"https://example.com/hook?token=abcdef","method":"POST"}' >/dev/null; api "action=list&$P")" \
212 'any(h["name"]=="qtoken" and h["url"].endswith("?<redacted>") for h in d["hooks"])'
213check_not "the listed url does not carry the pasted token" "abcdef" "$(api "action=list&$P")"
214
215# store file: mode 0600, and the secret really is in it
216if [ -f "$WEBHOOK_STORE_PATH" ]; then
217 mode=$(stat -c '%a' "$WEBHOOK_STORE_PATH" 2>/dev/null || stat -f '%Lp' "$WEBHOOK_STORE_PATH")
218 check "the store file is mode 0600" "600" "$mode"
219 check "the store file does hold the secret (it must, to sign)" "s3cr3t-value" "$(cat "$WEBHOOK_STORE_PATH")"
220else
221 fail "the store file was not written at \$WEBHOOK_STORE_PATH"
222fi
223
224# editing without resending a secret keeps it
225api_post "action=save&name=demo&$P" '{"name":"demo","url":"http://127.0.0.1:1/hook2","method":"PUT","desc":"edited","sig":"github","headers":[{"name":"Authorization"},{"name":"X-Custom","value":"two"}]}' >/dev/null
226json_ok "an edit without a secret keeps the stored HMAC secret" "$(api "action=list&$P")" \
227 'any(h["name"]=="demo" and h["method"]=="PUT" and h["has_secret"] for h in d["hooks"])'
228check "the stored secret survived the edit" "s3cr3t-value" "$(cat "$WEBHOOK_STORE_PATH")"
229check "the kept header value survived the edit" "Bearer abc123" "$(cat "$WEBHOOK_STORE_PATH")"
230check "the replaced header value is the new one" "two" "$(cat "$WEBHOOK_STORE_PATH")"
231
232# validation
233v1=$(api_post "action=save&$P" '{"name":"bad name with spaces","url":"https://example.com/x","method":"POST"}')
234json_ok "a name with spaces is refused" "$v1" 'd["ok"] is False and "name" in d["error"].lower()'
235v2=$(api_post "action=save&$P" '{"name":"badurl","url":"ftp://example.com/x","method":"POST"}')
236json_ok "a non-http scheme is refused" "$v2" 'd["ok"] is False'
237v3=$(api_post "action=save&$P" '{"name":"badverbm","url":"https://example.com/x","method":"TRACE"}')
238json_ok "an unsupported method is refused" "$v3" 'd["ok"] is False'
239v4=$(api_post "action=save&$P" '{"name":"nosigsecret","url":"https://example.com/x","method":"POST","sig":"v2"}')
240json_ok "a signature scheme with no secret is refused" "$v4" 'd["ok"] is False'
241v5=$(api_post "action=save&$P" '{"name":"creds","url":"https://user:pw@example.com/x","method":"POST"}')
242json_ok "credentials in the url are refused" "$v5" 'd["ok"] is False'
243v6=$(api_post "action=save&$P" 'not json')
244json_ok "a non-JSON body is refused" "$v6" 'd["ok"] is False'
245v7=$(api_post "action=save&$P" '{"name":"crlf","url":"https://example.com/x","method":"POST","headers":[{"name":"X-Bad","value":"a\r\nB: c"}]}')
246json_ok "a header value with CRLF is refused" "$v7" 'd["ok"] is False'
247v8=$(api_post "action=save&$P" '{"name":"badhdr","url":"https://example.com/x","method":"POST","headers":[{"name":"X Bad","value":"v"}]}')
248json_ok "a header name with a space is refused" "$v8" 'd["ok"] is False'
249v9=$(api_post "action=save&$P" '{"name":"demo","url":"https://example.com/x","method":"POST"}')
250json_ok "a duplicate name is refused on create" "$v9" 'd["ok"] is False and "exists" in d["error"]'
251
252# =====================================================================
253section "SSRF policy"
254# =====================================================================
255ssrf=$(api_post "action=save&$P" '{"name":"local","url":"http://127.0.0.1:9/hook","method":"POST"}')
256json_ok "a loopback hook can be stored (it is not fired yet)" "$ssrf" 'd["ok"] is True'
257FIREBODY='{"name":"local","payload":"{}"}'
258fire_raw=$(printf '%s' "$FIREBODY" | CONTENT_LENGTH=${#FIREBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN)
259fire=$(body "$fire_raw")
260check "firing at loopback is refused while the policy is closed" "Status: 502" "$fire_raw"
261json_ok "the refusal names the reason" "$fire" 'd["ok"] is False and ("private" in d["error"] or "reserved" in d["error"] or "refused" in d["error"])'
262
263# =====================================================================
264section "delivery against a recording receiver"
265# =====================================================================
266LOG="$tmpdir/recv.jsonl"
267python3 tests/mockrecv.py --port 0 --log "$LOG" --delay 0.3 > "$tmpdir/recv.out" 2>"$tmpdir/recv.err" &
268RECV_PID=$!
269i=0
270while [ $i -lt 60 ]; do
271 PORT=$(awk '/^PORT /{print $2}' "$tmpdir/recv.out" 2>/dev/null)
272 [ -n "${PORT:-}" ] && break
273 i=$((i + 1)); sleep 0.1
274done
275if [ -z "${PORT:-}" ]; then
276 fail "the recording receiver did not start"; cat "$tmpdir/recv.err" | head -5
277else
278 pass "the recording receiver is listening on 127.0.0.1:$PORT"
279fi
280
281export WEBHOOK_ALLOW_PRIVATE=1
282json_ok "the list reports the opt-in once it is set" "$(api "action=list&$P")" 'd["allow_private"] is True'
283
284api_post "action=save&$P" "{\"name\":\"recv\",\"url\":\"http://127.0.0.1:$PORT/hook\",\"method\":\"POST\",\"sig\":\"github\",\"secret\":\"hmac-key-1\",\"headers\":[{\"name\":\"Authorization\",\"value\":\"Bearer tok-42\"},{\"name\":\"X-Custom\",\"value\":\"alpha\"}]}" >/dev/null
285
286PAYLOAD='{"event":"deploy","n":1,"nested":{"a":[1,2,3]}}'
287fire=$(api_post "action=fire&$P" "{\"name\":\"recv\",\"payload\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$PAYLOAD")}")
288json_ok "a fire to the mock succeeds" "$fire" 'd["ok"] is True and d["delivered"] is True'
289json_ok "the fire reports HTTP 200" "$fire" 'd["status"]==200 and d["ok_status"] is True'
290json_ok "the fire reports bytes and latency" "$fire" 'd["bytes"]>0 and d["ms"]>=0'
291
292python3 - "$LOG" "$PAYLOAD" <<'PY'
293import hashlib, hmac, json, sys
294log, payload = sys.argv[1], sys.argv[2]
295lines = [json.loads(l) for l in open(log) if l.strip()]
296ok = 0
297bad = []
298
299def want(cond, msg):
300 global ok
301 if cond:
302 ok += 1
303 else:
304 bad.append(msg)
305
306want(len(lines) == 1, "exactly one request was recorded (got %d)" % len(lines))
307if lines:
308 r = lines[0]
309 h = {k.lower(): v for k, v in r["headers"].items()}
310 want(r["method"] == "POST", "method is POST (got %s)" % r["method"])
311 want(r["path"] == "/hook", "path is /hook (got %s)" % r["path"])
312 want(r["body"] == payload, "the body arrived byte-identical")
313 want(h.get("authorization") == "Bearer tok-42",
314 "the Authorization header carried the stored token (got %r)" % h.get("authorization"))
315 want(h.get("x-custom") == "alpha", "the custom header arrived")
316 want(h.get("content-type", "").startswith("application/json"),
317 "a JSON content type was added (got %r)" % h.get("content-type"))
318 want(h.get("content-length") == str(len(payload)),
319 "the content length matches the body")
320 want(h.get("user-agent", "").startswith("SCORPIOXBOT-webhook"),
321 "the user agent identifies the plugin")
322 sig = h.get("x-hub-signature-256", "")
323 expect = "sha256=" + hmac.new(b"hmac-key-1", payload.encode(), hashlib.sha256).hexdigest()
324 want(sig == expect, "X-Hub-Signature-256 is the HMAC of the exact body\n"
325 " want %s\n got %s" % (expect, sig))
326for b in bad:
327 print(" " + b)
328print("MATCHED %d" % ok)
329PY
330sigres=$?
331if [ $sigres -eq 0 ]; then pass "the recorded request matches the hook definition, including its HMAC"; else fail "the recorded request did not match the hook definition"; fi
332
333json_ok "the delivery was logged" "$(api "action=list&$P")" \
334 'd["log"] and d["log"][0]["name"]=="recv" and d["log"][0]["status"]==200 and d["log"][0]["ok"] is True'
335
336# --- query string, object payload, gitlab scheme ---------------------------
337api_post "action=save&$P" "{\"name\":\"recvq\",\"url\":\"http://127.0.0.1:$PORT/echo\",\"method\":\"POST\",\"sig\":\"gitlab\",\"secret\":\"tok-shared\"}" >/dev/null
338fireq=$(api_post "action=fire&$P" '{"name":"recvq","payload":{"a":1},"query":"event=deploy&env=prod"}')
339json_ok "a fire with a query string and an object payload succeeds" "$fireq" 'd["delivered"] is True'
340json_ok "an object payload is serialised as JSON" "$fireq" 'd["body_preview"]=="{\"a\":1}"'
341python3 - "$LOG" <<'PY'
342import json, sys
343lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
344last = lines[-1]
345h = {k.lower(): v for k, v in last["headers"].items()}
346assert last["path"] == "/echo?event=deploy&env=prod", last["path"]
347assert last["body"] == '{"a":1}', last["body"]
348assert h.get("x-gitlab-token") == "tok-shared", h.get("x-gitlab-token")
349PY
350if [ $? -eq 0 ]; then pass "the query was appended and the gitlab token header was sent"; else fail "query / gitlab token header mismatch"; fi
351
352# --- v2 timestamped signature ---------------------------------------------
353api_post "action=save&$P" "{\"name\":\"recvv2\",\"url\":\"http://127.0.0.1:$PORT/hook\",\"method\":\"POST\",\"sig\":\"v2\",\"secret\":\"v2-key\"}" >/dev/null
354api_post "action=fire&$P" '{"name":"recvv2","payload":"{\"x\":\"y\"}"}' >/dev/null
355python3 - "$LOG" <<'PY'
356import hashlib, hmac, json, sys, time
357lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
358last = lines[-1]
359h = {k.lower(): v for k, v in last["headers"].items()}
360ts = h.get("x-webhook-timestamp", "")
361sig = h.get("x-webhook-signature", "")
362body = last["body"]
363expect = hmac.new(b"v2-key", (ts + "." + body).encode(), hashlib.sha256).hexdigest()
364assert sig == "t=%s,v1=%s" % (ts, expect), (sig, expect)
365assert abs(int(ts) - int(time.time())) < 60, ts
366PY
367if [ $? -eq 0 ]; then pass "the v2 signature is HMAC(timestamp.body) and its timestamp is live"; else fail "v2 signature mismatch"; fi
368
369# --- methods --------------------------------------------------------------
370for m in GET PUT PATCH DELETE HEAD; do
371 api_post "action=save&$P" "{\"name\":\"m$m\",\"url\":\"http://127.0.0.1:$PORT/echo\",\"method\":\"$m\",\"desc\":\"$m verb\"}" >/dev/null
372 r=$(api_post "action=fire&$P" "{\"name\":\"m$m\",\"payload\":\"{}\"}")
373 json_ok "$m is delivered" "$r" 'd["delivered"] is True and d["status"]==200'
374done
375python3 - "$LOG" <<'PY'
376import json, sys
377lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
378verbs = [l["method"] for l in lines[-5:]]
379assert verbs == ["GET", "PUT", "PATCH", "DELETE", "HEAD"], verbs
380PY
381if [ $? -eq 0 ]; then pass "the method on the wire is the method configured"; else fail "method dispatch is wrong"; fi
382
383# --- response handling ----------------------------------------------------
384api_post "action=save&$P" "{\"name\":\"r418\",\"url\":\"http://127.0.0.1:$PORT/status/418\",\"method\":\"POST\"}" >/dev/null
385r=$(api_post "action=fire&$P" '{"name":"r418","payload":"{}"}')
386json_ok "a 4xx is delivered and reported as not-ok" "$r" 'd["delivered"] is True and d["status"]==418 and d["ok_status"] is False'
387json_ok "the 4xx body is carried back" "$r" '"requested" in d["body_preview"]'
388
389api_post "action=save&$P" "{\"name\":\"redir\",\"url\":\"http://127.0.0.1:$PORT/redirect\",\"method\":\"POST\"}" >/dev/null
390r=$(api_post "action=fire&$P" '{"name":"redir","payload":"{}"}')
391json_ok "a redirect is reported, never followed" "$r" 'd["delivered"] is True and d["status"]==302'
392
393api_post "action=save&$P" "{\"name\":\"chunky\",\"url\":\"http://127.0.0.1:$PORT/chunked\",\"method\":\"POST\"}" >/dev/null
394r=$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}')
395json_ok "a chunked response body is decoded" "$r" 'd["body_preview"]=="{\"chunked\":true}"'
396check_not "the chunk framing did not leak into the body" "2\r" "$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}')"
397
398api_post "action=save&$P" "{\"name\":\"big\",\"url\":\"http://127.0.0.1:$PORT/big\",\"method\":\"POST\"}" >/dev/null
399r=$(api_post "action=fire&$P" '{"name":"big","payload":"{}"}')
400json_ok "an oversized response is truncated and says so" "$r" 'd["truncated"] is True and d["bytes"]<=4096'
401
402# --- refusal paths --------------------------------------------------------
403NFBODY='{"name":"nope","payload":"{}"}'
404nf_raw=$(printf '%s' "$NFBODY" | CONTENT_LENGTH=${#NFBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN)
405nf=$(body "$nf_raw")
406check "firing an unknown hook answers 404" "Status: 404" "$nf_raw"
407json_ok "the unknown-hook body is JSON" "$nf" 'd["ok"] is False'
408
409dead=$(api_post "action=save&$P" '{"name":"dead","url":"http://127.0.0.1:1/hook","method":"POST"}')
410d=$(api_post "action=fire&$P" '{"name":"dead","payload":"{}"}')
411json_ok "an unreachable endpoint is reported, not crashed" "$d" 'd["ok"] is False and d["delivered"] is False and len(d["error"])>0'
412json_ok "the failed delivery is in the log" "$(api "action=list&$P")" \
413 'any(e["name"]=="dead" and e["ok"] is False for e in d["log"])'
414
415# =====================================================================
416section "--mcp tool calls against the live store"
417# =====================================================================
418tl=$(mcp '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}')
419check "webhook_list reports the stored hooks" "recv" "$tl"
420check_not "webhook_list never returns a header value" "Bearer tok-42" "$tl"
421check_not "webhook_list never returns the HMAC secret" "hmac-key-1" "$tl"
422check_not "webhook_list redacts the query string" "event=deploy" "$tl"
423
424tr=$(mcp '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"recv","payload":{"from":"mcp"}}}}')
425json_ok "webhook_trigger succeeds" "$tr" 'd["result"].get("isError") is not True'
426check "the tool result reports the HTTP status" "HTTP 200" "$tr"
427check_not "the tool result carries no secret" "hmac-key-1" "$tr"
428
429python3 - "$LOG" <<'PY'
430import hashlib, hmac, json, sys
431lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
432last = lines[-1]
433h = {k.lower(): v for k, v in last["headers"].items()}
434assert last["body"] == '{"from":"mcp"}', last["body"]
435expect = "sha256=" + hmac.new(b"hmac-key-1", last["body"].encode(), hashlib.sha256).hexdigest()
436assert h.get("x-hub-signature-256") == expect, h.get("x-hub-signature-256")
437PY
438if [ $? -eq 0 ]; then pass "an object payload over MCP is signed and delivered correctly"; else fail "MCP payload/signature mismatch"; fi
439
440badname=$(mcp '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"nope"}}}')
441json_ok "an unknown hook over MCP is a tool error, not a protocol error" "$badname" 'd["result"]["isError"] is True'
442check "the tool error lists the configured names" "recv" "$badname"
443
444noname=$(mcp '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{}}}')
445json_ok "a trigger with no name is a tool error" "$noname" 'd["result"]["isError"] is True'
446
447redacted=$(mcp '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"webhook_list","arguments":{"redact_url":false}}}')
448check "redact_url=false shows the real endpoint" "/hook" "$redacted"
449
450# =====================================================================
451section "delete"
452# =====================================================================
453api_post "action=delete&$P" '{"name":"dead"}' >/dev/null
454json_ok "a deleted hook is gone" "$(api "action=list&$P")" 'not any(h["name"]=="dead" for h in d["hooks"])'
455d2=$(api_post "action=delete&$P" '{"name":"dead"}')
456json_ok "deleting a missing hook answers 404" "$d2" 'd["ok"] is False'
457
458# =====================================================================
459section "store robustness"
460# =====================================================================
461BROKEN="$tmpdir/broken.json"
462printf 'not json at all' > "$BROKEN"
463b=$(WEBHOOK_STORE_PATH="$BROKEN" QUERY_STRING="action=list&$P" $BIN | body "$(cat)")
464json_ok "a corrupt store is reported, not silently replaced" "$(body "$(WEBHOOK_STORE_PATH="$BROKEN" QUERY_STRING="action=list&$P" $BIN)")" 'd["ok"] is False'
465check "the corrupt store was left untouched" "not json at all" "$(cat "$BROKEN")"
466
467DEEPBODY='{"name":"deep","url":"https://example.com/hook","method":"POST"}'
468WEBHOOK_STORE_PATH="$tmpdir/deep/er/hooks.json" QUERY_STRING="action=save&$P" \
469 REQUEST_METHOD=POST CONTENT_LENGTH=${#DEEPBODY} $BIN <<EOF >/dev/null
470$DEEPBODY
471EOF
472check "a nested store path is created on demand" "deep" "$(cat "$tmpdir/deep/er/hooks.json" 2>/dev/null)"
473if [ -f "$tmpdir/deep/er/hooks.json" ]; then
474 m2=$(stat -c '%a' "$tmpdir/deep/er/hooks.json" 2>/dev/null || stat -f '%Lp' "$tmpdir/deep/er/hooks.json")
475 check "a created store is 0600 too" "600" "$m2"
476fi
477
478# =====================================================================
479section "SHA-256 / HMAC known-answer tests"
480# =====================================================================
481if cc -O2 -std=c99 -Wall -Wextra -Werror -I src tests/sha256_vectors.c src/sha256.c -o "$tmpdir/vec" 2>"$tmpdir/vec.err"; then
482 vout=$("$tmpdir/vec")
483 n_ok=$(printf '%s\n' "$vout" | grep -c '^ok ')
484 if [ "$n_ok" -ge 9 ]; then
485 pass "all $n_ok FIPS / RFC 4231 known-answer vectors match"
486 else
487 fail "only $n_ok known-answer vectors ran"; printf '%s\n' "$vout"
488 fi
489else
490 fail "the vector test did not compile"; head -10 "$tmpdir/vec.err"
491fi
492
493# =====================================================================
494section "source and history safety"
495# =====================================================================
496src=$(cat src/*.c src/*.h 2>/dev/null)
497check_not "no system() call in the plugin" "system(" "$src"
498check_not "no popen() in the plugin" "popen(" "$src"
499check_not "no exec family call in the plugin" "execv(" "$src"
500check_not "the page has no remote script" "<script src=" "$(cat src/ui.html)"
501check_not "the page has no CDN reference" "cdnjs" "$(cat src/ui.html)"
502PRIVATE24="192"".""168."
503check_not "the source has no hard-coded private address" "$PRIVATE24" "$src"
504check_not "the source has no hard-coded loopback exception" "127.0.0.1" "$(cat src/wh_http.c src/plugin_webhook.c src/wh_store.c 2>/dev/null)"
505check "the SSRF deny list covers RFC1918" "0xAC100000u" "$(cat src/wh_http.c)"
506check "the SSRF deny list covers loopback" "0x7F000000u" "$(cat src/wh_http.c)"
507check "TLS verification is required, not optional" "MBEDTLS_SSL_VERIFY_REQUIRED" "$(cat src/wh_tls.c)"
508check_not "there is no insecure TLS bypass in the plugin" "VERIFY_NONE" "$(cat src/wh_tls.c)"
509check "the MCP reader uses read(2) rather than fread(2)" "read(fileno(stdin)" "$(cat src/plugin_webhook.c)"
510check "the page is generated from src/ui.html" "SX_WEBHOOK_UI_HTML_H" "$(cat src/ui_html.h)"
511
512# generated header must be current
513if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
514 pass "src/ui_html.h is up to date with src/ui.html"
515else
516 fail "src/ui_html.h is stale (run tools/gen_ui.py)"
517fi
518
519# =====================================================================
520section "sanitizer build"
521# =====================================================================
522if [ "${SKIP_ASAN:-0}" = "1" ]; then
523 pass "ASan build skipped (SKIP_ASAN=1)"
524else
525 if make -s asan >/dev/null 2>"$tmpdir/asan.log"; then
526 TMPSTORE="$tmpdir/asan-hooks.json"
527 a1=$(WEBHOOK_STORE_PATH="$TMPSTORE" QUERY_STRING="action=list&$P" ./plugin_webhook-asan 2>"$tmpdir/asan-run.err" | body "$(cat)")
528 json_ok "the ASan build answers a list" "$(body "$(WEBHOOK_STORE_PATH="$TMPSTORE" QUERY_STRING="action=list&$P" ./plugin_webhook-asan 2>>"$tmpdir/asan-run.err")")" 'd["ok"] is True'
529 WEBHOOK_STORE_PATH="$TMPSTORE" QUERY_STRING="action=save&$P" REQUEST_METHOD=POST CONTENT_LENGTH=79 ./plugin_webhook-asan >/dev/null 2>>"$tmpdir/asan-run.err" <<'EOF'
530{"name":"asan","url":"https://example.com/hook","method":"POST","sig":"v2","secret":"k"}
531EOF
532 WEBHOOK_STORE_PATH="$TMPSTORE" WEBHOOK_ALLOW_PRIVATE=1 REQUEST_METHOD=POST CONTENT_LENGTH=40 ./plugin_webhook-asan >/dev/null 2>>"$tmpdir/asan-run.err" <<'EOF'
533{"name":"asan","payload":"{\"a\":1}"}
534EOF
535 mcp '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' >/dev/null 2>>"$tmpdir/asan-run.err" || true
536 if grep -q "ERROR: AddressSanitizer\|runtime error:" "$tmpdir/asan-run.err" 2>/dev/null; then
537 fail "the ASan run reported a problem"; head -20 "$tmpdir/asan-run.err"
538 else
539 pass "the ASan/UBSan build ran the API and MCP paths clean"
540 fi
541 else
542 fail "the ASan build failed"; tail -20 "$tmpdir/asan.log"
543 fi
544fi
545
546if make -s fortify >/dev/null 2>"$tmpdir/fort.log"; then
547 f=$(WEBHOOK_STORE_PATH="$tmpdir/f-hooks.json" QUERY_STRING="action=list&$P" ./plugin_webhook-fortify 2>&1)
548 check "the _FORTIFY_SOURCE=2 build answers" '"ok":true' "$f"
549else
550 fail "the _FORTIFY_SOURCE=2 build failed"; tail -20 "$tmpdir/fort.log"
551fi
552
553# =====================================================================
554section "git history"
555# =====================================================================
556if command -v git >/dev/null 2>&1 && [ -d .git ]; then
557 # Every needle is assembled from fragments so this file, which lands in git
558 # history, never contains one whole (the scanner would flag its own line).
559 NEEDLES="ghp_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}|Xboxone""0909|RUNNER_+PASS=|macmini""2018i5"
560 hist=$(git log -p --all 2>/dev/null | grep -E "$NEEDLES" | head -3)
561 if [ -z "$hist" ]; then pass "no token, password or internal hostname in git history"
562 else fail "git history contains a secret or hostname"; printf '%s\n' "$hist"; fi
563 IPCORE="192""\\.168\\."
564 iphist=$(git log -p --all 2>/dev/null | grep -cE "(^|[^0-9])$IPCORE[0-9]+\\.[0-9]+" || true)
565 if [ "${iphist:-0}" = "0" ]; then pass "no private address anywhere in git history"
566 else fail "git history contains $iphist private address line(s)"; fi
567else
568 pass "git history check skipped (not a git checkout)"
569fi
570
571# =====================================================================
572printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
573[ "$FAIL" -eq 0 ] || exit 1
574exit 0