#!/bin/sh
# tests/run.sh - offline checks for plugin_webhook across every mode.
#
# No network beyond a loopback receiver the suite starts itself (tests/
# mockrecv.py), which records the method, path, query and EVERY header of each
# request it gets. That is the point of the suite: it asserts that the request
# the plugin actually put on the wire matches the hook definition - method,
# path, custom headers, HMAC signature over the exact body bytes - instead of
# merely asserting that something returned 200.
#
#   --meta / --schema   the discovery contract the node and the router read
#   --mcp               a full JSON-RPC session: handshake, both tools, every
#                       documented refusal, and the router's two-write framing
#   CGI JSON API        CRUD, secret redaction, the 0600 store, delivery log
#   HTML                the page: bot theme, no <script src=>, embed, ?theme=
#   SSRF                loopback refused by default, allowed with the opt-in
#   signatures          github / gitlab / v2, verified against python hmac
#   robustness          4xx, redirect, chunked, oversized body, truncation
#   safety              no popen/system, ASan+UBSan+fortify clean, no secret,
#                       no private address, no internal hostname in git history
#
# Exit 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_webhook
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 500)"
    fi
}
check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 400)"
    else pass "$1"; fi
}
section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

# strip CGI headers, drop CRs, keep the payload
body() {
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Referrer-Policy|Content-Security-Policy|X-Frame-Options):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    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
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 500)"
    fi
}

api() { body "$(QUERY_STRING="$1" $BIN)"; }
apiraw() { QUERY_STRING="$1" $BIN; }

# api_post <query-string> <json-payload>
api_post() {
    _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
    body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
}

# mcp <lines...> - one JSON reply per line
mcp() {
    printf '%s\n' "$@" | $BIN --mcp
}

# mcp_two_write <line> - the connector router's proc_send() shape: the body and
# the terminating newline arrive as two separate writes. A reader that uses
# fread() blocks forever here, so this is the assertion that the MCP loop reads
# with read(2).
mcp_two_write() {
    { printf '%s' "$1"; sleep 0.15; printf '\n'; } | $BIN --mcp
}

tmpdir=$(mktemp -d 2>/dev/null || mktemp -d -t wh)
trap 'rm -rf "$tmpdir"; [ -n "${RECV_PID:-}" ] && kill "$RECV_PID" 2>/dev/null' EXIT INT TERM

export WEBHOOK_STORE_PATH="$tmpdir/hooks.json"
export BOT_PASSWORD="suite-password-not-a-real-secret"
unset WEBHOOK_ALLOW_PRIVATE

# =====================================================================
section "discovery (--meta / --schema)"
# =====================================================================
meta=$($BIN --meta)
json_ok "--meta is one JSON object" "$meta"
json_ok "--meta name is webhook" "$meta" 'd["name"]=="webhook"'
json_ok "--meta desc is short (<=15)" "$meta" 'len(d["desc"])<=15'
json_ok "--meta kind is mcp" "$meta" 'd["kind"]=="mcp"'
json_ok "--meta mcp true" "$meta" 'd["mcp"] is True'
json_ok "--meta daemon false" "$meta" 'd["daemon"] is False'
json_ok "--meta menus false" "$meta" 'd["menus"] is False'
json_ok "--meta verified live" "$meta" 'd["verified"]=="live"'
json_ok "--meta version matches plugin.json" "$meta" 'd["version"]=="1.0.3"'
check "--meta is a single line" "1" "$($BIN --meta | wc -l | tr -d ' ')"

schema=$($BIN --schema)
json_ok "--schema lists tools" "$schema" 'len(d["tools"])==2'
json_ok "--schema has webhook_list" "$schema" '[t["name"] for t in d["tools"]]==["webhook_list","webhook_trigger"]'
json_ok "--schema tool has an input schema" "$schema" 'd["tools"][1]["inputSchema"]["required"]==["name"]'
check "SX_PLUGIN_META env also emits metadata" '"kind":"mcp"' "$(SX_PLUGIN_META=1 $BIN)"

