iamops.dev
Argo su X Feed RSS
ITItaliano

Lab Approfondimento · 35 minuti

Un receiver Shared Signals davanti a un server MCP: un evento CAEP ferma un agente

Un receiver SSF davanti a un server MCP, alimentato dal transmitter open source SSFgo: un evento CAEP session-revoked ha interrotto una chiamata in 8 ms.

Due catture del terminale dal mio lab Shared Signals: una chiamata di export interrotta con session revoked by the identity provider, e il log del gateway con l'evento e le risposte 401 successive.
In breveHo messo un receiver Shared Signals davanti a un server Model Context…
  • Ho messo un receiver Shared Signals davanti a un server Model Context Protocol (MCP), alimentato dal transmitter open source SSFgo. Un evento session-revoked per alice ha interrotto il suo export e rifiutato le chiamate successive, mentre l'agente di bob continuava.
  • Dalla chiamata admin all'applicazione dell'evento nel gateway sono passati 8 ms di mediana su dieci esecuzioni, su una sola macchina. Anche un token emesso nello stesso secondo della revoca è stato rifiutato, perché iat ha secondi interi.
  • Eventi falsificati, non firmati, mal indirizzati e ripetuti sono stati rifiutati o ignorati. L'evento ripetuto ha ricevuto 202 e non ha cambiato nulla.
  • Per interrompere una sessione di un agente invece dell'utente serviva un subject complesso. Il profilo di interoperabilità del Continuous Access Evaluation Profile (CAEP) lo rifiuta, e uno stream iscritto ad alice come iss_sub non l'ha mai ricevuto.
  • Non eseguito: un vero identity provider come transmitter, OAuth (Open Authorization) per l'interfaccia di programmazione (API) dello stream, la consegna in poll, un archivio di revoche persistente e un client MCP che gestisce il 401.
Ripeti questo lab 12 passi

Ho scritto questo lab perché tu possa rifarlo per conto tuo. Ogni passo ha i comandi da copiare e l'output che ho ottenuto io, e puoi segnarlo come fatto. Le spunte restano solo nel tuo browser.

Vai ai passi

Come funziona

Copia un prompt già pronto per Claude Code, Cursor, Codex o un altro agente di codice. Solo per ambienti di test.

Mostra il prompt
I want to run a hands-on lab from iamops.dev, and I would like your help to do it safely.

Lab: Un receiver Shared Signals davanti a un server MCP: un evento CAEP ferma un agente
Read the whole lab here (Markdown): https://iamops.dev/it/ssf-caep-receiver-mcp-gateway.md

What the lab needs before the first step:
- Linux with Go 1.26.10 or newer (tested with 1.27.3), Python 3.13, openssl, curl and jq
- An empty folder for the lab; run every step from inside it

How I want you to work:
1. Read the lab from start to finish first (each step lists its own prerequisites). Then check that the prerequisites are in place and that the tool versions match what the lab expects. Tell me what is missing before you run anything.
2. Run one step at a time. Before each command, show it to me and say in a sentence what it does.
3. Ask me before anything that costs money, creates cloud resources, touches a real tenant or account, or deletes anything. Wait for my answer.
4. Use the placeholders from the lab. Never paste real secrets, tokens or production identities into a command, a file or this chat. If a value is needed, tell me where to set it myself.
5. After each step, compare the output with the expected output in the lab. If it does not match, stop and tell me what differs. Do not carry on or invent a fix without asking me.
6. At the end, report what passed, what failed and which cleanup you did. Then offer to tick the steps off for me. The lab page keeps ticks only in my browser, so if you cannot do that, list the steps I should tick.

