Skip to content
Workload and AI agent identity · Chapter 15 of 20 Day 14: Revocation and emergency – the building badge is gone

Day 14: Revocation and emergency – the building badge is gone

Goal: block a stolen building badge and a stolen user token layer by layer – Kubernetes, Keycloak, session, service – and measure which block takes effect when and which does not · Duration: about 120 min · Prerequisite: Day 13 completed

Where we start

# on id1
mkdir -p ~/kurs/14

The MCP server’s building badge from Day 13 is valid for one hour. Renew it so the tool desk can exchange tokens today:

# on id1
kubectl create token lager-mcp -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 1h > ~/kurs/13/mcp-ausweis.jwt
# on id1
systemctl is-active keycloak lagerdienst lager-mcp

Expected:

active
active
active

If the kcadm.sh session has expired (Session has expired), log in again as on Day 4.

Introduction

So far you have built doors. Today someone breaks in. The assistant’s building badge – the file with its Kubernetes token – suddenly sits on a stranger’s machine, and from there someone fetches warehouse passes. Later, Anna’s token gets stolen too.

In an emergency, what counts is not what you could block, but what the block actually does and how fast. Today you block on four layers and, after each block, measure whether the attacker still gets through. At least one result will surprise you.

id2 plays the attacker’s machine.

Today you will learn:

  • why deleting a service account invalidates a stolen token in Kubernetes, but not at Keycloak,
  • how to disable a client in Keycloak and what happens to passes that have already been issued,
  • how to end a human’s sessions and what that does to a service that only checks tokens offline,
  • how to find the trail of a stolen token in the log,
  • why “recreate the service account” is not a fix – and what helps instead.

Background

The picture for today: the lost building badge

The runner has lost their building badge, and someone is using it. What do you do?

  • You call the badge office (Kubernetes) and have the badge declared invalid. Anyone who asks there learns: blocked.
  • But the reception desk (Keycloak) does not check with the badge office. It only checks the seal on the badge – and that is genuine. So reception has to record a block itself.
  • The visitor passes the thief has already received are in circulation. The warehouse door also only checks the seal. Against them, only short validity helps.
  • If the thief also has Anna’s power of attorney, you end Anna’s login at reception. Anyone who then wants to exchange it at reception is turned away.
  • And before the runner is sent out again, they get a badge with a new name – because reception recognizes badges by name, not by serial number.

The terms

Term Meaning in the picture
Revocation declaring a token that has not yet expired invalid blocking the badge
Offline check checking signature, aud, exp with the public key, without asking back looking at the seal
Online check asking the issuer (TokenReview, introspection) calling the badge office
Remaining lifetime time until exp of a stolen token how long a pass is still valid
jti / credential-id unique number of a token serial number of the badge
Disabling a client enabled=false in Keycloak reception no longer accepts the badge
Ending a session logging out all of a human’s logins withdrawing Anna’s powers of attorney

Remember: A block only takes effect where someone asks. Anyone who only checks the seal does not notice it.

Who checks what – the plan for today

Layer Block does anyone check there? measured in
Kubernetes delete service account TokenReview: yes Drill 2
Keycloak disable client every token request: yes Drill 3
Warehouse service – no, offline only Drill 3
Keycloak session log Anna out token exchange: yes Drill 4
MCP server – no, offline only Drill 4

Drill 1: The break-in

Where you are: on id1, on id2 (attacker) and on your machine.

What you have afterwards: an attacker on id2 who fetches warehouse passes with the assistant’s badge – and the traces of it.

Step 1 – a building badge for the assistant. As on Day 11, valid for one hour:

# on id1
kubectl create token assistent -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 1h > ~/kurs/14/assistent-ausweis.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/14/assistent-ausweis.jwt > ~/kurs/14/ausweis-inhalt.json
# on id1
jq '.payload | {sub, exp, "kubernetes.io"}' ~/kurs/14/ausweis-inhalt.json
  • .payload | {…} – only these three fields from the payload. "kubernetes.io" is in quotes because the name contains a dot.

Expected (your values for exp and uid will differ):

{
  "sub": "system:serviceaccount:laden:assistent",
  "exp": 1796243053,
  "kubernetes.io": {
    "namespace": "laden",
    "serviceaccount": {
      "name": "assistent",
      "uid": "aadec2cf-1b22-4852-9759-37194cabe040"
    }
  }
}