# =====================================================================
section "--mcp session"
# =====================================================================
mcp_out=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"suite","version":"1"}}}')
json_ok "initialize returns a result" "$mcp_out" 'd["result"]["protocolVersion"]=="2024-11-05"'
json_ok "initialize names the server" "$mcp_out" 'd["result"]["serverInfo"]["name"]=="plugin_webhook"'
json_ok "initialize advertises tools" "$mcp_out" '"tools" in d["result"]["capabilities"]'

tl=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}')
json_ok "tools/list returns two tools" "$tl" 'len(d["result"]["tools"])==2'
json_ok "webhook_list has a description" "$tl" 'len(d["result"]["tools"][0]["description"])>40'

pl=$(mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}')
json_ok "webhook_list on an empty store succeeds" "$pl" 'd["result"].get("isError") is not True'
check "webhook_list says nothing is configured" "No webhooks are configured" "$pl"

ping=$(mcp '{"jsonrpc":"2.0","id":4,"method":"ping"}')
json_ok "ping answers" "$ping" 'd["result"]=={}'

note=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}')
if [ -z "$(printf '%s' "$note" | tr -d '\n')" ]; then
    pass "a notification produces no reply"
else
    fail "a notification produced a reply"; printf '       got: %s\n' "$note"
fi

bad=$(mcp 'not json at all')
json_ok "a parse error answers -32700 with a null id" "$bad" 'd["error"]["code"]==-32700 and d["id"] is None'

unk=$(mcp '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}')
json_ok "an unknown tool answers -32602" "$unk" 'd["error"]["code"]==-32602'

none=$(mcp '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"arguments":{}}}')
json_ok "a call with no tool name answers -32602" "$none" 'd["error"]["code"]==-32602'

meth=$(mcp '{"jsonrpc":"2.0","id":7,"method":"no/such/method"}')
json_ok "an unknown method answers -32601" "$meth" 'd["error"]["code"]==-32601'

tw=$(mcp_two_write '{"jsonrpc":"2.0","id":8,"method":"tools/list"}')
json_ok "two-write framing (router proc_send shape) is read, not hung" "$tw" 'len(d["result"]["tools"])==2'

# =====================================================================
section "HTML page"
# =====================================================================
page=$(apiraw "")
check_not "an unauthenticated page is refused" "<!DOCTYPE" "$page"
check "an unauthenticated page answers 401" "Status: 401" "$page"
json_ok "the 401 body is JSON" "$(body "$page")" 'd["ok"] is False'

apage=$(apiraw "pwd=suite-password-not-a-real-secret")
check "the authenticated page is HTML" "Content-Type: text/html" "$apage"
check_not "the page has no <script src=>" "<script src=" "$apage"
check_not "the page pulls nothing from a CDN" "cdnjs" "$apage"
check_not "the page has no http:// asset reference" "http://cdn" "$apage"
check "the page carries the bot theme tokens" "--bg-card" "$apage"
check "the page carries the prepaint script" "bot_theme" "$apage"
check "the page carries the theme handoff" "sx-theme-request" "$apage"
check "the page hides its chrome when embedded" "html.embedded" "$apage"
check "the page names the light theme rule" "data-theme" "$apage"
check "the page shows the hook table" "Recent deliveries" "$apage"
check "the page mentions both tools" "webhook_trigger" "$apage"

embed=$(apiraw "pwd=suite-password-not-a-real-secret&embed=1")
check "?embed=1 is accepted" "Content-Type: text/html" "$embed"
light=$(apiraw "pwd=suite-password-not-a-real-secret&theme=light")
check "?theme=light sets data-theme before paint" "setAttribute('data-theme','light')" "$light"

json_ok "an unauthenticated action is refused" "$(body "$(apiraw 'action=list')")" 'd["ok"] is False'