iamops.dev tools to use on the way (they run in my browser; paste only the lab's own test values, never a real token or key):
- Step 5 (Get a token and read what the gateway checks): open iamops.dev JWT tool (https://iamops.dev/tools/jwt/). Look for: Paste the lab access token from alice.jwt. Check typ at+jwt, the aud that names the MCP endpoint, and the sid claim the gateway uses to revoke one session.
- Step 7 (Verify the SET the gateway received): open iamops.dev Shared Signals decoder (https://iamops.dev/tools/shared-signals/). Look for: Paste last-set.jwt. Check typ secevent+jwt, the session-revoked event type, the iss_sub subject and that there is no exp claim.

This lab is for test environments only. Do not run it against production, or against a tenant or account that holds real data or real users.

You may answer in my language.

Il 17 novembre 2026 il gruppo di lavoro Shared Signals ha accettato una modifica breve al CAEP Interoperability Profile: la sezione che imponeva di firmare ogni evento con RS256 e una chiave da 2048 bit non c’è più. La copia di lavoro porta la stessa data. Una seconda pull request, la #362, ancora aperta, propone formati di subject per agenti e workload.

Entrambe le modifiche ricadono sul receiver. Se il profilo non fissa più l’algoritmo, è il receiver a decidere cosa accetta. E quando il subject è un agente, il receiver di solito è ciò che sta davanti ai tool dell’agente. Così ne ho costruito uno: un receiver Shared Signals dentro un piccolo gateway davanti a un server MCP, alimentato da un transmitter open source, e ho provato a farlo sbagliare.

Se Shared Signals è nuovo per te, ho scritto una spiegazione breve e un articolo Knowledge più lungo su Shared Signals Framework (SSF), CAEP e Risk Incident Sharing and Coordination (RISC).

Cosa costruisce il lab#

  • Un identity provider di laboratorio sulla porta 9443 che firma gli access token per il server MCP e include il transmitter SSFgo v0.4.2 (SSF 1.0, CAEP 1.0, consegna push dei Security Event Token (SET) secondo la Request for Comments (RFC) 8935).
  • Un server MCP sulla porta 9000 con due tool: un list_orders rapido e un export_orders lento che riporta l’avanzamento per 20 secondi.
  • Un gateway sulla porta 9444 che controlla ogni bearer token, inoltra le richieste MCP e riceve gli eventi in push su /ssf/events.
  • Agenti basati sul kit di sviluppo software (SDK) MCP per Python 2.3.0, con la revisione MCP 2026-07-28.

La revisione MCP conta. Nella 2026-07-28 una richiesta Hypertext Transfer Protocol (HTTP) è un POST autonomo, senza handshake initialize e senza Mcp-Session-Id. Non c’è una sessione MCP da chiudere. L’unica sessione rimasta è quella presso l’identity provider, portata nel token come sid. Quindi quando arriva un evento il gateway ha due compiti: rifiutare da quel momento i token di quell’utente o di quella sessione, e interrompere ogni chiamata a un tool che sta ancora trasmettendo.

Diagramma di sequenza: un agente ottiene un token dall'IdP del lab e chiama export_orders attraverso il gateway, che inoltra al server MCP. L'IdP invia un SET CAEP session-revoked per alice; il gateway lo controlla, risponde 202, interrompe la chiamata in corso con l'errore JSON-RPC -32001 e risponde alla chiamata successiva con 401 invalid_token.
Il flusso come l'ho eseguito. Il token porta sub e sid. L'evento indica alice tramite issuer e subject. Il gateway interrompe ciò che è in corso e rifiuta ciò che arriva dopo.

Preparazione#

Tutto è girato su una macchina Linux il 22 novembre 2026: Go 1.27.3 per l’identity provider, Python 3.13.5 con l’SDK MCP 2.3.0, PyJWT 2.15.1, httpx 0.28.1 e Starlette 1.10.0 per il resto. SSF richiede https per l’issuer e per gli endpoint push, quindi make-certs.sh crea un’autorità di certificazione (CA) usa e getta e un certificato per localhost. Tre token casuali del lab finiscono in .env: uno che il gateway usa per l’API dello stream, uno che il transmitter deve inviare con ogni push, uno per l’azione admin che revoca un utente.

L’identity provider è un sostituto. Firma un token per chiunque lo chieda, quindi non dice nulla sul login. Mostra la parte dopo il login: un solo issuer per l’access token e per gli eventi, così iss e sub nel token sono la stessa coppia che l’evento nomina.

Di default SSFgo rifiuta di fare push verso indirizzi di loopback, come protezione contro un receiver che registra un indirizzo web (URL) interno. Il lab sostituisce il suo client HTTP con uno che si fida della CA del lab. In produzione terrei il default ed elencherei gli host interni in modo esplicito.

Lo stream#

Il gateway è un receiver, quindi comincia leggendo i metadati del transmitter. Lo strumento a riga di comando di SSFgo, usato come lo userebbe un receiver, li ha accettati. Poi ho creato uno stream push che chiede solo session-revoked, con l’endpoint di push e il valore bearer che il transmitter deve inviare.

Terminale: ssf metadata accetta il transmitter, i metadati elencano la consegna push e poll e default_subjects NONE, lo stream viene creato con events_delivered session-revoked e la configurazione dello stream restituisce l'header di autorizzazione del push per intero.
Metadati e stream. La configurazione dello stream torna con l'header di autorizzazione del push per intero.

L’ultima riga mi ha sorpreso. La risposta alla creazione restituiva authorization_header con il token di push completo. Chi può leggere la configurazione dello stream con il token del receiver può leggere il segreto di cui il gateway si fida per gli eventi in arrivo. Il token dell’API dello stream va trattato come un segreto dello stesso peso.

Il transmitter dichiara default_subjects: NONE, quindi il gateway deve aggiungere ogni subject per cui vuole eventi. Ho aggiunto alice e bob come subject iss_sub e ho chiesto un evento di verifica. Il transmitter ha registrato il push come consegnato in 10 ms.

Terminale: l'aggiunta dei subject alice e bob restituisce HTTP 200, lo stato dello stream è enabled, verify restituisce 204, il gateway registra l'evento di verifica con lo state lab-check-1 e il transmitter registra un push consegnato in 10 ms.
Subject e verifica. Il valore di state torna dentro un evento firmato, quindi il gateway sa che il percorso del push funziona da un capo all'altro.

Il token che il gateway controlla#

L’access token è un JavaScript Object Notation (JSON) Web Token (JWT) con typ at+jwt, come audience l’URL /mcp del gateway e un sid. L’ho incollato con il JSON Web Key Set (JWKS) dei token nel JWT tool di iamops.dev, con l’issuer e l’audience che mi aspetto. Firma, issuer e audience corrispondevano.

Terminale: l'header del token decodificato con alg RS256, kid at-1 e typ at+jwt, e il payload con aud https://localhost:9444/mcp, client_id support-agent, iss, sid, sub alice e una durata di un'ora.
L'access token. sub e sid sono ciò con cui il gateway confronta gli eventi.
JWT tool di iamops.dev: il token e la chiave incollati sono sfocati, firma valida con RS256 e kid at-1, durata 1h, non scaduto, audience e issuer corrispondono, e la tabella dei claim con sid e sub alice.
Lo stesso token nel JWT tool di iamops.dev. Token e chiave incollati sono sfocati e l'impronta della chiave è sostituita.

Tagliare fuori gli agenti di alice#

Tre agenti giravano insieme: l’agente di export di alice sul tool lento, l’agente di fatturazione di alice che chiamava il tool rapido ogni due secondi e l’agente di supporto di bob che faceva lo stesso. Dopo sette secondi ho revocato alice presso l’identity provider.

Terminale: l'agente di export mostra l'avanzamento dal 5 al 35 per cento e poi refused con MCPError session revoked by the identity provider, call cut. L'agente di fatturazione di alice riesce quattro volte e viene rifiutato dopo la revoca. L'agente di supporto di bob riesce ogni volta.
L'interruzione. L'export si è fermato al 35 per cento. L'agente di fatturazione di alice è stato rifiutato dalla chiamata successiva. bob non è stato toccato.

Il log del gateway mostra l’ordine. L’evento è arrivato alle 10:39:50.971, l’export in corso è stato interrotto nello stesso millisecondo e ogni richiesta successiva con un token di alice ha ricevuto 401. Il transmitter ha registrato un push, consegnato in 4 ms.

Terminale: righe del log del gateway con le chiamate di bob e alice inoltrate, poi ssf session-revoked per tutte le sessioni di alice con una chiamata in corso interrotta, cut in-flight export_orders, e 401 per la sessione di fatturazione di alice mentre le chiamate di bob vengono ancora inoltrate. Il log dell'IdP mostra un push consegnato in 4 ms.
Il log del gateway. Un evento, una chiamata in corso interrotta, poi 401 per alice e inoltro per bob.

Ogni tentativo rifiutato compare due volte nel log. Il client dell’SDK prova prima con server/discover e, se fallisce, tenta il vecchio handshake initialize. Entrambi hanno ricevuto 401. L’agente ha stampato solo “Server returned an error response”: l’SDK non ha mostrato al mio codice né il 401 né l’header WWW-Authenticate.

Il SET sul filo#

Il gateway ha salvato l’ultimo evento accettato. ssf verify di SSFgo lo ha controllato con le chiavi pubblicate dal transmitter, l’issuer e l’audience, come farebbe un receiver. Il subject è iss_sub con alice, e l’evento porta initiating_entity admin e il motivo che avevo scritto.

Terminale: ssf verify stampa verified true, l'header con alg RS256, typ secevent+jwt e kid ssf-set-1, sub_id iss_sub alice e l'evento session-revoked con event_timestamp, initiating_entity admin e reason_admin Agent misuse reported.
L'evento. Un Security Event Token: typ secevent+jwt, sub_id al posto di sub, nessun exp.

Il decoder di SET Shared Signals di iamops.dev ha letto lo stesso evento con il JWKS del transmitter e ha verificato la firma. Indica il tipo di evento, spiega il subject iss_sub e segnala il claim txn aggiunto da SSFgo.

Decoder di SET Shared Signals di iamops.dev: il SET e il JWKS incollati sono sfocati, il SET è ben formato per SSF 1.0, la firma è verificata con kid ssf-set-1, l'evento CAEP session revoked con motivo Agent misuse reported, il subject iss_sub alice e i claim del SET con gli id casuali sostituiti.
Lo stesso SET nel decoder di iamops.dev. I valori incollati sono sfocati, gli id casuali sostituiti.

Eventi falsificati e ripetuti#

attacks.py fa POST direttamente su /ssf/events. Senza il token di push, o con quello sbagliato, il gateway ha risposto 401. Un corpo JSON ha ricevuto 400 invalid_request. Un evento firmato con una mia chiave ma con il kid del transmitter ha ricevuto 400 invalid_key, e lo stesso alg: none, perché il gateway accetta solo RS256. Un typ JWT è stato rifiutato. La ripetizione dell’ultimo evento reale ha ricevuto 202, come prevede RFC 8935 per un evento che il receiver ha già, e non ha cambiato nulla: il gateway conserva ogni jti che ha applicato.

Terminale: sette push con risultati 401, 401, 400 invalid_request, 400 invalid_key per una chiave estranea, 400 invalid_key per alg none, 400 invalid_request per typ JWT, 202 per la ripetizione; la lista degli utenti revocati contiene ancora solo alice. Un evento per carol, che non è nello stream, viene emesso ma non inviato. Un nuovo login di alice funziona.
Eventi non validi. Sei rifiutati, la ripetizione accettata e ignorata. Un evento per un subject che non è nello stream non è mai stato inviato.

Altri due risultati nella stessa cattura. Un evento per carol, che non è nello stream, è stato emesso dall’identity provider ma mai inviato. E alice ha rifatto il login dopo la revoca e ha ottenuto un token funzionante. Una revoca di sessione chiude le sessioni, non blocca l’account. Se l’account deve restare bloccato, è l’identity provider a dover rifiutare il login, e l’evento da inviare è un altro.

Non ho provato un’audience o un issuer sbagliati con un evento firmato correttamente. Servirebbe un secondo stream o un secondo transmitter con chiavi proprie, e non ho eseguito né l’uno né l’altro.

Quanto è veloce, e il buco dello stesso secondo#

measure.py ha chiamato l’endpoint admin dieci volte e ha interrogato il gateway finché non aveva applicato ogni evento: 8, 8, 8, 8, 9, 7, 8, 7, 7 e 7 ms, con una mediana di 8 ms. È una sola macchina su loopback, quindi misura il software, non una rete.

Terminale: dieci esecuzioni tra 7 e 9 ms con mediana di 8 ms; poi un estratto del log in cui il session-revoked per alice viene applicato alle 10:40:58.059, un token per alice viene emesso nello stesso secondo e il gateway risponde 401 per quella nuova sessione.
Tempi, e un effetto collaterale. Un token emesso meno di un secondo dopo la revoca, nello stesso secondo, è stato rifiutato.

L’effetto collaterale veniva dalla mia regola. Il gateway rifiuta ogni token di un utente revocato con iat uguale o precedente all’ora dell’evento, ed entrambi sono in secondi interi. L’ultima misura ha revocato alice alle 10:40:58.059. Il passo successivo l’ha fatta entrare alle 10:40:58 e quel token è stato rifiutato. Arrotondare dall’altra parte lascerebbe passare un token emesso appena prima della revoca. Ho tenuto il lato rigoroso e farei lo stesso in produzione, con una nota per l’help desk.

Revocare una sessione di un agente, non l’utente#

Revocare alice ha interrotto tutti i suoi agenti. Spesso si vuole meno: chiudere la sessione dell’agente di fatturazione e lasciare girare gli altri suoi agenti. SSF ha un subject complesso per questo, con un membro user e un membro session.

Il profilo di interoperabilità CAEP, come lo applica SSFgo, ammette solo subject email e iss_sub, quindi il transmitter ha rifiutato l’evento con HTTP 422. Ho riavviato l’identity provider con le regole semplici di SSF 1.0 e CAEP 1.0, ho ricreato lo stream e iscritto alice come iss_sub. L’evento di sessione è stato emesso e mai inviato. Le regole di corrispondenza dei subject nella sezione 8.1.3 di SSF 1.0 definiscono la corrispondenza tra due subject semplici e tra due subject complessi, e non dicono nulla di un caso misto. SSFgo la legge così: un subject semplice non corrisponde mai a uno complesso.

Terminale: la revoca con un id di sessione è rifiutata con HTTP 422 perché con il profilo interop gli eventi CAEP devono usare un subject email o iss_sub; l'IdP riparte con il profilo ssf, viene creato un nuovo stream e alice viene aggiunta come iss_sub; l'evento di sessione viene emesso ma il log del transmitter non mostra alcun push e il gateway ha contato zero eventi session-revoked.
Due modi di perdere un evento di sessione. Il profilo lo rifiuta, e un'iscrizione semplice non gli corrisponde.

La soluzione è stata iscrivere un subject complesso con il solo user. I membri che l’iscrizione omette valgono come jolly, quindi corrisponde a qualsiasi sessione di alice. Così l’evento è arrivato, il gateway ha revocato solo il sid dell’agente di fatturazione e l’agente di supporto di alice ha continuato a ricevere 200.

Diagramma di sequenza: con il profilo interop un subject complesso è rifiutato con 422; dopo il riavvio con il profilo semplice l'evento viene emesso ma non inviato perché non corrisponde all'iscrizione iss_sub; dopo l'iscrizione di un subject complesso con user alice il SET arriva, il gateway revoca un sid, l'agente di fatturazione riceve 401 e l'agente di supporto riceve 200.
Una sessione, tre tentativi. Solo l'iscrizione complessa l'ha consegnato.
Terminale: l'aggiunta di un subject complesso con user alice restituisce 200; girano due agenti di alice; la revoca con il sid dell'agente di fatturazione restituisce subject_format complex; l'agente di fatturazione è rifiutato dalla chiamata successiva mentre l'agente di supporto riesce ogni volta; il gateway registra session-revoked per una sessione e l'IdP un push consegnato in 7 ms.
Una sessione di un agente interrotta. Stesso utente, due agenti, uno rifiutato.

Il decoder mostra il subject complesso in due parti: alice come iss_sub e la sessione come id opaque.

Decoder di SET Shared Signals di iamops.dev con un SET session-revoked il cui sub_id è complex, con un membro user iss_sub alice e un membro session opaque con l'id di sessione; firma verificata, valori incollati sfocati.
Un subject complesso nel decoder. user e session insieme indicano una sessione di un agente.

Il 401 che vede l’agente#

Con curl la risposta è chiara. Prima dell’evento la chiamata ha restituito 200. Dopo, lo stesso token ha ricevuto 401 con WWW-Authenticate: Bearer error="invalid_token", error_description="session revoked". Un agente che legge quell’header sa che deve rifare il login invece di riprovare.

Terminale: un tools/call con gli header mcp-method e mcp-name restituisce 200 con il risultato degli ordini, la revoca di quella sessione restituisce subject_format complex, e la stessa chiamata restituisce poi 401 con WWW-Authenticate Bearer error invalid_token, error_description session revoked.
Prima e dopo, sul filo. La stessa richiesta, 200 e poi 401.

La richiesta grezza ha avuto bisogno anche degli header Mcp-Method e Mcp-Name e di due chiavi in _meta prima che il server 2026-07-28 la accettasse. Senza, il server ha risposto 400 con un errore JSON-RPC. Un gateway può leggere il nome del tool dall’header, ma il server lo confronta comunque con il corpo.

Insidie#

  • La configurazione dello stream ripete il segreto del push. Proteggi il token dell’API dello stream quanto il token di push.
  • SSFgo rifiuta di default i push verso loopback. Utile in produzione, una sorpresa in un lab.
  • Il profilo interop richiede che sia dichiarata la consegna in poll. Il transmitter si è rifiutato di partire con il profilo finché non ho elencato RFC 8936 accanto al push.
  • Secondi interi da entrambe le parti. Una revoca e un nuovo login nello stesso secondo si scontrano. Scegli un lato di proposito.
  • In questo lab le revoche stanno in memoria. Un riavvio del gateway le dimentica, e un token emesso prima della revoca tornerebbe valido fino alla scadenza. Conservale almeno per la durata dell’access token, in un archivio che sopravvive ai riavvii.
  • Un evento session-revoked non blocca l’account. alice è rientrata poco dopo.

Cosa ne farei#

  1. Mettere il receiver dove arriva ogni richiesta degli agenti: il gateway MCP, non ogni singolo tool.
  2. Mettere sid negli access token dei tuoi agenti e assicurarti che l’issuer dei token e quello degli eventi sia lo stesso, oppure tenere una mappatura.
  3. Iscrivere i subject che ti servono nella forma che il transmitter invierà. Se vuoi eventi per sessione, iscrivi un subject complesso con user.
  4. Fissare gli algoritmi accettati, ora che il profilo non lo fa più. Solo RS256, niente none, chiavi dal jwks_uri del transmitter.
  5. Interrompere le chiamate ai tool in corso, non solo le nuove. Con MCP 2026-07-28 non c’è una sessione da chiudere, quindi il gateway deve tenere traccia di ciò che sta trasmettendo.

Cosa non è stato eseguito#

Il transmitter è SSFgo dentro il mio identity provider di laboratorio, non un identity provider commerciale. L’API dello stream ha usato un bearer token statico, non OAuth come richiede il profilo interop. Non ho eseguito la consegna in poll, gli aggiornamenti, la pausa o la cancellazione di uno stream, né l’evento di cambio credenziali. Non ho provato un evento firmato correttamente con audience o issuer sbagliati. L’archivio delle revoche è in memoria e non ho provato un riavvio del gateway. Non ho eseguito la suite di conformità OpenID contro il gateway. I client MCP erano script basati sull’SDK, non un vero prodotto agente, e nessuno ha reagito al 401 rifacendo il login. Per questo lab non c’è una registrazione.

Le immagini del terminale sono state generate dall’output salvato dell’esecuzione del 22 novembre 2026, ora Europe/Zurich. I token, le chiavi e i certificati del lab erano casuali, sono rimasti su una sola macchina per meno di un’ora e sono stati cancellati alla fine.

Ripeti questo lab#

Tutto ciò che serve per eseguire questo lab su una macchina Linux in circa 35 minuti, senza account: una CA usa e getta, un IdP basato su SSFgo, un server MCP e un gateway che riceve eventi CAEP. Apri ogni passo, copia i blocchi e confronta il tuo output con quello atteso.

Ogni valore tra parentesi angolari è un segnaposto per il tuo ambiente di test. Nulla in questa pagina è un identificativo o un segreto reale.

Imposta le variabili una sola volta

text · env.sh
# Paste into every terminal you use for this lab, from inside the lab folder. No account or real secret is needed.
export T="https://localhost:9443"   # lab IdP and SSF transmitter
export A="https://localhost:9444"   # gateway: SSF receiver in front of the MCP server
export C="--cacert certs/ca.pem"    # curl trusts the throwaway lab CA
[ -f .env ] && . ./.env             # the three random lab tokens, once step 3 wrote them
[ -d .venv ] && . .venv/bin/activate
Passo 1Crea la CA e compila l’IdP

Obiettivo. Salva make-certs.sh e la cartella idp, crea una CA usa e getta con un certificato per localhost, compila l’IdP del lab su SSFgo v0.4.2 e installa lo strumento a riga di comando ssf.

Prerequisiti

  • Linux con Go 1.26.10 o successivo (provato con 1.27.3), Python 3.13, openssl, curl e jq
  • Una cartella vuota per il lab; esegui ogni passo da lì
text · make-certs.sh
#!/usr/bin/env bash
# A throwaway lab CA and one certificate for localhost, valid 2 days.
set -euo pipefail
mkdir -p certs && cd certs
openssl req -x509 -newkey rsa:2048 -nodes -days 2 -subj "/CN=ssf-mcp lab CA" \
  -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" \
  -keyout ca.key -out ca.pem 2>/dev/null
openssl req -newkey rsa:2048 -nodes -subj "/CN=localhost" \
  -keyout localhost.key -out localhost.csr 2>/dev/null
printf "subjectAltName=DNS:localhost,IP:127.0.0.1\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nauthorityKeyIdentifier=keyid\n" > san.ext
openssl x509 -req -in localhost.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
  -days 2 -extfile san.ext -out localhost.pem 2>/dev/null
chmod 600 *.key
openssl x509 -in localhost.pem -noout -subject -ext subjectAltName
text · idp/go.mod
module ssfmcp/idp

go 1.26.10

require github.com/idfoundry/ssfgo v0.4.2
text · idp/main.go
// idp is a lab identity provider on https://localhost:9443. It does two jobs:
//   - signs short-lived access tokens for an MCP gateway (POST /token), and
//   - runs an SSFgo Transmitter (SSF 1.0, CAEP 1.0) that pushes
//     session-revoked events to the gateway (POST /admin/revoke).
// It signs a token for whoever asks: it stands in for a real sign-in.
package main

import (
	"context"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"flag"
	"log"
	"log/slog"
	"math/big"
	"net/http"
	"os"
	"time"

	ssf "github.com/idfoundry/ssfgo"
	"github.com/idfoundry/ssfgo/caep"
	"github.com/idfoundry/ssfgo/caep/interop"
	"github.com/idfoundry/ssfgo/storage/memstore"
	"github.com/idfoundry/ssfgo/transmitter"
)

const issuer = "https://localhost:9443"

func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }

func main() {
	profile := flag.String("profile", "interop", "interop (CAEP Interoperability Profile) or ssf (plain SSF 1.0 + CAEP 1.0)")
	flag.Parse()
	receiverToken, adminToken := os.Getenv("RECEIVER_TOKEN"), os.Getenv("ADMIN_TOKEN")
	if receiverToken == "" || adminToken == "" {
		log.Fatal("set RECEIVER_TOKEN and ADMIN_TOKEN")
	}
	audience := os.Getenv("GATEWAY_AUDIENCE") // the gateway's SET audience
	ctx := context.Background()

	setKey, _ := rsa.GenerateKey(rand.Reader, 2048) // signs SETs
	atKey, _ := rsa.GenerateKey(rand.Reader, 2048)  // signs access tokens

	cfg := transmitter.Config{
		Assurance:       ssf.AssuranceDevelopment,
		Limits:          transmitter.RecommendedLimits(),
		PushRetry:       transmitter.RecommendedPushRetry(),
		Issuer:          issuer,
		SigningKeys:     []transmitter.SigningKey{{Signer: setKey, Algorithm: ssf.RS256, KeyID: "ssf-set-1"}},
		EventsSupported: interop.EventTypes(),
		DeliveryMethods: []ssf.DeliveryMethod{ssf.DeliveryPush, ssf.DeliveryPoll},
		DefaultSubjects: ssf.DefaultSubjectsNone,
		Store:           memstore.NewStreamStore(),
		Authorize: func(_ context.Context, token string) (transmitter.Receiver, error) {
			if token != receiverToken {
				return transmitter.Receiver{}, transmitter.ErrInvalidToken
			}
			return transmitter.Receiver{ID: "mcp-gateway", Audience: []string{audience}, Access: transmitter.AccessManage}, nil
		},
		PermitEvent: transmitter.PermitAll,
		Hooks: transmitter.Hooks{Push: func(_ context.Context, i transmitter.PushInfo) {
			log.Printf("push attempt %d: %s in %v", i.Attempt, i.Outcome, i.Duration.Round(time.Millisecond))
		}},
		Logger: slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})),
	}
	if *profile == "interop" {
		if err := interop.ApplyTransmitter(&cfg); err != nil {
			log.Fatal(err)
		}
	}
	// SSFgo refuses to push to loopback by default (SSRF protection). This lab
	// pushes to https://localhost:9444, so it uses a client that trusts the lab CA.
	ca, err := os.ReadFile("certs/ca.pem")
	if err != nil {
		log.Fatal(err)
	}
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(ca)
	cfg.HTTPClient = &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}}
	tx, err := transmitter.New(cfg)
	if err != nil {
		log.Fatal(err)
	}
	go func() { _ = tx.Run(ctx) }()

	mux := http.NewServeMux()
	mux.Handle("/", tx.Handler()) // SSF metadata, JWKS, streams, subjects, status, verify

	// Access tokens for the MCP gateway.
	atJWKS := map[string]any{"keys": []map[string]any{{
		"kty": "RSA", "kid": "at-1", "use": "sig", "alg": "RS256",
		"n": b64(atKey.N.Bytes()), "e": b64(big.NewInt(int64(atKey.E)).Bytes()),
	}}}
	mux.HandleFunc("GET /token-jwks", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("content-type", "application/json")
		_ = json.NewEncoder(w).Encode(atJWKS)
	})
	mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
		user, client := r.FormValue("user"), r.FormValue("client_id")
		if user == "" || client == "" {
			http.Error(w, `{"error":"invalid_request"}`, 400)
			return
		}
		now := time.Now()
		sid := "sid-" + b64(randBytes(6))
		claims := map[string]any{
			"iss": issuer, "sub": user, "aud": os.Getenv("MCP_RESOURCE"), "client_id": client,
			"sid": sid, "scope": "mcp:tools", "iat": now.Unix(), "exp": now.Add(time.Hour).Unix(),
			"jti": b64(randBytes(9)),
		}
		hdr, _ := json.Marshal(map[string]string{"alg": "RS256", "typ": "at+jwt", "kid": "at-1"})
		body, _ := json.Marshal(claims)
		in := b64(hdr) + "." + b64(body)
		sum := sha256.Sum256([]byte(in))
		sig, _ := rsa.SignPKCS1v15(rand.Reader, atKey, crypto.SHA256, sum[:])
		log.Printf("token issued: sub=%s client_id=%s sid=%s", user, client, sid)
		w.Header().Set("content-type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"access_token": in + "." + b64(sig), "token_type": "Bearer", "expires_in": 3600, "sid": sid})
	})

	// Admin action: revoke a user's sessions (iss_sub subject) or one session
	// (complex subject: user + session).
	mux.HandleFunc("POST /admin/revoke", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("authorization") != "Bearer "+adminToken {
			http.Error(w, "unauthorized", 401)
			return
		}
		var in struct{ Sub, Sid, Reason string }
		_ = json.NewDecoder(r.Body).Decode(&in)
		user := ssf.IssSubSubject{Issuer: issuer, Subject: in.Sub}
		var subject ssf.Subject = user
		if in.Sid != "" {
			subject = ssf.ComplexSubject{User: user, Session: ssf.OpaqueSubject{ID: in.Sid}}
		}
		err := tx.Emit(r.Context(), subject, caep.SessionRevoked{Common: caep.Common{
			EventTimestamp:   ssf.NewNumericDate(time.Now()),
			InitiatingEntity: caep.InitiatedByAdmin,
			ReasonAdmin:      ssf.LocalizedText{"en": in.Reason},
		}})
		w.Header().Set("content-type", "application/json")
		if err != nil {
			log.Printf("emit refused: %v", err)
			w.WriteHeader(422)
			_ = json.NewEncoder(w).Encode(map[string]string{"emitted": "false", "error": err.Error()})
			return
		}
		log.Printf("emitted session-revoked: subject=%s sid=%q", in.Sub, in.Sid)
		_ = json.NewEncoder(w).Encode(map[string]string{"emitted": "true", "subject_format": string(subject.Format())})
	})

	log.Printf("idp on %s, profile=%s", issuer, *profile)
	srv := &http.Server{Addr: "127.0.0.1:9443", Handler: mux}
	log.Fatal(srv.ListenAndServeTLS("certs/localhost.pem", "certs/localhost.key"))
}