What you see: Besides the name, the badge carries the service account’s uid – the serial number. Remember it for Drill 2.

Step 2 – the theft. The badge ends up on id2. In the lab you copy it yourself:

# on your machine
scp -3 id1:kurs/14/assistent-ausweis.jwt id2:gestohlen.jwt

No output. -3 copies via your machine, as on Day 3.

Step 3 – the attacker gets a warehouse pass. The same request the assistant made on Day 10, only from id2 and with scope=lager:lesen as since Day 12:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -o ~/beute.json -w "%{http_code}\n"

Expected:

200
# on id2
jq '{expires_in, scope}' ~/beute.json

Expected:

{
  "expires_in": 60,
  "scope": "profile email lager:lesen"
}

Step 4 – the attacker reads the stock.

# on id2
jq -r '"Authorization: Bearer " + .access_token' ~/beute.json > ~/kopf-beute.txt
# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8090/bestand -H @$HOME/kopf-beute.txt

Expected:

{"kisten": 40, "lieferschein": "Lieferung vom Montag: 12 Kisten Äpfel, Lieferant Obsthof Krause."}
200

Step 5 – and checking out? The same request as in step 3 with scope=lager:schreiben and the file ~/beute2.json:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:schreiben -o ~/beute2.json -w "%{http_code}\n"

Expected:

200
# on id2
jq '{expires_in, scope}' ~/beute2.json

Expected:

{
  "expires_in": 60,
  "scope": "profile email"
}

What you see: No lager:schreiben – the assistant’s service account does not have the role (Day 11). The work of the last few days limits the damage: the thief can read but not check out.

Step 6 – the trail in the warehouse.

# on id1
journalctl -u lagerdienst --since "-3 min" --no-pager -o cat

Expected (excerpt):

BESTAND sub=de272a37-f521-4946-b01d-f5e0f4dda19c azp=assistent name=service-account-assistent
172.16.0.228 - - [02/Dec/2026 19:24:21] "GET /bestand HTTP/1.1" 200 -

What you see: To the warehouse, it was the assistant. Only the access line from http.server reveals the address: 172.16.0.228 – id2, not id1, where the assistant lives.

Remember: Whoever has the building badge is the runner as far as reception is concerned. How much damage that does depends on how little the runner itself is allowed to do.

Save your progress? Sign up for free

Drill 2: The badge office blocks

Where you are: on id1 and id2.

What you have afterwards: measured that deleting the service account works in Kubernetes – and not at reception.

The obvious reaction: delete the service account. A Kubernetes token is bound to the service account’s uid; once the account no longer exists, the token is worthless to Kubernetes.

Step 1 – asking the badge office, before. A TokenReview as on Day 2, this time with the reception’s audience:

# on id1
jq -n --rawfile t $HOME/kurs/14/assistent-ausweis.jwt '{apiVersion: "authentication.k8s.io/v1", kind: "TokenReview", spec: {token: ($t | rtrimstr("\n")), audiences: ["http://172.16.0.126:8080/realms/gebaeude"]}}' > ~/kurs/14/review.json

You know the options from Day 2, Drill 3.

# on id1
kubectl create -f ~/kurs/14/review.json -o jsonpath="{.status}{\"\n\"}"
  • -o jsonpath="{.status}{\"\n\"}" – only the status part of the response, followed by a line break.

Expected:

{"audiences":["http://172.16.0.126:8080/realms/gebaeude"],"authenticated":true,"user":{"extra":{"authentication.kubernetes.io/credential-id":["JTI=8dcf5ce3-4afd-450a-95be-63b4ba9e8012"]},"groups":["system:serviceaccounts","system:serviceaccounts:laden","system:authenticated"],"uid":"aadec2cf-1b22-4852-9759-37194cabe040","username":"system:serviceaccount:laden:assistent"}}

What you see: authenticated: true. Note the credential-id (JTI=8dcf…) – the serial number of exactly this token. You will find it again in the Keycloak log in Drill 3.

Step 2 – deleting the service account.

# on id1
kubectl delete serviceaccount assistent -n laden

Expected:

serviceaccount "assistent" deleted from laden namespace

Step 3 – asking the badge office, after. The same command as in step 1:

# on id1
kubectl create -f ~/kurs/14/review.json -o jsonpath="{.status}{\"\n\"}"

