Skip to content

Verificare la firma ​

Ogni richiesta è firmata con il segreto dell'endpoint. Verifica la firma prima di elaborare l'evento: è ciò che ti permette di controllare che arrivi da Mailiqo e che nessuno abbia modificato il contenuto lungo il percorso.

La firma segue la specifica Standard Webhooks, quindi puoi verificarla con le sue librerie oppure a mano.

HeaderContenuto
webhook-idIdentificatore dell'evento. È lo stesso in tutti i tentativi di consegna
webhook-timestampMomento di questo tentativo di consegna, in secondi Unix. Cambia a ogni nuovo tentativo
webhook-signatureUna o più firme separate da spazi, ciascuna nel formato v1,<firma in base64>

Come si calcola ​

  1. Contenuto firmato: il valore di webhook-id, un punto, il valore di webhook-timestamp, un altro punto e il corpo della richiesta esattamente come arriva.
  2. Chiave: il segreto senza il prefisso whsec_, decodificato da base64.
  3. Firma: l'HMAC-SHA256 del contenuto firmato con quella chiave, codificato in base64.

Per verificare una richiesta:

  • Calcola la firma e confrontala con ciascuna di quelle presenti in webhook-signature. Basta che ne coincida una. Usa un confronto a tempo costante.
  • Rifiuta la richiesta se webhook-timestamp si discosta di più di 5 minuti dall'ora attuale. In questo modo una richiesta intercettata non può essere inviata di nuovo più tardi.

Usa il corpo non elaborato

La firma si calcola sui byte esatti del corpo. Se il tuo framework converte il JSON in un oggetto e tu lo serializzi di nuovo, il risultato non coincide e la firma fallisce. Leggi il corpo grezzo, verifica e solo dopo interpreta il JSON.

AmbienteCome leggere il corpo grezzo
Expressexpress.raw({ type: 'application/json' }) sulla route del webhook
PHPfile_get_contents('php://input')
Laravel e Symfony$request->getContent()
Flaskrequest.get_data()
Djangorequest.body
FastAPIawait request.body()

Con le librerie di Standard Webhooks ​

bash
npm install standardwebhooks                          # Node.js
composer require standard-webhooks/standard-webhooks  # PHP
pip install standardwebhooks                          # Python

Il segreto si passa così come lo mostra il pannello, con il prefisso whsec_. Le librerie controllano la firma e l'età di webhook-timestamp.

js
import express from 'express';
import { Webhook } from 'standardwebhooks';

const app = express();
const webhook = new Webhook(process.env.MAILIQO_WEBHOOK_SECRET);

app.post('/webhooks/mailiqo', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = webhook.verify(req.body, req.headers);
  } catch (err) {
    return res.status(400).end();
  }

  // Metti l'evento in una coda e rispondi subito.
  res.status(204).end();
});
php
<?php

require 'vendor/autoload.php';

$payload = file_get_contents('php://input');
$headers = [
    'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
];

try {
    $webhook = new \StandardWebhooks\Webhook(getenv('MAILIQO_WEBHOOK_SECRET'));
    $event = $webhook->verify($payload, $headers);
} catch (\StandardWebhooks\Exception\WebhookVerificationException $e) {
    http_response_code(400);
    exit;
}

// Metti l'evento in una coda e rispondi subito.
http_response_code(204);
python
import json
import os

from flask import Flask, request
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

app = Flask(__name__)
webhook = Webhook(os.environ['MAILIQO_WEBHOOK_SECRET'])


@app.post('/webhooks/mailiqo')
def mailiqo_webhook():
    payload = request.get_data()
    try:
        webhook.verify(payload, request.headers)
    except WebhookVerificationError:
        return '', 400

    event = json.loads(payload)
    # Metti l'evento in una coda e rispondi subito.
    return '', 204

Senza librerie ​

Se preferisci non aggiungere una dipendenza, la verifica richiede poche righe:

js
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

export function verifyMailiqoSignature(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !timestamp || !signatures) return false;

  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!(age <= TOLERANCE_SECONDS)) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();

  return signatures.split(' ').some((entry) => {
    const [version, signature] = entry.split(',');
    if (version !== 'v1' || !signature) return false;
    const received = Buffer.from(signature, 'base64');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}
php
<?php

function verifyMailiqoSignature(string $rawBody, string $id, string $timestamp, string $signatures, string $secret): bool
{
    if ($id === '' || abs(time() - (int) $timestamp) > 300) {
        return false;
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true));

    foreach (explode(' ', $signatures) as $entry) {
        [$version, $signature] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $signature)) {
            return true;
        }
    }

    return false;
}

$valid = verifyMailiqoSignature(
    file_get_contents('php://input'),
    $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
    getenv('MAILIQO_WEBHOOK_SECRET')
);
python
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify_mailiqo_signature(raw_body: bytes, headers, secret: str) -> bool:
    event_id = headers.get('webhook-id', '')
    timestamp = headers.get('webhook-timestamp', '')
    signatures = headers.get('webhook-signature', '')
    if not event_id or not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix('whsec_'))
    signed_content = f'{event_id}.{timestamp}.'.encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode()

    return any(
        hmac.compare_digest(expected, entry.partition(',')[2])
        for entry in signatures.split(' ')
        if entry.startswith('v1,')
    )

I nomi degli header non distinguono tra maiuscole e minuscole. Alcuni server li forniscono in un'altra forma, come Webhook-Id o HTTP_WEBHOOK_ID.

Ruotare il segreto ​

Nella scheda Webhook del dominio, apri il menu ⋯ dell'endpoint e clicca su Ruota il segreto. Viene generato un nuovo segreto, mostrato una sola volta.

Nelle 24 ore successive ogni evento porta due firme, una con il nuovo segreto e una con il precedente, separate da uno spazio. Il tuo server continua a validare con il segreto precedente finché non distribuisci quello nuovo, e non perdi eventi durante il cambio. Trascorse le 24 ore si firma solo con il nuovo.

Le librerie e gli esempi di questa pagina controllano già tutte le firme dell'header.

Se pensi che il segreto sia stato divulgato, ruotalo e distribuisci quello nuovo il prima possibile: appena il tuo server smette di usare il precedente, una firma fatta con esso non è più valida per te.

Per far smettere di firmare il segreto precedente senza aspettare le 24 ore, clicca su Fai scadere ora accanto all'avviso del segreto precedente. Fallo quando il tuo server usa già quello nuovo: da quel momento gli eventi portano una sola firma.

Dove conservare il segreto ​

  • In una variabile d'ambiente o in un gestore di segreti, non nel codice né nel repository.
  • Ogni endpoint ha il proprio segreto. Se ricevi eventi da più domini, usa il segreto dell'endpoint che corrisponde a ciascun URL.
  • Il segreto di test, che inizia con whsec_test, è solo per i tuoi ambienti di sviluppo. Vedi Test.

Built with VitePress