Saltar al contenido principal

Firmas de webhooks

Comprueba que las peticiones de webhook vienen realmente de OrcaRail validando sus firmas.

¿Por qué verificar las firmas?​

Las firmas de los webhooks garantizan que:

  • La petición viene realmente de OrcaRail
  • El payload no se ha manipulado
  • No estás procesando peticiones maliciosas

Cómo funciona​

OrcaRail firma cada petición de webhook con HMAC SHA-256 usando tu secreto de webhook. Tu servidor debe verificar esta firma antes de procesar el evento.

Cabecera de la firma​

OrcaRail incluye la firma en la cabecera x-webhook-signature:

x-webhook-signature: abc123def456...

Secreto del webhook​

El secreto de firma del webhook es el secreto de tu clave de API (sk_live_...), el mismo valor que recibiste al crear la clave de API. Configúralo mediante PAYMENTS_WEBHOOK_SECRET (o la variable de entorno de tu app). Mantenlo a salvo y nunca lo expongas en código del lado del cliente.

Proceso de verificación​

1. Obtén la firma​

Extrae la firma de la cabecera x-webhook-signature:

const signature = req.headers['x-webhook-signature']

2. Calcula la firma esperada​

Calcula la firma esperada con HMAC SHA-256:

const crypto = require('crypto')
const webhookSecret = process.env.PAYMENTS_WEBHOOK_SECRET

// Get the raw request body
const payload = JSON.stringify(req.body)

// Compute HMAC SHA-256
const expectedSignature = crypto
.createHmac('sha256', webhookSecret)
.update(payload)
.digest('hex')

3. Compara las firmas​

Compara la firma recibida con la esperada usando una comparación de tiempo constante:

const crypto = require('crypto')

function verifySignature(receivedSignature, expectedSignature) {
if (!receivedSignature || !expectedSignature) {
return false
}

const receivedBuffer = Buffer.from(receivedSignature)
const expectedBuffer = Buffer.from(expectedSignature)

// Use timing-safe comparison to prevent timing attacks
if (receivedBuffer.length !== expectedBuffer.length) {
return false
}

return crypto.timingSafeEqual(receivedBuffer, expectedBuffer)
}

Ejemplo completo​

Node.js (Express)​

const express = require('express')
const crypto = require('crypto')

const app = express()

// Middleware to capture raw body for signature verification
app.use('/webhooks/orcarail', express.raw({ type: 'application/json' }))

app.post('/webhooks/orcarail', (req, res) => {
const webhookSecret = process.env.PAYMENTS_WEBHOOK_SECRET

if (!webhookSecret) {
console.warn(
'PAYMENTS_WEBHOOK_SECRET not set, skipping signature verification'
)
// In production, you should always verify signatures
// return res.status(500).json({ error: 'Webhook secret not configured' });
}

// Get signature from header
const receivedSignature = req.headers['x-webhook-signature']

if (!receivedSignature && webhookSecret) {
return res.status(400).json({ error: 'Missing webhook signature' })
}

// Compute expected signature
const payload = req.body.toString()
const expectedSignature = crypto
.createHmac('sha256', webhookSecret)
.update(payload)
.digest('hex')

// Verify signature
if (webhookSecret && !verifySignature(receivedSignature, expectedSignature)) {
return res.status(400).json({ error: 'Invalid webhook signature' })
}

// Parse JSON payload
const event = JSON.parse(payload)

// Process event
handleWebhookEvent(event)

res.status(200).json({ received: true })
})

function verifySignature(receivedSignature, expectedSignature) {
if (!receivedSignature || !expectedSignature) {
return false
}

const receivedBuffer = Buffer.from(receivedSignature)
const expectedBuffer = Buffer.from(expectedSignature)

if (receivedBuffer.length !== expectedBuffer.length) {
return false
}

return crypto.timingSafeEqual(receivedBuffer, expectedBuffer)
}

Python (Flask)​

import hmac
import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhooks/orcarail', methods=['POST'])
def webhook():
webhook_secret = os.environ.get('PAYMENTS_WEBHOOK_SECRET')

if not webhook_secret:
return jsonify({'error': 'Webhook secret not configured'}), 500