Right after deleting, the lab still returned the same answer as in step 1 – "authenticated":true. The API server caches token review results for a few seconds. Repeat the command after about 15 seconds.

Expected:

{"error":"[invalid bearer token, serviceaccounts \"assistent\" not found]","user":{}}

Step 4 – and at reception? The attacker on id2 repeats the request from Drill 1, step 3:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -o ~/beute.json -w "%{http_code}\n"

Expected:

200
# on id2
jq '{expires_in, scope}' ~/beute.json

Expected:

{
  "expires_in": 60,
  "scope": "profile email lager:lesen"
}

What you see: Kubernetes says “invalid”, Keycloak issues passes anyway. The identity provider cluster from Day 4 checks the badge offline: signature with the cluster’s public key, iss, aud, exp, and sub against jwt.credential.sub on the client. It does not ask whether the service account still exists.

Remember: Deleting the service account blocks the badge at the badge office. Anyone who only checks the seal – here, reception – keeps accepting it until exp.

Save your progress? Sign up for free

Drill 3: Reception blocks

Where you are: on id1 and id2.

What you have afterwards: a disabled client, a measurement of how long already issued passes still work, and the thief’s trail in the Keycloak log.

Step 1 – the thief gets one more pass beforehand. The request from Drill 2, step 4 once more, then the header:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -o ~/beute.json -w "%{http_code}\n"

Expected:

200
# on id2
jq -r '"Authorization: Bearer " + .access_token' ~/beute.json > ~/kopf-beute.txt

One minute starts now. Do the next steps quickly.

Step 2 – disabling the client.

# on id1
/opt/keycloak/bin/kcadm.sh update clients/58d9e65d-9d53-43e9-aef2-e2b4402b8532 -r gebaeude -s enabled=false
  • enabled=false – the client keeps its entire configuration but no longer accepts requests. Re-enabling means enabled=true.

No output.

Step 3 – a new request from the thief. The same request, this time without -o, so you see the response:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -w "\n%{http_code}\n"

Expected:

{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}
401

Step 4 – the pass the thief already has.

# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8090/bestand -H @$HOME/kopf-beute.txt

Expected:

{"kisten": 40, "lieferschein": "Lieferung vom Montag: 12 Kisten Äpfel, Lieferant Obsthof Krause."}
200

What you see: The warehouse checks the pass offline and knows nothing about the block. In the lab, five seconds passed between the block and this call.

Step 5 – one minute later. Wait until more than 60 seconds have passed since step 1, and repeat step 4:

# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8090/bestand -H @$HOME/kopf-beute.txt

Expected:

{"fehler": "Schein ungültig: Signature has expired"}
401

What you see: Now the thief is out. The 60 seconds from Day 12 are the longest time a stolen pass still works after the block. With the realm default of five minutes, it would have been five minutes.

Step 6 – the trail.

# on id1
sudo journalctl -u keycloak --since "-2 min" --no-pager --grep CLIENT_LOGIN_ERROR

Expected (one line, wrapped here):

… type="CLIENT_LOGIN_ERROR", realmId="d81caa11-8866-4606-bcb2-1f06c54984e4", realmName="gebaeude",
  clientId="null", userId="null", ipAddress="172.16.0.228", error="client_not_found",
  client_assertion_issuer="https://172.16.0.126:6443",
  client_assertion_id="8dcf5ce3-4afd-450a-95be-63b4ba9e8012",
  client_assertion_sub="system:serviceaccount:laden:assistent", grant_type="client_credentials"
Field Meaning
ipAddress where the request came from – id2
error="client_not_found" a disabled client counts as non-existent
client_assertion_id the badge’s jti – the same number as credential-id in the TokenReview
client_assertion_sub whose badge it was

What you see: With client_assertion_id you can prove that it was this stolen badge, and not a new one fetched by the real assistant.

Remember: The block at reception takes effect immediately for new passes. Against passes in circulation, only their short validity helps.

Save your progress? Sign up for free

Drill 4: Anna’s power of attorney is stolen

Where you are: on id1, id2 and in the browser.

What you have afterwards: measured what ending Anna’s sessions does at the tool desk.

A second case: someone has grabbed Anna’s token for the tool desk, for example from the file on their machine.

Step 1 – Anna logs in. As in Day 13, Drill 3, step 5 to mcp-cli with scope=openid lager:lesen, this time with ~/kurs/14/ in all file names. Then:

# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/14/anmeldung-anna.json > ~/kurs/14/kopf-anna.txt