func randBytes(n int) []byte { b := make([]byte, n); _, _ = rand.Read(b); return b }
text · build.sh
chmod +x make-certs.sh
./make-certs.sh
cd idp && go mod tidy && go build -o ../idp-bin . && cd ..
grep ssfgo idp/go.mod
cd idp && go build -o ../ssf github.com/idfoundry/ssfgo/cmd/ssf && cd .. && ls idp-bin ssf

Output atteso

output
subject=CN=localhost
X509v3 Subject Alternative Name: 
    DNS:localhost, IP Address:127.0.0.1
require github.com/idfoundry/ssfgo v0.4.2
idp-bin
ssf
Passo 2Installa la parte Python

Obiettivo. Crea un venv con versioni fissate e salva il server MCP, il gateway che fa anche da receiver SSF e l’agente di prova.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · venv.sh
python3 -m venv .venv && . .venv/bin/activate
pip install -q mcp==2.3.0 pyjwt==2.15.1 cryptography==50.0.2 httpx==0.28.1 starlette==1.10.0 uvicorn==0.54.0
pip list 2>/dev/null | grep -i -E "^(mcp|pyjwt|cryptography|httpx|starlette|uvicorn) "
text · mcp_server.py
"""A small MCP server on http://127.0.0.1:9000/mcp (loopback only).

It trusts the gateway in front of it: the gateway checks the token and
forwards the caller in X-Lab-User. Two tools: a quick read and a slow export
that reports progress for 20 seconds.
"""
import anyio
from mcp.server import MCPServer
from mcp.server.mcpserver import Context

