| 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 | |
| 24 | set -u |
| 25 | |
| 26 | ROOT=$(cd "$(dirname "$0")/.." && pwd) |
| 27 | cd "$ROOT" || exit 1 |
| 28 | |
| 29 | BIN=./plugin_webhook |
| 30 | PASS=0 |
| 31 | FAIL=0 |
| 32 | |
| 33 | if [ -t 1 ]; then |
| 34 | C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') |
| 35 | else |
| 36 | C_OK=; C_BAD=; C_B=; C_0= |
| 37 | fi |
| 38 | pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } |
| 39 | fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } |
| 40 | |
| 41 | check() { # 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 | } |
| 46 | check_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 | } |
| 51 | section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } |
| 52 | |
| 53 | # strip CGI headers, drop CRs, keep the payload |
| 54 | body() { |
| 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 | |
| 64 | json_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 | |
| 73 | api() { body "$(QUERY_STRING="$1" $BIN)"; } |
| 74 | apiraw() { QUERY_STRING="$1" $BIN; } |
| 75 | |
| 76 | # api_post <query-string> <json-payload> |
| 77 | api_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 |
| 83 | mcp() { |
| 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). |
| 91 | mcp_two_write() { |
| 92 | { printf '%s' "$1"; sleep 0.15; printf '\n'; } | $BIN --mcp |
| 93 | } |
| 94 | |
| 95 | tmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t wh) |
| 96 | trap 'rm -rf "$tmpdir"; [ -n "${RECV_PID:-}" ] && kill "$RECV_PID" 2>/dev/null' EXIT INT TERM |
| 97 | |
| 98 | export WEBHOOK_STORE_PATH="$tmpdir/hooks.json" |
| 99 | export BOT_PASSWORD="suite-password-not-a-real-secret" |
| 100 | unset WEBHOOK_ALLOW_PRIVATE |
| 101 | |
| 102 | # ===================================================================== |
| 103 | section "discovery (--meta / --schema)" |
| 104 | # ===================================================================== |
| 105 | meta=$($BIN --meta) |
| 106 | json_ok "--meta is one JSON object" "$meta" |
| 107 | json_ok "--meta name is webhook" "$meta" 'd["name"]=="webhook"' |
| 108 | json_ok "--meta desc is short (<=15)" "$meta" 'len(d["desc"])<=15' |
| 109 | json_ok "--meta kind is mcp" "$meta" 'd["kind"]=="mcp"' |
| 110 | json_ok "--meta mcp true" "$meta" 'd["mcp"] is True' |
| 111 | json_ok "--meta daemon false" "$meta" 'd["daemon"] is False' |
| 112 | json_ok "--meta menus false" "$meta" 'd["menus"] is False' |
| 113 | json_ok "--meta verified live" "$meta" 'd["verified"]=="live"' |
| 114 | json_ok "--meta version matches plugin.json" "$meta" 'd["version"]=="1.0.3"' |
| 115 | check "--meta is a single line" "1" "$($BIN --meta | wc -l | tr -d ' ')" |
| 116 | |
| 117 | schema=$($BIN --schema) |
| 118 | json_ok "--schema lists tools" "$schema" 'len(d["tools"])==2' |
| 119 | json_ok "--schema has webhook_list" "$schema" '[t["name"] for t in d["tools"]]==["webhook_list","webhook_trigger"]' |
| 120 | json_ok "--schema tool has an input schema" "$schema" 'd["tools"][1]["inputSchema"]["required"]==["name"]' |
| 121 | check "SX_PLUGIN_META env also emits metadata" '"kind":"mcp"' "$(SX_PLUGIN_META=1 $BIN)" |
| 122 | |
| 123 | # ===================================================================== |
| 124 | section "--mcp session" |
| 125 | # ===================================================================== |
| 126 | mcp_out=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"suite","version":"1"}}}') |
| 127 | json_ok "initialize returns a result" "$mcp_out" 'd["result"]["protocolVersion"]=="2024-11-05"' |
| 128 | json_ok "initialize names the server" "$mcp_out" 'd["result"]["serverInfo"]["name"]=="plugin_webhook"' |
| 129 | json_ok "initialize advertises tools" "$mcp_out" '"tools" in d["result"]["capabilities"]' |
| 130 | |
| 131 | tl=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}') |
| 132 | json_ok "tools/list returns two tools" "$tl" 'len(d["result"]["tools"])==2' |
| 133 | json_ok "webhook_list has a description" "$tl" 'len(d["result"]["tools"][0]["description"])>40' |
| 134 | |
| 135 | pl=$(mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}') |
| 136 | json_ok "webhook_list on an empty store succeeds" "$pl" 'd["result"].get("isError") is not True' |
| 137 | check "webhook_list says nothing is configured" "No webhooks are configured" "$pl" |
| 138 | |
| 139 | ping=$(mcp '{"jsonrpc":"2.0","id":4,"method":"ping"}') |
| 140 | json_ok "ping answers" "$ping" 'd["result"]=={}' |
| 141 | |
| 142 | note=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}') |
| 143 | if [ -z "$(printf '%s' "$note" | tr -d '\n')" ]; then |
| 144 | pass "a notification produces no reply" |
| 145 | else |
| 146 | fail "a notification produced a reply"; printf ' got: %s\n' "$note" |
| 147 | fi |
| 148 | |
| 149 | bad=$(mcp 'not json at all') |
| 150 | json_ok "a parse error answers -32700 with a null id" "$bad" 'd["error"]["code"]==-32700 and d["id"] is None' |
| 151 | |
| 152 | unk=$(mcp '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}') |
| 153 | json_ok "an unknown tool answers -32602" "$unk" 'd["error"]["code"]==-32602' |
| 154 | |
| 155 | none=$(mcp '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"arguments":{}}}') |
| 156 | json_ok "a call with no tool name answers -32602" "$none" 'd["error"]["code"]==-32602' |
| 157 | |
| 158 | meth=$(mcp '{"jsonrpc":"2.0","id":7,"method":"no/such/method"}') |
| 159 | json_ok "an unknown method answers -32601" "$meth" 'd["error"]["code"]==-32601' |
| 160 | |
| 161 | tw=$(mcp_two_write '{"jsonrpc":"2.0","id":8,"method":"tools/list"}') |
| 162 | json_ok "two-write framing (router proc_send shape) is read, not hung" "$tw" 'len(d["result"]["tools"])==2' |
| 163 | |
| 164 | # ===================================================================== |
| 165 | section "HTML page" |
| 166 | # ===================================================================== |
| 167 | page=$(apiraw "") |
| 168 | check_not "an unauthenticated page is refused" "<!DOCTYPE" "$page" |
| 169 | check "an unauthenticated page answers 401" "Status: 401" "$page" |
| 170 | json_ok "the 401 body is JSON" "$(body "$page")" 'd["ok"] is False' |
| 171 | |
| 172 | apage=$(apiraw "pwd=suite-password-not-a-real-secret") |
| 173 | check "the authenticated page is HTML" "Content-Type: text/html" "$apage" |
| 174 | check_not "the page has no <script src=>" "<script src=" "$apage" |
| 175 | check_not "the page pulls nothing from a CDN" "cdnjs" "$apage" |
| 176 | check_not "the page has no http:// asset reference" "http://cdn" "$apage" |
| 177 | check "the page carries the bot theme tokens" "--bg-card" "$apage" |
| 178 | check "the page carries the prepaint script" "bot_theme" "$apage" |
| 179 | check "the page carries the theme handoff" "sx-theme-request" "$apage" |
| 180 | check "the page hides its chrome when embedded" "html.embedded" "$apage" |
| 181 | check "the page names the light theme rule" "data-theme" "$apage" |
| 182 | check "the page shows the hook table" "Recent deliveries" "$apage" |
| 183 | check "the page mentions both tools" "webhook_trigger" "$apage" |
| 184 | |
| 185 | embed=$(apiraw "pwd=suite-password-not-a-real-secret&embed=1") |
| 186 | check "?embed=1 is accepted" "Content-Type: text/html" "$embed" |
| 187 | light=$(apiraw "pwd=suite-password-not-a-real-secret&theme=light") |
| 188 | check "?theme=light sets data-theme before paint" "setAttribute('data-theme','light')" "$light" |
| 189 | |
| 190 | json_ok "an unauthenticated action is refused" "$(body "$(apiraw 'action=list')")" 'd["ok"] is False' |
| 191 | |
| 192 | # ===================================================================== |
| 193 | section "store CRUD, secrets, and the 0600 file" |
| 194 | # ===================================================================== |
| 195 | P="pwd=suite-password-not-a-real-secret" |
| 196 | lst=$(api "action=list&$P") |
| 197 | json_ok "an empty store lists zero hooks" "$lst" 'd["count"]==0 and d["hooks"]==[] and d["log"]==[]' |
| 198 | json_ok "the list reports the SSRF policy" "$lst" 'd["allow_private"] is False' |
| 199 | |
| 200 | saved=$(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"}]}') |
| 201 | json_ok "save creates a hook" "$saved" 'd["ok"] is True and d["saved"]=="demo"' |
| 202 | |
| 203 | lst=$(api "action=list&$P") |
| 204 | json_ok "the hook is listed" "$lst" 'd["count"]==1 and d["hooks"][0]["name"]=="demo"' |
| 205 | check_not "the list does not leak the header value" "Bearer abc123" "$lst" |
| 206 | check_not "the list does not leak the HMAC secret" "s3cr3t-value" "$lst" |
| 207 | json_ok "the header is reported as a secret presence only" "$lst" 'd["hooks"][0]["headers"][0]=={"name":"Authorization","has_secret":True}' |
| 208 | json_ok "the hook reports it has an HMAC secret" "$lst" 'd["hooks"][0]["has_secret"] is True' |
| 209 | json_ok "the signature scheme is reported" "$lst" 'd["hooks"][0]["sig"]=="github"' |
| 210 | json_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"])' |
| 213 | check_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 |
| 216 | if [ -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")" |
| 220 | else |
| 221 | fail "the store file was not written at \$WEBHOOK_STORE_PATH" |
| 222 | fi |
| 223 | |
| 224 | # editing without resending a secret keeps it |
| 225 | api_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 |
| 226 | json_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"])' |
| 228 | check "the stored secret survived the edit" "s3cr3t-value" "$(cat "$WEBHOOK_STORE_PATH")" |
| 229 | check "the kept header value survived the edit" "Bearer abc123" "$(cat "$WEBHOOK_STORE_PATH")" |
| 230 | check "the replaced header value is the new one" "two" "$(cat "$WEBHOOK_STORE_PATH")" |
| 231 | |
| 232 | # validation |
| 233 | v1=$(api_post "action=save&$P" '{"name":"bad name with spaces","url":"https://example.com/x","method":"POST"}') |
| 234 | json_ok "a name with spaces is refused" "$v1" 'd["ok"] is False and "name" in d["error"].lower()' |
| 235 | v2=$(api_post "action=save&$P" '{"name":"badurl","url":"ftp://example.com/x","method":"POST"}') |
| 236 | json_ok "a non-http scheme is refused" "$v2" 'd["ok"] is False' |
| 237 | v3=$(api_post "action=save&$P" '{"name":"badverbm","url":"https://example.com/x","method":"TRACE"}') |
| 238 | json_ok "an unsupported method is refused" "$v3" 'd["ok"] is False' |
| 239 | v4=$(api_post "action=save&$P" '{"name":"nosigsecret","url":"https://example.com/x","method":"POST","sig":"v2"}') |
| 240 | json_ok "a signature scheme with no secret is refused" "$v4" 'd["ok"] is False' |
| 241 | v5=$(api_post "action=save&$P" '{"name":"creds","url":"https://user:pw@example.com/x","method":"POST"}') |
| 242 | json_ok "credentials in the url are refused" "$v5" 'd["ok"] is False' |
| 243 | v6=$(api_post "action=save&$P" 'not json') |
| 244 | json_ok "a non-JSON body is refused" "$v6" 'd["ok"] is False' |
| 245 | v7=$(api_post "action=save&$P" '{"name":"crlf","url":"https://example.com/x","method":"POST","headers":[{"name":"X-Bad","value":"a\r\nB: c"}]}') |
| 246 | json_ok "a header value with CRLF is refused" "$v7" 'd["ok"] is False' |
| 247 | v8=$(api_post "action=save&$P" '{"name":"badhdr","url":"https://example.com/x","method":"POST","headers":[{"name":"X Bad","value":"v"}]}') |
| 248 | json_ok "a header name with a space is refused" "$v8" 'd["ok"] is False' |
| 249 | v9=$(api_post "action=save&$P" '{"name":"demo","url":"https://example.com/x","method":"POST"}') |
| 250 | json_ok "a duplicate name is refused on create" "$v9" 'd["ok"] is False and "exists" in d["error"]' |
| 251 | |
| 252 | # ===================================================================== |
| 253 | section "SSRF policy" |
| 254 | # ===================================================================== |
| 255 | ssrf=$(api_post "action=save&$P" '{"name":"local","url":"http://127.0.0.1:9/hook","method":"POST"}') |
| 256 | json_ok "a loopback hook can be stored (it is not fired yet)" "$ssrf" 'd["ok"] is True' |
| 257 | FIREBODY='{"name":"local","payload":"{}"}' |
| 258 | fire_raw=$(printf '%s' "$FIREBODY" | CONTENT_LENGTH=${#FIREBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN) |
| 259 | fire=$(body "$fire_raw") |
| 260 | check "firing at loopback is refused while the policy is closed" "Status: 502" "$fire_raw" |
| 261 | json_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 | # ===================================================================== |
| 264 | section "delivery against a recording receiver" |
| 265 | # ===================================================================== |
| 266 | LOG="$tmpdir/recv.jsonl" |
| 267 | python3 tests/mockrecv.py --port 0 --log "$LOG" --delay 0.3 > "$tmpdir/recv.out" 2>"$tmpdir/recv.err" & |
| 268 | RECV_PID=$! |
| 269 | i=0 |
| 270 | while [ $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 |
| 274 | done |
| 275 | if [ -z "${PORT:-}" ]; then |
| 276 | fail "the recording receiver did not start"; cat "$tmpdir/recv.err" | head -5 |
| 277 | else |
| 278 | pass "the recording receiver is listening on 127.0.0.1:$PORT" |
| 279 | fi |
| 280 | |
| 281 | export WEBHOOK_ALLOW_PRIVATE=1 |
| 282 | json_ok "the list reports the opt-in once it is set" "$(api "action=list&$P")" 'd["allow_private"] is True' |
| 283 | |
| 284 | api_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 | |
| 286 | PAYLOAD='{"event":"deploy","n":1,"nested":{"a":[1,2,3]}}' |
| 287 | fire=$(api_post "action=fire&$P" "{\"name\":\"recv\",\"payload\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$PAYLOAD")}") |
| 288 | json_ok "a fire to the mock succeeds" "$fire" 'd["ok"] is True and d["delivered"] is True' |
| 289 | json_ok "the fire reports HTTP 200" "$fire" 'd["status"]==200 and d["ok_status"] is True' |
| 290 | json_ok "the fire reports bytes and latency" "$fire" 'd["bytes"]>0 and d["ms"]>=0' |
| 291 | |
| 292 | python3 - "$LOG" "$PAYLOAD" <<'PY' |
| 293 | import hashlib, hmac, json, sys |
| 294 | log, payload = sys.argv[1], sys.argv[2] |
| 295 | lines = [json.loads(l) for l in open(log) if l.strip()] |
| 296 | ok = 0 |
| 297 | bad = [] |
| 298 | |
| 299 | def want(cond, msg): |
| 300 | global ok |
| 301 | if cond: |
| 302 | ok += 1 |
| 303 | else: |
| 304 | bad.append(msg) |
| 305 | |
| 306 | want(len(lines) == 1, "exactly one request was recorded (got %d)" % len(lines)) |
| 307 | if 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)) |
| 326 | for b in bad: |
| 327 | print(" " + b) |
| 328 | print("MATCHED %d" % ok) |
| 329 | PY |
| 330 | sigres=$? |
| 331 | if [ $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 | |
| 333 | json_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 --------------------------- |
| 337 | api_post "action=save&$P" "{\"name\":\"recvq\",\"url\":\"http://127.0.0.1:$PORT/echo\",\"method\":\"POST\",\"sig\":\"gitlab\",\"secret\":\"tok-shared\"}" >/dev/null |
| 338 | fireq=$(api_post "action=fire&$P" '{"name":"recvq","payload":{"a":1},"query":"event=deploy&env=prod"}') |
| 339 | json_ok "a fire with a query string and an object payload succeeds" "$fireq" 'd["delivered"] is True' |
| 340 | json_ok "an object payload is serialised as JSON" "$fireq" 'd["body_preview"]=="{\"a\":1}"' |
| 341 | python3 - "$LOG" <<'PY' |
| 342 | import json, sys |
| 343 | lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] |
| 344 | last = lines[-1] |
| 345 | h = {k.lower(): v for k, v in last["headers"].items()} |
| 346 | assert last["path"] == "/echo?event=deploy&env=prod", last["path"] |
| 347 | assert last["body"] == '{"a":1}', last["body"] |
| 348 | assert h.get("x-gitlab-token") == "tok-shared", h.get("x-gitlab-token") |
| 349 | PY |
| 350 | if [ $? -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 --------------------------------------------- |
| 353 | api_post "action=save&$P" "{\"name\":\"recvv2\",\"url\":\"http://127.0.0.1:$PORT/hook\",\"method\":\"POST\",\"sig\":\"v2\",\"secret\":\"v2-key\"}" >/dev/null |
| 354 | api_post "action=fire&$P" '{"name":"recvv2","payload":"{\"x\":\"y\"}"}' >/dev/null |
| 355 | python3 - "$LOG" <<'PY' |
| 356 | import hashlib, hmac, json, sys, time |
| 357 | lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] |
| 358 | last = lines[-1] |
| 359 | h = {k.lower(): v for k, v in last["headers"].items()} |
| 360 | ts = h.get("x-webhook-timestamp", "") |
| 361 | sig = h.get("x-webhook-signature", "") |
| 362 | body = last["body"] |
| 363 | expect = hmac.new(b"v2-key", (ts + "." + body).encode(), hashlib.sha256).hexdigest() |
| 364 | assert sig == "t=%s,v1=%s" % (ts, expect), (sig, expect) |
| 365 | assert abs(int(ts) - int(time.time())) < 60, ts |
| 366 | PY |
| 367 | if [ $? -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 -------------------------------------------------------------- |
| 370 | for 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' |
| 374 | done |
| 375 | python3 - "$LOG" <<'PY' |
| 376 | import json, sys |
| 377 | lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] |
| 378 | verbs = [l["method"] for l in lines[-5:]] |
| 379 | assert verbs == ["GET", "PUT", "PATCH", "DELETE", "HEAD"], verbs |
| 380 | PY |
| 381 | if [ $? -eq 0 ]; then pass "the method on the wire is the method configured"; else fail "method dispatch is wrong"; fi |
| 382 | |
| 383 | # --- response handling ---------------------------------------------------- |
| 384 | api_post "action=save&$P" "{\"name\":\"r418\",\"url\":\"http://127.0.0.1:$PORT/status/418\",\"method\":\"POST\"}" >/dev/null |
| 385 | r=$(api_post "action=fire&$P" '{"name":"r418","payload":"{}"}') |
| 386 | json_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' |
| 387 | json_ok "the 4xx body is carried back" "$r" '"requested" in d["body_preview"]' |
| 388 | |
| 389 | api_post "action=save&$P" "{\"name\":\"redir\",\"url\":\"http://127.0.0.1:$PORT/redirect\",\"method\":\"POST\"}" >/dev/null |
| 390 | r=$(api_post "action=fire&$P" '{"name":"redir","payload":"{}"}') |
| 391 | json_ok "a redirect is reported, never followed" "$r" 'd["delivered"] is True and d["status"]==302' |
| 392 | |
| 393 | api_post "action=save&$P" "{\"name\":\"chunky\",\"url\":\"http://127.0.0.1:$PORT/chunked\",\"method\":\"POST\"}" >/dev/null |
| 394 | r=$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}') |
| 395 | json_ok "a chunked response body is decoded" "$r" 'd["body_preview"]=="{\"chunked\":true}"' |
| 396 | check_not "the chunk framing did not leak into the body" "2\r" "$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}')" |
| 397 | |
| 398 | api_post "action=save&$P" "{\"name\":\"big\",\"url\":\"http://127.0.0.1:$PORT/big\",\"method\":\"POST\"}" >/dev/null |
| 399 | r=$(api_post "action=fire&$P" '{"name":"big","payload":"{}"}') |
| 400 | json_ok "an oversized response is truncated and says so" "$r" 'd["truncated"] is True and d["bytes"]<=4096' |
| 401 | |
| 402 | # --- refusal paths -------------------------------------------------------- |
| 403 | NFBODY='{"name":"nope","payload":"{}"}' |
| 404 | nf_raw=$(printf '%s' "$NFBODY" | CONTENT_LENGTH=${#NFBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN) |
| 405 | nf=$(body "$nf_raw") |
| 406 | check "firing an unknown hook answers 404" "Status: 404" "$nf_raw" |
| 407 | json_ok "the unknown-hook body is JSON" "$nf" 'd["ok"] is False' |
| 408 | |
| 409 | dead=$(api_post "action=save&$P" '{"name":"dead","url":"http://127.0.0.1:1/hook","method":"POST"}') |
| 410 | d=$(api_post "action=fire&$P" '{"name":"dead","payload":"{}"}') |
| 411 | json_ok "an unreachable endpoint is reported, not crashed" "$d" 'd["ok"] is False and d["delivered"] is False and len(d["error"])>0' |
| 412 | json_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 | # ===================================================================== |
| 416 | section "--mcp tool calls against the live store" |
| 417 | # ===================================================================== |
| 418 | tl=$(mcp '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}') |
| 419 | check "webhook_list reports the stored hooks" "recv" "$tl" |
| 420 | check_not "webhook_list never returns a header value" "Bearer tok-42" "$tl" |
| 421 | check_not "webhook_list never returns the HMAC secret" "hmac-key-1" "$tl" |
| 422 | check_not "webhook_list redacts the query string" "event=deploy" "$tl" |
| 423 | |
| 424 | tr=$(mcp '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"recv","payload":{"from":"mcp"}}}}') |
| 425 | json_ok "webhook_trigger succeeds" "$tr" 'd["result"].get("isError") is not True' |
| 426 | check "the tool result reports the HTTP status" "HTTP 200" "$tr" |
| 427 | check_not "the tool result carries no secret" "hmac-key-1" "$tr" |
| 428 | |
| 429 | python3 - "$LOG" <<'PY' |
| 430 | import hashlib, hmac, json, sys |
| 431 | lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] |
| 432 | last = lines[-1] |
| 433 | h = {k.lower(): v for k, v in last["headers"].items()} |
| 434 | assert last["body"] == '{"from":"mcp"}', last["body"] |
| 435 | expect = "sha256=" + hmac.new(b"hmac-key-1", last["body"].encode(), hashlib.sha256).hexdigest() |
| 436 | assert h.get("x-hub-signature-256") == expect, h.get("x-hub-signature-256") |
| 437 | PY |
| 438 | if [ $? -eq 0 ]; then pass "an object payload over MCP is signed and delivered correctly"; else fail "MCP payload/signature mismatch"; fi |
| 439 | |
| 440 | badname=$(mcp '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"nope"}}}') |
| 441 | json_ok "an unknown hook over MCP is a tool error, not a protocol error" "$badname" 'd["result"]["isError"] is True' |
| 442 | check "the tool error lists the configured names" "recv" "$badname" |
| 443 | |
| 444 | noname=$(mcp '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{}}}') |
| 445 | json_ok "a trigger with no name is a tool error" "$noname" 'd["result"]["isError"] is True' |
| 446 | |
| 447 | redacted=$(mcp '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"webhook_list","arguments":{"redact_url":false}}}') |
| 448 | check "redact_url=false shows the real endpoint" "/hook" "$redacted" |
| 449 | |
| 450 | # ===================================================================== |
| 451 | section "delete" |
| 452 | # ===================================================================== |
| 453 | api_post "action=delete&$P" '{"name":"dead"}' >/dev/null |
| 454 | json_ok "a deleted hook is gone" "$(api "action=list&$P")" 'not any(h["name"]=="dead" for h in d["hooks"])' |
| 455 | d2=$(api_post "action=delete&$P" '{"name":"dead"}') |
| 456 | json_ok "deleting a missing hook answers 404" "$d2" 'd["ok"] is False' |
| 457 | |
| 458 | # ===================================================================== |
| 459 | section "store robustness" |
| 460 | # ===================================================================== |
| 461 | BROKEN="$tmpdir/broken.json" |
| 462 | printf 'not json at all' > "$BROKEN" |
| 463 | b=$(WEBHOOK_STORE_PATH="$BROKEN" QUERY_STRING="action=list&$P" $BIN | body "$(cat)") |
| 464 | json_ok "a corrupt store is reported, not silently replaced" "$(body "$(WEBHOOK_STORE_PATH="$BROKEN" QUERY_STRING="action=list&$P" $BIN)")" 'd["ok"] is False' |
| 465 | check "the corrupt store was left untouched" "not json at all" "$(cat "$BROKEN")" |
| 466 | |
| 467 | DEEPBODY='{"name":"deep","url":"https://example.com/hook","method":"POST"}' |
| 468 | WEBHOOK_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 |
| 471 | EOF |
| 472 | check "a nested store path is created on demand" "deep" "$(cat "$tmpdir/deep/er/hooks.json" 2>/dev/null)" |
| 473 | if [ -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" |
| 476 | fi |
| 477 | |
| 478 | # ===================================================================== |
| 479 | section "SHA-256 / HMAC known-answer tests" |
| 480 | # ===================================================================== |
| 481 | if 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 |
| 489 | else |
| 490 | fail "the vector test did not compile"; head -10 "$tmpdir/vec.err" |
| 491 | fi |
| 492 | |
| 493 | # ===================================================================== |
| 494 | section "source and history safety" |
| 495 | # ===================================================================== |
| 496 | src=$(cat src/*.c src/*.h 2>/dev/null) |
| 497 | check_not "no system() call in the plugin" "system(" "$src" |
| 498 | check_not "no popen() in the plugin" "popen(" "$src" |
| 499 | check_not "no exec family call in the plugin" "execv(" "$src" |
| 500 | check_not "the page has no remote script" "<script src=" "$(cat src/ui.html)" |
| 501 | check_not "the page has no CDN reference" "cdnjs" "$(cat src/ui.html)" |
| 502 | PRIVATE24="192"".""168." |
| 503 | check_not "the source has no hard-coded private address" "$PRIVATE24" "$src" |
| 504 | check_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)" |
| 505 | check "the SSRF deny list covers RFC1918" "0xAC100000u" "$(cat src/wh_http.c)" |
| 506 | check "the SSRF deny list covers loopback" "0x7F000000u" "$(cat src/wh_http.c)" |
| 507 | check "TLS verification is required, not optional" "MBEDTLS_SSL_VERIFY_REQUIRED" "$(cat src/wh_tls.c)" |
| 508 | check_not "there is no insecure TLS bypass in the plugin" "VERIFY_NONE" "$(cat src/wh_tls.c)" |
| 509 | check "the MCP reader uses read(2) rather than fread(2)" "read(fileno(stdin)" "$(cat src/plugin_webhook.c)" |
| 510 | check "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 |
| 513 | if 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" |
| 515 | else |
| 516 | fail "src/ui_html.h is stale (run tools/gen_ui.py)" |
| 517 | fi |
| 518 | |
| 519 | # ===================================================================== |
| 520 | section "sanitizer build" |
| 521 | # ===================================================================== |
| 522 | if [ "${SKIP_ASAN:-0}" = "1" ]; then |
| 523 | pass "ASan build skipped (SKIP_ASAN=1)" |
| 524 | else |
| 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"} |
| 531 | EOF |
| 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}"} |
| 534 | EOF |
| 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 |
| 544 | fi |
| 545 | |
| 546 | if 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" |
| 549 | else |
| 550 | fail "the _FORTIFY_SOURCE=2 build failed"; tail -20 "$tmpdir/fort.log" |
| 551 | fi |
| 552 | |
| 553 | # ===================================================================== |
| 554 | section "git history" |
| 555 | # ===================================================================== |
| 556 | if 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 |
| 567 | else |
| 568 | pass "git history check skipped (not a git checkout)" |
| 569 | fi |
| 570 | |
| 571 | # ===================================================================== |
| 572 | printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0" |
| 573 | [ "$FAIL" -eq 0 ] || exit 1 |
| 574 | exit 0 |