Vai al contenuto

Webhook

Verificare la firma

L'intestazione Voaaro-Signature, come viene calcolato il suo HMAC-SHA256 e come verificarla in Node, Python, PHP e Go.

Ogni richiesta di webhook contiene l'intestazione:

HTTP
Voaaro-Signature: t=1731403802,v1=5e2b0c…
  • t: l'ora dell'invio, in secondi dal 1970 (UTC);
  • v1: HMAC-SHA256(secret, "<t>.<corpo grezzo>") in esadecimale, dove la chiave è il segreto completo (whsec_…, prefisso compreso).

Durante un cambio di segreto con periodo di tolleranza, l'intestazione contiene due v1: il primo calcolato con il nuovo segreto, il secondo con il vecchio (t=…,v1=…,v1=…).

Per verificarla:

  1. leggi il corpo grezzo, byte per byte, prima di qualsiasi decodifica JSON;
  2. ricalcola l'HMAC di t + . + corpo con il tuo segreto;
  3. confrontalo con ciascun v1 in tempo costante; accetta la richiesta se uno di essi corrisponde;
  4. rifiutala se t si discosta di oltre 5 minuti dall'ora attuale (protezione contro la ripetizione).

Con gli SDK

Ogni SDK verifica la firma e l'età del messaggio, poi restituisce l'evento decodificato; una firma errata solleva un errore.

Node / Bun

import express from "express"
import { Voaaro } from "@deveryidea/voaaro"

const voaaro = new Voaaro(process.env.VOAARO_API_KEY, { baseUrl: "https://mail.example.com" })
const app = express()

// Raw body: express.raw, not express.json.
app.post("/webhooks/voaaro", express.raw({ type: "application/json" }), (req, res) => {
  let event
  try {
    event = voaaro.webhooks.verify(req.body, req.headers, process.env.VOAARO_WEBHOOK_SECRET!)
  } catch {
    return res.status(400).send("invalid signature")
  }
  if (event.type === "email.bounced") console.log("bounce", event.data.recipient)
  res.sendStatus(204)
})

Python

import os
import voaaro
from flask import Flask, request

app = Flask(__name__)

@app.post("/webhooks/voaaro")
def webhook():
    try:
        event = voaaro.Webhooks.verify(request.get_data(), request.headers, os.environ["VOAARO_WEBHOOK_SECRET"])
    except voaaro.WebhookVerificationError:
        return "invalid signature", 400
    if event["type"] == "email.bounced":
        print("bounce", event["data"]["recipient"])
    return "", 204

PHP

use Voaaro\Webhook;
use Voaaro\Exceptions\WebhookVerificationException;

$payload = file_get_contents('php://input');
try {
    $event = Webhook::verify($payload, getallheaders(), getenv('VOAARO_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $e) {
    http_response_code(400);
    exit('invalid signature');
}
if ($event->type === 'email.bounced') {
    error_log('bounce ' . $event->data->recipient);
}
http_response_code(204);

Go

http.HandleFunc("/webhooks/voaaro", func(w http.ResponseWriter, r *http.Request) {
	event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}
	if event.Type == "email.bounced" {
		log.Println("bounce", event.Data.Recipient)
	}
	w.WriteHeader(http.StatusNoContent)
})

Senza SDK

Node / Bun

import { createHmac, timingSafeEqual } from "node:crypto"

export function verify(rawBody: string, header: string, secret: string) {
  let t = 0
  const signatures: Buffer[] = []
  for (const part of header.split(",")) {
    const [key, value = ""] = part.trim().split("=", 2)
    if (key === "t") t = Number(value)
    else if (key === "v1") signatures.push(Buffer.from(value, "hex"))
  }
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) throw new Error("too old")
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest()
  // During a rotation, the header carries two v1: only one has to match.
  if (!signatures.some((s) => s.length === 32 && timingSafeEqual(s, expected))) throw new Error("invalid signature")
  return JSON.parse(rawBody)
}

Python

import hashlib, hmac, json, time

def verify(raw_body: bytes, header: str, secret: str) -> dict:
    t, signatures = 0, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            t = int(value)
        elif key == "v1":
            signatures.append(value)
    if abs(time.time() - t) > 300:
        raise ValueError("too old")
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    # During a rotation, the header carries two v1: only one has to match.
    if not any(hmac.compare_digest(expected, s) for s in signatures):
        raise ValueError("invalid signature")
    return json.loads(raw_body)

PHP

function verify(string $rawBody, string $header, string $secret): array {
    $t = 0;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't') {
            $t = (int) $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if (abs(time() - $t) > 300) {
        throw new RuntimeException('too old');
    }
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    // During a rotation, the header carries two v1: only one has to match.
    foreach ($signatures as $given) {
        if (hash_equals($expected, $given)) {
            return json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);
        }
    }
    throw new RuntimeException('invalid signature');
}

Go

func verify(rawBody []byte, header, secret string) error {
	var t int64
	var signatures [][]byte
	for _, p := range strings.Split(header, ",") {
		k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
		switch k {
		case "t":
			t, _ = strconv.ParseInt(v, 10, 64)
		case "v1":
			if sig, err := hex.DecodeString(v); err == nil {
				signatures = append(signatures, sig)
			}
		}
	}
	if d := time.Since(time.Unix(t, 0)); d > 5*time.Minute || d < -5*time.Minute {
		return errors.New("too old")
	}
	mac := hmac.New(sha256.New, []byte(secret))
	fmt.Fprintf(mac, "%d.", t)
	mac.Write(rawBody)
	expected := mac.Sum(nil)
	// During a rotation, the header carries two v1: only one has to match.
	for _, sig := range signatures {
		if hmac.Equal(sig, expected) {
			return nil
		}
	}
	return errors.New("invalid signature")
}

