TL;DR
- I put a Shared Signals receiver in front of a Model Context Protocol (MCP) server, fed by the open-source SSFgo transmitter. One session-revoked event for alice cut her running export and refused her next calls, while bob's agent kept working.
- From the admin call to the gateway applying the event took a median of 8 ms over ten runs on one machine. A token issued in the same second as the revoke was refused too, because iat has whole seconds.
- Forged, unsigned, misdirected and replayed events were rejected or ignored. The replayed event got 202 and changed nothing.
- Cutting one agent session instead of the user needed a complex subject. The interoperability profile of the Continuous Access Evaluation Profile (CAEP) refuses that, and a stream subscribed to alice as iss_sub never received it.
- Not run: a real identity provider as transmitter, OAuth (Open Authorization) for the stream application programming interface (API), poll delivery, a durable revocation store and an MCP client that handles the 401.
Repeat this lab
I wrote this lab so you can run it yourself. Each step has the commands to copy and the output I got, and you can tick it as done. Your ticks stay in this browser only.
Copies a ready-made prompt for Claude Code, Cursor, Codex or any coding agent. For test environments only.
Show prompt
I want to run a hands-on lab from iamops.dev, and I would like your help to do it safely. Lab: A Shared Signals receiver in front of an MCP server: one CAEP event cuts an agent off Read the whole lab here (Markdown): https://iamops.dev/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.
On 17 November 2026 the Shared Signals working group merged a short change to the CAEP Interoperability Profile: the section that required every event to be signed with RS256 and a 2048-bit key is gone. The working copy is dated the same day. A second pull request, #362, still open, proposes subject formats for agents and workloads.
Both changes land on the receiver. Without a fixed algorithm in the profile, the receiver has to decide what it accepts. And when the subject is an agent, the receiver is usually the thing in front of the agent’s tools. So I built one: a Shared Signals receiver inside a small gateway in front of an MCP server, fed by an open-source transmitter, and I tried to make it fail.
If Shared Signals is new to you, I wrote a short explainer and a longer Knowledge article on the Shared Signals Framework (SSF), CAEP and Risk Incident Sharing and Coordination (RISC).
What the lab builds#
- A lab identity provider on port 9443 that signs access tokens for the MCP server and embeds the SSFgo v0.4.2 transmitter (SSF 1.0, CAEP 1.0, push delivery of Security Event Tokens (SET) as in Request for Comments (RFC) 8935).
- An MCP server on port 9000 with two tools: a quick
list_ordersand a slowexport_ordersthat reports progress for 20 seconds. - A gateway on port 9444 that checks every bearer token, forwards MCP requests and receives pushed events at
/ssf/events. - Agents built on the MCP Python software development kit (SDK) 2.3.0, talking MCP revision 2026-07-28.
The MCP revision matters here. In 2026-07-28 a request over Hypertext Transfer Protocol (HTTP) is a self-contained POST with no initialize handshake and no Mcp-Session-Id. There is no MCP session to end. The only session left is the one at the identity provider, carried in the token as sid. So the gateway has two jobs when an event arrives: refuse that user’s or that session’s tokens from now on, and cut any tool call that is still streaming.

Setup#
Everything ran on one Linux machine on 22 November 2026: Go 1.27.3 for the identity provider, Python 3.13.5 with the MCP SDK 2.3.0, PyJWT 2.15.1, httpx 0.28.1 and Starlette 1.10.0 for the rest. SSF requires https for the issuer and for push endpoints, so make-certs.sh creates a throwaway certificate authority (CA) and a certificate for localhost. Three random lab tokens go into .env: one the gateway uses for the stream API, one the transmitter must send with every push, one for the admin action that revokes a user.
The identity provider is a stand-in. It signs a token for whoever asks, so it says nothing about sign-in. What it shows is the part after sign-in: one issuer for both the access token and the events, so the iss and sub in the token are the same pair the event names.
SSFgo refuses to push to loopback addresses by default, as protection against a receiver that registers an internal web address (URL). The lab replaces its HTTP client with one that trusts the lab CA. In production I would keep the default and list internal hosts explicitly.
The stream#
The gateway is a receiver, so it starts by reading the transmitter metadata. SSFgo’s own command line tool, run as a receiver would, accepted it. Then I created a push stream that asks for session-revoked only, with the push endpoint and the bearer value the transmitter must send.