Step 2 – the theft. The thief gets Anna’s header and the two requests from Day 13:

# on your machine
scp -3 id1:kurs/14/kopf-anna.txt id2:kopf-anna.txt
# on your machine
scp -3 id1:kurs/13/bestand.json id2:bestand.json
# on your machine
scp -3 id1:kurs/13/liste.json id2:liste.json

None of the three produces output.

Step 3 – the thief calls a tool.

# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8091/mcp -H @$HOME/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/bestand.json

Expected:

{"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "{\"kisten\": 40, \"lieferschein\": \"Lieferung vom Montag: 12 Kisten Äpfel, Lieferant Obsthof Krause.\"}"}], "isError": false}}
200

Step 4 – ending Anna’s sessions. The ID is Anna’s user ID from Day 9:

# on id1
/opt/keycloak/bin/kcadm.sh create users/ebaf76a2-697c-40f3-910a-75e4d935cb6c/logout -r gebaeude
  • create users/<id>/logout – a POST to this path logs the user out everywhere: all sessions end, refresh tokens become worthless.

No output.

Step 5 – the thief asks for tools.

# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8091/mcp -H @$HOME/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/liste.json -o /dev/null
  • -o /dev/null – throw away the body, only the status code matters.

Expected:


200

What you see: The tool desk checks Anna’s token offline – and it has not expired yet.

Step 6 – the thief calls a tool. The same command as in step 3:

# on id2
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8091/mcp -H @$HOME/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/bestand.json

Expected:


000

What you see: No more stock – but no proper response either. 000 means: curl did not get any HTTP response at all. You will find out why in the diagnosis task.

Remember: Logging out blocks the power of attorney where reception is asked – during the exchange. Anything that only checks offline lets it through until exp.

Save your progress? Sign up for free

Diagnosis task

After Drill 4, curl reports 000 for the tool call. But the tool desk is still running, isn’t it?

Solution path:

  1. Look into the tool desk’s log:

    # on id1
    journalctl -u lager-mcp --since "-3 min" --no-pager -o cat

    Expected (excerpt):

    WERKZEUG lager_bestand sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=mcp-cli name=anna
    ----------------------------------------
    Exception occurred during processing of request from ('172.16.0.228', 43794)
    Traceback (most recent call last):
    …
      File "/home/ubuntu/kurs/13/mcp_lager.py", line 153, in do_POST
        schein = lagerschein(self.headers["Authorization"].removeprefix("Bearer "), bereich)
    …
      File "/home/ubuntu/kurs/13/mcp_lager.py", line 67, in lagerschein
        with urllib.request.urlopen(url, rumpf, timeout=10) as antwort:
    …
    urllib.error.HTTPError: HTTP Error 400: Bad Request
  2. Line 67 is the exchange. Keycloak answered with 400, urlopen then raises an exception, and nobody catches it. http.server drops the connection without answering. The service itself keeps running – only this one request died.

  3. Why 400? Keycloak says so in its own log:

    # on id1
    sudo journalctl -u keycloak --since "-4 min" --no-pager --grep TOKEN_EXCHANGE_ERROR

    Expected (excerpt, wrapped):

    … type="TOKEN_EXCHANGE_ERROR", … clientId="http://172.16.0.126:8091/mcp", …
      error="invalid_token", … reason="subject_token validation failure", …
      client_assertion_sub="system:serviceaccount:laden:lager-mcp", client_auth_method="federated-jwt"

    Anna’s token belongs to a session that no longer exists. The block worked. Solution: The tool desk has to catch a failed exchange and tell the client that its token is no longer good – with 401 and invalid_token, so that an honest client has Anna log in again. Change the program:

