Skip to content

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

ProviderSignature MethodReplay Protection
StripeHMAC-SHA256✅ Timestamp + Event ID
GitHubHMAC-SHA256✅ Delivery ID
SlackHMAC-SHA256✅ Timestamp
TwilioHMAC-SHA1✅
CustomConfigurableConfigurable

Basic Setup

1. Capture Raw Body

Webhook signatures are computed over the raw request body. You must capture it before parsing:

```javascript import express from 'express'; import { contractshield, rawBodyCapture } from '@cshield/pep-express';
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;
}
}
}));
```
```javascript import Fastify from 'fastify'; import { contractshieldPlugin } from '@cshield/pep-fastify';
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.updated

Replay 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 store
const replayStore = new MemoryReplayStore();
// Production: Redis store
const 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.deleted

GitHub

routes:
- id: github.webhook
match:
method: POST
path: /webhooks/github
webhook:
provider: github
secretRef: GITHUB_WEBHOOK_SECRET
replayProtection: true
allowedEventTypes:
- push
- pull_request
- issues
- release

Slack

routes:
- id: slack.webhook
match:
method: POST
path: /webhooks/slack
webhook:
provider: slack
secretRef: SLACK_SIGNING_SECRET
timestampTolerance: 300
replayProtection: true

Twilio

routes:
- id: twilio.webhook
match:
method: POST
path: /webhooks/twilio
webhook:
provider: twilio
secretRef: TWILIO_AUTH_TOKEN
replayProtection: true

Custom 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: true

Accessing 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

  1. Always validate signatures - Never trust webhook payloads without verification
  2. Use replay protection - Especially for payment and security-sensitive webhooks
  3. Whitelist event types - Only accept events your application handles
  4. Keep secrets secure - Use environment variables, never commit to code
  5. Monitor blocked webhooks - Alert on signature failures (could indicate compromise)

Troubleshooting

”Invalid signature” errors

  1. Ensure rawBodyCapture() is called BEFORE express.json()
  2. Check that the secret matches the one in your provider’s dashboard
  3. Verify the signature header name is correct

”Replay detected” errors

  1. Ensure your replayStore is working (Redis connected, etc.)
  2. Check the event ID is being extracted correctly
  3. Verify events aren’t being sent multiple times by the provider

Next Steps