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

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.1

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.1
File Size Uploaded Provenance Actions
cm_email_webhook_verification-1.0.1.tar.gz 6.5 kB Without provenance Details for cm_email_webhook_verification-1.0.1.tar.gz

Built distribution (wheel)

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

Total release size: 12.8 kB

Release files / cm_email_webhook_verification-1.0.1.tar.gz

Download URL cm_email_webhook_verification-1.0.1.tar.gz
Size 6.5 kB
Tags Source
SHA-256 checksum
How to use checksums
52d956d873f5908e21898cba3550cc0d50314852ca938b6fb1d5e00e34010ea4
BLAKE2b-256 checksum
How to use checksums
3a526aa79fd6c719b7ccc6a60ae799c812592c43ea17de7b207a982a0c3957e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

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

Download URL cm_email_webhook_verification-1.0.1-py3-none-any.whl
Size 6.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c3238091eedf90b49224a4bfd916ba999603156ce524b0ab6f2f97cb629dd1fa
BLAKE2b-256 checksum
How to use checksums
41cefbdf696cdc881a2d28e06bec8a391ff9aaf17f602a5f725a0c1554617fa0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for cm-email-webhook-verification 1.0.1

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