# on id1
nano ~/kurs/13/mcp_lager.py
kurs/13/mcp_lager.py changes in green
"""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 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():
            tor = f'Bearer error="insufficient_scope", scope="{bereich}", resource_metadata="{METADATEN}"'
            return self.antworte(403, {"fehler": f"Bereich {bereich} fehlt"}, tor)
        print(
            f"WERKZEUG {name} sub={inhalt.get('sub')} azp={inhalt.get('azp')}"
            f" name={inhalt.get('preferred_username')}",
            flush=True,
        )
        schein, grund = lagerschein(self.headers["Authorization"].removeprefix("Bearer "), bereich)
        if schein is None:
            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)
        antwort = {"content": [{"type": "text", "text": text}], "isError": status != 200}
        self.antworte(200, ergebnis(nummer, antwort))


HTTPServer(("0.0.0.0", 8091), Mcp).serve_forever()
Line Change
55 lagerschein now returns a pair
67–71 catch errors from reception, return error_description as the reason
156–159 without a pass: 401 with invalid_token and the reason from reception
# on id1
sudo systemctl restart lager-mcp

Repeat Drill 4 from step 1 (new login, header to id2, tool call, logout). The call from step 6, this time with -i instead of -w:

# on id2
curl -s -i http://172.16.0.126:8091/mcp -H @$HOME/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/bestand.json

Expected:

HTTP/1.0 401 Unauthorized
Server: BaseHTTP/0.6 Python/3.12.3
Date: Wed, 02 Dec 2026 19:30:18 GMT
Content-Type: application/json; charset=utf-8
WWW-Authenticate: Bearer resource_metadata="http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp", error="invalid_token"
Content-Length: 36

{"fehler": "Empfang: Invalid token"}

The lesson: in an emergency, error paths show up that never run in normal operation. And: the WERKZEUG … line is in the log even though the call failed – it is written before the exchange. Anyone who wants to read from logs what really happened needs to know that (Day 15).

Challenge

The assistant is supposed to work again. A colleague suggests: “Recreate the service account assistent, re-enable the client, done.” But the stolen badge on id2 is still valid for an hour. What happens? Write down your guess, then try it.

Solution:

# on id1
kubectl create serviceaccount assistent -n laden

Expected:

serviceaccount/assistent created
# on id1
/opt/keycloak/bin/kcadm.sh update clients/58d9e65d-9d53-43e9-aef2-e2b4402b8532 -r gebaeude -s enabled=true

The thief tries again (request from Drill 2, step 4):

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -o ~/beute.json -w "%{http_code}\n"

Expected:

200

The thief is back in. And yet Kubernetes knows better:

# on id1
kubectl create -f ~/kurs/14/review.json -o jsonpath="{.status}{\"\n\"}"

Expected:

{"error":"[invalid bearer token, service account UID (27ac2fdc-fd47-4085-b1c8-8613c3b7be74) does not match claim (aadec2cf-1b22-4852-9759-37194cabe040)]","user":{}}

The new service account has a new uid; the stolen badge carries the old one. Kubernetes compares the uid, Keycloak only the name in sub. The name is the same again – so the badge fits again.

Two clean ways:

  1. Wait until the stolen badge’s exp has passed (Drill 1, step 1), and only then re-enable. With a one-hour lifetime, that means one hour of downtime.
  2. New name. The assistant gets a service account with a different name, and the client accepts only that one. This takes effect immediately:
# on id1
kubectl delete serviceaccount assistent -n laden
# on id1
kubectl create serviceaccount assistent-neu -n laden

Expected:

serviceaccount/assistent-neu created
# on id1
/opt/keycloak/bin/kcadm.sh update clients/58d9e65d-9d53-43e9-aef2-e2b4402b8532 -r gebaeude -s 'attributes."jwt.credential.sub"=system:serviceaccount:laden:assistent-neu'

No output. The thief, this time without -o:

# on id2
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/gestohlen.jwt --data-urlencode scope=lager:lesen -w "\n%{http_code}\n"

Expected:

{"error":"invalid_client","error_description":"Invalid client or Invalid client credentials"}
401

And the real assistant with a new badge – this time valid for only ten minutes:

# on id1
kubectl create token assistent-neu -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 10m > ~/kurs/14/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/14/assistent-ausweis.jwt --data-urlencode scope=lager:lesen -o ~/kurs/14/assistent-antwort.json -w "%{http_code}\n"

Expected:

200
# on id1
jq '{expires_in, scope}' ~/kurs/14/assistent-antwort.json

Expected:

{
  "expires_in": 60,
  "scope": "profile email lager:lesen"
}

The lesson: if you recognize badges only by name, you have to change the name in an emergency. And the shorter badges are valid, the shorter the window in which a stolen one still works.

Save your progress? Sign up for free

Checkpoint

# on id1
kubectl get serviceaccount assistent-neu -n laden

Expected (your age will differ):

NAME            AGE
assistent-neu   3m3s
# on id1
jq '{expires_in, scope}' ~/kurs/14/assistent-antwort.json

Expected: "scope": "profile email lager:lesen" as at the end of the challenge.

# on id1
systemctl is-active lager-mcp

Expected:

active

Test yourself

  1. Why does Keycloak still issue passes after the service account has been deleted?
  2. The client is disabled. For how long at most can the thief still get into the warehouse with their passes?
  3. How do you recognize in the Keycloak log that a specific stolen badge was used?
  4. Anna is logged out. Why does tools/list still work with the stolen token, but tools/call does not?
  5. Why is it not enough to recreate the service account and re-enable the client?
  6. Name two settings from this course that limited the damage of the break-in.

Answers:

  1. The identity provider cluster checks the badge offline – signature, iss, aud, exp and sub. It does not ask Kubernetes whether the service account still exists.
  2. Until the exp of the last pass fetched, so at most 60 seconds after the block – that is how long an assistant pass has been valid since Day 12.
  3. By client_assertion_id: it is the badge’s jti and matches the credential-id in the TokenReview. Plus ipAddress.
  4. tools/list only checks offline, and Anna’s token has not expired yet. tools/call has to exchange at reception, and reception rejects tokens of ended sessions.
  5. Keycloak recognizes the badge only by the name in sub. With the same name, the stolen badge fits again, even though Kubernetes recognizes it as wrong by its uid.
  6. For example: the role binding of lager:schreiben (Day 11, the thief could not check out); 60 seconds lifetime (Day 12, short remaining lifetime); exchange instead of passthrough (Day 13, the session block takes effect during the exchange).

Interview note

“A workload token has leaked. What do you do?” – Good answer: First narrow down which parties trust the token and how they check it. Online checkers (Kubernetes via TokenReview, the IdP on every request) react to blocks; offline checkers (JWT validation via JWKS) do not. So: disable the client or the federation rule at the IdP, do not just delete the service account – federated IdPs usually check the Kubernetes token offline. Access tokens already issued will expire; hence short lifetimes. Secure the trail via jti and source IP. Before restarting, change the identity or wait for the remaining lifetime to run out, because a recreated account with the same name opens the door again. The last resort is rotating the signing key – that invalidates all tokens.

Enterprise note

  • Write the emergency plan beforehand. For every identity: who trusts it, how do you block it there, how long does the remaining lifetime last. The “Who checks what” table above is the start.
  • Projected tokens instead of kubectl create token. In pods, tokens are bound to the pod and get renewed; with expirationSeconds: 600 the remaining lifetime is at most ten minutes.
  • SPIFFE/SPIRE. A deleted registration entry (Day 6) means: no new SVIDs. Those already issued remain valid until they expire – the short SVID lifetime from Day 8 is the limit here too.
  • Online checks where it counts. For writing tools, a service can ask reception via token introspection. That costs one request per call, but makes blocks take effect immediately.
  • Do not block customers automatically. Automated reactions only with a dry run and approval; a wrong block can do more harm than the break-in.

Summary

  • A stolen building badge of the assistant gets the thief read passes, but no write permission.
  • Deleting the service account: TokenReview negative after a few seconds, Keycloak keeps issuing passes (offline check).
  • Disabling the client (enabled=false): new requests immediately get invalid_client; passes already issued remain valid until exp, here at most 60 seconds.
  • Keycloak logs the source IP and client_assertion_id – the serial number of the stolen badge.
  • Logging Anna out: the exchange fails, offline-checked calls (tools/list) keep working until exp.
  • The tool desk now catches a failed exchange and answers 401 invalid_token.
  • Recreating the service account opens the door again; only a new name (assistent-neu) blocks the old badge for good.

Commands at a glance

Command What for
kubectl delete serviceaccount <name> -n <ns> delete a service account – blocks only for online checkers
kubectl create -f review.json -o jsonpath="{.status}" TokenReview: is the token still valid for Kubernetes?
kcadm.sh update clients/<id> -s enabled=false disable a client
kcadm.sh create users/<id>/logout end all sessions of a user
kcadm.sh update clients/<id> -s 'attributes."jwt.credential.sub"=…' bind a client to a new workload identity
journalctl -u keycloak --grep CLIENT_LOGIN_ERROR rejected client logins with IP and jti
journalctl -u keycloak --grep TOKEN_EXCHANGE_ERROR failed exchanges with reason
scp -3 id1:<datei> id2:<datei> copy a file between two VMs via your own machine

Contents

More