webhook-verify
One function to verify inbound webhooks from any provider.
Every backend that accepts webhooks ends up hand-rolling HMAC verification for
Stripe, GitHub, Shopify, Slack, and a dozen other services — and getting subtle
details wrong (raw body vs. re-serialized JSON, non-constant-time comparison,
missing replay protection, provider-specific encoding quirks). webhook-verify
is a small, dependency-light, audited-primitive-backed crate that does this
once, correctly, for every major provider, behind a single API.
use ;
let headers: = vec!;
let raw_body = b"{\"id\": \"evt_test\"}";
let result = verify;
match result
That's it. No client SDK to pull in, no per-provider crate to learn, no hand-copied signing-string logic to get wrong.
Why this exists
- The pain is universal. Nearly every SaaS integrates outbound webhooks
from payment processors, source control, chat platforms, and e-commerce
tools. Verifying them correctly is small in code size but easy to get
wrong, and wrong verification is a real security hole (forged
payment.succeeded/order.createdevents). - Rust has no incumbent. Go (
trusthook) and TypeScript (webhook-signature,hookinbox-verify) both grew "one API, many providers" webhook verifiers in the last year. Rust still doesn't have one — only heavyweight per-vendor SDKs (async-stripe,shopify-sdk, ...) that happen to include verification as a minor feature, plus a handful of single-provider crates. - This should be a library, not a tutorial. Search "verify [provider] webhook signature" for any provider and you'll find blog posts re-teaching the same HMAC recipe. That volume of repeated how-to content is the classic signal that the logic belongs in a dependency, not a copy-pasted snippet.
Design principles
- Correctness over cleverness. Every provider implementation is backed by test vectors taken from that provider's own documentation where they exist, and locally-constructed deterministic vectors over exactly the documented signed-string construction where a provider publishes none. No provider ships without them.
- No custom cryptography. All primitives come from
RustCrypto (
hmac,sha2,sha1,ed25519-dalek,subtlefor constant-time comparison). This crate only owns parsing and orchestration, never hashing or signature math. - Headless core, thin adapters. The value is in
verify(), a pure, synchronous, allocation-light function. Framework integration (Axum, Actix Web, Tower) is optional sugar behind feature flags, not the point of the crate. - Fail closed, explain why. Errors are structured
(
VerifyError::{MissingHeader, BadEncoding, SignatureMismatch, TimestampOutOfTolerance, UnsupportedProvider, ...}) so callers can log and alert meaningfully instead of getting a barefalse. - No unbounded scope creep. This crate verifies signatures. It does not deserialize event payloads, manage retries, store idempotency keys, or proxy webhooks. Those are separate, composable concerns (and separate crates) on purpose.
Supported providers (target v0.1 matrix)
| Provider | Scheme | Status |
|---|---|---|
| GitHub | HMAC-SHA256, X-Hub-Signature-256 |
✅ |
| Stripe | HMAC-SHA256 over timestamp.body, tolerance window |
✅ |
| Shopify | HMAC-SHA256, base64, X-Shopify-Hmac-Sha256 |
✅ |
| Slack | HMAC-SHA256 v0= scheme, X-Slack-Signature + timestamp |
✅ |
| Linear | HMAC-SHA256, linear-signature |
✅ |
| Square | HMAC-SHA256 over notification URL + body, base64, X-Square-HmacSha256-Signature (needs VerifyOptions::request_url) |
✅ |
| Twilio | HMAC-SHA1 over URL + sorted form params, X-Twilio-Signature (needs VerifyOptions::request_url + form_params) |
✅ |
| Discord | Ed25519 (public-key), no shared secret | ✅ |
| PayPal | RSASSA-PKCS1-v1_5 SHA-256 over `transmission_id | time |
| SendGrid | ECDSA P-256 over timestamp.body, public key via VerifyOptions::verifying_material (needs sendgrid feature) |
✅ |
| Zoom | HMAC-SHA256, v0= scheme, x-zm-signature + timestamp |
✅ |
| Dropbox | HMAC-SHA256, X-Dropbox-Signature |
✅ |
| Standard Webhooks spec (Svix, Clerk, Resend, ...) | HMAC-SHA256, webhook-signature (v1, base64, rotation list) + replay window |
✅ |
| Custom | User-supplied HMAC scheme via Provider::Custom(..) (SHA-256/SHA-1/SHA-512, hex/base64, optional prefix + timestamp replay window) |
✅ |
Some providers ship behind crate features: calling verify() on PayPal
or SendGrid without the corresponding feature compiled in fails closed
with VerifyError::UnsupportedProvider. See spec.md for the
exact signed-string construction, header names, and encoding for each
provider, and the process for adding new ones.
SendGrid verification is compiled only with the crate feature:
[]
= { = "0.1", = ["sendgrid"] }
For no_std + alloc targets, keep default-features = false together with
features = ["sendgrid"].
PayPal verification is compiled only with the crate feature:
[]
= { = "0.1", = ["paypal"] }
It verifies against the caller-supplied certificate (the crate never fetches
PayPal-Cert-Url — see spec.md §7) and needs both the webhook
subscription ID and the certificate to be configured:
let opts = default
.with_webhook_id
.with_verifying_material;
let result = verify;
Secret rotation
During a signing-key rotation window, Stripe and other standard-webhook
providers accept requests signed by either the old or the new key.
verify_any() tries each secret in turn and accepts the request if any one
of them verifies:
use ;
let result = verify_any;
- A match on any key returns
Ok(()); the request is safe to process. - Structural errors (
MissingHeader,MalformedHeader,BadEncoding,UnsupportedProvider,MissingContext,TimestampOutOfTolerance) are deterministic across all secrets and return immediately. - A garbled/undecodable key (
InvalidSecret) does not abort the search — a still-healthy key later in the slice can verify. If every key is well-formed but wrong, you getSignatureMismatch; only when every key is malformed do you getInvalidSecret(an operator-configuration signal, not a forgery). Full decision record inspec.md§2.1.
Installation
[]
= "0.1"
# verify straight against http::HeaderMap (axum, tower, hyper, ...)
= { = "0.1", = ["http"] }
# generic tower middleware (works with axum routers too)
= { = "0.1", = ["tower"] }
# actix-web 4 extractor + header bridge
= { = "0.1", = ["actix"] }
With the http feature enabled, any http::HeaderMap (from axum, tower, or
hyper requests) implements HeaderMap and can be passed to verify() directly.
no_std support
The core verification path is no_std + alloc compatible (validated against
wasm32-unknown-unknown). The std feature (on by default) provides the wall
clock used for replay protection and the std::error::Error impl. Disable it
for constrained targets:
# no wall clock; supply your own Clock for timestamped providers
= { = "0.1", = false }
Without std, [Clock::now] returns unix seconds directly, SystemClock is
unavailable, and VerifyError does not implement std::error::Error — see
spec.md §7.
Framework adapters
Tower (also Axum)
webhook-verify::tower::VerifyLayer is a generic tower::Layer. It buffers
the request body as raw bytes, rejects requests whose signature headers arrive
duplicated with conflicting values (400, see spec §4.4), verifies with
verify(), and forwards the exact buffered bytes downstream — handlers can
then deserialize freely. Verification failures never reach your handler:
| Failure class | Status |
|---|---|
| Missing / malformed signature headers | 400 Bad Request |
| Signature mismatch / stale timestamp | 401 Unauthorized |
| Operator misconfiguration | 500 Internal Server Error |
Plain tower stacks receive Request<Bytes>; axum users get their own body
type back automatically via type inference:
use ;
use VerifyLayer;
let layer = new;
// Plain tower: inner service takes http::Request<Bytes>.
let svc = layer.clone.layer;
// Axum: same layer, inferred as axum::body::Body.
// Router::new()
// .route("/webhooks/stripe", post(handle_stripe))
// .layer(layer);
Axum
Axum routers are tower services, so VerifyLayer is the supported axum
integration — no separate feature or module is needed:
use ;
use ;
use VerifyLayer;
let app = new
.route
.layer;
The layer buffers and verifies the raw body before routing, so handlers can
use extractors freely (Json, Bytes, ...) — the bytes they receive are
already verified.
⚠️ If you bypass the middleware, verify before any extractor touches the body. Extractors run top-down and body-consuming ones (
Json,Bytes,String) drain the request; once they have run, the original wire bytes are gone. Capture the body first (e.g.Bytesas your first extractor), callverify()on those exact bytes with anhttp::HeaderMap(thehttpfeature), and only then deserialize a copy.
Actix Web
Enable the actix feature and register a WebhookConfig on your app; the
VerifiedBody extractor then verifies the signature and hands your handler
the exact raw bytes:
use ;
use ;
use ;
new
.app_data
.route;
Because actix-web 4 reads the body only during extraction, VerifiedBody
captures it before anything else can touch it — do not also take
web::Json<T> in the same handler (extractors run left-to-right and Json
would consume the body first); deserialize from body's exact bytes instead.
Requests whose scheme headers arrive duplicated with conflicting values are
rejected with 400 before verification (spec §4.4). Failure statuses match
the tower table above. A guard is intentionally not provided: guards run
before the body is read, but verification requires those bytes.
⚠️ Raw body required. All frameworks buffer and re-parse JSON by default, which changes byte-for-byte content (key ordering, whitespace). The tower adapter and actix extractor capture the exact bytes off the wire before anything else touches them; if you call
verify()directly instead, make sure you pass those same untouched bytes (with thehttpfeature for axum/tower/hyper maps, or the bridge provided by theactixfeature).
Security notes
- All signature comparisons use constant-time equality (
subtle::ConstantTimeEq). - Timestamp-based replay protection is enabled by default wherever the
provider supports it (
VerifyOptions::max_age, default 5 minutes). - This crate does not log secrets, request bodies, or computed signatures under any log level.
- Secrets are wrapped in a
Secrettype that redactsDebug/Displayoutput.
Non-goals
- Sending/registering webhooks (that's the provider's own SDK's job).
- Event payload parsing/typing.
- Idempotency / deduplication of already-verified events.
- A hosted or proxying service (this is a plain library).
Versioning & MSRV
Semantic versioning. New providers are additive (minor version bumps). Changes to an existing provider's verification logic that could reject previously-accepted requests are treated as breaking (major version bump), except where required to fix a genuine security defect, which will be called out explicitly in the changelog and a security advisory.
MSRV: 1.85 (first Rust release with edition 2024 support), checked in CI.
Contributing
New providers, corrected test vectors, and encoding edge cases are the
highest-value contributions. See AGENTS.md for the
step-by-step process (used by both human and AI contributors) and
spec.md for the technical contract each provider
implementation must satisfy.
License
Dual-licensed under MIT or Apache-2.0, at your option.