Webhook Ingestion Security Architecture
Building tamper-proof webhook listeners: HMAC-SHA256 signature verification, raw payload hashing, timestamp drift validation, and distributed replay caching.
Building tamper-proof webhook listeners: HMAC-SHA256 signature verification, raw payload hashing, timestamp drift validation, and distributed replay caching.
1. The 3 Invariants of Secure Webhook Handling
- Raw Body Verification: Always verify the HMAC signature against the exact, raw, unparsed request bytes. JSON re-serialization alters whitespace, breaking signature verification.
- Timestamp Drift Checks: Include a timestamp in the signed payload and reject requests older than 5 minutes (300 seconds) to prevent replay attacks.
- Constant-Time Verification: Use constant-time comparisons to prevent timing attacks.
2. Production Hardened Webhook Listener in Node.js
const express = require('express');
const crypto = require('crypto');
const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
const MAX_DRIFT_SECONDS = 300; // 5-minute replay window
// Crucial: Capture raw body buffer for signature calculation
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
app.post('/api/webhooks/stripe', (req, res) => {
const signatureHeader = req.headers['x-signature'];
const timestampHeader = req.headers['x-timestamp'];
if (!signatureHeader || !timestampHeader) {
return res.status(401).json({ error: 'Missing security headers' });
}
// 1. Verify timestamp to defeat replay attacks
const currentTime = Math.floor(Date.now() / 1000);
const webhookTime = parseInt(timestampHeader, 10);
if (Math.abs(currentTime - webhookTime) > MAX_DRIFT_SECONDS) {
return res.status(400).json({ error: 'Timestamp expired (possible replay attack)' });
}
// 2. Compute HMAC over timestamp + raw payload
const signedPayload = `${timestampHeader}.${req.rawBody}`;
const expectedSig = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(signedPayload)
.digest('hex');
// 3. Constant-time comparison
const expectedBuffer = Buffer.from(expectedSig, 'hex');
const clientBuffer = Buffer.from(signatureHeader, 'hex');
if (expectedBuffer.length !== clientBuffer.length || !crypto.timingSafeEqual(expectedBuffer, clientBuffer)) {
return res.status(403).json({ error: 'Invalid HMAC signature' });
}
// Process verified webhook event safely
res.status(200).json({ received: true });
});