Webhook Validation
import { Aside, Tabs, TabItem } from ‘@astrojs/starlight/components’;
Webhook Validation
ContractShield includes built-in validation for webhooks from popular services. It verifies signatures, prevents replay attacks, and validates event types.
Supported Providers
| Provider | Signature Method | Replay Protection |
|---|---|---|
| Stripe | HMAC-SHA256 | ✅ Timestamp + Event ID |
| GitHub | HMAC-SHA256 | ✅ Delivery ID |
| Slack | HMAC-SHA256 | ✅ Timestamp |
| Twilio | HMAC-SHA1 | ✅ |
| Custom | Configurable | Configurable |
Basic Setup
1. Capture Raw Body
Webhook signatures are computed over the raw request body. You must capture it before parsing:
const app = express();
// IMPORTANT: rawBodyCapture must come BEFORE express.json()app.use(rawBodyCapture());app.use(express.json());
app.use(contractshield({ policy: './policy.yaml', pdpOptions: { getSecret: ({ provider }) => { if (provider === 'stripe') return process.env.STRIPE_WEBHOOK_SECRET; if (provider === 'github') return process.env.GITHUB_WEBHOOK_SECRET; } }}));```const app = Fastify({ // Fastify preserves raw body by default});
await app.register(contractshieldPlugin, { policy: './policy.yaml', pdpOptions: { getSecret: ({ provider }) => { if (provider === 'stripe') return process.env.STRIPE_WEBHOOK_SECRET; if (provider === 'github') return process.env.GITHUB_WEBHOOK_SECRET; } }});```2. Configure Policy
routes: - id: stripe.webhook match: method: POST path: /webhooks/stripe webhook: provider: stripe secretRef: STRIPE_WEBHOOK_SECRET # Used by getSecret() timestampTolerance: 300 # 5 minutes replayProtection: true # Requires replayStore allowedEventTypes: - checkout.session.completed - payment_intent.succeeded - invoice.paid - customer.subscription.updatedReplay Protection
Replay attacks send the same valid webhook multiple times. Enable protection with a replay store:
import { MemoryReplayStore, createRedisReplayStore } from '@cshield/pdp';
// Development: In-memory storeconst replayStore = new MemoryReplayStore();
// Production: Redis storeconst replayStore = createRedisReplayStore({ client: redisClient, keyPrefix: 'cs:replay:', defaultTtlSeconds: 86400 // 24 hours});
app.use(contractshield({ policy: './policy.yaml', pdpOptions: { replayStore, getSecret: ({ provider }) => { /* ... */ } }}));Provider-Specific Configuration
Stripe
routes: - id: stripe.webhook match: method: POST path: /webhooks/stripe webhook: provider: stripe secretRef: STRIPE_WEBHOOK_SECRET timestampTolerance: 300 replayProtection: true allowedEventTypes: - checkout.session.completed - payment_intent.succeeded - payment_intent.payment_failed - invoice.paid - invoice.payment_failed - customer.subscription.created - customer.subscription.updated - customer.subscription.deletedGitHub
routes: - id: github.webhook match: method: POST path: /webhooks/github webhook: provider: github secretRef: GITHUB_WEBHOOK_SECRET replayProtection: true allowedEventTypes: - push - pull_request - issues - releaseSlack
routes: - id: slack.webhook match: method: POST path: /webhooks/slack webhook: provider: slack secretRef: SLACK_SIGNING_SECRET timestampTolerance: 300 replayProtection: trueTwilio
routes: - id: twilio.webhook match: method: POST path: /webhooks/twilio webhook: provider: twilio secretRef: TWILIO_AUTH_TOKEN replayProtection: trueCustom Webhook Providers
Register your own webhook plugin for unsupported providers:
import { registerWebhookPlugin } from '@cshield/pdp';import crypto from 'crypto';
registerWebhookPlugin({ name: 'acme',
verifySignature: async (route, ctx, { getSecret }) => { const secret = getSecret({ provider: 'acme', routeId: route.id, ctx }); const signature = ctx.request.headers['x-acme-signature']; const payload = ctx.request.rawBody;
const expected = crypto .createHmac('sha256', secret) .update(payload) .digest('hex');
return { valid: crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expected) ) }; },
extractEventId: (ctx) => { return ctx.request.headers['x-acme-event-id']; }});Then use it in your policy:
routes: - id: acme.webhook match: method: POST path: /webhooks/acme webhook: provider: acme secretRef: ACME_WEBHOOK_SECRET replayProtection: trueAccessing Webhook Context
The webhook validation result is available in the decision:
app.post('/webhooks/stripe', (req, res) => { const { decision, context } = req.contractshield;
if (context.webhook) { console.log('Provider:', context.webhook.provider); console.log('Signature valid:', context.webhook.signatureValid); console.log('Is replay:', context.webhook.replayed); }
// Process webhook const event = req.body; // ...});Best Practices
- Always validate signatures - Never trust webhook payloads without verification
- Use replay protection - Especially for payment and security-sensitive webhooks
- Whitelist event types - Only accept events your application handles
- Keep secrets secure - Use environment variables, never commit to code
- Monitor blocked webhooks - Alert on signature failures (could indicate compromise)
Troubleshooting
”Invalid signature” errors
- Ensure
rawBodyCapture()is called BEFOREexpress.json() - Check that the secret matches the one in your provider’s dashboard
- Verify the signature header name is correct
”Replay detected” errors
- Ensure your
replayStoreis working (Redis connected, etc.) - Check the event ID is being extracted correctly
- Verify events aren’t being sent multiple times by the provider
Next Steps
- Vulnerability Checks - Built-in attack detection
- Deployment - Production deployment patterns