mcp = MCPServer("orders")

@mcp.tool()
def list_orders(customer: str) -> dict:
    """List open orders for a customer."""
    return {"customer": customer, "open_orders": 2}

@mcp.tool()
async def export_orders(customer: str, ctx: Context) -> str:
    """Export a customer's order history (slow, 20 steps of one second)."""
    for step in range(1, 21):
        await ctx.report_progress(step, 20, f"exported {step * 5}%")
        await anyio.sleep(1)
    return f"export for {customer} done"

if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
text · gateway.py
"""MCP gateway on https://localhost:9444: an SSF receiver in front of an MCP server.

/mcp        checks the bearer token (signature, iss, aud, exp) and the
            revocation state, then proxies to the MCP server on 127.0.0.1:9000.
/ssf/events receives pushed SETs (RFC 8935), checks them and applies
            CAEP session-revoked: refuse the user's (or one session's)
            tokens from now on and cut any tool call still streaming.
"""
import json, os, ssl, sys, time
import anyio, httpx, jwt, uvicorn
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, Response, StreamingResponse
from starlette.routing import Route

IDP = "https://localhost:9443"
MCP_RESOURCE = os.environ["MCP_RESOURCE"]          # aud of access tokens
SET_AUDIENCE = os.environ["GATEWAY_AUDIENCE"]      # aud of SETs
PUSH_TOKEN = os.environ["PUSH_TOKEN"]              # what the transmitter must send
UPSTREAM = "http://127.0.0.1:9000/mcp"
CA = "certs/ca.pem"
SESSION_REVOKED = "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
VERIFICATION = "https://schemas.openid.net/secevent/ssf/event-type/verification"

