Skip to main content

CM Email Webhook Verification SDK (Python)

SDK for verifying the authenticity of webhooks sent by CM Email services.

Installation

pip install cm-email-webhook-verification

Usage

from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError

# Initialize with your webhook secret key
validator = WebhookValidator("your-secret-key")

# Extract headers and payload from incoming request
headers = {
    "svix-id": request.headers["svix-id"],
    "svix-timestamp": request.headers["svix-timestamp"],
    "svix-signature": request.headers["svix-signature"],
}
payload = request.body.decode("utf-8")

try:
    data = validator.verify(payload, headers)
    # Process verified webhook data
    print(f"Received event: {data}")
except WebhookVerificationError as e:
    # Handle verification failure
    print(f"Webhook verification failed: {e}")

Flask Example

from flask import Flask, request, jsonify
from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError

app = Flask(__name__)
validator = WebhookValidator("your-secret-key")

@app.route("/webhook", methods=["POST"])
def webhook():
    headers = {
        "svix-id": request.headers.get("svix-id"),
        "svix-timestamp": request.headers.get("svix-timestamp"),
        "svix-signature": request.headers.get("svix-signature"),
    }
    payload = request.get_data(as_text=True)

    try:
        data = validator.verify(payload, headers)
        return jsonify({"status": "ok"}), 200
    except WebhookVerificationError:
        return jsonify({"error": "Invalid webhook"}), 401

FastAPI Example

from fastapi import FastAPI, Request, HTTPException
from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError

app = FastAPI()
validator = WebhookValidator("your-secret-key")

@app.post("/webhook")
async def webhook(request: Request):
    headers = {
        "svix-id": request.headers.get("svix-id"),
        "svix-timestamp": request.headers.get("svix-timestamp"),
        "svix-signature": request.headers.get("svix-signature"),
    }
    payload = (await request.body()).decode("utf-8")

    try:
        data = validator.verify(payload, headers)
        return {"status": "ok"}
    except WebhookVerificationError:
        raise HTTPException(status_code=401, detail="Invalid webhook")

Custom Tolerance

By default, webhooks are valid for 5 minutes. You can customize this:

# Accept webhooks up to 10 minutes old
validator = WebhookValidator("your-secret-key", tolerance_in_seconds=600)

The svix-timestamp header is a Unix timestamp in milliseconds. The tolerance you configure is in seconds.

Replay Protection and Duplicate Events

The timestamp check limits how long a captured webhook stays valid (5 minutes by default). It does not stop an exact copy of a valid webhook from being accepted again inside that window. The signature still prevents anyone without your secret key from changing a webhook. We can also deliver the same event more than once, for example when we retry a delivery.

To make your handler safe, deduplicate on data.id from the verified payload:

processed_event_ids = set()  # use a shared store in production, for example a database unique key or Redis SET NX

data = validator.verify(payload, headers)
event_id = data["data"]["id"]

if event_id in processed_event_ids:
    return  # already handled, still respond with 200
processed_event_ids.add(event_id)

# Process the event

Do not use the svix-id header for this. It is the ID of the email message, so all events for one message (for example sent, delivered and bounced) share it, and skipping on it would drop real events. data.id is unique per event and stays the same when we retry that event. Events can also arrive out of order, so compare createdAt before an older event overwrites newer state.

See Best practices in the webhook verification docs.

Exceptions

Exception Description
WebhookVerificationError Base exception for all verification errors
InvalidSignatureError Signature does not match
TimestampExpiredError Timestamp outside tolerance window
MissingHeaderError Required headers missing (or headers is None)
InvalidPayloadError Payload is empty or not valid JSON
InvalidTimestampError svix-timestamp is not a valid integer

Security

This SDK uses:

  • HMAC-SHA512 for signature generation
  • Constant-time comparison to prevent timing attacks
  • Timestamp validation to limit how long a captured webhook stays valid (see Replay Protection and Duplicate Events)

Metadata

Release files for cm-email-webhook-verification 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cm-email-webhook-verification 1.0.2
File Size Uploaded Provenance Actions
cm_email_webhook_verification-1.0.2.tar.gz 7.7 kB Without provenance Details for cm_email_webhook_verification-1.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cm-email-webhook-verification 1.0.2
File Interpreter ABI Platform Actions
cm_email_webhook_verification-1.0.2-py3-none-any.whl Python 3 none any Details for cm_email_webhook_verification-1.0.2-py3-none-any.whl

Total release size: 14.3 kB

Release files / cm_email_webhook_verification-1.0.2.tar.gz

Download URL cm_email_webhook_verification-1.0.2.tar.gz
Size 7.7 kB
Tags Source
SHA-256 checksum
How to use checksums
691fc706b73ad1de3b6ff5cc7f67105774aaf88aeacbe91a07f0de424b8d1a08
BLAKE2b-256 checksum
How to use checksums
164b4056d6d5583f42c5edfaf282100a4433b95b4ca898e582071bdbbc5edc03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / cm_email_webhook_verification-1.0.2-py3-none-any.whl

Download URL cm_email_webhook_verification-1.0.2-py3-none-any.whl
Size 6.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9b8ca2d0bd76c71132eaf14ae120859c436145a0d36e7c1fb1ac7ba6f738b83e
BLAKE2b-256 checksum
How to use checksums
d92a9efd60ee45f98189c0adb952af5b6b333359cfac48af7c42eb81550477ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Security for cm-email-webhook-verification 1.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page