跳到正文
DEV Community· Obligra Verify·· 1 小時前AI 評分58

如何驗證審核工具發出的 Webhook:簽名、防重放與重試處理

Is That Webhook Really From Your Review Tool? Signatures, Replays and Retries

AI 導讀

這篇教學示範如何為審核工具 Webhook 驗證 HMAC 簽名、拒收過期投遞,並以事件 ID 避免重複處理。它按 Standard Webhooks 的做法,把訊息 ID、Unix 時間戳和原始請求內容一併簽署,並在密鑰輪替期間檢查新舊密鑰。接收端應先儲存事件再回覆 2xx,交由 worker 後續處理;有效 HMAC 只表示發送方持有共享密鑰,而且不同發送方的標頭名稱與編碼可能不同。

正文

Here's an illustrative setup. Your app drafts replies with a model, and a separate review tool lets a person approve, edit or reject each draft. When the reviewer acts, the tool sends a webhook to /hooks/review and your app updates the case.

That endpoint is public. Anyone who finds the URL can post {"action": "approved"} to it. And even honest deliveries arrive more than once, because senders retry when they don't get a quick 2xx.

So a review webhook handler has three jobs before it touches your data: check that the sender holds the shared secret, refuse old deliveries someone recorded and replayed, and make a repeated delivery harmless.

What the sender signs

GitHub's guide to validating webhook deliveries describes the common shape: the sender computes an HMAC-SHA256 of the payload with a secret you both hold and puts it in a header. You compute the same thing and compare. It also says to never compare with a plain ==; use a constant-time function instead.

Signing only the body leaves a gap: a captured delivery replays forever with a valid signature. The Standard Webhooks spec closes it by signing the message ID, a Unix timestamp and the body together (msg_id.timestamp.payload). It asks receivers to check the timestamp against a tolerance and to use the ID as an idempotency key. The signature header can carry several space-separated signatures, which allows secret rotation without downtime.

 POST /hooks/review
   headers: webhook-id, webhook-timestamp, webhook-signature
   body: raw bytes
     |
     v
 timestamp within tolerance? -- no --> 401
     | yes
 HMAC(id.timestamp.body) matches any secret? -- no --> 401
     | yes
 INSERT id into inbox (ignore if present) --> 2xx; worker applies it

The code

Here's a stdlib-only receiver core that follows that scheme. secrets holds raw key bytes (in Standard Webhooks, that's the base64-decoded part after the whsec_ prefix).

import base64, hashlib, hmac

TOLERANCE_SECONDS = 300  # illustrative; pick yours on purpose

class Rejected(Exception):
    pass

def sign(secret, msg_id, timestamp, body):
    signed = f"{msg_id}.{timestamp}.".encode() + body
    mac = hmac.new(secret, signed, hashlib.sha256).digest()
    return "v1," + base64.b64encode(mac).decode()

def verify(secrets, headers, body, now):
    msg_id = headers.get("webhook-id", "")
    ts = headers.get("webhook-timestamp", "")
    if not msg_id or not ts.isdigit():
        raise Rejected("missing id or timestamp")
    if abs(now - int(ts)) > TOLERANCE_SECONDS:
        raise Rejected("timestamp outside tolerance")
    offered = headers.get("webhook-signature", "").split()
    for secret in secrets:  # current and previous during rotation
        expected = sign(secret, msg_id, ts, body)
        if any(hmac.compare_digest(expected, s) for s in offered):
            return msg_id
    raise Rejected("no matching signature")

def accept_once(db, msg_id, body):
    """Store the event; return False if this ID was already seen."""
    with db:
        cur = db.execute(
            "INSERT OR IGNORE INTO inbox (msg_id, body) VALUES (?, ?)",
            (msg_id, body))
    return cur.rowcount == 1

A few choices worth calling out:

  • Verify the raw bytes. Compute the HMAC over the body exactly as received, before any JSON parsing. GitHub's troubleshooting notes say to make sure a proxy or load balancer doesn't modify the payload or headers first. Re-serialized JSON fails the same way.
  • Check the timestamp first. It's cheap, and a stale delivery is rejected even when its signature is perfect.
  • Try every current secret. During rotation you accept both the new and the previous key for a while, then remove the old one.
  • Store, then acknowledge. The handler saves the event and returns 2xx. A worker applies the review decision later, so slow downstream work doesn't delay the response and invite retries.

Tests

import hashlib, hmac, sqlite3
import pytest
from webhook import Rejected, sign, verify, accept_once

KEY = b"test-secret-not-a-real-one"
NOW = 1_795_800_000
BODY = b'{"review_id":"r_42","action":"edited"}'

def headers(secret=KEY, ts=NOW, body=BODY, msg_id="msg_1"):
    return {"webhook-id": msg_id, "webhook-timestamp": str(ts),
            "webhook-signature": sign(secret, msg_id, ts, body)}

def test_hmac_matches_published_vector():
    # GitHub's documented test values for HMAC-SHA256 hex digests
    mac = hmac.new(b"It's a Secret to Everybody", b"Hello, World!",
                   hashlib.sha256).hexdigest()
    assert mac.startswith("757107ea0eb2509fc211221cce984b8a")

def test_valid_delivery_is_accepted():
    assert verify([KEY], headers(), BODY, NOW) == "msg_1"

def test_changed_body_is_rejected():
    with pytest.raises(Rejected):
        verify([KEY], headers(), BODY.replace(b"edited", b"approved"),
               NOW)

def test_old_delivery_is_rejected_even_if_signed():
    with pytest.raises(Rejected, match="tolerance"):
        verify([KEY], headers(ts=NOW - 3600), BODY, NOW)

def test_previous_secret_still_works_during_rotation():
    old, new = b"old-secret", b"new-secret"
    assert verify([new, old], headers(secret=old), BODY, NOW)

def test_duplicate_delivery_is_processed_once():
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE inbox (msg_id TEXT PRIMARY KEY, body BLOB)")
    assert accept_once(db, "msg_1", BODY) is True
    assert accept_once(db, "msg_1", BODY) is False

The first test pins your HMAC call to a published value, so an encoding mistake (hex vs. base64, string vs. bytes) shows up before you debug against a live sender.

Wiring it in

Your framework's job is small: hand verify the raw request body and the three headers, return 401 on Rejected, and call accept_once before answering. Read secrets from your secret store at startup, not from code. And log the message ID and the rejection reason, not the body: review payloads often contain the draft text you were trying to keep out of logs.

Limits

  • A valid HMAC shows the sender had the shared secret. It doesn't show the payload is correct, or that the reviewer meant what they clicked.
  • The tolerance window depends on clocks. Skewed servers cause false rejections; a long window gives replays more room. Use the ID check as the second line.
  • accept_once only dedupes within the inbox's lifetime. If you expire old IDs, keep them longer than the timestamp tolerance so the timestamp check covers anything older.
  • Every sender has its own header names and encoding. Follow the provider's docs; this is the general shape, not a drop-in for a specific one.

Where this fits

We work on Obligra Verify, which is designed to retain the evidence your application selects. Our webhook events page describes the receiver shape this post relies on: accept and enqueue quickly, dedupe on the event ID, check the environment field, and fetch authoritative details through the API rather than trusting the notification alone.

This article was generated by an AI agent (Claude) for the Obligra Verify team and checked against the linked sources.

來源:DEV Community · dev.to