Skip to main content

Receive webhooks

Handle events from LumoAuth in your backend: verify the signature, answer fast, and survive a repeat.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Packages
lumo
Works with
JavaScript / TypeScriptPythonGolumo CLIExpressFastAPIGo net/http

What it shows​

  1. A receiver reads the body of the request as bytes, and checks the HMAC signature and the time of the signature.
  2. The receiver answers with 200 at once, and does its work after the answer.
  3. The receiver remembers the ID of each delivery, so a delivery that arrives twice is handled once.
  4. While you develop, lumo tunnel forwards the events of your organization to the receiver on your laptop.
  5. For the deployed receiver, the CLI creates the webhook, sends a test event, and rotates the signing secret.

The receiver is the same in Express, FastAPI and Go. It uses the framework and the standard library only: the signature is plain HMAC-SHA256.

Before you start​

  • The lumo CLI and jq, for the scripts of the CLI tab.
  • An API key with the scopes admin:webhooks:read and admin:webhooks:write. Create it in the portal under Applications & developer tools, API keys.
  • For the last step, a receiver at a public HTTPS address. LumoAuth refuses a webhook that points at localhost or at a private network. On your laptop, use the tunnel.
VariableValue
LUMOAUTH_WEBHOOK_SECRETThe receiver reads it: the signing secret of the webhook. webhook.sh saves the answer of the creation, so set it with export LUMOAUTH_WEBHOOK_SECRET=$(jq -r .data.secret ~/lumoauth-webhook.json).
ALLOW_UNSIGNEDSet it to 1 only on your laptop, while lumo tunnel forwards the events. The tunnel does not sign.
PORTOptional. The port of the receiver. Default: 3000.
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYThe CLI scripts read it: an API key with the scopes admin:webhooks:read and admin:webhooks:write.
WEBHOOK_URLFor webhook.sh: the public HTTPS address of your deployed receiver, for example https://api.example.com/webhooks.
WEBHOOK_EVENTSOptional, for webhook.sh. The events, with commas between them. Default: user.created,user.login.
WEBHOOK_IDFor rotate.sh: the ID of the webhook. webhook.sh prints it.

Code​

Start a receiver in one terminal, and the tunnel in a second one. Then do something in your organization, for example create a user: the event arrives at the receiver.

Run each command from the recipes folder of the examples repository. Set the folder up once for your language.

operations/receive-webhooks/js/receiver.mjs
// Receive webhooks from LumoAuth in Express: verify the signature, answer at
// once, and ignore a repeat.
//
// node operations/receive-webhooks/js/receiver.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';

const secret = process.env.LUMOAUTH_WEBHOOK_SECRET;
// `lumo tunnel` forwards events to your laptop without a signature. Set
// ALLOW_UNSIGNED=1 only for that, never on a deployed receiver.
const allowUnsigned = process.env.ALLOW_UNSIGNED === '1';
const port = Number(process.env.PORT ?? 3000);

if (!secret && !allowUnsigned) {
console.error('Set LUMOAUTH_WEBHOOK_SECRET, or ALLOW_UNSIGNED=1 for lumo tunnel.');
process.exit(1);
}

// The clocks of two servers differ a little. Five minutes is a common limit.
const MAX_AGE_SECONDS = 300;

// The delivery IDs that were handled. A real app keeps them in a store that
// all its instances share, and removes them after a few days.
const seen = new Set();

/** Checks one signature header. Returns the delivery ID, or null. */
function verify(header, rawBody) {
if (!header || !secret) return null;
// The header is "kid=...,t=<unix time>,id=<delivery ID>,v1=<hex HMAC>".
const fields = Object.fromEntries(
header.split(',').map((field) => {
const at = field.indexOf('=');
return [field.slice(0, at), field.slice(at + 1)];
}),
);
if (!fields.t || !fields.id || !fields.v1) return null;
if (Math.abs(Date.now() / 1000 - Number(fields.t)) > MAX_AGE_SECONDS) return null;

// LumoAuth signs the time, the delivery ID and the body exactly as it was sent.
const expected = createHmac('sha256', secret).update(`${fields.t}.${fields.id}.`).update(rawBody).digest();
const given = Buffer.from(fields.v1, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected) ? fields.id : null;
}