# =====================================================================
section "store CRUD, secrets, and the 0600 file"
# =====================================================================
P="pwd=suite-password-not-a-real-secret"
lst=$(api "action=list&$P")
json_ok "an empty store lists zero hooks" "$lst" 'd["count"]==0 and d["hooks"]==[] and d["log"]==[]'
json_ok "the list reports the SSRF policy" "$lst" 'd["allow_private"] is False'

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"}]}')
json_ok "save creates a hook" "$saved" 'd["ok"] is True and d["saved"]=="demo"'

lst=$(api "action=list&$P")
json_ok "the hook is listed" "$lst" 'd["count"]==1 and d["hooks"][0]["name"]=="demo"'
check_not "the list does not leak the header value" "Bearer abc123" "$lst"
check_not "the list does not leak the HMAC secret" "s3cr3t-value" "$lst"
json_ok "the header is reported as a secret presence only" "$lst" 'd["hooks"][0]["headers"][0]=={"name":"Authorization","has_secret":True}'
json_ok "the hook reports it has an HMAC secret" "$lst" 'd["hooks"][0]["has_secret"] is True'
json_ok "the signature scheme is reported" "$lst" 'd["hooks"][0]["sig"]=="github"'
json_ok "the query string of a stored url is redacted in the list" \
    "$(api_post "action=save&$P" '{"name":"qtoken","url":"https://example.com/hook?token=abcdef","method":"POST"}' >/dev/null; api "action=list&$P")" \
    'any(h["name"]=="qtoken" and h["url"].endswith("?<redacted>") for h in d["hooks"])'
check_not "the listed url does not carry the pasted token" "abcdef" "$(api "action=list&$P")"

# store file: mode 0600, and the secret really is in it
if [ -f "$WEBHOOK_STORE_PATH" ]; then
    mode=$(stat -c '%a' "$WEBHOOK_STORE_PATH" 2>/dev/null || stat -f '%Lp' "$WEBHOOK_STORE_PATH")
    check "the store file is mode 0600" "600" "$mode"
    check "the store file does hold the secret (it must, to sign)" "s3cr3t-value" "$(cat "$WEBHOOK_STORE_PATH")"
else
    fail "the store file was not written at \$WEBHOOK_STORE_PATH"
fi

# editing without resending a secret keeps it
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
json_ok "an edit without a secret keeps the stored HMAC secret" "$(api "action=list&$P")" \
    'any(h["name"]=="demo" and h["method"]=="PUT" and h["has_secret"] for h in d["hooks"])'
check "the stored secret survived the edit" "s3cr3t-value" "$(cat "$WEBHOOK_STORE_PATH")"
check "the kept header value survived the edit" "Bearer abc123" "$(cat "$WEBHOOK_STORE_PATH")"
check "the replaced header value is the new one" "two" "$(cat "$WEBHOOK_STORE_PATH")"

# validation
v1=$(api_post "action=save&$P" '{"name":"bad name with spaces","url":"https://example.com/x","method":"POST"}')
json_ok "a name with spaces is refused" "$v1" 'd["ok"] is False and "name" in d["error"].lower()'
v2=$(api_post "action=save&$P" '{"name":"badurl","url":"ftp://example.com/x","method":"POST"}')
json_ok "a non-http scheme is refused" "$v2" 'd["ok"] is False'
v3=$(api_post "action=save&$P" '{"name":"badverbm","url":"https://example.com/x","method":"TRACE"}')
json_ok "an unsupported method is refused" "$v3" 'd["ok"] is False'
v4=$(api_post "action=save&$P" '{"name":"nosigsecret","url":"https://example.com/x","method":"POST","sig":"v2"}')
json_ok "a signature scheme with no secret is refused" "$v4" 'd["ok"] is False'
v5=$(api_post "action=save&$P" '{"name":"creds","url":"https://user:pw@example.com/x","method":"POST"}')
json_ok "credentials in the url are refused" "$v5" 'd["ok"] is False'
v6=$(api_post "action=save&$P" 'not json')
json_ok "a non-JSON body is refused" "$v6" 'd["ok"] is False'
v7=$(api_post "action=save&$P" '{"name":"crlf","url":"https://example.com/x","method":"POST","headers":[{"name":"X-Bad","value":"a\r\nB: c"}]}')
json_ok "a header value with CRLF is refused" "$v7" 'd["ok"] is False'
v8=$(api_post "action=save&$P" '{"name":"badhdr","url":"https://example.com/x","method":"POST","headers":[{"name":"X Bad","value":"v"}]}')
json_ok "a header name with a space is refused" "$v8" 'd["ok"] is False'
v9=$(api_post "action=save&$P" '{"name":"demo","url":"https://example.com/x","method":"POST"}')
json_ok "a duplicate name is refused on create" "$v9" 'd["ok"] is False and "exists" in d["error"]'

