# API Webhook Security

> Use when testing or hardening webhook endpoints on an authorized engagement. Covers signature verification, replay protection, SSRF through webhook URLs, and retry and idempotency abuse. Use when an application receives webhooks from a payment, messaging, or CI provider, when webhook handlers trigger internal actions, or when testing OWASP API Security issues in event driven integrations.

- Skill: `mizazhaider-ceh/api-webhook-security` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/api-webhook-security`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/api-webhook-security/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/api-webhook-security

---


Webhooks turn an inbound HTTP endpoint into a trigger for real
actions: charging, shipping, provisioning, or deleting. An attacker
who can forge, replay, or redirect a webhook can trigger those
actions without any user account. This skill covers webhook
security on systems you are authorized to assess: signature
verification done correctly, replay windows that actually close,
SSRF through attacker controlled webhook URLs, and retries that
double-apply an effect.

## Quick Workflow

1. Inventory webhooks: every inbound endpoint, its provider, and
   the action each event type triggers.
2. Test signature verification: no signature, wrong signature,
   and a valid signature over a tampered body.
3. Test replay protection: send the same signed delivery twice,
   and send an old signed delivery after the timestamp window.
4. Test SSRF via webhook URLs: register a webhook pointing at
   internal addresses and see what the server fetches.
5. Test retry and idempotency: deliver the same payment or order
   event repeatedly and check for double application.
6. Test event confusion: an event type the handler does not expect,
   and a valid signature from one provider used on another's
   endpoint.
7. Check logging and failure handling: failed verifications must
   be logged and must not leak the expected signature.
8. Report per endpoint with the verification, replay, SSRF, and
   idempotency verdicts.

## 1. Signature verification

```python
#!/usr/bin/env python3
"""Webhook signature checks, done the way a correct verifier does.

HMAC over the raw body with the shared secret, compared in
constant time, with the timestamp inside the signed payload. The
test cases below show what a broken verifier accepts.
"""
import hashlib
import hmac

SECRET = b"test-webhook-secret"
BODY = b'{"type": "payment.succeeded", "order_id": "ord_123"}'
TIMESTAMP = "1700000000"


def sign(body, ts):
    msg = ts.encode() + b"." + body
    return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()


good = sign(BODY, TIMESTAMP)
tampered = sign(b'{"type": "payment.succeeded", "order_id": "ord_999"}',
                TIMESTAMP)
print("valid signature:  ", good)
print("tampered signature:", tampered)
print("verifier must compare with hmac.compare_digest, never ==,")
print("and must reject a signature computed over a different body,")
print("a missing timestamp, and a signature from another endpoint")
```

```bash
# Live tests against an authorized webhook endpoint
echo "== no signature at all"
curl -s -o /dev/null -w '%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -d '{"type": "payment.succeeded", "order_id": "ord_123"}' \
  "https://target.example/webhooks/payments"
echo "== wrong signature"
curl -s -o /dev/null -w '%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -H 'X-Signature: deadbeef' \
  -d '{"type": "payment.succeeded", "order_id": "ord_123"}' \
  "https://target.example/webhooks/payments"
echo "want 401 or 403 for both; a 200 on either is a critical finding"
```

## 2. Replay protection

```python
#!/usr/bin/env python3
"""Replay tests: same delivery twice, and an old delivery late.

A correct handler rejects a reused delivery id and a timestamp
outside its window (five minutes is the common provider default).
Run against an authorized test endpoint with a test secret.
"""
import hashlib
import hmac
import subprocess

SECRET = b"test-webhook-secret"
BODY = b'{"type": "payment.succeeded", "order_id": "ord_123", "id": "evt_test_1"}'
URL = "https://target.example/webhooks/payments"


def deliver(ts, body=BODY):
    sig = hmac.new(SECRET, ts.encode() + b"." + body,
                   hashlib.sha256).hexdigest()
    out = subprocess.run(
        ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
         "-H", "Content-Type: application/json",
         "-H", f"X-Timestamp: {ts}",
         "-H", f"X-Signature: {sig}",
         "-d", body.decode(), URL],
        capture_output=True, text=True).stdout.strip()
    return out


print("first delivery:         ", deliver("1700000000"))
print("same delivery replayed: ", deliver("1700000000"),
      "(want a duplicate rejection, not a second action)")
