Day 2: ServiceAccount tokens – door, photo and expiry date
Goal: understand what a ServiceAccount token is bound to, request tokens specifically for an audience and a short lifetime, verify them the way a service would, and rebuild the till from Day 1 so that its badge is only valid for one door · Duration: about 110 min · Prerequisite: Day 1 completed, namespace
ladenwithlagerandkasse
Where we start
# on id1
kubectl get pods -n ladenExpected (age differs):
NAME READY STATUS RESTARTS AGE
kasse 1/1 Running 0 …
lager 1/1 Running 0 …
The home folder on id1 also contains besucher.jwt from
the Preparation and kasse.jwt as well as
cluster-ca.crt from Day 1:
# on id1
ls besucher.jwt kasse.jwt cluster-ca.crtExpected:
besucher.jwt cluster-ca.crt kasse.jwt
Introduction
On Day 1, a single stolen badge was enough to get the database password. The badge was meant for the API server, valid for a year, and through an overly generous Role it gave access to all Secrets. Today you take this problem apart – and find that Kubernetes already has an answer for each part.
A ServiceAccount token can be bound to three things: to an audience (which door it is valid for), to a time (how long it is valid) and to an object (as long as this pod exists). You check each of these bindings individually, with real requests against the API server. Then you rebuild the till: no more badge for the API server, but a day pass for exactly one door.
Today you will learn:
- why the stolen badge from Day 1 is no longer good for anything – and exactly when it became invalid,
- to request tokens via the TokenRequest API with
kubectl create token, with your own audience and lifetime, - to check with a TokenReview whether a token is genuine and whom it is valid for – the way a service would,
- to take the default badge away from a pod and give it a projected token for an audience instead,
- to switch off the extension to one year,
- to watch the kubelet renew a token before it expires.
Background
The picture for today: day pass instead of master key
The office building has a badge office. Until now it has issued every member of staff an annual badge valid for the main entrance, and some staff could use it to collect any envelope at reception. Today you change that:
- The audience is the door the badge is valid for. A badge labelled “Warehouse” only opens the warehouse. If you show it at the main entrance, the gatekeeper says: “That won’t get you in here.”
- The expiry date turns the annual badge into a day pass. Whoever steals it only has hours or minutes.
- The binding to a pod is the photo. If the member of staff leaves the building – the pod is deleted – their badge is blocked immediately, whatever date is printed on it.
- The TokenRequest API is the counter of the badge office. That is where you order a badge: for whom, for which door, for how long.
- A TokenReview is the gatekeeper’s call to the badge office: “Is this badge genuine, and is it valid for my door?”
- The kubelet is the caretaker who puts a fresh day pass on every staff member’s desk before the old one expires.
The terms
| Term | Meaning | in the picture |
|---|---|---|
Audience (aud) |
audience a token is meant for | door the badge is valid for |
exp |
expiry time | expiry date |
| bound token | token with a reference to a pod (or Secret, Node); becomes invalid with the object | photo on the badge |
| TokenRequest | API for ordering a token for a ServiceAccount | counter of the badge office |
| TokenReview | API for having a token verified | call to the badge office |
| projected token | token the kubelet puts into the pod as a file and renews | badge on the desk, swapped by the caretaker |
automountServiceAccountToken |
switches off the default badge for the API server | no main-entrance badge |
| SelfSubjectReview | “Who am I?” – asks the API server whom it sees the requester as | a look at your own badge in the gatekeeper’s mirror |
Remember: A good badge names the door and has an expiry date and a photo. A token without an audience, without a short lifetime and without a binding is a master key with a signature.
How the API server verifies a ServiceAccount token
When a request arrives with
Authorization: Bearer <token>, the API server checks
in order:
- Signature: was the token signed with one of the
cluster’s keys? The header names which key with
kid. - Issuer: does
isscontain its own name? - Audience: does
audcontain at least one of the values the API server accepts? With k3s those arehttps://kubernetes.default.svc.cluster.localandk3s. - Time: is now between
nbfandexp? - Binding: if the token names a pod (or Secret or Node), that object must still exist with exactly this UID. The ServiceAccount must also still exist.
Only after that comes the question from Day 1: may this ServiceAccount do what it is trying to do? That is RBAC. Today is only about the five steps before it.
Drill 1: What the old badges are still good for
Where you are: on id1.
What you have afterwards: proof that a pod token dies with the pod – regardless of the expiry date printed on it.
In the Preparation you saved besucher.jwt and then
deleted the pod. According to exp, the token is valid for a
year. Is it really?
Step 1 – Load the deleted visitor’s badge into a variable.
# on id1
TOKEN=$(cat besucher.jwt)Step 2 – Knock on the API server’s door with it.
# on id1
curl -s --cacert cluster-ca.crt -H "Authorization: Bearer $TOKEN" https://172.16.0.126:6443/api/v1/namespaces/default/podsExpected:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}
What you see: 401 – the API server no
longer accepts the badge, even though exp is still almost a
year away. The pod besucher, whose UID the token was issued
for, no longer exists.
Step 3 – The till’s badge is still alive. The till
from Day 1 is still running. Instead of fetching Secrets again, this
time you only ask the API server: “Whom do you see me as?” For that
there is the SelfSubjectReview resource, which every
authenticated user may create:
# on id1
TOKEN=$(cat kasse.jwt)# on id1
curl -s --cacert cluster-ca.crt -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview"}' https://172.16.0.126:6443/apis/authentication.k8s.io/v1/selfsubjectreviews| Option | Value | Meaning |
|---|---|---|
-X POST |
create a resource instead of reading one | |
-H "Content-Type: …" |
application/json |
the request body is JSON |
-d '…' |
an empty SelfSubjectReview |
the body; nothing more than kind and version is needed |
| Address | …/authentication.k8s.io/v1/selfsubjectreviews |
the endpoint for “Who am I?” |
Expected:
{
"kind": "SelfSubjectReview",
"apiVersion": "authentication.k8s.io/v1",
"metadata": {
"creationTimestamp": "2026-12-01T08:21:43Z"
},
"status": {
"userInfo": {
"username": "system:serviceaccount:laden:kasse",
"uid": "04227230-2017-48ab-add6-5e89a22782ac",
"groups": [
"system:serviceaccounts",
"system:serviceaccounts:laden",
"system:authenticated"
],
"extra": {
"authentication.kubernetes.io/credential-id": [
"JTI=c7550ec1-0f76-4153-89fb-6e86a0f1335f"
],
"authentication.kubernetes.io/node-name": [
"id1"
],
"authentication.kubernetes.io/node-uid": [
"4bee6d80-8467-4725-92f0-65fcf0151197"
],
"authentication.kubernetes.io/pod-name": [
"kasse"
],
"authentication.kubernetes.io/pod-uid": [
"871267eb-80d7-4886-83b8-9d92f7a2bbfb"
]
}
}
}
}
| Field | Value | Meaning |
|---|---|---|
username |
system:serviceaccount:laden:kasse |
the request counts as coming from this user |
groups |
three groups | all ServiceAccounts, all in the namespace laden, all
authenticated users – RBAC can grant permissions to any of them |
credential-id |
JTI=c7550ec1-… |
the ID of exactly this token from the jti field; it
ends up in the audit log (Day 15) |
pod-name, node-name |
kasse, id1 |
the binding the API server checked |
What you see: the API server knows not only the
ServiceAccount but also the pod and node the token is bound to. By the
way, the till was running on id1 – the Day 1 manifest had no
nodeName, so the scheduler decided.
Step 4 – The till leaves the building.
# on id1
kubectl delete pod -n laden kasseExpected:
pod "kasse" deleted from laden namespace
Step 5 – The same badge, a minute later.
TOKEN still contains kasse.jwt:
# on id1
curl -s --cacert cluster-ca.crt -H "Authorization: Bearer $TOKEN" https://172.16.0.126:6443/api/v1/namespaces/laden/secrets/lager-zugangExpected:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}
Step 6 – The log says why. The API server only tells the requester “Unauthorized”, so that an attacker learns nothing. It writes the reason to its own log:
# on id1
sudo journalctl -u k3s --since "-2 min" --no-pager --grep "Unable to authenticate"-u k3sshows only the log of the k3s service.--since "-2 min"only the last two minutes.--grepfilters lines that contain the expression – without a pipe.
Expected (excerpt, one line):
Dec 01 08:22:22 id1 k3s[91820]: E1201 08:22:22.588575 91820 authentication.go:76] "Unable to authenticate the request" err="[invalid bearer token, service account token has been invalidated]"
What you see:
service account token has been invalidated – the token is
validly signed and not expired, but its pod is gone. The stolen badge
from Day 1 is no longer good for anything. But if the attacker had used
it while the till was running, nothing would have stopped
them.
Remember: A pod token dies with its pod. The expiry date is the upper limit, not the actual lifetime.
Save your progress? Sign up for free
Drill 2: At the counter of the badge office
Where you are: on id1.
What you have afterwards: three token orders via the TokenRequest API and the difference between the default badge, a badge for a door of your own and a rejected order.
kubectl create token orders a token for a ServiceAccount
from the TokenRequest API. This is also how the kubelet gets the tokens
for the pods – except that it also adds the binding to the pod.
Step 1 – A token with default values.
# on id1
kubectl create token kasse -n laden > kurz.jwtcreate token <serviceaccount> prints the token to
standard output; you redirect it into a file.
# on id1
step crypto jwt inspect --insecure < kurz.jwtExpected (signature omitted):
{
"header": {
"alg": "RS256",
"kid": "IgxVgJZWT78AbhR-GQDTcPv2lHU2X_x6hHv1u_4m7zM"
},
"payload": {
"aud": [
"https://kubernetes.default.svc.cluster.local",
"k3s"
],
"exp": 1796116956,
"iat": 1796113356,
"iss": "https://kubernetes.default.svc.cluster.local",
"jti": "3e12bff9-87b0-41f8-ad3d-cafa709ef949",
"kubernetes.io": {
"namespace": "laden",
"serviceaccount": {
"name": "kasse",
"uid": "04227230-2017-48ab-add6-5e89a22782ac"
}
},
"nbf": 1796113356,
"sub": "system:serviceaccount:laden:kasse"
},
What you see: two differences from the pod token in
the Preparation. exp − iat is
1796116956 − 1796113356 = 3600 seconds, exactly one hour,
with no extension to one year. And under kubernetes.io,
pod and node are missing: this token is not
bound to any pod. It is valid for one hour, as long as the
ServiceAccount exists.
Step 2 – A badge for the warehouse door, valid for ten minutes.
# on id1
kubectl create token kasse -n laden --audience lager --duration 10m > lager.jwt--audience lagersets the audience. The value can be chosen freely; the service that verifies the token must expect exactly this value.--duration 10msets the desired lifetime.
# on id1
step crypto jwt inspect --insecure < lager.jwtExpected (excerpt, payload only):
"payload": {
"aud": [
"lager"
],
"exp": 1796113960,
"iat": 1796113360,
"iss": "https://kubernetes.default.svc.cluster.local",
"jti": "a90b8c94-bf0a-4d5d-8071-1eb969b4ebf0",
"kubernetes.io": {
"namespace": "laden",
"serviceaccount": {
"name": "kasse",
"uid": "04227230-2017-48ab-add6-5e89a22782ac"
}
},
"nbf": 1796113360,
"sub": "system:serviceaccount:laden:kasse"
},
What you see: aud now contains only
lager, and exp − iat = 600 – ten minutes.
Step 3 – Even shorter?
# on id1
kubectl create token kasse -n laden --duration 1mExpected:
error: failed to create token: TokenRequest.authentication.k8s.io "" is invalid: spec.expirationSeconds: Invalid value: 60: may not specify a duration less than 10 minutes
What you see: ten minutes is the lower limit. Kubernetes wants to prevent tokens from expiring in transit when the clocks of two machines are slightly apart.
Remember: At the counter of the badge office you order door and lifetime. If you don’t specify anything, you get the badge for the main entrance, valid for one hour.
Save your progress? Sign up for free
Drill 3: The gatekeeper calls
Where you are: on id1.
What you have afterwards: proof that a token for the warehouse door isn’t valid at the main entrance, and a TokenReview a service can use to check whether a token is meant for it.
Step 1 – The warehouse badge at the main entrance.
# on id1
TOKEN=$(cat lager.jwt)# on id1
curl -s --cacert cluster-ca.crt -H "Authorization: Bearer $TOKEN" https://172.16.0.126:6443/api/v1/namespaces/laden/secrets/lager-zugangExpected:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}
What you see: 401. The token is
genuine, fresh and signed by this cluster – but not meant for the API
server. You read the exact reason from the log in the diagnosis
task.
Step 2 – Play the gatekeeper. A “warehouse” service would be shown this token. How does it verify it? It can ask the API server, with a TokenReview. It contains the token and the audience the service expects. Create the folder for today:
# on id1
mkdir -p ~/kurs/02The TokenReview is a small JSON document. Instead of copying the long token in by hand, you let jq build it:
# on id1
jq -n --rawfile t lager.jwt '{apiVersion: "authentication.k8s.io/v1", kind: "TokenReview", spec: {token: ($t | rtrimstr("\n")), audiences: ["lager"]}}' > ~/kurs/02/review-lager.json| Option | Meaning |
|---|---|
-n |
start without input – jq builds a new document |
--rawfile t lager.jwt |
load the file’s contents as a string into the variable
$t |
$t \| rtrimstr("\n") |
remove the trailing line break – it isn’t part of the token |
audiences: ["lager"] |
the audience the verifying service expects |
Step 3 – Send the review.
# on id1
kubectl create -f ~/kurs/02/review-lager.json -o yamlcreate creates the object; a TokenReview is not stored
but answered immediately. -o yaml shows the response.
Expected (excerpt – the token under
spec is omitted):
apiVersion: authentication.k8s.io/v1
kind: TokenReview
metadata: {}
spec:
audiences:
- lager
status:
audiences:
- lager
authenticated: true
user:
extra:
authentication.kubernetes.io/credential-id:
- JTI=a90b8c94-bf0a-4d5d-8071-1eb969b4ebf0
groups:
- system:serviceaccounts
- system:serviceaccounts:laden
- system:authenticated
uid: 04227230-2017-48ab-add6-5e89a22782ac
username: system:serviceaccount:laden:kasse
What you see: authenticated: true and
the username. The “warehouse” service now knows: this request comes from
the till in the namespace laden, and the badge is valid for
its door.
Step 4 – The main-entrance badge at the warehouse
door. Now the same with kurz.jwt, the token for
the API server:
# on id1
jq -n --rawfile t kurz.jwt '{apiVersion: "authentication.k8s.io/v1", kind: "TokenReview", spec: {token: ($t | rtrimstr("\n")), audiences: ["lager"]}}' > ~/kurs/02/review-kurz.json# on id1
kubectl create -f ~/kurs/02/review-kurz.json -o jsonpath="{.status}"Expected:
{"error":"[invalid bearer token, token audiences [\"https://kubernetes.default.svc.cluster.local\" \"k3s\"] is invalid for the target audiences [\"lager\"]]","user":{}}
What you see: rejected, with the exact reason: the token is valid for the API server, not for the warehouse. This is exactly what protects the service from someone presenting a badge that was issued for a different door.
Remember: The audience separates the doors. A service checks not only “is the badge genuine?” but “was it issued for me?” – otherwise any service you show a token to can use it against you.
Save your progress? Sign up for free
Drill 4: The till gets a day pass for one door
Where you are: on id1.
What you have afterwards: a till without access to the API server and without a Role for Secrets, with a projected token for the audience
lager, valid for ten minutes, bound to the pod.
Step 1 – Remove the Role from Day 1. The till no
longer needs to read Secrets. Delete the Role and binding specifically –
not the whole file from Day 1, because it also contains the
ServiceAccount and the pod kasse:
# on id1
kubectl delete role,rolebinding -n laden kasse-liest-secretsrole,rolebinding names two resource kinds at once; both
are called kasse-liest-secrets.
Expected:
role.rbac.authorization.k8s.io "kasse-liest-secrets" deleted from laden namespace
rolebinding.rbac.authorization.k8s.io "kasse-liest-secrets" deleted from laden namespace
# on id1
kubectl auth can-i list secrets -n laden --as system:serviceaccount:laden:kasseExpected:
no
Step 2 – Describe the new till.
# on id1
nano ~/kurs/02/kasse-v2.yamlapiVersion: v1
kind: Pod
metadata:
name: kasse
namespace: laden
spec:
serviceAccountName: kasse
automountServiceAccountToken: false
containers:
- name: shell
image: curlimages/curl:8.17.0
command: ["sleep", "infinity"]
volumeMounts:
- name: lager-ausweis
mountPath: /var/run/secrets/lager
readOnly: true
volumes:
- name: lager-ausweis
projected:
sources:
- serviceAccountToken:
audience: lager
expirationSeconds: 600
path: token| Field | Value | Meaning |
|---|---|---|
automountServiceAccountToken |
false |
no default token for the API server under
/var/run/secrets/kubernetes.io/… |
volumes.projected.sources.serviceAccountToken |
the kubelet orders a token and stores it as a file | |
audience |
lager |
audience of the token |
expirationSeconds |
600 |
lifetime: ten minutes, the minimum |
path |
token |
file name in the volume |
mountPath |
/var/run/secrets/lager |
where the file appears in the container |
readOnly |
true |
the container cannot change the file |
Step 3 – Start the till.
# on id1
kubectl apply -f ~/kurs/02/kasse-v2.yamlExpected:
pod/kasse created
# on id1
kubectl wait -n laden --for=condition=Ready pod/kasse --timeout=120sExpected:
pod/kasse condition met
Step 4 – Which badges does the till have now?
# on id1
kubectl exec -n laden kasse -- ls /var/run/secrets/Expected:
lager
What you see: only the lager folder.
The kubernetes.io folder with the token for the API server
is missing.
Step 5 – Read the new badge. Note the time first – you need it in Drill 6:
# on id1
date -u +%TExpected (your time):
08:24:29
# on id1
kubectl exec -n laden kasse -- cat /var/run/secrets/lager/token > kasse-v2-a.jwt# on id1
step crypto jwt inspect --insecure < kasse-v2-a.jwtExpected (excerpt, payload only):
"payload": {
"aud": [
"lager"
],
"exp": 1796114063,
"iat": 1796113463,
"iss": "https://kubernetes.default.svc.cluster.local",
"jti": "dcf6a75c-ad15-4d1a-b1e2-ab108e60c79c",
"kubernetes.io": {
"namespace": "laden",
"node": {
"name": "id2",
"uid": "52aba4e0-1660-4c14-a9a5-209b4671bd08"
},
"pod": {
"name": "kasse",
"uid": "732f34ab-1ff0-4669-b549-0cf7cc5801d7"
},
"serviceaccount": {
"name": "kasse",
"uid": "043ce935-af06-4d95-86fa-64e67fff68e6"
}
},
"nbf": 1796113463,
"sub": "system:serviceaccount:laden:kasse"
},
What you see: all three bindings on one badge: door
(aud: lager), expiry date (exp − iat = 600)
and photo (pod with UID, node). This time the
scheduler placed the till on id2. And there is no warnafter
– a token with its own audience is never extended to one year.
Step 6 – Can the till still reach the API server?
Finally, the counter-proof. TOKEN still contains
lager.jwt; now take the new till’s badge:
# on id1
TOKEN=$(cat kasse-v2-a.jwt)# on id1
curl -s --cacert cluster-ca.crt -H "Authorization: Bearer $TOKEN" https://172.16.0.126:6443/api/v1/namespaces/laden/secrets/lager-zugangExpected:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}
What you see: if someone steals this badge, it won’t get them into the API server – and into the warehouse door for ten minutes at most.
Remember:
automountServiceAccountToken: falsetakes the main-entrance badge away from the pod; a projected token gives it a day pass for exactly the door it needs.
Save your progress? Sign up for free
Drill 5: Abolish the annual badge
Where you are: on id1.
What you have afterwards: an API server that no longer extends default pod tokens to one year.
In the Preparation, exp was one year after
iat. That comes from the API server setting
service-account-extend-token-expiration. It is on by
default so that old programs that read their token only once at startup
don’t fail after an hour. Modern client libraries re-read the file
regularly. If you know that your applications do this, you switch off
the extension.
Step 1 – Create a configuration file for k3s. At
startup, k3s reads /etc/rancher/k3s/config.yaml. Each entry
corresponds to a command-line option:
# on id1
sudo nano /etc/rancher/k3s/config.yamldisable:
- traefik
kube-apiserver-arg:
- service-account-extend-token-expiration=false| Entry | Meaning |
|---|---|
disable: [traefik] |
the same as --disable traefik during installation – now
permanently in the file |
kube-apiserver-arg |
list of options k3s passes on to the built-in API server |
service-account-extend-token-expiration=false |
no longer extend pod tokens to one year |
Step 2 – Restart k3s.
# on id1
sudo systemctl restart k3sRunning pods stay in place; only the server and the kubelet on id1 restart.
# on id1
kubectl wait --for=condition=Ready node/id1 --timeout=120sExpected:
node/id1 condition met
Step 3 – Receive a new visitor. The pod from the Preparation gets the default badge:
# on id1
kubectl apply -f ~/kurs/00/besucher.yamlExpected:
pod/besucher created
# on id1
kubectl wait --for=condition=Ready pod/besucher --timeout=120sExpected:
pod/besucher condition met
# on id1
kubectl exec besucher -- cat /var/run/secrets/kubernetes.io/serviceaccount/token > besucher-neu.jwt# on id1
step crypto jwt inspect --insecure < besucher-neu.jwtExpected (excerpt – look for the lines with
exp, iat and warnafter):
"exp": 1796117112,
"iat": 1796113505,
What you see: exp − iat = 3607 seconds
– one hour and seven seconds. No more warnafter under
kubernetes.io, no year. The kubelet adds the seven extra
seconds for clock skew between the nodes. Yesterday’s badge would no
longer have been good for anything today.
Remember: The extension to one year is a concession to old programs. Switching it off turns every default badge into an hour pass.
If it doesn’t work
If k3s doesn’t start after the restart,
sudo journalctl -u k3s --since "-5 min" --no-pager shows
the error message. The most common mistake: indentation in the YAML file
– the list entries need two spaces and a hyphen.
Save your progress? Sign up for free
Drill 6: The caretaker swaps the badge
Where you are: on id1.
What you have afterwards: observed when the kubelet renews the till’s token, and checked how long the old badge is still valid afterwards.
A token with a ten-minute lifetime only helps if the pod gets a new one in time. The kubelet takes care of that: it swaps a projected token when 80 percent of its lifetime has passed or the token is older than 24 hours.
Step 1 – Look at the timestamp of the current file.
# on id1
date -u +%TExpected (your time):
08:25:18
# on id1
kubectl exec -n laden kasse -- ls -l --full-time /var/run/secrets/lager/..data/--full-timeshows date and time with seconds...data/is the hidden folder where the real file lives;tokenis just a link to it.
Expected:
total 4
-rw-r--r-- 1 root root 1048 2026-12-01 08:24:23 +0000 token
What you see: the file was written at 08:24:23 –
matching iat in Drill 4. It is readable by every user in
the container (-rw-r--r--). If you want to restrict that,
set defaultMode in the volume.
Step 2 – Wait eight minutes. 80 percent of 600 seconds is 480 seconds. Get yourself a coffee and then repeat the two commands from step 1 until the file’s time has changed:
# on id1
date -u +%TExpected (your time):
08:33:23
# on id1
kubectl exec -n laden kasse -- ls -l --full-time /var/run/secrets/lager/..data/Expected:
total 4
-rw-r--r-- 1 root root 1048 2026-12-01 08:32:38 +0000 token
What you see: at 08:32:38 the kubelet stored a new token – 495 seconds after the first one, a little over 80 percent of the lifetime. The few extra seconds come from the kubelet checking its volumes only at intervals.
Step 3 – Read the new badge.
# on id1
kubectl exec -n laden kasse -- cat /var/run/secrets/lager/token > kasse-v2-b.jwt# on id1
step crypto jwt inspect --insecure < kasse-v2-b.jwtExpected (excerpt – look for exp,
iat, jti and the pod UID):
"exp": 1796114558,
"iat": 1796113958,
"jti": "456ed9e1-b21f-4af2-bd50-000e9580ee33",
"pod": {
"name": "kasse",
"uid": "732f34ab-1ff0-4669-b549-0cf7cc5801d7"
},
What you see: new jti, new times, same
pod. Nothing changes for the application as long as it re-reads the file
before every request – or at least every few minutes.
Step 4 – Is the old badge still valid? Build a TokenReview for the first badge, as in Drill 3:
# on id1
jq -n --rawfile t kasse-v2-a.jwt '{apiVersion: "authentication.k8s.io/v1", kind: "TokenReview", spec: {token: ($t | rtrimstr("\n")), audiences: ["lager"]}}' > ~/kurs/02/review-alt.json# on id1
date -u +%TExpected (your time):
08:33:39
# on id1
kubectl create -f ~/kurs/02/review-alt.json -o jsonpath="{.status.authenticated}"Expected:
true
What you see: the old badge is still valid, even
though the pod already has a new one. Renewing does not mean revoking –
the old one simply runs on until its exp. When is that?
# on id1
date -u -d @1796114063 +%TExpected:
08:34:23
Step 5 – After expiry. Repeat the review several
times after 08:34:23, each time with date -u +%T in front.
Instead of just authenticated, you now have the whole
status shown:
# on id1
kubectl create -f ~/kurs/02/review-alt.json -o jsonpath="{.status}"In the author’s lab this produced:
| Time | Seconds after exp |
Result |
|---|---|---|
| 08:34:44 | 21 | "authenticated":true |
| 08:35:05 | 42 | "authenticated":true |
| 08:35:52 | 89 | {"error":"[invalid bearer token, service account token has expired]","user":{}} |
What you see: even after exp, the API
server still accepted the badge for about a minute; only then did it
report service account token has expired. This tolerance is
meant to absorb clock skew between machines. For you this means: a
stolen token is valid until exp plus about a minute – plan
with that value, not with exp.
Remember: The caretaker puts down a new badge in time, but doesn’t collect the old one. A short lifetime is the real protection – renewing alone blocks nothing.
Save your progress? Sign up for free
Diagnosis task
A colleague rebuilt an application the same way you rebuilt the till in Drill 4. Since then, when it accesses the API server, it only reports:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}
They swear the token is fresh and valid. Find out what’s going on – you produced exactly this case yourself in Drill 3, step 1.
Solution path:
The response to the client deliberately reveals nothing. The reason is in the API server’s log. Narrow the time down to the moment of the request (your time from Drill 3):
# on id1 sudo journalctl -u k3s --since "08:22:50" --until "08:23:10" --no-pager --grep "Unable to authenticate"Expected:
Dec 01 08:22:51 id1 k3s[91820]: E1201 08:22:51.772059 91820 authentication.go:76] "Unable to authenticate the request" err="[invalid bearer token, token audiences [\"lager\"] is invalid for the target audiences [\"https://kubernetes.default.svc.cluster.local\" \"k3s\"]]"The message names both sides: the token has the audience
lager, the API server only acceptshttps://kubernetes.default.svc.cluster.localandk3s.Cross-check without the log:
step crypto jwt inspect --insecureon the application’s token shows the valuelagerin theaudfield.Cause: the token was issued for a different door. For the API server, the application needs a second projected token without
audience(then the API server’s default audience applies) – or, if it doesn’t need the API server at all, the error is exactly as it should be. SeveralserviceAccountTokenentries in one volume, each with its ownpathand its own audience, are allowed.
Challenge
The “warehouse” service should verify the till’s tokens itself via
TokenReview, as you did as administrator in Drill 3. It gets its own
ServiceAccount lager-pruefer. Which permission does this
ServiceAccount need, and which ready-made Kubernetes role bundle
provides it? Grant it without allowing it anything else. Write down the
commands before you read the solution.
Solution:
Create the ServiceAccount:
# on id1 nano ~/kurs/02/lager-pruefer.yaml~/kurs/02/lager-pruefer.yaml new fileapiVersion: v1 kind: ServiceAccount metadata: name: lager-pruefer namespace: laden# on id1 kubectl apply -f ~/kurs/02/lager-pruefer.yamlExpected:
serviceaccount/lager-pruefer createdMay it verify already?
# on id1 kubectl auth can-i create tokenreviews --as system:serviceaccount:laden:lager-prueferExpected:
Warning: resource 'tokenreviews' is not namespace scoped in group 'authentication.k8s.io' noThe warning says: TokenReviews don’t belong to any namespace. So the permission has to be granted cluster-wide.
Kubernetes ships the ClusterRole
system:auth-delegatorfor this:# on id1 kubectl get clusterrole system:auth-delegator -o yamlExpected (excerpt – the rules):
rules: - apiGroups: - authentication.k8s.io resources: - tokenreviews verbs: - create - apiGroups: - authorization.k8s.io resources: - subjectaccessreviews verbs: - createExactly two permissions: have tokens verified and ask whether someone may do something. Read nothing, change nothing.
Bind the role to the ServiceAccount:
# on id1 nano ~/kurs/02/lager-pruefer-recht.yaml~/kurs/02/lager-pruefer-recht.yaml new fileapiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: lager-pruefer-darf-pruefen subjects: - kind: ServiceAccount name: lager-pruefer namespace: laden roleRef: kind: ClusterRole name: system:auth-delegator apiGroup: rbac.authorization.k8s.io# on id1 kubectl apply -f ~/kurs/02/lager-pruefer-recht.yamlExpected:
clusterrolebinding.rbac.authorization.k8s.io/lager-pruefer-darf-pruefen createdCross-check:
# on id1 kubectl auth can-i create tokenreviews --as system:serviceaccount:laden:lager-prueferExpected (after the same warning):
yes# on id1 kubectl auth can-i list secrets -n laden --as system:serviceaccount:laden:lager-prueferExpected:
no
The gatekeeper may call the badge office – nothing more. On Day 3 you learn the second way: a service verifies the token itself with the cluster’s public key, without any call at all.
Save your progress? Sign up for free
Checkpoint
# on id1
kubectl exec -n laden kasse -- ls /var/run/secrets/Expected:
lager
# on id1
kubectl auth can-i list secrets -n laden --as system:serviceaccount:laden:kasseExpected:
no
# on id1
sudo cat /etc/rancher/k3s/config.yamlExpected: the three entries from Drill 5, including
service-account-extend-token-expiration=false.
Test yourself
- A token has
expone year away but is rejected by the API server. Name two possible reasons that have nothing to do with time. - How can you tell from a token whether it is bound to a pod?
- A service receives a token and only checks the signature and
exp. What can go wrong? - Why does the API server only return “Unauthorized” for a rejected token and no reason?
- The kubelet has renewed a pod’s token. Is the old badge blocked as a result?
- When does
automountServiceAccountToken: falsemake sense, and what does the pod lose?
Answers:
- The pod it is bound to was deleted
(
service account token has been invalidated), or the audience doesn’t match the API server. Others: the ServiceAccount was deleted, or the cluster’s signing key was changed. - Under
kubernetes.iothere is apodentry with name and UID (andnode). Tokens fromkubectl create tokenwithout--bound-object-…don’t have it. - It then also accepts tokens that were issued for a completely different service. Any service the till shows a token to could present that token to it. The audience must be checked.
- An attacker shouldn’t learn why their forged or stolen token fails. The server writes the reason only to its own log.
- No. The old one stays valid until its
exp– in the lab the API server even accepted it briefly afterwards. Renewing is not revoking; you block a token by deleting the pod or the ServiceAccount. - Whenever the pod doesn’t need to talk to the API server – that is, for most applications. The pod only loses the badge for the main entrance; it can still get projected tokens for other audiences.
Interview note
“What is a bound service account token?” – Good answer: a token from
the TokenRequest API that has an audience, an expiry time and a binding
to an object (usually the pod). The kubelet stores it as a projected
volume and renews it at 80 percent of its lifetime. It becomes invalid
when the pod is deleted. If they dig deeper: the old Secret-based tokens
without expiry have no longer been created automatically since
Kubernetes 1.24; the extension to one year can be switched off with
--service-account-extend-token-expiration=false.
Enterprise note
In production, a policy that enforces
automountServiceAccountToken: false for all pods that don’t
explicitly talk to the API server pays off (Kyverno can add it as a
mutation). Long-lived tokens from Secrets of type
kubernetes.io/service-account-token should be inventoried
and phased out;
kubectl get secrets -A --field-selector type=kubernetes.io/service-account-token
finds them. Services that verify tokens via TokenReview get
system:auth-delegator – never cluster-admin
“because it’s easier”.
Summary
- A pod token becomes invalid as soon as its pod is deleted – regardless of the expiry date.
kubectl create tokenorders tokens via the TokenRequest API;--audienceand--durationset door and lifetime, at least ten minutes.- A token with its own audience doesn’t open the API server. A TokenReview checks authenticity and audience for a service.
- The till now has no API badge and no Role for Secrets, but a
projected token for
lager, valid for ten minutes, bound to the pod. - Without
service-account-extend-token-expiration, default pod tokens are valid for one hour instead of one year. - The kubelet renews projected tokens at a little over 80 percent of their lifetime; the old one stays valid until it expires.
Commands at a glance
| Command | What for |
|---|---|
curl … -X POST -d '{"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview"}' …/selfsubjectreviews |
“Who am I?” with someone else’s token |
sudo journalctl -u k3s --since … --grep "Unable to authenticate" |
reason for a rejected token |
kubectl create token <sa> -n <ns> |
order a token via TokenRequest |
kubectl create token … --audience <aud> --duration 10m |
token for an audience, short lifetime |
jq -n --rawfile t <datei> '{…}' |
build JSON with the contents of a file |
kubectl create -f review.json -o yaml |
send a TokenReview |
kubectl delete role,rolebinding -n <ns> <name> |
delete Role and binding specifically |
automountServiceAccountToken: false |
switch off the default token |
projected.sources.serviceAccountToken |
projected token with audience and lifetime |
kube-apiserver-arg: [service-account-extend-token-expiration=false] |
switch off the extension to one year |
ls -l --full-time …/..data/ |
see when the kubelet renewed a token |
kubectl auth can-i create tokenreviews --as <sa> |
may a service have tokens verified? |