Esempio: un'iscrizione

I webhook di iscrizione si verificano allo stesso modo. Ad esempio, per aggiungere al tuo CRM ogni nuovo iscritto, qualunque sia l'origine dell'iscrizione (source):

Node / Bun

app.post("/webhooks/voaaro", express.raw({ type: "application/json" }), (req, res) => {
  let event
  try {
    event = voaaro.webhooks.verify(req.body, req.headers, process.env.VOAARO_WEBHOOK_SECRET!)
  } catch {
    return res.status(400).send("invalid signature")
  }
  // At-least-once delivery: ignore a Voaaro-Event-Id already handled.
  if (event.type === "contact.subscribed") crm.upsert(event.data.email, { newsletter: true, via: event.data.source })
  if (event.type === "contact.unsubscribed") crm.upsert(event.data.email, { newsletter: false })
  res.sendStatus(204)
})

Python

@app.post("/webhooks/voaaro")
def webhook():
    try:
        event = voaaro.Webhooks.verify(request.get_data(), request.headers, os.environ["VOAARO_WEBHOOK_SECRET"])
    except voaaro.WebhookVerificationError:
        return "invalid signature", 400
    if event["type"] == "contact.subscribed":
        crm.upsert(event["data"]["email"], newsletter=True, via=event["data"]["source"])
    return "", 204

PHP

try {
    $event = Webhook::verify(file_get_contents('php://input'), getallheaders(), getenv('VOAARO_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $e) {
    http_response_code(400);
    exit('invalid signature');
}
if ($event->type === 'contact.subscribed') {
    $crm->upsert($event->data->email, ['newsletter' => true, 'via' => $event->data->source]);
}
http_response_code(204);

Go

event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))
if err != nil {
	http.Error(w, "invalid signature", http.StatusBadRequest)
	return
}
if event.Type == "contact.subscribed" {
	crm.Upsert(event.Data.Email, true, string(event.Data.Source))
}
w.WriteHeader(http.StatusNoContent)

Verificare il tuo codice

Con il segreto whsec_test, l'ora 1700000000 e il corpo {"type":"email.delivered"}, l'intestazione attesa è:

Texte
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8

Durante una rotazione, con in più il vecchio segreto whsec_old, lo stesso corpo riporta:

Texte
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8,v1=ac4e8aa630365d68e2e6ad561135cfe2268e0eba907aa5ef10693a8a42f0f2c8

Il tuo codice deve accettarla sia con whsec_test sia con whsec_old, e rifiutarla con qualsiasi altro segreto.

Cambiare il segreto

Tramite l'API, senza interruzioni

POST /api/v1/webhooks/{id}/rotate-secret (dettagli) fornisce un nuovo segreto, che firma subito. Anche il vecchio continua a firmare durante il periodo di tolleranza: grace_hours, 24 ore per impostazione predefinita, da 0 a 72. In questo periodo ogni richiesta contiene due v1; una richiesta è valida se uno dei due corrisponde al tuo segreto.

  1. Esegui la rotazione e conserva il signing_secret ricevuto.
  2. Inserisci il nuovo segreto nella tua applicazione quando vuoi, purché prima di previous_secret_expires_at: le richieste vengono accettate sia con il vecchio sia con il nuovo.
  3. Alla scadenza di previous_secret_expires_at, il vecchio smette di firmare.

Per cambiare il segreto senza alcuna finestra di rifiuto, gli SDK accettano anche più segreti: tieni il vecchio accanto al nuovo durante il cambio, poi rimuovilo.

Node / Bun

// VOAARO_WEBHOOK_SECRET_OLD: empty once the period is over (an empty secret is ignored)
const event = voaaro.webhooks.verify(req.body, req.headers, [
  process.env.VOAARO_WEBHOOK_SECRET!,
  process.env.VOAARO_WEBHOOK_SECRET_OLD ?? "",
])

Python

secrets = [os.environ["VOAARO_WEBHOOK_SECRET"], os.environ.get("VOAARO_WEBHOOK_SECRET_OLD", "")]
event = voaaro.Webhooks.verify(request.get_data(), request.headers, secrets)  # an empty secret is ignored

PHP

$event = Webhook::verify($payload, getallheaders(), [
    getenv('VOAARO_WEBHOOK_SECRET'),
    getenv('VOAARO_WEBHOOK_SECRET_OLD'), // empty or missing: ignored
]);

Go

event, err := voaaro.VerifyWebhookRequestWithSecrets(r,
	os.Getenv("VOAARO_WEBHOOK_SECRET"),
	os.Getenv("VOAARO_WEBHOOK_SECRET_OLD")) // an empty secret is ignored

Gli esempi qui sopra e gli SDK accettano più v1. "grace_hours": 0 disattiva subito il vecchio segreto (segreto compromesso).

Nella console, immediatamente

Nuovo segreto (nella console) sostituisce il segreto immediatamente: il vecchio non firma più nulla, per il caso di un segreto compromesso. Inserisci subito dopo il nuovo segreto nella tua applicazione; le consegne rifiutate nel frattempo verranno inviate di nuovo dai tentativi successivi.

Esc