メインコンテンツまでスキップ

Webhookの署名と検証

Blüdhaven Petsプラットフォームでは、HTTPの直接リクエストサイクル外でライフサイクルイベントが発生した際に非同期Webhookを送信する。

本日ディスパッチされるイベントは以下の2つ:

イベント発生条件ペイロードのハイライト
adoption.hold.expired予約の保留状態が30分経過しても申請がない場合hold_id, animal_id, reason
veterinary.clearance.filed市立動物病院が認証情報を記録し、動物の里親募集が可能になる場合animal_id, certificate_number, status

すべてのデリバリーは、HTTPPOSTとして送信され、X-Bludhaven-Signatureヘッダー内にはJSONペイロードおよびHMAC-SHA256署名が含まれている。

署名を検証する理由​

公開されたWebhookエンドポイントはインターネットからのHTTPトラフィックを受け取る。暗号化検証がなければ:

  • 攻撃者はadoption.hold.expiredイベントを偽造して動物を不正に解放する可能性がある。
  • 攻撃者は偽のveterinary.clearance.filedイベントを注入することで、義務付けられた狂犬病検疫を回避できる。
  • 攻撃者は古い有効なペイロードを再送信することで、処理が二重に行われるようにすることができる。

署名検証により、Blüdhaven Petsがそのペイロードデータを生成したこと、およびデリバリーが最新であることが確認されます。

署名ヘッダーのフォーマット​

X-Bludhaven-SignatureヘッダーにはUNIXタイムスタンプとHMAC~SHA256の16進数ダイジストが含まれている:

X-Bludhaven-Signature: t=1795123456,v1=5d41402abc4b2a76b9719d911017c5926c459992f026a0b72a6a8b1a7f05252b
  • t:ゲートウェイがデリバリーに署名した時刻を秒単位で表すUNIXエポックタイムスタンプ。
  • v1:ウェブフックの署名シークレットを使用してt={timestamp},v1={raw_body}から計算された、小文字表記の16進数HMAC-SHA256ダイジスト。

サンドボックス内でのテスト​

検証には、JSONの解析前の正確な原始リクエストボディが必要です。パーサーは空白やキーの順序を変更するため、暗号化検証が失敗します。

verify-webhook.mjs
import crypto from 'node:crypto';

export function verifyWebhookSignature({ rawBody, signatureHeader, secret, toleranceSeconds = 300 }) {
if (!signatureHeader) {
throw new Error('Missing X-Bludhaven-Signature header');
}

// 1. Extract timestamp and signature from the header
const elements = Object.fromEntries(
signatureHeader.split(',').map((pair) => pair.split('='))
);

const timestamp = parseInt(elements.t, 10);
const expectedSignature = elements.v1;

if (isNaN(timestamp) || !expectedSignature) {
throw new Error('Malformed X-Bludhaven-Signature header');
}

// 2. Reject replays outside tolerance window (default 5 minutes)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - timestamp) > toleranceSeconds) {
throw new Error('Webhook timestamp falls outside tolerance window');
}

// 3. Recreate the signed string: t={timestamp},v1={raw_body}
const signedPayload = `t=${timestamp},v1=${rawBody}`;

// 4. Compute expected HMAC-SHA256
const computedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload, 'utf8')
.digest('hex');

// 5. Compare in constant time to prevent timing attacks. A digest of the
// wrong length makes timingSafeEqual throw RangeError, so check the length.
const computed = Buffer.from(computedSignature, 'hex');
const expected = Buffer.from(expectedSignature, 'hex');
const valid =
computed.length === expected.length &&
crypto.timingSafeEqual(computed, expected);

if (!valid) {
throw new Error('Invalid webhook signature');
}

return JSON.parse(rawBody);
}

Pythonで署名を検証する​

verify_webhook.py
import hmac
import hashlib
import time
import json

def verify_webhook(raw_bytes: bytes, sig_header: str, secret: str, tolerance: int = 300) -> dict:
parts = dict(item.split("=", 1) for item in sig_header.split(","))
timestamp = int(parts.get("t", 0))
expected_hex = parts.get("v1", "")

if abs(time.time() - timestamp) > tolerance:
raise ValueError("Timestamp outside acceptable replay window")

signed_data = f"t={timestamp},v1=".encode("utf-8") + raw_bytes
computed_hex = hmac.new(secret.encode("utf-8"), signed_data, hashlib.sha256).hexdigest()

if not hmac.compare_digest(computed_hex, expected_hex):
raise ValueError("Signature mismatch")

return json.loads(raw_bytes.decode("utf-8"))

サンドボックス内でのテストディスパッチ処理​

サンドボックスゲートウェイはテスト用のディスパッチエンドポイントを提供します。このエンドポイントは実際のペイロードに署名を加え、ヘッダー情報を返します。バックグラウンドイベントを待たずに、受信側をこのエンドポイントに向けることで署名処理の動作をテストできます。

参考コンソールでは、同じ呼び出しが「Webhooks」の下にリストアップされています。Browser demoサーバーを選択してそちらに送信してください。デモはリクエスト時に公開されたシークレットを使って署名を行うため、コンソールからコピーしたヘッダーはwhsec_sandbox_bludhaven_test_secret_9981と照合されます。保存されたファクトス(fixture)には古いタイムスタンプやディジットが含まれています。

curl -X POST https://sandbox.bludhaven-pets.workers.dev/webhooks/test-dispatch \
-H "Content-Type: application/json" \
-o webhook-dispatch.json

ボディ(body)を送信しないでください。ゲートウェイが完全なペイロードを署名します。{"event": "veterinary.clearance.filed"}を送信すると、そのオブジェクトがペイロードとして扱われます。

webhook-dispatch.json
{
"dispatched": true,
"event": "adoption.hold.expired",
"secret_used": "whsec_sandbox_bludhaven_test_secret_9981",
"headers": {
"Content-Type": "application/json",
"X-Bludhaven-Signature": "t=1795123456,v1=5d41402abc4b...",
"X-Bludhaven-Timestamp": "1795123456"
},
"payload": {
"id": "evt_wh_901ab2cd",
"event": "adoption.hold.expired",
"created_at": "2026-11-19T13:30:00Z",
"data": {
"hold_id": "hld_a8f90b",
"animal_id": "pet_krypto_210",
"reason": "30_MINUTE_WINDOW_LAPSED"
}
},
"verification_guide": {
"scheme": "HMAC-SHA256",
"signed_template": "t={timestamp},v1={raw_body}",
"header_format": "t={timestamp},v1={hex_signature}"
}
}

レスポンスには署名用のシークレット、計算された署名、およびペイロードが含まれます。サンドボックスワーカーレポジトリ内の検証ツールを使用してこれらを確認してください。

node scripts/verify-webhook.mjs webhook-dispatch.json
Output
event adoption.hold.expired
secret whsec_sandbox_bludhaven_test_secret_9981
signature header t=1795123456,v1=5d41402a...
computed header t=1795123456,v1=5d41402a...
signature match YES
delivery age 2s (tolerance 300s): fresh

PASS: HMAC-SHA256 signature verified.

検証者はファイルから応答を読み取り、再計算してダイジストを確認する。ペイロードをシェル変数やインラインのnode -e文字列を通じて渡してはならない。クォーテーション処理によりネストされたJSONが無効なデータとして扱われ、結果としてReferenceErrorが返される。

ペイロード内の1文字を変更すると、検証器は1からFAIL: signature does not matchへと状態が切り替わる。

検証ツールは300秒以上前のデータも拒否します。アーカイブされたファクトスを再実行する際には--ignore-ageを必ず渡してください。

関連ガイド​