Receive security events
Let your services learn at once that a session or an agent was revoked, with signed events in a standard format.
What it shows
- A stream tells LumoAuth where your service receives security events. LumoAuth sends each event as a signed token in one POST request.
- The receiver checks the bearer token of the request, then the signature, the issuer, the audience and the type of the event token.
- On a verification event, the receiver logs the
statevalue. You use this event to test the stream. - On
session-revoked, the receiver drops what it keeps for the subject. LumoAuth sends this event when an agent is suspended, revoked, deactivated or deleted. - The receiver answers
202. LumoAuth sends an event again after any other answer, with the samejti.
The events follow the OpenID Shared Signals Framework and its CAEP profile. Any receiver that follows these standards works with the stream.
Before you start
- Check that your plan includes shared signals in the plans matrix.
- A public https address for the receiver. LumoAuth refuses local and private addresses. For local work, use a tunnel service that gives a port of your machine a public https address.
- The setup script needs an API key with the scopes
admin:webhooks:readandadmin:webhooks:write, from a person who holdssettings.manage. Create it in the portal under Applications & developer tools, API keys. - You can also create the stream in the portal: open AI Agents, Agent activity, Security signals, and click Create stream on the Streams (outbound) tab. Enter the same three values under Delivery endpoint, Audience and Bearer token.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | For the setup script only: an API key with the scopes admin:webhooks:read and admin:webhooks:write. |
RECEIVER_URL | The public https address of the receiver, for example https://signals.example.com/security-events. |
SSF_AUDIENCE | The name of the receiver, usually its base address: https://signals.example.com. Every event carries it in aud. |
SSF_BEARER_TOKEN | A long random value that you choose, for example from openssl rand -hex 32. LumoAuth sends it with each event, and the receiver checks it. |
PORT | Optional: the port of the receiver. The default is 3000. |
The setup script creates the stream through the stream API and asks for one verification event. Start a receiver first.
node agents/security-events/setup.mjs
setup.mjs
// Creates a stream that pushes security events to your receiver, and asks
// LumoAuth to send one verification event. Start the receiver first.
//
// node agents/security-events/setup.mjs
//
// It reads RECEIVER_URL, SSF_AUDIENCE and SSF_BEARER_TOKEN, the same values
// that the receiver reads. The API key needs the scopes admin:webhooks:read
// and admin:webhooks:write.
import { call } from '../../_lib/admin.mjs';
const { RECEIVER_URL, SSF_AUDIENCE, SSF_BEARER_TOKEN } = process.env;
if (!RECEIVER_URL || !SSF_AUDIENCE || !SSF_BEARER_TOKEN) {
console.error('Set RECEIVER_URL, SSF_AUDIENCE and SSF_BEARER_TOKEN first.');
process.exit(1);
}
// LumoAuth never returns the bearer token of a stream. A second run therefore
// replaces the stream for this address.
const { streams } = await call('GET', '/ssf/stream');
for (const old of streams.filter((s) => s.delivery.endpoint_url === RECEIVER_URL)) {
await call('DELETE', `/ssf/stream?stream_id=${old.stream_id}`);
}
const stream = await call('POST', '/ssf/stream', {
delivery: {
method: 'urn:ietf:rfc:8935',
endpoint_url: RECEIVER_URL,
// LumoAuth sends this value as "Authorization: Bearer …" with each event.
authorization_token: SSF_BEARER_TOKEN,
},
// The `aud` claim of every event on this stream.
audience: SSF_AUDIENCE,
events_requested: ['https://schemas.openid.net/secevent/caep/event-type/session-revoked'],
});
console.log(`Stream ${stream.stream_id} sends ${stream.events_delivered.length} event type to ${RECEIVER_URL}`);
await call('POST', '/ssf/verify', { stream_id: stream.stream_id, state: 'hello-from-setup' });
console.log('Asked for a verification event. The receiver logs it within seconds.');
Code
Start one receiver, then run the setup script in a second terminal.
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The setup script did not run on the test organization: the stream API answered 401 to an API key.
- Node.js
- Python
- Go
// A receiver for security events from LumoAuth, with Express.
//
// node agents/security-events/js/receiver.mjs
import { timingSafeEqual } from 'node:crypto';
import express from 'express';
import { createRemoteJWKSet, jwtVerify } from 'jose';
const SESSION_REVOKED = 'https://schemas.openid.net/secevent/caep/event-type/session-revoked';
const VERIFICATION = 'https://schemas.openid.net/secevent/ssf/event-type/verification';
// LumoAuth signs each event with the signing key of your organization.
const issuer = `${process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
const keys = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
const expectedAuthorization = Buffer.from(`Bearer ${process.env.SSF_BEARER_TOKEN}`);
// What this service keeps for each caller. The key is the `sub` of the
// caller's access token: agent_<agent ID> for an agent.
const sessions = new Map();
// The IDs of the events that arrived. LumoAuth sends an event again with the same `jti`.
const seen = new Set();
const app = express();
app.post('/security-events', express.text({ type: 'application/secevent+jwt' }), async (req, res) => {
const authorization = Buffer.from(req.get('Authorization') ?? '');
if (authorization.length !== expectedAuthorization.length || !timingSafeEqual(authorization, expectedAuthorization)) {
return res.status(401).end();
}
let event;
try {
// The `typ` check refuses an access token that somebody sends as an event.
({ payload: event } = await jwtVerify(req.body, keys, {
issuer,
audience: process.env.SSF_AUDIENCE,
typ: 'secevent+jwt',
}));
} catch (error) {
return res.status(400).json({ err: 'invalid_request', description: error.message });
}
if (!seen.has(event.jti)) {
seen.add(event.jti);
for (const [type, details] of Object.entries(event.events)) {
if (type === SESSION_REVOKED) {
// For an agent, sub_id is { format: "iss_sub", iss, sub }.
const subject = event.sub_id.sub ?? event.sub_id.id;
sessions.delete(subject);
console.log(`session-revoked: dropped everything for ${subject}`);
} else if (type === VERIFICATION) {
console.log(`verification: state ${details.state}`);
}
}
}
// 202 says that the event is stored. LumoAuth sends it again after any other answer.
res.status(202).end();
});
const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => console.log(`Waiting for security events on http://localhost:${port}/security-events`));
node agents/security-events/js/receiver.mjs
Compiles. Not run against an organization. The receiver was tested with events from a local stand-in. LumoAuth delivers only to a public https address, which the test had not.
# A receiver for security events from LumoAuth, with FastAPI.
#
# python agents/security-events/python/receiver.py
import hmac
import os
import jwt
import uvicorn
from fastapi import FastAPI, Header, Request, Response
from fastapi.responses import JSONResponse
SESSION_REVOKED = "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
VERIFICATION = "https://schemas.openid.net/secevent/ssf/event-type/verification"
# LumoAuth signs each event with the signing key of your organization.
issuer = f"{os.environ.get('LUMOAUTH_URL', 'https://app.lumoauth.dev')}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
keys = jwt.PyJWKClient(f"{issuer}/.well-known/jwks.json")
expected_authorization = f"Bearer {os.environ['SSF_BEARER_TOKEN']}"
# What this service keeps for each caller. The key is the `sub` of the
# caller's access token: agent_<agent ID> for an agent.
sessions: dict[str, dict] = {}
# The IDs of the events that arrived. LumoAuth sends an event again with the same `jti`.
seen: set[str] = set()
app = FastAPI()
@app.post("/security-events")
async def receive(request: Request, authorization: str = Header(default="")):
if not hmac.compare_digest(authorization.encode(), expected_authorization.encode()):
return Response(status_code=401)
token = (await request.body()).decode()
try:
# The `typ` check refuses an access token that somebody sends as an event.
if jwt.get_unverified_header(token).get("typ") != "secevent+jwt":
raise jwt.InvalidTokenError("The token is not a security event token.")
event = jwt.decode(
token,
keys.get_signing_key_from_jwt(token).key,
algorithms=["RS256"],
issuer=issuer,
audience=os.environ["SSF_AUDIENCE"],
)
except jwt.PyJWTError as error:
return JSONResponse({"err": "invalid_request", "description": str(error)}, status_code=400)
if event["jti"] not in seen:
seen.add(event["jti"])
for event_type, details in event["events"].items():
if event_type == SESSION_REVOKED:
# For an agent, sub_id is {"format": "iss_sub", "iss": …, "sub": …}.
subject = event["sub_id"].get("sub") or event["sub_id"].get("id")
sessions.pop(subject, None)
print(f"session-revoked: dropped everything for {subject}", flush=True)
elif event_type == VERIFICATION:
print(f"verification: state {details.get('state')}", flush=True)
# 202 says that the event is stored. LumoAuth sends it again after any other answer.
return Response(status_code=202)
if __name__ == "__main__":
port = int(os.environ.get("PORT", "3000"))
print(f"Waiting for security events on http://localhost:{port}/security-events", flush=True)
uvicorn.run(app, port=port, log_level="warning")
python agents/security-events/python/receiver.py
Compiles. Not run against an organization. The receiver was tested with events from a local stand-in. LumoAuth delivers only to a public https address, which the test had not.
// A receiver for security events from LumoAuth, with net/http.
//
// go run ./agents/security-events/go
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"sync"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jws"
"github.com/lestrrat-go/jwx/v2/jwt"
)
const (
sessionRevoked = "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
verification = "https://schemas.openid.net/secevent/ssf/event-type/verification"
)
var (
mu sync.Mutex
// What this service keeps for each caller. The key is the `sub` of the
// caller's access token: agent_<agent ID> for an agent.
sessions = map[string]any{}
// The IDs of the events that arrived. LumoAuth sends an event again with the same `jti`.
seen = map[string]bool{}
)
func main() {
ctx := context.Background()
base := os.Getenv("LUMOAUTH_URL")
if base == "" {
base = "https://app.lumoauth.dev"
}
// LumoAuth signs each event with the signing key of your organization.
issuer := base + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
jwksURL := issuer + "/.well-known/jwks.json"
keys := jwk.NewCache(ctx)
if err := keys.Register(jwksURL); err != nil {
log.Fatal(err)
}
expectedAuthorization := []byte("Bearer " + os.Getenv("SSF_BEARER_TOKEN"))
http.HandleFunc("POST /security-events", func(w http.ResponseWriter, r *http.Request) {
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), expectedAuthorization) != 1 {
w.WriteHeader(http.StatusUnauthorized)
return
}
body, _ := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
event, err := verify(r.Context(), keys, jwksURL, body, issuer)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"err": "invalid_request", "description": err.Error()})
return
}
mu.Lock()
defer mu.Unlock()
if !seen[event.JwtID()] {
seen[event.JwtID()] = true
events, _ := event.Get("events")
for eventType, details := range events.(map[string]any) {
switch eventType {
case sessionRevoked:
// For an agent, sub_id is {"format": "iss_sub", "iss": …, "sub": …}.
subID, _ := event.Get("sub_id")
subject, _ := subID.(map[string]any)["sub"].(string)
if subject == "" {
subject, _ = subID.(map[string]any)["id"].(string)
}
delete(sessions, subject)
fmt.Printf("session-revoked: dropped everything for %s\n", subject)
case verification:
fmt.Printf("verification: state %v\n", details.(map[string]any)["state"])
}
}
}
// 202 says that the event is stored. LumoAuth sends it again after any other answer.
w.WriteHeader(http.StatusAccepted)
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
fmt.Printf("Waiting for security events on http://localhost:%s/security-events\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// verify checks the signature, the issuer, the audience and the type of a
// security event token.
func verify(ctx context.Context, keys *jwk.Cache, jwksURL string, token []byte, issuer string) (jwt.Token, error) {
// The `typ` check refuses an access token that somebody sends as an event.
message, err := jws.Parse(token)
if err != nil {
return nil, err
}
if len(message.Signatures()) != 1 || message.Signatures()[0].ProtectedHeaders().Type() != "secevent+jwt" {
return nil, fmt.Errorf("the token is not a security event token")
}
set, err := keys.Get(ctx, jwksURL)
if err != nil {
return nil, err
}
return jwt.Parse(token,
jwt.WithKeySet(set),
jwt.WithIssuer(issuer),
jwt.WithAudience(os.Getenv("SSF_AUDIENCE")),
)
}
go run ./agents/security-events/go
Compiles. Not run against an organization. The receiver was tested with events from a local stand-in. LumoAuth delivers only to a public https address, which the test had not.
Check the result
Waiting for security events on http://localhost:3000/security-events
verification: state hello-from-setup
session-revoked: dropped everything for agent_agt_0123456789abcdef
- The line
verificationarrives after the setup script. In the portal, Send verification on the stream sends the same event. - Suspend an agent, for example with the kill switch recipe. The receiver logs
session-revokedwith the subjectagent_followed by the ID of the agent. That subject is thesubclaim of the agent's access tokens. - The audit log holds
ssf.set_deliveredfor each delivery, andssf.set_delivery_failedfor each failed attempt.
Limits
- LumoAuth delivers by push only. A receiver cannot poll a stream.
- The receivers of this recipe keep the IDs of the events in memory. A service with more than one instance needs a shared store for them.
- The stream of this recipe asks for
session-revokedonly. The other event types are in the event catalog. - LumoAuth never returns the bearer token of a stream. The setup script therefore replaces the stream when you run it again.