const app = express();

// express.raw keeps the bytes of the body. A signature over parsed JSON
// that was written out again would not match.
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
let deliveryId;
if (req.get('X-LumoAuth-Signature')) {
// For 24 hours after a rotation, the second header holds a signature
// that was made with the secret from before the rotation.
deliveryId =
verify(req.get('X-LumoAuth-Signature'), req.body) ??
verify(req.get('X-LumoAuth-Signature-Previous'), req.body);
if (!deliveryId) {
console.log('rejected: the signature does not match');
return res.status(401).json({ error: 'invalid_signature' });
}
} else if (allowUnsigned) {
deliveryId = req.get('X-LumoAuth-Delivery');
} else {
console.log('rejected: no signature');
return res.status(401).json({ error: 'missing_signature' });
}

const event = req.get('X-LumoAuth-Event');
if (seen.has(deliveryId)) {
// A repeat is answered with 200 too, so that LumoAuth stops sending it.
console.log(`${event} ${deliveryId} repeat, ignored`);
return res.json({ received: true });
}
seen.add(deliveryId);

// Answer first: LumoAuth waits 5 seconds, then counts the delivery as failed.
res.json({ received: true });
console.log(`${event} ${deliveryId} accepted`);

setImmediate(() => handle(event, JSON.parse(req.body.toString('utf8'))));
});

/** The work of your app. It runs after the answer. */
function handle(event, body) {
// A delivery from LumoAuth wraps the event: { event, timestamp, tenant, data }.
// The tunnel sends the inner object only.
const data = body.data ?? body;
if (event === 'user.created') console.log(` new user: ${data.target_id}`);
}

app.listen(port, '127.0.0.1', () => console.log(`listening on http://localhost:${port}/webhooks`));
ALLOW_UNSIGNED=1 node operations/receive-webhooks/js/receiver.mjs

Compiles. Not run against an organization. The receiver accepted a webhook.test event of an organization through lumo tunnel, and it verified requests that were signed with the documented scheme. No signed delivery from an organization reached it: the test organization had no public receiver.

When the receiver is deployed, run webhook.sh once with its public address. The script stores the answer of LumoAuth, which holds the signing secret, in a file in your home folder. Give the secret to the deployed receiver as LUMOAUTH_WEBHOOK_SECRET, and do not set ALLOW_UNSIGNED there.

Check the result​

Output
listening on http://localhost:3000/webhooks
webhook.test 269139cb28c54a5100db88f853c9a586 accepted
webhook.test 269139cb28c54a5100db88f853c9a586 repeat, ignored
rejected: the signature does not match
  • The first line after the start is a delivery that the receiver accepted. The same delivery a second time gives "repeat, ignored": LumoAuth sends a delivery again when your receiver did not answer with a 2xx status in 5 seconds.
  • A request with a wrong signature, with no signature, or with a signature that is older than five minutes gets the status 401.
  • lumo webhooks deliveries list <webhook-id> shows each delivery with its status and the status code that your receiver answered. The portal shows the same list under Settings, Integrations, in the tab Webhooks: open the menu of the webhook and select Deliveries.
  • After rotate.sh, a receiver that still holds the old secret keeps working for 24 hours. In that time each delivery carries the header X-LumoAuth-Signature-Previous, which the receiver also checks.

Limits​

  • The tunnel does not sign what it forwards, and it sends the inner data object without the envelope. The receiver reads the name of the event from the header X-LumoAuth-Event for that reason.
  • A retry of a delivery repeats the delivery ID. A replay from the deliveries list is a new delivery with a new ID, so the receiver handles it again.
  • The receiver keeps the delivery IDs in memory. An app with more than one instance needs a shared store for them.
  • LumoAuth does not follow a redirect. An answer with a 3xx status counts as a failed delivery.
  • A webhook for Slack, Discord or Microsoft Teams gets a formatted message, not this JSON. See Get alerts for attacks.