# Get signature from header
received_signature = request.headers.get('x-webhook-signature')

if not received_signature:
return jsonify({'error': 'Missing webhook signature'}), 400

# Get raw request body
payload = request.get_data()

# Compute expected signature
expected_signature = hmac.new(
webhook_secret.encode('utf-8'),
payload,
hashlib.sha256
).hexdigest()

# Verify signature using timing-safe comparison
if not hmac.compare_digest(received_signature, expected_signature):
return jsonify({'error': 'Invalid webhook signature'}), 400

# Parse JSON payload
event = request.get_json()

# Process event
handle_webhook_event(event)

return jsonify({'received': True}), 200

Ruby (Rails)​

class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token

def orcarail
webhook_secret = ENV['PAYMENTS_WEBHOOK_SECRET']

unless webhook_secret
return render json: { error: 'Webhook secret not configured' }, status: 500
end

received_signature = request.headers['x-webhook-signature']

unless received_signature
return render json: { error: 'Missing webhook signature' }, status: 400
end

payload = request.body.read

expected_signature = OpenSSL::HMAC.hexdigest(
OpenSSL::Digest.new('sha256'),
webhook_secret,
payload
)

unless ActiveSupport::SecurityUtils.secure_compare(
received_signature,
expected_signature
)
return render json: { error: 'Invalid webhook signature' }, status: 400
end

event = JSON.parse(payload)

handle_webhook_event(event)

render json: { received: true }, status: 200
end
end

PHP​

El SDK de PHP verifica y analiza en una sola llamada:

use OrcaRail\Exception\SignatureVerificationException;
use OrcaRail\Webhook;

$payload = file_get_contents('php://input'); // raw body, not a parsed array

try {
$event = Webhook::constructEvent(
$payload,
$_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '',
getenv('PAYMENTS_WEBHOOK_SECRET'),
);
} catch (SignatureVerificationException $exception) {
http_response_code(400);
echo json_encode(['error' => 'Invalid webhook signature']);
exit;
}

handle_webhook_event($event);

http_response_code(200);
echo json_encode(['received' => true]);

Sin el SDK, calcula tú el HMAC y compáralo con hash_equals():

$expected = hash_hmac('sha256', $payload, getenv('PAYMENTS_WEBHOOK_SECRET'));

if (!hash_equals($expected, strtolower($_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? ''))) {
http_response_code(400);
exit;
}

Buenas prácticas de seguridad​

1. Verifica siempre las firmas en producción​

Nunca te saltes la verificación de firmas en producción, aunque sea opcional:

if (process.env.NODE_ENV === 'production' && !webhookSecret) {
throw new Error('PAYMENTS_WEBHOOK_SECRET must be set in production')
}

2. Usa comparaciones de tiempo constante​

Usa siempre funciones de comparación de tiempo constante para evitar ataques de temporización:

  • Node.js: crypto.timingSafeEqual()
  • Python: hmac.compare_digest()
  • Ruby: ActiveSupport::SecurityUtils.secure_compare()
  • PHP: hash_equals()

3. Mantén tu secreto a salvo​

  • Guarda el secreto del webhook en variables de entorno
  • Nunca lo subas al control de versiones
  • Rótalo periódicamente
  • Usa secretos distintos para cada entorno

4. Gestiona correctamente las firmas ausentes​

Si falta la firma, rechaza la petición:

if (!receivedSignature) {
return res.status(400).json({ error: 'Missing webhook signature' })
}

Pruebas sin firmas​

Para el desarrollo local, puedes desactivar temporalmente la verificación de firmas:

const webhookSecret = process.env.PAYMENTS_WEBHOOK_SECRET

// Skip verification in development if secret not set
if (!webhookSecret && process.env.NODE_ENV === 'development') {
console.warn('Skipping webhook signature verification in development')
// Process event without verification
} else {
// Verify signature
if (!verifySignature(receivedSignature, expectedSignature)) {
return res.status(400).json({ error: 'Invalid webhook signature' })
}
}

:::warning Importante Nunca desactives la verificación de firmas en producción, ni siquiera para hacer pruebas. :::

Próximos pasos​