The last line surprised me. The create response returned authorization_header with the complete push token. Anyone who can read the stream configuration with the receiver’s token can read the secret the gateway trusts for incoming events. Treat the stream API token as a secret of the same weight.
The transmitter advertises default_subjects: NONE, so the gateway has to add each subject it wants events for. I added alice and bob as iss_sub subjects and asked for a verification event. The transmitter logged the push as delivered in 10 ms.

The token the gateway checks#
The access token is a JavaScript Object Notation (JSON) Web Token (JWT) with typ at+jwt, an audience of the gateway’s /mcp URL and a sid. I pasted it with the token JSON Web Key Set (JWKS) into the iamops.dev JWT tool, with the issuer and audience I expect. The signature, the issuer and the audience all matched.


Cutting alice’s agents off#
Three agents ran at once: alice’s export agent on the slow tool, alice’s billing agent calling the quick tool every two seconds, and bob’s support agent doing the same. Seven seconds in, I revoked alice at the identity provider.

The gateway log shows the order. The event arrived at 10:39:50.971, the running export was cut in the same millisecond, and every later request with an alice token got a 401. The transmitter logged one push, delivered in 4 ms.

Each refused attempt shows up twice in the log. The SDK’s client first probes with server/discover and, when that fails, tries the older initialize handshake. Both got 401. The agent printed only “Server returned an error response”: the SDK did not show the 401 or the WWW-Authenticate header to my code.
The SET on the wire#
The gateway saved the last event it accepted. SSFgo’s ssf verify checked it against the transmitter’s published keys, issuer and audience, as a receiver would. The subject is iss_sub with alice, and the event carries initiating_entity admin and the reason I typed.

The iamops.dev Shared Signals SET decoder read the same event with the transmitter JWKS and verified the signature. It names the event type, explains the iss_sub subject and notes the txn claim that SSFgo added.

Forged and replayed events#
attacks.py posts straight to /ssf/events. Without the push token, or with the wrong one, the gateway answered 401. A JSON body got 400 invalid_request. An event signed with my own key but the transmitter’s kid got 400 invalid_key, and so did alg: none, because the gateway accepts RS256 only. A typ of JWT was refused. Replaying the last real event got 202, as RFC 8935 expects for an event the receiver already has, and changed nothing: the gateway keeps every jti it has applied.

Two more results in the same capture. An event for carol, who is not on the stream, was emitted at the identity provider but never pushed. And alice signed in again after the revoke and got a token that worked. A session revoke ends sessions, it does not lock the account. If the account should stay locked, the identity provider has to refuse the sign-in, and the event to send is a different one.
I did not test a wrong audience or a wrong issuer with a correctly signed event. That needs a second stream or a second transmitter with its own keys, and I ran neither.
How fast, and the same-second gap#
measure.py called the admin endpoint ten times and polled the gateway until it had applied each event: 8, 8, 8, 8, 9, 7, 8, 7, 7 and 7 ms, a median of 8 ms. That is one machine and loopback, so it measures the software, not a network.

The side effect came from my own rule. The gateway refuses every token of a revoked user with iat at or before the event time, and both are whole seconds. The last timing run revoked alice at 10:40:58.059. The next step signed her in at 10:40:58 and that token was refused. Rounding the other way would let a token issued just before the revoke through. I kept the strict side and would do the same in production, with a note for the help desk.
Revoking one agent session, not the user#
Revoking alice cut all her agents. Often you want less: end the billing agent’s session and leave her other agents running. SSF has a complex subject for that, with a user and a session member.
The CAEP interoperability profile, as SSFgo applies it, allows only email and iss_sub subjects, so the transmitter refused the event with HTTP 422. I restarted the identity provider with the plain SSF 1.0 and CAEP 1.0 rules, created the stream again and subscribed alice as iss_sub. The session event was emitted and never pushed. The subject matching rules in section 8.1.3 of SSF 1.0 define matching between two simple subjects and between two complex subjects, and say nothing about a mix. SSFgo reads that as: a simple subject never matches a complex one.