http = httpx.AsyncClient(verify=CA, timeout=None)
idp_meta = httpx.get(f"{IDP}/.well-known/ssf-configuration", verify=CA).json()
set_keys = jwt.PyJWKClient(idp_meta["jwks_uri"], ssl_context=ssl.create_default_context(cafile=CA))
at_keys = jwt.PyJWKClient(f"{IDP}/token-jwks", ssl_context=ssl.create_default_context(cafile=CA))

revoked_users: dict[str, float] = {}   # "iss|sub" -> revoked at (epoch seconds)
revoked_sids: set[str] = set()
seen_jti: set[str] = set()
applied = {"session_revoked": 0}
inflight: dict[str, dict] = {}          # request key -> {"user","sid","cut": anyio.Event, "id"}

def log(msg: str) -> None:
    print(time.strftime("%H:%M:%S") + f".{int(time.time() * 1000) % 1000:03d} {msg}", flush=True)

def unauthorized(desc: str) -> Response:
    return JSONResponse({"error": "invalid_token", "error_description": desc}, 401,
                        headers={"www-authenticate": f'Bearer error="invalid_token", error_description="{desc}"'})

# ---------- the MCP side ----------
async def mcp(request: Request) -> Response:
    auth = request.headers.get("authorization", "")
    if not auth.startswith("Bearer "):
        return unauthorized("no bearer token")
    token = auth[7:]
    try:
        key = at_keys.get_signing_key_from_jwt(token).key
        claims = jwt.decode(token, key, algorithms=["RS256"], audience=MCP_RESOURCE, issuer=IDP,
                            options={"require": ["exp", "iat", "sub", "sid"]})
    except Exception as e:
        log(f"mcp: refused token: {type(e).__name__}")
        return unauthorized(type(e).__name__)
    user, sid = f'{claims["iss"]}|{claims["sub"]}', claims["sid"]
    cutoff = revoked_users.get(user)
    if sid in revoked_sids or (cutoff is not None and claims["iat"] <= int(cutoff)):
        log(f"mcp: 401 for sub={claims['sub']} sid={sid}: session revoked")
        return unauthorized("session revoked")
    body = await request.body()
    try:
        msg = json.loads(body) if body else {}
    except ValueError:
        msg = {}
    method = msg.get("method", request.method)
    tool = (msg.get("params") or {}).get("name", "")
    log(f"mcp: {method} {tool} sub={claims['sub']} client={claims.get('client_id')} sid={sid} -> forward")
    headers = {k: v for k, v in request.headers.items()
               if k.lower() in ("content-type", "accept", "mcp-session-id", "mcp-protocol-version", "last-event-id")
               or k.lower().startswith("mcp-")}
    headers["x-lab-user"] = claims["sub"]
    upstream = await http.send(http.build_request(request.method, UPSTREAM, headers=headers, content=body), stream=True)
    key = f"{sid}:{msg.get('id')}:{time.time()}"
    entry = {"user": user, "sid": sid, "cut": anyio.Event(), "id": msg.get("id"), "tool": tool}
    inflight[key] = entry

    async def stream():
        try:
            async with anyio.create_task_group() as tg:
                async def watch():
                    await entry["cut"].wait()
                    tg.cancel_scope.cancel()
                tg.start_soon(watch)
                async for chunk in upstream.aiter_raw():
                    yield chunk
                tg.cancel_scope.cancel()
            if entry["cut"].is_set() and "text/event-stream" in upstream.headers.get("content-type", ""):
                err = {"jsonrpc": "2.0", "id": entry["id"],
                       "error": {"code": -32001, "message": "session revoked by the identity provider (CAEP), call cut"}}
                yield f"event: message\ndata: {json.dumps(err)}\n\n".encode()
                log(f"mcp: cut in-flight {tool} for sid={sid}")
        finally:
            inflight.pop(key, None)
            await upstream.aclose()

    passthrough = {k: v for k, v in upstream.headers.items()
                   if k.lower() in ("content-type", "mcp-session-id", "cache-control")}
    return StreamingResponse(stream(), status_code=upstream.status_code, headers=passthrough)

# ---------- the SSF receiver side ----------
def push_error(err: str, desc: str) -> Response:
    log(f"ssf: rejected SET: {err}: {desc}")
    return JSONResponse({"err": err, "description": desc}, 400)

async def ssf_events(request: Request) -> Response:
    if request.headers.get("authorization") != f"Bearer {PUSH_TOKEN}":
        log("ssf: 401, wrong or missing push authorization")
        return Response(status_code=401)
    if request.headers.get("content-type", "").split(";")[0].strip() != "application/secevent+jwt":
        return push_error("invalid_request", "content-type must be application/secevent+jwt")
    set_jwt = (await request.body()).decode().strip()
    try:
        header = jwt.get_unverified_header(set_jwt)
        if header.get("typ") != "secevent+jwt":
            return push_error("invalid_request", f"typ {header.get('typ')!r}")
        key = set_keys.get_signing_key_from_jwt(set_jwt).key
        claims = jwt.decode(set_jwt, key, algorithms=["RS256"], audience=SET_AUDIENCE, issuer=IDP,
                            options={"require": ["iat", "jti"], "verify_exp": False})
    except jwt.InvalidAudienceError as e:
        return push_error("invalid_audience", str(e))
    except jwt.InvalidIssuerError as e:
        return push_error("invalid_issuer", str(e))
    except (jwt.InvalidSignatureError, jwt.PyJWKClientError, jwt.InvalidAlgorithmError) as e:
        return push_error("invalid_key", f"{type(e).__name__}: {e}")
    except Exception as e:
        return push_error("invalid_request", f"{type(e).__name__}: {e}")
    if claims["jti"] in seen_jti:
        log(f"ssf: duplicate jti, already applied, 202 and nothing else")
        return Response(status_code=202)
    seen_jti.add(claims["jti"])
    with open("last-set.jwt", "w") as f:  # kept for the replay test and the SET decoder
        f.write(set_jwt)
    events = claims.get("events", {})
    sub_id = claims.get("sub_id", {})
    if VERIFICATION in events:
        log(f"ssf: verification event, state={events[VERIFICATION].get('state')}")
        return Response(status_code=202)
    if SESSION_REVOKED in events:
        ev = events[SESSION_REVOKED]
        when = float(ev.get("event_timestamp", time.time()))
        if sub_id.get("format") == "iss_sub":
            user = f'{sub_id["iss"]}|{sub_id["sub"]}'
            revoked_users[user] = max(revoked_users.get(user, 0), when)
            cut = [e for e in inflight.values() if e["user"] == user]
            scope = f"all sessions of sub={sub_id['sub']}"
        elif sub_id.get("format") == "complex" and (sub_id.get("session") or {}).get("format") == "opaque":
            sid = sub_id["session"]["id"]
            revoked_sids.add(sid)
            cut = [e for e in inflight.values() if e["sid"] == sid]
            scope = f"one session sid={sid}"
        else:
            log(f"ssf: session-revoked with a subject I cannot map: {sub_id.get('format')}")
            return Response(status_code=202)
        for e in cut:
            e["cut"].set()
        applied["session_revoked"] += 1
        log(f"ssf: session-revoked ({ev.get('reason_admin', {}).get('en')}) -> {scope}; "
            f"in-flight calls cut: {len(cut)}")
        return Response(status_code=202)
    log(f"ssf: event types {list(events)} ignored")
    return Response(status_code=202)

