Day 15: Audit trail – who did what on whose behalf
Goal: store Keycloak events, extend the visitor logs of the warehouse and the tool desk with session and token numbers, and trace an operation backwards from the warehouse entry to Anna’s login in the browser · Duration: about 100 min · Prerequisite: Day 14 completed
Where we start
# on id1
mkdir -p ~/kurs/15# on id1
kubectl create token lager-mcp -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 1h > ~/kurs/13/mcp-ausweis.jwtNo output. If the kcadm.sh session has expired, log in
again as on Day 4.
Introduction
On Day 14 you worked your way through logs: an IP address in the
warehouse, a serial number in the Keycloak log, a
credential-id in the TokenReview. That worked because you
knew what you were looking for. In a real incident, someone else asks:
“On Tuesday at 20:30, two crates were checked out. Who was it, through
which program, and did they log in for it themselves?”
That takes an audit trail: logs that can be linked across service boundaries. Today you turn on Keycloak’s event storage, give every visitor log the two numbers that hold everything together – session and token –, and answer the question above completely.
Today you will learn:
- how to store and query user and admin events in Keycloak,
- which two fields connect an operation across all services:
sidandjti, - how to trace an operation from the warehouse back to the login in the browser,
- how to trace an access without a human back to the Kubernetes badge,
- why success events are not in the journal,
- what logs have to do with data protection.
Background
The picture for today: the routing slip numbers
Every visitor log in the building records what happens at its door – but so far with names that do not match up. The warehouse writes “Anna, brought by the tool desk”, the tool desk “Anna, via mcp-cli”, reception “exchange for Anna”. Whether that was the same operation three times, nobody knows.
From today on, every entry carries two numbers:
- the visit number (
sid): assigned once when Anna logs in at reception, and noted on every pass that results from it – exchanged ones too, - the pass number (
jti): unique for every single pass.
With the pass number from the warehouse you find, at reception, the exchange that produced the pass. With the visit number you find everything that belongs to Anna’s visit – right back to the login in the browser.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Audit trail | complete, linkable trail of actions | all visitor logs together |
| User event | Keycloak event of a user or client (LOGIN,
TOKEN_EXCHANGE, CLIENT_LOGIN) |
entry at reception |
| Admin event | change to the configuration (UPDATE of a client) |
entry in the caretaker’s log |
sid / sessionId |
session a token comes from | visit number |
jti / token_id |
unique number of a token | pass number |
client_assertion_id |
jti of the badge a client authenticated with |
serial number of the building badge |
| Retention period | how long events stay stored | when old logs are destroyed |
Remember: Names say who. Numbers say which operation. An audit trail needs both in every visitor log.
Which number is where
| Visitor log | sid |
jti |
additionally |
|---|---|---|---|
Keycloak LOGIN |
sessionId |
– | browser IP, consent |
Keycloak OAUTH2_DEVICE_CODE_TO_TOKEN |
sessionId |
token_id = jti of Anna’s token |
client mcp-cli |
| Tool desk | sid |
jti of Anna’s token |
tool, result |
Keycloak TOKEN_EXCHANGE |
sessionId |
token_id = jti of the warehouse pass |
who exchanged |
| Warehouse | sid |
jti of the warehouse pass |
what was checked out |
Drill 1: Having reception keep records
Where you are: on id1,
kcadm.shlogged in.What you have afterwards: a realm that stores user and admin events for seven days.
So far Keycloak only writes errors to the journal (Days 11 and 14).
Successful logins and exchanges leave no trace. You change that for the
realm gebaeude:
Step 1 – turning on events.
# on id1
/opt/keycloak/bin/kcadm.sh update realms/gebaeude -s eventsEnabled=true -s eventsExpiration=604800 -s adminEventsEnabled=true -s adminEventsDetailsEnabled=true| Option | Value | Meaning |
|---|---|---|
eventsEnabled |
true |
store user events in the database |
eventsExpiration |
604800 |
delete after 604,800 seconds (seven days) |
adminEventsEnabled |
true |
store configuration changes |
adminEventsDetailsEnabled |
true |
for changes, also store the new content |
No output.
# on id1
/opt/keycloak/bin/kcadm.sh get realms/gebaeude --fields eventsEnabled,eventsExpiration,adminEventsEnabled,adminEventsDetailsEnabledExpected:
{
"eventsEnabled" : true,
"eventsExpiration" : 604800,
"adminEventsEnabled" : true,
"adminEventsDetailsEnabled" : true
}
Which event types are stored is defined in
enabledEventTypes. The list is empty in the lab – then
Keycloak stores its default set. It contains all the types you need
today – Drill 4 shows them.
Remember: What is not stored, nobody can check afterwards. You turn on events before something happens.
Save your progress? Sign up for free
Drill 2: The visitor logs get numbers
Where you are: on id1.
What you have afterwards: the warehouse and the tool desk write
sidandjti; the tool desk only writes after the result.
Step 1 – the warehouse. Only the
besucherbuch function changes:
# on id1
nano ~/kurs/10/lagerdienst.py"""Lagerdienst: Bestand lesen, Kisten ausbuchen – nur mit gültigem Besucherschein."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import jwt
AUSSTELLER = "http://172.16.0.126:8080/realms/gebaeude"
TUER = "lager"
LIEFERSCHEIN = Path.home() / "kurs/10/lieferschein.txt"
musterkarte = jwt.PyJWKClient(AUSSTELLER + "/protocol/openid-connect/certs")
bestand = {"kisten": 42}
def pruefe(kopf, bereich):
"""Gibt (Inhalt, None) zurück oder (None, (Status, Grund))."""
if not kopf or not kopf.startswith("Bearer "):
return None, (401, "kein Besucherschein")
schein = kopf.removeprefix("Bearer ")
try:
schluessel = musterkarte.get_signing_key_from_jwt(schein)
inhalt = jwt.decode(
schein, schluessel.key, algorithms=["RS256"], audience=TUER, issuer=AUSSTELLER
)
except jwt.PyJWTError as fehler:
return None, (401, f"Schein ungültig: {fehler}")
if bereich not in inhalt.get("scope", "").split():
return None, (403, f"Bereich {bereich} fehlt")
return inhalt, None
class Lager(BaseHTTPRequestHandler):
def antworte(self, status, daten):
text = json.dumps(daten, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(text)))
self.end_headers()
self.wfile.write(text)
def besucherbuch(self, inhalt, was):
print(
f"{was} sub={inhalt.get('sub')} azp={inhalt.get('azp')}"
f" name={inhalt.get('preferred_username')}"
f" sid={inhalt.get('sid')} jti={inhalt.get('jti')}",
flush=True,
)
def do_GET(self):
if self.path != "/bestand":
return self.antworte(404, {"fehler": "unbekannter Pfad"})
inhalt, fehler = pruefe(self.headers.get("Authorization"), "lager:lesen")
if fehler:
return self.antworte(fehler[0], {"fehler": fehler[1]})
self.besucherbuch(inhalt, "BESTAND")
hinweis = LIEFERSCHEIN.read_text().strip() if LIEFERSCHEIN.exists() else ""
self.antworte(200, {"kisten": bestand["kisten"], "lieferschein": hinweis})
def do_POST(self):
if self.path != "/ausbuchen":
return self.antworte(404, {"fehler": "unbekannter Pfad"})
inhalt, fehler = pruefe(self.headers.get("Authorization"), "lager:schreiben")
if fehler:
return self.antworte(fehler[0], {"fehler": fehler[1]})
laenge = int(self.headers.get("Content-Length", 0))
kisten = int(json.loads(self.rfile.read(laenge))["kisten"])
if not 0 < kisten <= bestand["kisten"]:
return self.antworte(409, {"fehler": f"nur {bestand['kisten']} Kisten da"})
bestand["kisten"] -= kisten
self.besucherbuch(inhalt, f"AUSGEBUCHT kisten={kisten}")
self.antworte(200, {"ausgebucht": kisten, "kisten": bestand["kisten"]})
HTTPServer(("0.0.0.0", 8090), Lager).serve_forever()Lines 46–47: after the name come sid and
jti from the pass. The warehouse never writes the pass
itself to the log – otherwise anyone reading the log could use it.
# on id1
sudo systemctl restart lagerdienstStep 2 – the tool desk. On Day 14 you saw that the
WERKZEUG … line was in the log even when the exchange
failed. Now it gets the result and the two numbers:
# on id1
nano ~/kurs/13/mcp_lager.py"""Lager-MCP-Server: Lager-Werkzeuge per MCP, nur mit einem Token für genau diesen Server."""
import json
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import jwt
AUSSTELLER = "http://172.16.0.126:8080/realms/gebaeude"
ICH = "http://172.16.0.126:8091/mcp"
METADATEN = "http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp"
AUSWEIS = Path.home() / "kurs/13/mcp-ausweis.jwt"
LAGER = "http://127.0.0.1:8090"
VERSION = "2026-07-28"
WERKZEUGE = {
"lager_bestand": {
"bereich": "lager:lesen",
"description": "Liefert den Lagerbestand in Kisten und den Lieferschein.",
"inputSchema": {"type": "object", "properties": {}},
},
"lager_ausbuchen": {
"bereich": "lager:schreiben",
"description": "Bucht Kisten aus dem Lager aus.",
"inputSchema": {
"type": "object",
"properties": {"kisten": {"type": "integer"}},
"required": ["kisten"],
},
},
}
musterkarte = jwt.PyJWKClient(AUSSTELLER + "/protocol/openid-connect/certs")
def pruefe(kopf):
"""Gibt (Inhalt, None) zurück oder (None, Grund); Grund None heißt: gar kein Token."""
if not kopf or not kopf.startswith("Bearer "):
return None, None
schein = kopf.removeprefix("Bearer ")
try:
schluessel = musterkarte.get_signing_key_from_jwt(schein)
inhalt = jwt.decode(
schein, schluessel.key, algorithms=["RS256"], audience=ICH, issuer=AUSSTELLER
)
except jwt.PyJWTError as fehler:
return None, str(fehler)
return inhalt, None
def lagerschein(schein, bereich):
"""Eigener Schein fürs Lager per Token Exchange; gibt (Schein, None) oder (None, Grund)."""
rumpf = urllib.parse.urlencode(
{
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": AUSWEIS.read_text().strip(),
"subject_token": schein,
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"scope": bereich,
}
).encode()
url = AUSSTELLER + "/protocol/openid-connect/token"
try:
with urllib.request.urlopen(url, rumpf, timeout=10) as antwort:
return json.loads(antwort.read())["access_token"], None
except urllib.error.HTTPError as fehler:
return None, json.loads(fehler.read() or b"{}").get("error_description", str(fehler))
def lager(name, argumente, schein):
kopf = {"Authorization": "Bearer " + schein, "Content-Type": "application/json"}
if name == "lager_bestand":
anfrage = urllib.request.Request(LAGER + "/bestand", headers=kopf)
else:
rumpf = json.dumps({"kisten": argumente.get("kisten")}).encode()
anfrage = urllib.request.Request(LAGER + "/ausbuchen", rumpf, kopf)
try:
with urllib.request.urlopen(anfrage, timeout=10) as antwort:
return antwort.status, antwort.read().decode()
except urllib.error.HTTPError as fehler:
return fehler.code, fehler.read().decode()
def ergebnis(nummer, inhalt):
return {"jsonrpc": "2.0", "id": nummer, "result": inhalt}
def fehler(nummer, code, text):
return {"jsonrpc": "2.0", "id": nummer, "error": {"code": code, "message": text}}
class Mcp(BaseHTTPRequestHandler):
def protokoll(self, inhalt, name, ergebnis):
print(
f"WERKZEUG {name} ergebnis={ergebnis} sub={inhalt.get('sub')}"
f" azp={inhalt.get('azp')} name={inhalt.get('preferred_username')}"
f" sid={inhalt.get('sid')} jti={inhalt.get('jti')}",
flush=True,
)
def antworte(self, status, daten, tor=None):
text = json.dumps(daten, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
if tor:
self.send_header("WWW-Authenticate", tor)
self.send_header("Content-Length", str(len(text)))
self.end_headers()
self.wfile.write(text)
def do_GET(self):
if self.path != "/.well-known/oauth-protected-resource/mcp":
return self.antworte(404, {"fehler": "unbekannter Pfad"})
self.antworte(
200,
{
"resource": ICH,
"authorization_servers": [AUSSTELLER],
"scopes_supported": ["lager:lesen", "lager:schreiben"],
"bearer_methods_supported": ["header"],
},
)
def do_POST(self):
if self.path != "/mcp":
return self.antworte(404, {"fehler": "unbekannter Pfad"})
inhalt, grund = pruefe(self.headers.get("Authorization"))
if inhalt is None:
tor = f'Bearer resource_metadata="{METADATEN}"'
if grund:
tor += f', error="invalid_token", error_description="{grund}"'
return self.antworte(401, {"fehler": grund or "kein Token"}, tor)
laenge = int(self.headers.get("Content-Length", 0))
anfrage = json.loads(self.rfile.read(laenge))
nummer, methode = anfrage.get("id"), anfrage.get("method")
params = anfrage.get("params", {})
version = params.get("_meta", {}).get("io.modelcontextprotocol/protocolVersion")
if self.headers.get("MCP-Protocol-Version") != VERSION or version != VERSION:
return self.antworte(400, fehler(nummer, -32602, f"nur Protokollversion {VERSION}"))
if methode == "tools/list":
liste = [
{"name": n, "description": w["description"], "inputSchema": w["inputSchema"]}
for n, w in WERKZEUGE.items()
]
return self.antworte(200, ergebnis(nummer, {"tools": liste}))
if methode != "tools/call":
return self.antworte(404, fehler(nummer, -32601, "Method not found"))
name = params.get("name")
if name not in WERKZEUGE:
return self.antworte(400, fehler(nummer, -32602, f"unbekanntes Werkzeug {name}"))
bereich = WERKZEUGE[name]["bereich"]
if bereich not in inhalt.get("scope", "").split():
self.protokoll(inhalt, name, "bereich-fehlt")
tor = f'Bearer error="insufficient_scope", scope="{bereich}", resource_metadata="{METADATEN}"'
return self.antworte(403, {"fehler": f"Bereich {bereich} fehlt"}, tor)
schein, grund = lagerschein(self.headers["Authorization"].removeprefix("Bearer "), bereich)
if schein is None:
self.protokoll(inhalt, name, "tausch-abgelehnt")
tor = f'Bearer resource_metadata="{METADATEN}", error="invalid_token"'
return self.antworte(401, {"fehler": f"Empfang: {grund}"}, tor)
status, text = lager(name, params.get("arguments", {}), schein)
self.protokoll(inhalt, name, f"lager-{status}")
antwort = {"content": [{"type": "text", "text": text}], "isError": status != 200}
self.antworte(200, ergebnis(nummer, antwort))
HTTPServer(("0.0.0.0", 8091), Mcp).serve_forever()| Lines | Change |
|---|---|
| 97–104 | new method protokoll with tool, result,
sub, azp, name, sid,
jti |
| 157 | scope missing: entry ergebnis=bereich-fehlt |
| 162 | exchange rejected: entry ergebnis=tausch-abgelehnt |
| 166 | after the walk to the warehouse: entry with the warehouse’s status |
The earlier print(…) line before the exchange is
gone.
# on id1
sudo systemctl restart lager-mcpRemember: A log entry describes what happened – not what was about to be attempted. It belongs after the result.
Save your progress? Sign up for free
Drill 3: Three operations
Where you are: on id1 and in the browser.
What you have afterwards: three operations that you trace back in Drill 4 and in the challenge.
Step 1 – Anna checks out via the tool desk. Anna
logs in to mcp-cli as in Day 13, Drill 3, step 5, with
scope=openid lager:lesen lager:schreiben and
~/kurs/15/ in all file names. Then:
# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/15/anmeldung-anna.json > ~/kurs/15/kopf-anna.txt# on id1
curl -s http://172.16.0.126:8091/mcp -H @$HOME/kurs/15/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/ausbuchen.json -o ~/kurs/15/antwort.json -w "%{http_code}\n"Expected:
200
# on id1
jq -r ".result.content[0].text" ~/kurs/15/antwort.json.result.content[0].text– the text of the first content block from the MCP response.
Expected:
{"ausgebucht": 2, "kisten": 40}
Step 2 – Ben tries the same. Ben logs in the same
way, file names with ben:
# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/15/anmeldung-ben.json > ~/kurs/15/kopf-ben.txt# on id1
curl -s http://172.16.0.126:8091/mcp -H @$HOME/kurs/15/kopf-ben.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/ausbuchen.json -o /dev/null -w "%{http_code}\n"Expected:
403
Step 3 – the assistant checks for itself. With its new identity from Day 14 and its own pass, without a human:
# on id1
kubectl create token assistent-neu -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 10m > ~/kurs/15/assistent-ausweis.jwt# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token --data-urlencode grant_type=client_credentials --data-urlencode client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer --data-urlencode client_assertion@$HOME/kurs/15/assistent-ausweis.jwt --data-urlencode scope=lager:lesen -o ~/kurs/15/assistent-antwort.json -w "%{http_code}\n"Expected:
200
# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/15/assistent-antwort.json > ~/kurs/15/kopf-assistent.txt# on id1
curl -s http://127.0.0.1:8090/bestand -H @$HOME/kurs/15/kopf-assistent.txt -w "\n%{http_code}\n"Expected:
{"kisten": 40, "lieferschein": "Lieferung vom Montag: 12 Kisten Äpfel, Lieferant Obsthof Krause."}
200
Step 4 – the visitor logs.
# on id1
journalctl -u lager-mcp --since "-5 min" --no-pager -o cat --grep WERKZEUGExpected (your numbers will differ):
WERKZEUG lager_ausbuchen ergebnis=lager-200 sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=mcp-cli name=anna sid=t5Fvd4ThKhXY2dvsSgE-rOGL jti=onrtdg:8acc34ad-871b-3a4d-8f69-17b17193f6ad
WERKZEUG lager_ausbuchen ergebnis=bereich-fehlt sub=12abc4f2-39eb-47ac-8b25-b75f72c48fb3 azp=mcp-cli name=ben sid=TDszbPU0KD4vksp_VWj8_Rd1 jti=onrtdg:21268c15-d74a-3dfe-e336-389cd40f1473
# on id1
journalctl -u lagerdienst --since "-5 min" --no-pager -o cat --grep "BESTAND|AUSGEBUCHT"Expected (your numbers will differ):
AUSGEBUCHT kisten=2 sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=http://172.16.0.126:8091/mcp name=anna sid=t5Fvd4ThKhXY2dvsSgE-rOGL jti=ntrtte:371277e9-954c-a966-b2de-95fa7a943a87
BESTAND sub=de272a37-f521-4946-b01d-f5e0f4dda19c azp=assistent name=service-account-assistent sid=None jti=trrtcc:f180bac3-4c03-a68d-a5ff-bfee63aa0171
What you see:
- Anna’s checkout has the same
sidin both logs, but differentjti– the tool desk saw Anna’s pass, the warehouse saw the exchanged one. - Ben’s attempt only shows up at the tool desk; it never reached the warehouse.
- The assistant has
sid=None: a pass fromclient_credentialsdoes not belong to any human’s login.
Remember: Same
sidmeans: the same visit. Differentjtimeans: different passes. The exchange connects them.
Save your progress? Sign up for free
Drill 4: Backwards from the warehouse to the browser
Where you are: on id1.
What you have afterwards: the answer to “Who checked out two crates at 20:30, how, and did they log in themselves?”
Step 1 – fetching the events.
# on id1
/opt/keycloak/bin/kcadm.sh get events -r gebaeude > ~/kurs/15/events.jsonget events– the stored user events, newest first.
# on id1
jq length ~/kurs/15/events.jsonExpected (your number will differ):
12
Step 2 – from the warehouse pass to the exchange.
The jti from the AUSGEBUCHT line is the
token_id of an event. Insert your number:
# on id1
jq '.[] | select(.details.token_id == "ntrtte:371277e9-954c-a966-b2de-95fa7a943a87") | {zeit: (.time / 1000 | floor | todate), type, clientId, sessionId, ipAddress, details: {username: .details.username, subject_token_client_id: .details.subject_token_client_id, client_assertion_sub: .details.client_assertion_sub, scope: .details.scope}}' ~/kurs/15/events.json| Part | Meaning |
|---|---|
.[] \| select(…) |
each event individually, only the one with this
token_id |
.time / 1000 \| floor \| todate |
Keycloak counts milliseconds; divide by 1000, round down, as a date |
{…, details: {…}} |
only the fields that answer the question |
Expected:
{
"zeit": "2026-12-02T20:30:58Z",
"type": "TOKEN_EXCHANGE",
"clientId": "http://172.16.0.126:8091/mcp",
"sessionId": "t5Fvd4ThKhXY2dvsSgE-rOGL",
"ipAddress": "172.16.0.126",
"details": {
"username": "anna",
"subject_token_client_id": "mcp-cli",
"client_assertion_sub": "system:serviceaccount:laden:lager-mcp",
"scope": "profile lager:schreiben email"
}
}
What you see: The exchange was done by the tool desk
– authenticated with the Kubernetes account lager-mcp – for
Anna, whose pass came from mcp-cli.
Step 3 – everything from Anna’s visit. Now with the
sessionId:
# on id1
jq -c '.[] | select(.sessionId == "t5Fvd4ThKhXY2dvsSgE-rOGL") | {zeit: (.time / 1000 | floor | todate), type, clientId, ipAddress}' ~/kurs/15/events.json-c– each result compactly on one line.
Expected:
{"zeit":"2026-12-02T20:30:58Z","type":"TOKEN_EXCHANGE","clientId":"http://172.16.0.126:8091/mcp","ipAddress":"172.16.0.126"}
{"zeit":"2026-12-02T20:30:56Z","type":"OAUTH2_DEVICE_CODE_TO_TOKEN","clientId":"mcp-cli","ipAddress":"172.16.0.126"}
{"zeit":"2026-12-02T20:30:54Z","type":"LOGIN","clientId":"mcp-cli","ipAddress":"172.16.0.31"}
Step 4 – and at the tool desk?
# on id1
journalctl -u lager-mcp --since "-10 min" --no-pager -o cat --grep t5Fvd4ThKhXY2dvsSgE-rOGLExpected:
WERKZEUG lager_ausbuchen ergebnis=lager-200 sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=mcp-cli name=anna sid=t5Fvd4ThKhXY2dvsSgE-rOGL jti=onrtdg:8acc34ad-871b-3a4d-8f69-17b17193f6ad
Step 5 – the timeline. Put together (all times UTC):
| Time | Where | What | Number |
|---|---|---|---|
| 20:30:54 | Keycloak LOGIN |
Anna logs in in the browser, from 172.16.0.31, gives consent | sid |
| 20:30:56 | Keycloak OAUTH2_DEVICE_CODE_TO_TOKEN |
mcp-cli collects Anna’s token |
sid |
| 20:30:58 | Tool desk | lager_ausbuchen with Anna’s token, result 200 |
sid, jti of Anna’s token |
| 20:30:58 | Keycloak TOKEN_EXCHANGE |
the tool desk exchanges for Anna | sid, token_id = warehouse pass |
| 20:30:58 | Warehouse | AUSGEBUCHT kisten=2 |
sid, jti of the warehouse pass |
What you see: The answer to the question from the
introduction: Anna, logged in from 172.16.0.31 (your machine in the lab)
four seconds earlier, via the tool desk, with their explicit consent for
mcp-cli. The IP 172.16.0.126 for the exchange
and the token pickup is id1 itself, where curl and the tool
desk run.
Remember: The
jtileads from the warehouse to reception, thesidleads from reception through the whole visit.
Save your progress? Sign up for free
Diagnosis task
A colleague looks for Anna’s login not via kcadm.sh but
in the journal – after all, that is where the Keycloak events were on
Days 11 and 14:
# on id1
sudo journalctl -u keycloak --since '-15 min' --no-pager --grep 'type="LOGIN"' -o catExpected: no output.
The login did happen. Why is it not in the journal?
Solution path:
- So far the journal only contained
…_ERRORevents:TOKEN_EXCHANGE_ERROR,CLIENT_LOGIN_ERROR. - The event listener
jboss-loggingwrites to the journal – it is listed in the realm’seventsListeners. It logs errors at levelwarn, but successes by default only atdebug– anddebugdoes not end up in the log. - The storage from Drill 1 (
eventsEnabled) is a different path: into the database, queryable viakcadm.sh get events. The login is there (Drill 4, step 3). - Solution: Use
kcadm.sh get eventsfor the investigation. If you also need successes in the journal or in a central log collection, raise the level for success events of thejboss-logginglistener when starting Keycloak (option--spi-events-listener--jboss-logging--success-level=info). In the lab this is not necessary.
The lesson: check where a system stores its events before you conclude from an empty search that nothing happened.
Challenge
Two questions from everyday work. Answer them only from logs and events.
Question 1: The warehouse shows
BESTAND … name=service-account-assistent sid=None jti=trrtcc:f180….
No human, no session. Which Kubernetes badge was it?
Question 2: In the evening Anna reports: “Logging in
to the tool desk doesn’t work any more.” Reproduce it – disable
mcp-cli the way you disabled the assistant on Day 14 – and
find out who it was and when.
Solution 1: The jti from the warehouse
is the token_id of an event:
# on id1
jq '.[] | select(.details.token_id == "trrtcc:f180bac3-4c03-a68d-a5ff-bfee63aa0171") | {zeit: (.time / 1000 | floor | todate), type, clientId, ipAddress, details: {client_assertion_id: .details.client_assertion_id, client_assertion_sub: .details.client_assertion_sub, scope: .details.scope}}' ~/kurs/15/events.jsonExpected:
{
"zeit": "2026-12-02T20:31:13Z",
"type": "CLIENT_LOGIN",
"clientId": "assistent",
"ipAddress": "172.16.0.126",
"details": {
"client_assertion_id": "627952f2-795d-4e63-8941-c0c12899d141",
"client_assertion_sub": "system:serviceaccount:laden:assistent-neu",
"scope": "profile email lager:lesen"
}
}
client_assertion_id is the jti of the
building badge. Compare it with the badge from Drill 3:
# on id1
step crypto jwt inspect --insecure < ~/kurs/15/assistent-ausweis.jwt > ~/kurs/15/ausweis-inhalt.json# on id1
jq '.payload | {jti, sub, iat: (.iat | todate)}' ~/kurs/15/ausweis-inhalt.jsonExpected:
{
"jti": "627952f2-795d-4e63-8941-c0c12899d141",
"sub": "system:serviceaccount:laden:assistent-neu",
"iat": "2026-12-02T20:31:12Z"
}
The same number: it was the badge you created at 20:31:12 with
kubectl create token, used from id1. Had someone stolen it,
ipAddress would show a different address (Day 14).
Solution 2: Disable it:
# on id1
/opt/keycloak/bin/kcadm.sh update clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5 -r gebaeude -s enabled=falseAnna’s attempt to start a login:
# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=mcp-cli -d scope=openid -w "\n%{http_code}\n"Expected:
{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}
401
Now the caretaker’s log:
# on id1
/opt/keycloak/bin/kcadm.sh get admin-events -r gebaeude > ~/kurs/15/admin-events.json# on id1
jq '.[0] | {zeit: (.time / 1000 | floor | todate), operationType, resourceType, resourcePath, authDetails, representation: (.representation | fromjson | {clientId, enabled})}' ~/kurs/15/admin-events.json.[0]– the newest admin event..representation | fromjson– the new content is stored as text;fromjsonturns it back into JSON.
Expected:
{
"zeit": "2026-12-02T20:32:09Z",
"operationType": "UPDATE",
"resourceType": "CLIENT",
"resourcePath": "clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5",
"authDetails": {
"realmId": "634d70af-7cca-40c9-9cc7-d646a741ef02",
"clientId": "b37af319-6d6f-4fa8-a235-6a617d7debbd",
"userId": "bdb3ae47-3d30-451c-a9f8-ebdbfa33c80e",
"ipAddress": "127.0.0.1"
},
"representation": {
"clientId": "mcp-cli",
"enabled": false
}
}
authDetails only names IDs, and they come from the realm
master, where administrators log in:
# on id1
/opt/keycloak/bin/kcadm.sh get users/bdb3ae47-3d30-451c-a9f8-ebdbfa33c80e -r master --fields usernameExpected:
{
"username" : "admin"
}
# on id1
/opt/keycloak/bin/kcadm.sh get clients/b37af319-6d6f-4fa8-a235-6a617d7debbd -r master --fields clientIdExpected:
{
"clientId" : "admin-cli"
}
The user admin disabled mcp-cli at
20:32:09, via admin-cli (that is kcadm.sh)
from 127.0.0.1 – that is, directly on id1. Re-enable the client:
# on id1
/opt/keycloak/bin/kcadm.sh update clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5 -r gebaeude -s enabled=trueAnd an uncomfortable insight: how many admin events were there before this block?
# on id1
jq length ~/kurs/15/admin-events.jsonExpected:
1
Just one. The block of the assistant on Day 14 and all changes before
it were not recorded – admin events only exist since Drill 1. The fact
that all changes went through the admin account does not
make it better: a shared admin account does not say
which human it was.
Save your progress? Sign up for free
Checkpoint
# on id1
/opt/keycloak/bin/kcadm.sh get realms/gebaeude --fields eventsEnabled,eventsExpiration,adminEventsEnabled,adminEventsDetailsEnabledExpected: all three switches true,
eventsExpiration 604800 (output as in Drill 1).
# on id1
journalctl -u lagerdienst --since "-5 min" --no-pager -o cat --grep "BESTAND|AUSGEBUCHT"Expected (if you were in the warehouse in the last
five minutes): lines with sid= and jti= at the
end.
Test yourself
- Which two numbers connect an operation across the tool desk, reception and the warehouse, and what do they mean?
- Why does Anna’s checkout have the same
sidat the tool desk and in the warehouse, but differentjti? - A warehouse entry has
sid=None. What does that mean, and how do you still get to the originator? - Why does
journalctl --grep 'type="LOGIN"'not find the login? - Why does the tool desk now write its entry only after the result?
- What speaks against keeping events forever?
Answers:
sid(the session a token comes from – the visit number) andjti(unique number of a token – the pass number). In Keycloak they are calledsessionIdandtoken_id.- The exchange creates a new pass (new
jti), but it belongs to the same session (samesid). - The pass comes from
client_credentials– no human, no session. Via thejtiyou find theCLIENT_LOGINevent, whoseclient_assertion_idis thejtiof the Kubernetes badge. - The
jboss-logginglistener writes success events only at leveldebug; they are stored in the database (kcadm.sh get events). - So that the entry says what happened. Before, failed calls also appeared as if they had been carried out.
- Events contain user names and IP addresses – personal data. They may only be kept as long as necessary for the purpose; besides, the database keeps growing.
Interview note
“How do you reconstruct which human triggered an action of an AI
agent?” – Good answer: Every service logs, besides sub and
azp (or act), the session ID sid
and the token ID jti of the presented token, never the
token itself. The identity provider stores events for login, token
issuance and token exchange with the same IDs. That way the
jti leads from the downstream service to the exchange, and
the sid leads through the whole session to the login with
IP and consent. For workloads without a session, the client assertion ID
leads to the workload token. Events are collected centrally, with a
retention period, and admin changes go through personal accounts, not
through a shared admin.
Enterprise note
- Collect centrally. Keycloak events, service logs and the Kubernetes audit log belong in a shared, tamper-proof store. Otherwise, the first thing an intruder deletes is the local logs.
- Personal admin accounts. An admin event from
adminsays nothing. Every human gets their own account, ideally via the company login. - Data protection. User names and IP addresses are personal data. Set a retention period (here seven days), document the purpose, restrict access to the events.
- Never log tokens.
jtiandsidare enough for linking. A token in the log is a master key for everyone allowed to read the log. - Uniform format. In the lab, the services write
schluessel=wert. In larger environments, JSON with fixed field names and a shared trace ID (W3Ctraceparent, which MCP allows in_meta) pays off.
Summary
- The realm
gebaeudestores user and admin events for seven days (eventsEnabled,adminEventsEnabled,adminEventsDetailsEnabled). - The warehouse and the tool desk write
sidandjti; the tool desk logs after the result (lager-200,bereich-fehlt,tausch-abgelehnt). - Backward search:
jtiin the warehouse →TOKEN_EXCHANGE(token_id) →sessionId→LOGINwith browser IP and consent. - Without a session (
sid=None),token_id→CLIENT_LOGIN→client_assertion_idleads to thejtiof the Kubernetes badge. - Success events are not in the journal, only in the database.
- Admin events name user, client and IP – but only from the moment they are turned on, and only as precisely as the accounts are personal.
Commands at a glance
| Command | What for |
|---|---|
kcadm.sh update realms/<realm> -s eventsEnabled=true -s eventsExpiration=<s> |
store user events |
kcadm.sh update realms/<realm> -s adminEventsEnabled=true -s adminEventsDetailsEnabled=true |
store admin events |
kcadm.sh get events -r <realm> |
query user events |
kcadm.sh get admin-events -r <realm> |
query admin events |
jq '.[] \| select(.details.token_id == "<jti>")' |
find the event for a token |
jq '.[] \| select(.sessionId == "<sid>")' |
all events of a session |
jq '.time / 1000 \| floor \| todate' |
make Keycloak timestamps readable |
journalctl -u <dienst> --grep <sid> |
service log for a session |