Get started
Webhooks

Verify webhook signatures

Verify webhook signatures

Every delivery carries a Mountaya-Signature header. Verify it on the raw body before you trust the event.

Header
Mountaya-Signature: t=1763111564,v1=ad18de77c0892dba398f210f0f3205666e41c17025feaf8d42ae5998d8545f5d

How it is computed

  1. Read t, the time Mountaya signed the delivery, in Unix seconds.
  2. Join t, a period and the raw request body: <t>.<body>.
  3. Compute its HMAC-SHA256, keyed by your whole secret as UTF-8, whsk_ included.
  4. Compare the lowercase hexadecimal result with each v1 of the header, in constant time.
  5. Refuse a t more than 300 seconds away from your clock.

The secret is the one the endpoint was created with. Keep it in MOUNTAYA_WEBHOOK_SECRET on your server.

With the TypeScript SDK

constructWebhookEvent checks the signature and the timestamp, then parses the event. It throws MountayaWebhookSignatureError when either check fails.

TypeScript
import {
  constructWebhookEvent,
  MountayaWebhookSignatureError,
  type WebhookEvent,
} from "@mountaya/client";

const secret = process.env.MOUNTAYA_WEBHOOK_SECRET ?? "";

// A route handler that receives a Fetch API Request, as Next.js, Hono, Bun and Deno do.
export async function POST(request: Request): Promise<Response> {
  let event: WebhookEvent;
  try {
    event = await constructWebhookEvent(
      await request.text(),
      request.headers.get("Mountaya-Signature"),
      secret,
      { toleranceSeconds: 300 },
    );
  } catch (error) {
    if (error instanceof MountayaWebhookSignatureError) {
      return new Response(error.reason, { status: 400 });
    }
    throw error;
  }

  // Queue the event and answer at once. Deduplicate on event.id later.
  console.log(event.id, event.type);
  return new Response(null, { status: 200 });
}

By hand in Python

The standard library is enough: hmac computes and compares, hashlib supplies SHA-256.

Python
import hashlib
import hmac
import time


def verify(secret: str, header: str, body: bytes, now: int | None = None, tolerance: int = 300) -> bool:
    """Tell whether a delivery is Mountaya's: one v1 matches, and t is within the tolerance."""
    timestamps, signatures = [], []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamps.append(value)
        elif key == "v1":
            signatures.append(value)

    if len(timestamps) != 1 or not signatures:
        return False
    # ASCII digits only, and few enough to be a time: int() raises on anything else.
    if not timestamps[0].isascii() or not timestamps[0].isdigit() or len(timestamps[0]) > 15:
        return False
    current = int(time.time()) if now is None else now
    if abs(current - int(timestamps[0])) > tolerance:
        return False

    signed = timestamps[0].encode() + b"." + body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest().encode()
    return any(hmac.compare_digest(expected, signature.encode()) for signature in signatures)

Call it with the body exactly as it arrived. In Flask, that is request.get_data():

Python
import json
import os

from flask import Flask, request

app = Flask(__name__)


@app.post("/mountaya")
def receive():
    body = request.get_data()
    if not verify(os.environ["MOUNTAYA_WEBHOOK_SECRET"], request.headers.get("Mountaya-Signature", ""), body):
        return "Invalid signature", 400

    event = json.loads(body)
    # Queue the event and answer at once. Deduplicate on event["id"] later.
    print(event["id"], event["type"])
    return "", 200

Rotation

Rotating a secret in the Mountaya app keeps the previous one signing for up to 7 days. Meanwhile, the header carries one v1 per secret:

Header
Mountaya-Signature: t=1763111564,v1=ad18de77c0892dba398f210f0f3205666e41c17025feaf8d42ae5998d8545f5d,v1=4e6b9453fbe787bdc2f4a686b21a2e572f6070a0c5ec7bdfa418198b8e253174

Accept a delivery when any v1 matches your secret. Deploy the new secret before the overlap ends. If a secret leaked, rotate with no overlap: every earlier secret stops at once.

Test your verifier

Check your code against the published test vectors before real deliveries reach it. Each case gives a secret, a clock, a header, a body and the expected verdict.

Contract v0.8.0 publishes them: download the test vectors.

CaseWhat it checksVerifies
validOne secret in force, and the receiver's clock 5 seconds past t.Yes
rotation-new-secretDuring a rotation the header carries one v1 per secret; a receiver holding the new secret verifies the first.Yes
rotation-previous-secretThe same delivery, verified by a receiver still holding the previous secret, which matches the second v1.Yes
tampered-bodyThe header was computed over the body as sent, and the body was changed on the way: no v1 matches.No: signature
outside-toleranceA correct signature, received 301 seconds after t: past the 300-second tolerance, a replay is refused.No: timestamp
Python
import json

with open("signature-vectors.json") as file:
    vectors = json.load(file)

for case in vectors["cases"]:
    verified = verify(case["secret"], case["header"], case["body"].encode(), now=case["now"])
    assert verified == case["expect"]["valid"], case["name"]

print(f"{len(vectors['cases'])} cases pass")

Next steps

Last updated