async def state(request: Request) -> Response:
    return JSONResponse({"applied": applied["session_revoked"], "revoked_users": revoked_users, "revoked_sids": sorted(revoked_sids),
                         "inflight": [{k: v for k, v in e.items() if k != "cut"} for e in inflight.values()]})

app = Starlette(routes=[Route("/mcp", mcp, methods=["GET", "POST", "DELETE"]),
                        Route("/ssf/events", ssf_events, methods=["POST"]),
                        Route("/debug/state", state)])

if __name__ == "__main__":
    log(f"gateway: SSF issuer {idp_meta['issuer']}, jwks {idp_meta['jwks_uri']}")
    uvicorn.run(app, host="127.0.0.1", port=9444, log_level="warning",
                ssl_certfile="certs/localhost.pem", ssl_keyfile="certs/localhost.key")
text · agent.py
"""A lab agent: gets a token from the IdP and calls MCP tools through the gateway.

usage: python agent.py USER CLIENT_ID [list|export] [repeat]
"""
import asyncio, sys, time
import httpx, httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client

IDP, GW, CA = "https://localhost:9443", "https://localhost:9444/mcp", "certs/ca.pem"

def ts() -> str:
    return time.strftime("%H:%M:%S")

async def main(user: str, client_id: str, mode: str, repeat: int) -> None:
    tok = httpx.post(f"{IDP}/token", data={"user": user, "client_id": client_id}, verify=CA).json()
    print(f"{ts()} {client_id}: token for {user}, sid={tok['sid']}", flush=True)
    headers = {"authorization": f"Bearer {tok['access_token']}"}
    for i in range(repeat):
        try:
            async with httpx2.AsyncClient(headers=headers, verify=CA, timeout=60) as hc:
                async with Client(streamable_http_client(GW, http_client=hc)) as c:
                    if mode == "export":
                        async def progress(p, total, message):
                            print(f"{ts()} {client_id}: progress {message}", flush=True)
                        r = await c.call_tool("export_orders", {"customer": "c-1001"}, progress_callback=progress)
                    else:
                        r = await c.call_tool("list_orders", {"customer": "c-1001"})
                    text = " ".join((r.content[0].text if r.content else str(r)).split())
                    print(f"{ts()} {client_id}: {'error' if r.is_error else 'ok'}: {text}", flush=True)
        except Exception as e:
            while getattr(e, "exceptions", None):
                e = e.exceptions[0]
            msg = f"{type(e).__name__}: {e}"
            print(f"{ts()} {client_id}: refused: {msg[:160]}", flush=True)
        await asyncio.sleep(2)

if __name__ == "__main__":
    a = sys.argv[1:]
    asyncio.run(main(a[0], a[1], a[2] if len(a) > 2 else "list", int(a[3]) if len(a) > 3 else 1))

Output atteso

output
cryptography              50.0.2
httpx                     0.28.1
mcp                       2.3.0
PyJWT                     2.15.1
starlette                 1.10.0
uvicorn                   0.54.0
Passo 3Crea i token del lab e avvia tutto

Obiettivo. Scrivi tre token casuali del lab in .env, poi avvia l’IdP con il profilo di interoperabilità CAEP, il server MCP e il gateway.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
  • Porte 9000, 9443 e 9444 libere su localhost
text · start.sh
#!/usr/bin/env bash
# Start the IdP (SSFgo transmitter), the MCP server and the gateway. Usage: ./start.sh [interop|ssf]
. ./.env
./idp-bin -profile "${1:-interop}" > idp.log 2>&1 &
python mcp_server.py > mcp.log 2>&1 &
sleep 2
python gateway.py > gw.log 2>&1 &
sleep 3
ss -ltnH | awk '{print $4}' | grep -E ":(9000|9443|9444)$" | sort
text · stop.sh
#!/usr/bin/env bash
pkill -f "[i]dp-bin"; pkill -f "[m]cp_server.py"; pkill -f "[g]ateway.py"; sleep 1
ss -ltnH | grep -c -E ":(9000|9443|9444) " || true
text · run.sh
chmod +x start.sh stop.sh
for v in RECEIVER_TOKEN PUSH_TOKEN ADMIN_TOKEN; do echo "export $v=$(openssl rand -hex 16)"; done > .env
echo "export MCP_RESOURCE=https://localhost:9444/mcp GATEWAY_AUDIENCE=https://localhost:9444" >> .env
chmod 600 .env && . ./.env && echo "tokens set: ${#RECEIVER_TOKEN} ${#PUSH_TOKEN} ${#ADMIN_TOKEN} characters"
./start.sh interop
cat idp.log gw.log

Output atteso

output
tokens set: 32 32 32 characters
127.0.0.1:9000
127.0.0.1:9443
127.0.0.1:9444
<date> <time> idp on https://localhost:9443, profile=interop
<time> gateway: SSF issuer https://localhost:9443, jwks https://localhost:9443/ssf/jwks.json
Passo 4Crea lo stream e aggiungi alice e bob

Obiettivo. Controlla i metadati SSF con lo strumento ssf, crea uno stream push per session-revoked, aggiungi due utenti come subject e chiedi un evento di verifica. La risposta dello stream ripete per intero il token di push.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · stream.sh
./ssf metadata -ca-file certs/ca.pem $T 2>&1 >/dev/null
curl -s $C $T/.well-known/ssf-configuration | jq -c "{issuer, jwks_uri, delivery_methods_supported, default_subjects}"
printf "{\"delivery\":{\"method\":\"urn:ietf:rfc:8935\",\"endpoint_url\":\"$A/ssf/events\",\"authorization_header\":\"Bearer $PUSH_TOKEN\"},\"events_requested\":[\"https://schemas.openid.net/secevent/caep/event-type/session-revoked\"]}" > stream-request.json
curl -s $C -X POST $T/ssf/stream -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d @stream-request.json > stream.json
jq "del(.delivery.authorization_header, .events_supported)" stream.json
jq -r .delivery.authorization_header stream.json | sed -E "s/[0-9a-f]{32}/<the PUSH_TOKEN, in full>/"
SID=$(jq -r .stream_id stream.json)
for u in alice bob; do curl -s $C -X POST $T/ssf/subjects:add -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d "{\"stream_id\":\"$SID\",\"subject\":{\"format\":\"iss_sub\",\"iss\":\"$T\",\"sub\":\"$u\"}}" -w "subjects:add $u -> HTTP %{http_code}\n"; done
curl -s $C "$T/ssf/status?stream_id=$SID" -H "authorization: Bearer $RECEIVER_TOKEN" | jq -c "{status}"
curl -s $C -X POST $T/ssf/verify -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d "{\"stream_id\":\"$SID\",\"state\":\"lab-check-1\"}" -w "verify -> HTTP %{http_code}\n"
sleep 1; grep verification gw.log; grep push idp.log

Output atteso

output
accepted: the metadata names the issuer, its endpoints are https on trusted origins, and its signing keys were fetched
{"issuer":"https://localhost:9443","jwks_uri":"https://localhost:9443/ssf/jwks.json","delivery_methods_supported":["urn:ietf:rfc:8935","urn:ietf:rfc:8936"],"default_subjects":"NONE"}
{
  "stream_id": "<random-id>",
  "iss": "https://localhost:9443",
  "aud": "https://localhost:9444",
  "events_requested": [
    "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
  ],
  "events_delivered": [
    "https://schemas.openid.net/secevent/caep/event-type/session-revoked"
  ],
  "delivery": {
    "method": "urn:ietf:rfc:8935",
    "endpoint_url": "https://localhost:9444/ssf/events"
  }
}
Bearer <the PUSH_TOKEN, in full>
subjects:add alice -> HTTP 200
subjects:add bob -> HTTP 200
{"status":"enabled"}
verify -> HTTP 204
<time> ssf: verification event, state=lab-check-1
<date> <time> push attempt 1: delivered in 10ms
Passo 5Ottieni un token e leggi cosa controlla il gateway

Obiettivo. Chiedi all’IdP un access token per alice e decodificalo. Il gateway controlla issuer, audience, scadenza e firma, e gli serve il claim sid per revocare una sola sessione.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · token.sh
curl -s $C -X POST $T/token -d user=alice -d client_id=support-agent | jq -r .access_token > alice.jwt
cut -d. -f1 alice.jwt | base64 -d 2>/dev/null; echo
cut -d. -f2 alice.jwt | tr "_-" "/+" | base64 -d 2>/dev/null | jq .

Output atteso