The fix was to subscribe a complex subject with only user set. Members the subscription leaves out act as wildcards, so it matches any session of alice. With that in place the event arrived, the gateway revoked the billing agent’s sid only, and alice’s support agent kept getting 200.


The decoder shows the complex subject as two parts: alice as iss_sub and the session as an opaque id.

The 401 the agent sees#
With curl the answer is plain. Before the event the call returned 200. After it, the same token got 401 with WWW-Authenticate: Bearer error="invalid_token", error_description="session revoked". An agent that reads that header knows to sign in again rather than retry.

The raw request also needed the Mcp-Method and Mcp-Name headers and two keys in _meta before the 2026-07-28 server accepted it. Without them the server answered 400 with a JSON-RPC error. A gateway can read the tool name from the header, but the server still checks it against the body.
Gotchas#
- The stream configuration echoes the push secret. Keep the stream API token as safe as the push token.
- SSFgo refuses loopback pushes by default. Good for production, a surprise in a lab.
- The interop profile needs poll delivery advertised. The transmitter refused to start under the profile until I listed RFC 8936 next to push.
- Whole seconds on both sides. A revoke and a new sign-in in the same second collide. Pick a side on purpose.
- Revocations live in memory in this lab. A gateway restart forgets them, and a token issued before the revoke would work again until it expires. Keep them for at least the access token lifetime, in a store that survives restarts.
- A session-revoked event does not lock the account. alice signed in again a moment later.
What I would do with this#
- Put the receiver where every agent request lands: the MCP gateway, not each tool.
- Put
sidin the access tokens your agents get, and make sure the issuer of the tokens and of the events is the same, or keep a mapping. - Subscribe the subjects you need in the form the transmitter will send. If you want per-session events, subscribe a complex subject with
user. - Pin the algorithms you accept now that the profile no longer does. RS256 only, no
none, keys from the transmitter’sjwks_uri. - Cut running tool calls, not only new ones. With MCP 2026-07-28 there is no session to close, so the gateway has to track what it is streaming.
What was not run#
The transmitter is SSFgo inside my own lab identity provider, not a commercial identity provider. The stream API used a static bearer token, not OAuth as the interop profile requires. I did not run poll delivery, stream updates, pausing or deleting a stream, or the credential-change event. I did not test a correctly signed event with a wrong audience or issuer. The revocation store is in memory and I did not test a gateway restart. I did not run the OpenID conformance suite against the gateway. The MCP clients were scripts on the SDK, not a real agent product, and none of them reacted to the 401 by signing in again. There is no recording for this lab.
Terminal images were rendered from the saved output of the run on 22 November 2026, Europe/Zurich time. The lab tokens, keys and certificates were random, lived on one machine for under an hour and were deleted at the end.
Repeat this lab#
Everything you need to run this lab on one Linux machine in about 35 minutes, with no accounts: a throwaway CA, an IdP built on SSFgo, an MCP server and a gateway that receives CAEP events. Open each step, copy the blocks, and compare your output with the expected output.
Every value in angle brackets is a placeholder for your own test environment. Nothing on this page is a real identifier or secret.
Set your variables once
# 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 0 of 12 steps done
Step 1Create the CA and build the IdP
Goal. Save make-certs.sh and the idp folder, create a throwaway CA with a localhost certificate, build the lab IdP on SSFgo v0.4.2 and install the ssf command line tool.
Prerequisites
- 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
#!/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 module ssfmcp/idp
go 1.26.10
require github.com/idfoundry/ssfgo v0.4.2 // 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 } 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 Expected 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 Step 2Install the Python side
Goal. Create a venv with pinned versions and save the MCP server, the gateway that is also the SSF receiver, and the test agent.
Prerequisites
- The previous step finished as shown, in the same terminal
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) " """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) """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") """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)) Expected 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 Step 3Make the lab tokens and start everything
Goal. Write three random lab tokens to .env, then start the IdP with the CAEP interoperability profile, the MCP server and the gateway.
Prerequisites
- The previous step finished as shown, in the same terminal
- Ports 9000, 9443 and 9444 free on localhost
#!/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 #!/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 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 Expected 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 Step 4Create the stream and add alice and bob
Goal. Check the SSF metadata with the ssf tool, create a push stream for session-revoked, add two users as subjects and ask for a verification event. The stream answer echoes the push token in full.
Prerequisites
- The previous step finished as shown, in the same terminal
./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 Expected 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 Step 5Get a token and read what the gateway checks
Goal. Ask the IdP for an access token for alice and decode it. The gateway checks issuer, audience, expiry and signature, and needs the sid claim to revoke one session.
Prerequisites
- The previous step finished as shown, in the same terminal
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 . Expected 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"
} Step 6Revoke alice while three agents work
Goal. Start a long export and a repeating lookup for alice and a lookup for bob, then emit session-revoked for alice. The export is cut mid-stream, alice’s other agent gets 401s, bob keeps working.
Prerequisites
- The previous step finished as shown, in the same terminal
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}" Expected 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":[]} Step 7Verify the SET the gateway received
Goal. Check the last pushed Security Event Token with ssf verify: signature, typ secevent+jwt, issuer and audience. Then log alice in again to see that the event did not lock her account.
Prerequisites
- The previous step finished as shown, in the same terminal
./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 Expected 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 } Step 8Send forged and replayed events
Goal. Push seven bad events at the receiver: no or wrong bearer, wrong content type, a foreign key, alg none, the wrong typ and a replay. None may change the revocation list. Then revoke carol, who is not on the stream.
Prerequisites
- The previous step finished as shown, in the same terminal
"""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"])) 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 Expected 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="" Step 9Measure the cut-off time
Goal. Run ten revokes and time each one from the admin call until the gateway has applied it. Then look at the side effect: a token issued in the same second as a revoke is refused.
Prerequisites
- The previous step finished as shown, in the same terminal
"""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") 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 Expected 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 Step 10Revoke one agent session, not the user
Goal. The interop profile refuses a complex subject with a session, so restart the IdP with plain SSF, subscribe a complex subject for alice and revoke only the billing agent’s session.
Prerequisites
- The previous step finished as shown, in the same terminal
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" 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 Expected 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 Step 11See the 401 on the wire
Goal. Call the MCP endpoint with curl, revoke that one session and call again. The agent SDK only says that the server returned an error; the raw answer has the WWW-Authenticate reason.
Prerequisites
- The previous step finished as shown, in the same terminal
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 Expected 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"} Step 12Clean up
Goal. Stop the three processes and delete the certificates, the lab tokens, logs and binaries. Only the source files stay.
Prerequisites
- Done with the lab
./stop.sh
rm -rf certs .env *.log *.json *.jwt billing.sid verify.txt idp-bin ssf
ls
deactivate; rm -rf .venv Expected output
0
agent.py
attacks.py
gateway.py
idp
make-certs.sh
mcp_server.py
measure.py
start.sh
stop.sh Sources#
- openid/sharedsignals PR #368, Drop event signatures (merged 17 Nov 2026)
- CAEP Interoperability Profile 1.0, working copy dated 17 November 2026
- openid/sharedsignals PR #362, agent and workload as subject (open)
- OpenID Shared Signals Framework Specification 1.0 (Final)
- OpenID Continuous Access Evaluation Profile 1.0 (Final)
- RFC 8935: Push-Based Security Event Token Delivery Using HTTP
- RFC 8417: Security Event Token (SET)
- RFC 9493: Subject Identifiers for Security Event Tokens
- SSFgo, an SSF 1.0 transmitter and receiver for Go (v0.4.2)
- Model Context Protocol specification 2026-07-28: Transports
This post as Markdown · RSS · JSON feed
New posts by email
One email a week with new posts and labs. Unsubscribe anytime.
Your address is stored with Kit, which sends the emails. Details