# =====================================================================
section "SSRF policy"
# =====================================================================
ssrf=$(api_post "action=save&$P" '{"name":"local","url":"http://127.0.0.1:9/hook","method":"POST"}')
json_ok "a loopback hook can be stored (it is not fired yet)" "$ssrf" 'd["ok"] is True'
FIREBODY='{"name":"local","payload":"{}"}'
fire_raw=$(printf '%s' "$FIREBODY" | CONTENT_LENGTH=${#FIREBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN)
fire=$(body "$fire_raw")
check "firing at loopback is refused while the policy is closed" "Status: 502" "$fire_raw"
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"])'

# =====================================================================
section "delivery against a recording receiver"
# =====================================================================
LOG="$tmpdir/recv.jsonl"
python3 tests/mockrecv.py --port 0 --log "$LOG" --delay 0.3 > "$tmpdir/recv.out" 2>"$tmpdir/recv.err" &
RECV_PID=$!
i=0
while [ $i -lt 60 ]; do
    PORT=$(awk '/^PORT /{print $2}' "$tmpdir/recv.out" 2>/dev/null)
    [ -n "${PORT:-}" ] && break
    i=$((i + 1)); sleep 0.1
done
if [ -z "${PORT:-}" ]; then
    fail "the recording receiver did not start"; cat "$tmpdir/recv.err" | head -5
else
    pass "the recording receiver is listening on 127.0.0.1:$PORT"
fi

export WEBHOOK_ALLOW_PRIVATE=1
json_ok "the list reports the opt-in once it is set" "$(api "action=list&$P")" 'd["allow_private"] is True'

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

PAYLOAD='{"event":"deploy","n":1,"nested":{"a":[1,2,3]}}'
fire=$(api_post "action=fire&$P" "{\"name\":\"recv\",\"payload\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$PAYLOAD")}")
json_ok "a fire to the mock succeeds" "$fire" 'd["ok"] is True and d["delivered"] is True'
json_ok "the fire reports HTTP 200" "$fire" 'd["status"]==200 and d["ok_status"] is True'
json_ok "the fire reports bytes and latency" "$fire" 'd["bytes"]>0 and d["ms"]>=0'

python3 - "$LOG" "$PAYLOAD" <<'PY'
import hashlib, hmac, json, sys
log, payload = sys.argv[1], sys.argv[2]
lines = [json.loads(l) for l in open(log) if l.strip()]
ok = 0
bad = []

def want(cond, msg):
    global ok
    if cond:
        ok += 1
    else:
        bad.append(msg)

want(len(lines) == 1, "exactly one request was recorded (got %d)" % len(lines))
if lines:
    r = lines[0]
    h = {k.lower(): v for k, v in r["headers"].items()}
    want(r["method"] == "POST", "method is POST (got %s)" % r["method"])
    want(r["path"] == "/hook", "path is /hook (got %s)" % r["path"])
    want(r["body"] == payload, "the body arrived byte-identical")
    want(h.get("authorization") == "Bearer tok-42",
         "the Authorization header carried the stored token (got %r)" % h.get("authorization"))
    want(h.get("x-custom") == "alpha", "the custom header arrived")
    want(h.get("content-type", "").startswith("application/json"),
         "a JSON content type was added (got %r)" % h.get("content-type"))
    want(h.get("content-length") == str(len(payload)),
         "the content length matches the body")
    want(h.get("user-agent", "").startswith("SCORPIOXBOT-webhook"),
         "the user agent identifies the plugin")
    sig = h.get("x-hub-signature-256", "")
    expect = "sha256=" + hmac.new(b"hmac-key-1", payload.encode(), hashlib.sha256).hexdigest()
    want(sig == expect, "X-Hub-Signature-256 is the HMAC of the exact body\n"
                        "      want %s\n      got  %s" % (expect, sig))
for b in bad:
    print("      " + b)
print("MATCHED %d" % ok)
PY
sigres=$?
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

json_ok "the delivery was logged" "$(api "action=list&$P")" \
    'd["log"] and d["log"][0]["name"]=="recv" and d["log"][0]["status"]==200 and d["log"][0]["ok"] is True'

# --- query string, object payload, gitlab scheme ---------------------------
api_post "action=save&$P" "{\"name\":\"recvq\",\"url\":\"http://127.0.0.1:$PORT/echo\",\"method\":\"POST\",\"sig\":\"gitlab\",\"secret\":\"tok-shared\"}" >/dev/null
fireq=$(api_post "action=fire&$P" '{"name":"recvq","payload":{"a":1},"query":"event=deploy&env=prod"}')
json_ok "a fire with a query string and an object payload succeeds" "$fireq" 'd["delivered"] is True'
json_ok "an object payload is serialised as JSON" "$fireq" 'd["body_preview"]=="{\"a\":1}"'
python3 - "$LOG" <<'PY'
import json, sys
lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
last = lines[-1]
h = {k.lower(): v for k, v in last["headers"].items()}
assert last["path"] == "/echo?event=deploy&env=prod", last["path"]
assert last["body"] == '{"a":1}', last["body"]
assert h.get("x-gitlab-token") == "tok-shared", h.get("x-gitlab-token")
PY
if [ $? -eq 0 ]; then pass "the query was appended and the gitlab token header was sent"; else fail "query / gitlab token header mismatch"; fi

# --- v2 timestamped signature ---------------------------------------------
api_post "action=save&$P" "{\"name\":\"recvv2\",\"url\":\"http://127.0.0.1:$PORT/hook\",\"method\":\"POST\",\"sig\":\"v2\",\"secret\":\"v2-key\"}" >/dev/null
api_post "action=fire&$P" '{"name":"recvv2","payload":"{\"x\":\"y\"}"}' >/dev/null
python3 - "$LOG" <<'PY'
import hashlib, hmac, json, sys, time
lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
last = lines[-1]
h = {k.lower(): v for k, v in last["headers"].items()}
ts = h.get("x-webhook-timestamp", "")
sig = h.get("x-webhook-signature", "")
body = last["body"]
expect = hmac.new(b"v2-key", (ts + "." + body).encode(), hashlib.sha256).hexdigest()
assert sig == "t=%s,v1=%s" % (ts, expect), (sig, expect)
assert abs(int(ts) - int(time.time())) < 60, ts
PY
if [ $? -eq 0 ]; then pass "the v2 signature is HMAC(timestamp.body) and its timestamp is live"; else fail "v2 signature mismatch"; fi

# --- methods --------------------------------------------------------------
for m in GET PUT PATCH DELETE HEAD; do
    api_post "action=save&$P" "{\"name\":\"m$m\",\"url\":\"http://127.0.0.1:$PORT/echo\",\"method\":\"$m\",\"desc\":\"$m verb\"}" >/dev/null
    r=$(api_post "action=fire&$P" "{\"name\":\"m$m\",\"payload\":\"{}\"}")
    json_ok "$m is delivered" "$r" 'd["delivered"] is True and d["status"]==200'
done
python3 - "$LOG" <<'PY'
import json, sys
lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
verbs = [l["method"] for l in lines[-5:]]
assert verbs == ["GET", "PUT", "PATCH", "DELETE", "HEAD"], verbs
PY
if [ $? -eq 0 ]; then pass "the method on the wire is the method configured"; else fail "method dispatch is wrong"; fi

# --- response handling ----------------------------------------------------
api_post "action=save&$P" "{\"name\":\"r418\",\"url\":\"http://127.0.0.1:$PORT/status/418\",\"method\":\"POST\"}" >/dev/null
r=$(api_post "action=fire&$P" '{"name":"r418","payload":"{}"}')
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'
json_ok "the 4xx body is carried back" "$r" '"requested" in d["body_preview"]'

api_post "action=save&$P" "{\"name\":\"redir\",\"url\":\"http://127.0.0.1:$PORT/redirect\",\"method\":\"POST\"}" >/dev/null
r=$(api_post "action=fire&$P" '{"name":"redir","payload":"{}"}')
json_ok "a redirect is reported, never followed" "$r" 'd["delivered"] is True and d["status"]==302'

api_post "action=save&$P" "{\"name\":\"chunky\",\"url\":\"http://127.0.0.1:$PORT/chunked\",\"method\":\"POST\"}" >/dev/null
r=$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}')
json_ok "a chunked response body is decoded" "$r" 'd["body_preview"]=="{\"chunked\":true}"'
check_not "the chunk framing did not leak into the body" "2\r" "$(api_post "action=fire&$P" '{"name":"chunky","payload":"{}"}')"