output
{"alg":"RS256","kid":"at-1","typ":"at+jwt"}
{
  "aud": "https://localhost:9444/mcp",
  "client_id": "support-agent",
  "exp": <unix time>,
  "iat": <unix time>,
  "iss": "https://localhost:9443",
  "jti": "<random>",
  "scope": "mcp:tools",
  "sid": "sid-<random>",
  "sub": "alice"
}
Passo 6Revoca alice mentre lavorano tre agenti

Obiettivo. Avvia un export lungo e una ricerca ripetuta per alice e una ricerca per bob, poi emetti session-revoked per alice. L’export si interrompe a metà, l’altro agente di alice riceve 401, bob continua a lavorare.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · cut.sh
python agent.py alice export-agent export 1 > export-agent.log 2>&1 &
python agent.py alice billing-agent list 6 > billing-agent.log 2>&1 &
python agent.py bob support-agent list 6 > bob-agent.log 2>&1 &
sleep 7
curl -s $C -X POST $T/admin/revoke -H "authorization: Bearer $ADMIN_TOKEN" -d "{\"sub\":\"alice\",\"reason\":\"Agent misuse reported\"}"; echo
sleep 8
cat export-agent.log
cat billing-agent.log bob-agent.log
grep -E "10:39:(4[4-9]|5[0-4])" gw.log | grep -v -E "tools/list|server/discover" | cut -c1-120
grep "10:39:5" idp.log
curl -s $C $A/debug/state | jq -c "{revoked_users, inflight}"

Output atteso

output
{"emitted":"true","subject_format":"iss_sub"}

10:39:44 export-agent: token for alice, sid=sid-N0kqUoJ1
10:39:44 export-agent: progress exported 5%
10:39:45 export-agent: progress exported 10%
10:39:46 export-agent: progress exported 15%
10:39:47 export-agent: progress exported 20%
10:39:48 export-agent: progress exported 25%
10:39:49 export-agent: progress exported 30%
10:39:50 export-agent: progress exported 35%
10:39:50 export-agent: refused: MCPError: session revoked by the identity provider (CAEP), call cut
10:39:44 billing-agent: token for alice, sid=sid-4GpXzD_u
10:39:44 billing-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:50 billing-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:52 billing-agent: refused: MCPError: Server returned an error response
10:39:54 billing-agent: refused: MCPError: Server returned an error response
10:39:44 support-agent: token for bob, sid=sid-CVg8IkTk
10:39:44 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:50 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:52 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:54 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:39:44.406 mcp: tools/call list_orders sub=bob client=support-agent sid=sid-CVg8IkTk -> forward
10:39:44.407 mcp: tools/call export_orders sub=alice client=export-agent sid=sid-N0kqUoJ1 -> forward
10:39:44.408 mcp: tools/call list_orders sub=alice client=billing-agent sid=sid-4GpXzD_u -> forward
... (the same three calls every two seconds, shortened here)
10:39:50.971 ssf: session-revoked (Agent misuse reported) -> all sessions of sub=alice; in-flight calls cut: 1
10:39:50.971 mcp: cut in-flight export_orders for sid=sid-N0kqUoJ1
10:39:52.496 mcp: 401 for sub=alice sid=sid-4GpXzD_u: session revoked
10:39:52.498 mcp: 401 for sub=alice sid=sid-4GpXzD_u: session revoked
10:39:52.501 mcp: tools/call list_orders sub=bob client=support-agent sid=sid-CVg8IkTk -> forward
10:39:54.506 mcp: 401 for sub=alice sid=sid-4GpXzD_u: session revoked
10:39:54.508 mcp: 401 for sub=alice sid=sid-4GpXzD_u: session revoked
10:39:54.520 mcp: tools/call list_orders sub=bob client=support-agent sid=sid-CVg8IkTk -> forward
2026/11/22 10:39:50 emitted session-revoked: subject=alice sid=""
2026/11/22 10:39:50 push attempt 1: delivered in 4ms
{"revoked_users":{"https://localhost:9443|alice":1795340390.0},"inflight":[]}
Passo 7Verifica il SET ricevuto dal gateway

Obiettivo. Controlla l’ultimo Security Event Token ricevuto con ssf verify: firma, typ secevent+jwt, issuer e audience. Poi fai rientrare alice per vedere che l’evento non ha bloccato l’account.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · set.sh
./ssf verify -ca-file certs/ca.pem -issuer $T -audience $GATEWAY_AUDIENCE last-set.jwt 2>verify.txt | jq "{verified, header, sub_id: .claims.sub_id, events: .claims.events}"
cat verify.txt | sed -E "s/[0-9a-f]{32}/<jti>/"
python agent.py alice billing-agent list 1

Output atteso

output
{
  "verified": true,
  "header": {
    "alg": "RS256",
    "typ": "secevent+jwt",
    "kid": "ssf-set-1"
  },
  "sub_id": {
    "format": "iss_sub",
    "iss": "https://localhost:9443",
    "sub": "alice"
  },
  "events": {
    "https://schemas.openid.net/secevent/caep/event-type/session-revoked": {
      "event_timestamp": 1795340390,
      "initiating_entity": "admin",
      "reason_admin": {
        "en": "Agent misuse reported"
      }
    }
  }
}
verified: "<jti>" event https://schemas.openid.net/secevent/caep/event-type/session-revoked about iss_sub
10:40:35 billing-agent: token for alice, sid=sid-hlgqlwFF
10:40:35 billing-agent: ok: { "customer": "c-1001", "open_orders": 2 }
Passo 8Invia eventi falsi e ripetuti

Obiettivo. Spingi sette eventi sbagliati al receiver: bearer assente o errato, content type errato, una chiave estranea, alg none, typ errato e un replay. Nessuno deve cambiare la lista delle revoche. Poi revoca carol, che non è nello stream.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · attacks.py
"""Push forged, malformed and replayed SETs straight at the gateway's /ssf/events."""
import json, os, time, uuid
import httpx, jwt
from cryptography.hazmat.primitives.asymmetric import rsa

URL, CA = "https://localhost:9444/ssf/events", "certs/ca.pem"
PUSH = {"authorization": f"Bearer {os.environ['PUSH_TOKEN']}", "content-type": "application/secevent+jwt"}
ISS, AUD = "https://localhost:9443", os.environ["GATEWAY_AUDIENCE"]
REVOKED = "https://schemas.openid.net/secevent/caep/event-type/session-revoked"

def set_claims(sub="bob", aud=AUD):
    return {"iss": ISS, "aud": aud, "iat": int(time.time()), "jti": uuid.uuid4().hex,
            "sub_id": {"format": "iss_sub", "iss": ISS, "sub": sub},
            "events": {REVOKED: {"event_timestamp": int(time.time()), "reason_admin": {"en": "forged"}}}}

def push(name, body, headers=PUSH):
    r = httpx.post(URL, content=body, headers=headers, verify=CA)
    print(f"{name:<44} -> {r.status_code} {r.text.strip()[:110]}")

attacker = rsa.generate_private_key(public_exponent=65537, key_size=2048)
hdr = {"typ": "secevent+jwt", "kid": "ssf-set-1"}  # the real kid, the wrong key

push("1. no push authorization", "x", {"content-type": "application/secevent+jwt"})
push("2. wrong push token", "x", {**PUSH, "authorization": "Bearer not-the-push-token"})
push("3. wrong content type (application/json)", "{}", {**PUSH, "content-type": "application/json"})
push("4. revoke bob, signed with an attacker key", jwt.encode(set_claims(), attacker, "RS256", headers=hdr))
unsigned = jwt.encode(set_claims(), None, "none", headers={"typ": "secevent+jwt", "kid": "ssf-set-1"})
push("5. revoke bob, alg none", unsigned)
push("6. revoke bob, typ JWT instead of secevent+jwt", jwt.encode(set_claims(), attacker, "RS256", headers={"kid": "ssf-set-1", "typ": "JWT"}))
push("7. replay the last real SET", open("last-set.jwt").read())
print("revoked users after the attacks:", json.dumps(httpx.get("https://localhost:9444/debug/state", verify=CA).json()["revoked_users"]))
text · attacks.sh
python attacks.py
curl -s $C -X POST $T/admin/revoke -H "authorization: Bearer $ADMIN_TOKEN" -d "{\"sub\":\"carol\",\"reason\":\"not on the stream\"}"; echo
sleep 2; tail -2 idp.log

Output atteso

output
1. no push authorization                     -> 401 
2. wrong push token                          -> 401 
3. wrong content type (application/json)     -> 400 {"err":"invalid_request","description":"content-type must be application/secevent+jwt"}
4. revoke bob, signed with an attacker key   -> 400 {"err":"invalid_key","description":"InvalidSignatureError: Signature verification failed"}
5. revoke bob, alg none                      -> 400 {"err":"invalid_key","description":"InvalidAlgorithmError: The specified alg value is not allowed"}
6. revoke bob, typ JWT instead of secevent+jwt -> 400 {"err":"invalid_request","description":"typ 'JWT'"}
7. replay the last real SET                  -> 202 
revoked users after the attacks: {"https://localhost:9443|alice": 1795340390.0}
{"emitted":"true","subject_format":"iss_sub"}