print("old delivery, one hour later timestamp:",
      deliver("1699996400"), "(want rejection outside the window)")
```

## 3. SSRF via webhook URLs

```bash
# Register webhooks pointing at internal and redirecting targets,
# then watch what the server fetches. Use only targets you own or
# are authorized to probe; internal addresses here are test values.
for url in "http://169.254.169.254/meta-data/" \
           "http://localhost:8080/admin" \
           "http://internal.example/" \
           "https://canary.example/redirect-to-localhost"; do
  echo "== registering webhook URL: $url"
  curl -s "https://target.example/api/v1/webhooks" \
    -H 'Authorization: Bearer user-token-value' \
    -H 'Content-Type: application/json' \
    -d "{\"url\": \"$url\", \"events\": [\"order.created\"]}"
  echo
done
echo "a fetch to link local metadata or localhost from the server"
echo "is SSRF; check the canary host and the server logs for proof"
```

```python
#!/usr/bin/env python3
"""SSRF allowlist logic a webhook registrar should enforce.

Reject private and link-local ranges, resolve DNS first and check
the resolved address (not just the hostname string), and refuse
redirects that land on a private address.
"""
import ipaddress
import socket


def is_public(host):
    try:
        addr = socket.gethostbyname(host)
    except socket.gaierror:
        return False
    ip = ipaddress.ip_address(addr)
    return not (ip.is_private or ip.is_loopback or ip.is_link_local
                or ip.is_reserved or ip.is_multicast)


for host in ("example.com", "localhost", "169.254.169.254",
             "internal.example"):
    print(f"{host}: public = {is_public(host)}")
print("note: DNS rebinding defeats a check done once at registration,")
print("so the fetch itself must re-validate the resolved address")
```

## 4. Retry and idempotency abuse

```bash
# Deliver the same payment event five times in a row and compare
# the resulting order state after each delivery
for i in 1 2 3 4 5; do
  code=$(curl -s -o /dev/null -w '%{http_code}' \
    -H 'Content-Type: application/json' \
    -H 'X-Signature: valid-test-signature' \
    -H 'X-Delivery-Id: evt_test_1' \
    -d '{"type": "payment.succeeded", "order_id": "ord_123", "id": "evt_test_1"}' \
    "https://target.example/webhooks/payments")
  echo "delivery $i -> HTTP $code"
done
echo "then check the order: charged once means idempotent, charged"
echo "five times means retries are a money bug, not just a nuisance"
```

```bash
# Event confusion: a valid signature from provider A replayed on
# provider B's endpoint, and an unknown event type on a known one
curl -s -o /dev/null -w '%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -H 'X-Signature: provider-a-valid-signature' \
  -d '{"type": "payment.succeeded", "order_id": "ord_123"}' \
  "https://target.example/webhooks/messaging"
echo "want rejection: signatures are per endpoint and per secret"
curl -s -o /dev/null -w '%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -H 'X-Signature: valid-test-signature' \
  -d '{"type": "account.deleted", "order_id": "ord_123"}' \
  "https://target.example/webhooks/payments"
echo "want a clean rejection of the unknown type, not a crash or a"
echo "default action that treats every event as a success"
```

## Edge cases

- The provider signs with a rotating secret. Then the verifier must
  accept the current and previous secret during rotation, and the
  test must cover both, plus rejection after rotation completes.
- The handler returns 200 before verifying, to acknowledge quickly.
  That is safe only if the action is queued and verified before it
  runs; a 200 that also applies the action is not acknowledgement.
- Retries arrive out of order: a refund event before its payment
  event. The handler must tolerate ordering, not crash or apply
  the refund to a nonexistent order.
- Webhook URLs are user controlled in a multi-tenant app. Then one
  tenant's SSRF probe can reach another tenant's internal services,
  so the allowlist must be global, not per tenant configuration.
- The signature secret is shared across environments. A staging
  secret that verifies production webhooks collapses the boundary;
  check that each environment has its own secret.

## Key references

- OWASP API Security Top 10 and OWASP guidance on SSRF prevention.
- Provider webhook documentation for the signature scheme in use,
  including its timestamp window and retry schedule.
- Related skills: api-gateway-security, api-key-management,
  api-security-testing.