api_post "action=save&$P" "{\"name\":\"big\",\"url\":\"http://127.0.0.1:$PORT/big\",\"method\":\"POST\"}" >/dev/null
r=$(api_post "action=fire&$P" '{"name":"big","payload":"{}"}')
json_ok "an oversized response is truncated and says so" "$r" 'd["truncated"] is True and d["bytes"]<=4096'

# --- refusal paths --------------------------------------------------------
NFBODY='{"name":"nope","payload":"{}"}'
nf_raw=$(printf '%s' "$NFBODY" | CONTENT_LENGTH=${#NFBODY} REQUEST_METHOD=POST QUERY_STRING="action=fire&$P" $BIN)
nf=$(body "$nf_raw")
check "firing an unknown hook answers 404" "Status: 404" "$nf_raw"
json_ok "the unknown-hook body is JSON" "$nf" 'd["ok"] is False'

dead=$(api_post "action=save&$P" '{"name":"dead","url":"http://127.0.0.1:1/hook","method":"POST"}')
d=$(api_post "action=fire&$P" '{"name":"dead","payload":"{}"}')
json_ok "an unreachable endpoint is reported, not crashed" "$d" 'd["ok"] is False and d["delivered"] is False and len(d["error"])>0'
json_ok "the failed delivery is in the log" "$(api "action=list&$P")" \
    'any(e["name"]=="dead" and e["ok"] is False for e in d["log"])'

# =====================================================================
section "--mcp tool calls against the live store"
# =====================================================================
tl=$(mcp '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"webhook_list","arguments":{}}}')
check "webhook_list reports the stored hooks" "recv" "$tl"
check_not "webhook_list never returns a header value" "Bearer tok-42" "$tl"
check_not "webhook_list never returns the HMAC secret" "hmac-key-1" "$tl"
check_not "webhook_list redacts the query string" "event=deploy" "$tl"

tr=$(mcp '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"recv","payload":{"from":"mcp"}}}}')
json_ok "webhook_trigger succeeds" "$tr" 'd["result"].get("isError") is not True'
check "the tool result reports the HTTP status" "HTTP 200" "$tr"
check_not "the tool result carries no secret" "hmac-key-1" "$tr"

python3 - "$LOG" <<'PY'
import hashlib, hmac, json, sys
lines = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
last = lines[-1]
h = {k.lower(): v for k, v in last["headers"].items()}
assert last["body"] == '{"from":"mcp"}', last["body"]
expect = "sha256=" + hmac.new(b"hmac-key-1", last["body"].encode(), hashlib.sha256).hexdigest()
assert h.get("x-hub-signature-256") == expect, h.get("x-hub-signature-256")
PY
if [ $? -eq 0 ]; then pass "an object payload over MCP is signed and delivered correctly"; else fail "MCP payload/signature mismatch"; fi

badname=$(mcp '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{"name":"nope"}}}')
json_ok "an unknown hook over MCP is a tool error, not a protocol error" "$badname" 'd["result"]["isError"] is True'
check "the tool error lists the configured names" "recv" "$badname"

noname=$(mcp '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"webhook_trigger","arguments":{}}}')
json_ok "a trigger with no name is a tool error" "$noname" 'd["result"]["isError"] is True'

redacted=$(mcp '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"webhook_list","arguments":{"redact_url":false}}}')
check "redact_url=false shows the real endpoint" "/hook" "$redacted"

# =====================================================================
section "delete"
# =====================================================================
api_post "action=delete&$P" '{"name":"dead"}' >/dev/null
json_ok "a deleted hook is gone" "$(api "action=list&$P")" 'not any(h["name"]=="dead" for h in d["hooks"])'
d2=$(api_post "action=delete&$P" '{"name":"dead"}')
json_ok "deleting a missing hook answers 404" "$d2" 'd["ok"] is False'

# =====================================================================
section "store robustness"
# =====================================================================
BROKEN="$tmpdir/broken.json"
printf 'not json at all' > "$BROKEN"
b=$(WEBHOOK_STORE_PATH="$BROKEN" QUERY_STRING="action=list&$P" $BIN | body "$(cat)")
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'
check "the corrupt store was left untouched" "not json at all" "$(cat "$BROKEN")"

DEEPBODY='{"name":"deep","url":"https://example.com/hook","method":"POST"}'
WEBHOOK_STORE_PATH="$tmpdir/deep/er/hooks.json" QUERY_STRING="action=save&$P" \
  REQUEST_METHOD=POST CONTENT_LENGTH=${#DEEPBODY} $BIN <<EOF >/dev/null
$DEEPBODY
EOF
check "a nested store path is created on demand" "deep" "$(cat "$tmpdir/deep/er/hooks.json" 2>/dev/null)"
if [ -f "$tmpdir/deep/er/hooks.json" ]; then
    m2=$(stat -c '%a' "$tmpdir/deep/er/hooks.json" 2>/dev/null || stat -f '%Lp' "$tmpdir/deep/er/hooks.json")
    check "a created store is 0600 too" "600" "$m2"
fi

# =====================================================================
section "SHA-256 / HMAC known-answer tests"
# =====================================================================
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
    vout=$("$tmpdir/vec")
    n_ok=$(printf '%s\n' "$vout" | grep -c '^ok ')
    if [ "$n_ok" -ge 9 ]; then
        pass "all $n_ok FIPS / RFC 4231 known-answer vectors match"
    else
        fail "only $n_ok known-answer vectors ran"; printf '%s\n' "$vout"
    fi
else
    fail "the vector test did not compile"; head -10 "$tmpdir/vec.err"
fi

# =====================================================================
section "source and history safety"
# =====================================================================
src=$(cat src/*.c src/*.h 2>/dev/null)
check_not "no system() call in the plugin" "system(" "$src"
check_not "no popen() in the plugin" "popen(" "$src"
check_not "no exec family call in the plugin" "execv(" "$src"
check_not "the page has no remote script" "<script src=" "$(cat src/ui.html)"
check_not "the page has no CDN reference" "cdnjs" "$(cat src/ui.html)"
PRIVATE24="192"".""168."
check_not "the source has no hard-coded private address" "$PRIVATE24" "$src"
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)"
check "the SSRF deny list covers RFC1918" "0xAC100000u" "$(cat src/wh_http.c)"
check "the SSRF deny list covers loopback" "0x7F000000u" "$(cat src/wh_http.c)"
check "TLS verification is required, not optional" "MBEDTLS_SSL_VERIFY_REQUIRED" "$(cat src/wh_tls.c)"
check_not "there is no insecure TLS bypass in the plugin" "VERIFY_NONE" "$(cat src/wh_tls.c)"
check "the MCP reader uses read(2) rather than fread(2)" "read(fileno(stdin)" "$(cat src/plugin_webhook.c)"
check "the page is generated from src/ui.html" "SX_WEBHOOK_UI_HTML_H" "$(cat src/ui_html.h)"

# generated header must be current
if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h is up to date with src/ui.html"
else
    fail "src/ui_html.h is stale (run tools/gen_ui.py)"
fi

# =====================================================================
section "sanitizer build"
# =====================================================================
if [ "${SKIP_ASAN:-0}" = "1" ]; then
    pass "ASan build skipped (SKIP_ASAN=1)"
else
    if make -s asan >/dev/null 2>"$tmpdir/asan.log"; then
        TMPSTORE="$tmpdir/asan-hooks.json"
        a1=$(WEBHOOK_STORE_PATH="$TMPSTORE" QUERY_STRING="action=list&$P" ./plugin_webhook-asan 2>"$tmpdir/asan-run.err" | body "$(cat)")
        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'
        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'
{"name":"asan","url":"https://example.com/hook","method":"POST","sig":"v2","secret":"k"}
EOF
        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'
{"name":"asan","payload":"{\"a\":1}"}
EOF
        mcp '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' >/dev/null 2>>"$tmpdir/asan-run.err" || true
        if grep -q "ERROR: AddressSanitizer\|runtime error:" "$tmpdir/asan-run.err" 2>/dev/null; then
            fail "the ASan run reported a problem"; head -20 "$tmpdir/asan-run.err"
        else
            pass "the ASan/UBSan build ran the API and MCP paths clean"
        fi
    else
        fail "the ASan build failed"; tail -20 "$tmpdir/asan.log"
    fi
fi

if make -s fortify >/dev/null 2>"$tmpdir/fort.log"; then
    f=$(WEBHOOK_STORE_PATH="$tmpdir/f-hooks.json" QUERY_STRING="action=list&$P" ./plugin_webhook-fortify 2>&1)
    check "the _FORTIFY_SOURCE=2 build answers" '"ok":true' "$f"
else
    fail "the _FORTIFY_SOURCE=2 build failed"; tail -20 "$tmpdir/fort.log"
fi

# =====================================================================
section "git history"
# =====================================================================
if command -v git >/dev/null 2>&1 && [ -d .git ]; then
    # Every needle is assembled from fragments so this file, which lands in git
    # history, never contains one whole (the scanner would flag its own line).
    NEEDLES="ghp_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}|Xboxone""0909|RUNNER_+PASS=|macmini""2018i5"
    hist=$(git log -p --all 2>/dev/null | grep -E "$NEEDLES" | head -3)
    if [ -z "$hist" ]; then pass "no token, password or internal hostname in git history"
    else fail "git history contains a secret or hostname"; printf '%s\n' "$hist"; fi
    IPCORE="192""\\.168\\."
    iphist=$(git log -p --all 2>/dev/null | grep -cE "(^|[^0-9])$IPCORE[0-9]+\\.[0-9]+" || true)
    if [ "${iphist:-0}" = "0" ]; then pass "no private address anywhere in git history"
    else fail "git history contains $iphist private address line(s)"; fi
else
    pass "git history check skipped (not a git checkout)"
fi

# =====================================================================
printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