2026/11/22 10:40:37 emitted session-revoked: subject=carol sid=""
2026/11/22 10:40:46 emitted session-revoked: subject=carol sid=""
Passo 9Misura il tempo di blocco

Obiettivo. Esegui dieci revoche e misura ognuna dalla chiamata admin fino a quando il gateway l’ha applicata. Poi guarda l’effetto collaterale: un token emesso nello stesso secondo di una revoca viene rifiutato.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · measure.py
"""Time from the admin revoke call at the IdP to the gateway having applied it, 10 runs."""
import os, statistics, time
import httpx
CA, ADMIN = "certs/ca.pem", os.environ["ADMIN_TOKEN"]
state = lambda: httpx.get("https://localhost:9444/debug/state", verify=CA).json()["applied"]
runs = []
for i in range(10):
    before = state()
    t0 = time.perf_counter()
    httpx.post("https://localhost:9443/admin/revoke", headers={"authorization": f"Bearer {ADMIN}"},
               json={"sub": "alice", "reason": f"timing run {i + 1}"}, verify=CA)
    while state() == before:
        time.sleep(0.002)
    runs.append((time.perf_counter() - t0) * 1000)
    time.sleep(0.3)
print("ms per run:", " ".join(f"{r:.0f}" for r in runs))
print(f"median {statistics.median(runs):.0f} ms, min {min(runs):.0f} ms, max {max(runs):.0f} ms")
text · timing.sh
python measure.py
python agent.py alice billing-agent list 1 | head -1 | grep -o "sid-.*" > billing.sid; cat billing.sid
grep -E "timing run 10|$(cat billing.sid)" gw.log | cut -c1-100
grep -E "10:40:58" idp.log | tail -2  # use the second of your own run 10

Output atteso

output
ms per run: 8 8 8 8 9 7 8 7 7 7
median 8 ms, min 7 ms, max 9 ms
# Started right after measure.py, the agent got its token in the same second as run 10 (head also prints a BrokenPipeError traceback here):
sid-Xh0iV7nQ
10:40:58.059 ssf: session-revoked (timing run 10) -> all sessions of sub=alice; in-flight calls cut:
10:40:58.877 mcp: 401 for sub=alice sid=sid-Xh0iV7nQ: session revoked
10:40:58.879 mcp: 401 for sub=alice sid=sid-Xh0iV7nQ: session revoked
2026/11/22 10:40:58 push attempt 1: delivered in 1ms
2026/11/22 10:40:58 token issued: sub=alice client_id=billing-agent sid=sid-Xh0iV7nQ
Passo 10Revoca una sessione di un agente, non l’utente

Obiettivo. Il profilo interop rifiuta un subject complesso con una sessione, quindi riavvia l’IdP con SSF semplice, iscrivi un subject complesso per alice e revoca solo la sessione dell’agente di fatturazione.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · interop-refuses.sh
curl -s $C -X POST $T/admin/revoke -H "authorization: Bearer $ADMIN_TOKEN" -d "{\"sub\":\"alice\",\"sid\":\"$(cat billing.sid)\",\"reason\":\"one agent session\"}" -w "\nHTTP %{http_code}\n"
./stop.sh
./start.sh ssf
head -1 idp.log
curl -s $C -X POST $T/ssf/stream -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d @stream-request.json > stream.json && SID=$(jq -r .stream_id stream.json) && echo "new stream created"
curl -s $C -X POST $T/ssf/subjects:add -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d "{\"stream_id\":\"$SID\",\"subject\":{\"format\":\"iss_sub\",\"iss\":\"$T\",\"sub\":\"alice\"}}" -w "subjects:add alice -> HTTP %{http_code}\n"
text · one-session.sh
SID=$(jq -r .stream_id stream.json)
curl -s $C -X POST $T/ssf/subjects:add -H "authorization: Bearer $RECEIVER_TOKEN" -H "content-type: application/json" -d "{\"stream_id\":\"$SID\",\"subject\":{\"format\":\"complex\",\"user\":{\"format\":\"iss_sub\",\"iss\":\"$T\",\"sub\":\"alice\"}}}" -w "subjects:add complex {user: alice} -> HTTP %{http_code}\n"
python agent.py alice billing-agent list 5 > billing-agent.log 2>&1 &
python agent.py alice support-agent list 5 > support-agent.log 2>&1 &
sleep 3; BSID=$(head -1 billing-agent.log | grep -o "sid-.*"); echo "billing-agent sid: $BSID"
curl -s $C -X POST $T/admin/revoke -H "authorization: Bearer $ADMIN_TOKEN" -d "{\"sub\":\"alice\",\"sid\":\"$BSID\",\"reason\":\"one agent session\"}"; echo
sleep 7
cat billing-agent.log support-agent.log
grep -E "ssf:|401" gw.log | cut -c1-110
tail -1 idp.log

Output atteso

output
{"emitted":"false","error":"transmitter: emit: caep interop profile: §2.5: CAEP events must use an email or iss_sub subject, not \"complex\""}

HTTP 422
0
127.0.0.1:9000
127.0.0.1:9443
127.0.0.1:9444
<date> <time> idp on https://localhost:9443, profile=ssf
new stream created
subjects:add alice -> HTTP 200
subjects:add complex {user: alice} -> HTTP 200
billing-agent sid: sid-2IbmSe2p
{"emitted":"true","subject_format":"complex"}

10:42:11 billing-agent: token for alice, sid=sid-2IbmSe2p
10:42:11 billing-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:42:13 billing-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:42:15 billing-agent: refused: MCPError: Server returned an error response
10:42:11 support-agent: token for alice, sid=sid-p9pSH-uY
10:42:11 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:42:13 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:42:15 support-agent: ok: { "customer": "c-1001", "open_orders": 2 }
10:42:13.822 ssf: session-revoked (one agent session) -> one session sid=sid-2IbmSe2p; in-flight calls cut: 0
10:42:15.377 mcp: 401 for sub=alice sid=sid-2IbmSe2p: session revoked
10:42:15.379 mcp: 401 for sub=alice sid=sid-2IbmSe2p: session revoked
2026/11/22 10:42:13 push attempt 1: delivered in 7ms
Passo 11Guarda il 401 sul filo

Obiettivo. Chiama l’endpoint MCP con curl, revoca quella sessione e richiama. L’SDK dell’agente dice solo che il server ha risposto con un errore; la risposta grezza contiene il motivo in WWW-Authenticate.

Prerequisiti

  • Il passo precedente è finito come mostrato, nello stesso terminale
text · wire.sh
echo "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"list_orders\",\"arguments\":{\"customer\":\"c-1001\"},\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{}}}}" > call.json
call() { curl -s -i $C $A/mcp -H "authorization: Bearer $(jq -r .access_token tok.json)" -H "content-type: application/json" -H "accept: application/json, text/event-stream" -H "mcp-protocol-version: 2026-07-28" -H "mcp-method: tools/call" -H "mcp-name: list_orders" -d @call.json | grep -i -E "^HTTP|^www-authenticate|^\{" | cut -c1-120; }
curl -s $C -X POST $T/token -d user=alice -d client_id=curl-agent > tok.json; S=$(jq -r .sid tok.json); echo "sid: $S"
call
curl -s $C -X POST $T/admin/revoke -H "authorization: Bearer $ADMIN_TOKEN" -d "{\"sub\":\"alice\",\"sid\":\"$S\",\"reason\":\"wire check\"}"; echo; sleep 0.5
call

Output atteso

output
sid: sid-RmQBQsIP
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"{\n  \"customer\": \"c-1001\",\n  \"open_orders\": 2\n}","type":"t
{"emitted":"true","subject_format":"complex"}

HTTP/1.1 401 Unauthorized
www-authenticate: Bearer error="invalid_token", error_description="session revoked"
{"error":"invalid_token","error_description":"session revoked"}
Passo 12Pulizia

Obiettivo. Ferma i tre processi e cancella certificati, token del lab, log e binari. Restano solo i file sorgente.

Prerequisiti

  • Hai finito il lab
text · cleanup.sh
./stop.sh
rm -rf certs .env *.log *.json *.jwt billing.sid verify.txt idp-bin ssf
ls
deactivate; rm -rf .venv

Output atteso

output
0
agent.py
attacks.py
gateway.py
idp
make-certs.sh
mcp_server.py
measure.py
start.sh
stop.sh

Fonti#

Discutine su X o LinkedIn

Segui su X

Nuovi articoli via email

Una email a settimana con nuovi articoli e lab. Disiscrizione in qualsiasi momento.

Il tuo indirizzo è salvato su Kit, il servizio che invia le email. Dettagli

Articoli e laboratori correlati