Reading width
Wide uses the full column for everything, text, diagrams, code, and exercises. Narrow keeps the standard reading width.
Text size
Scales the body text. Headings and code blocks keep their size.
In this section
0.7 Identity for Software
Introduction
Every agent in this course acts through software that has to prove who it is. The hunting agent reads logs through an API; the response agent calls one that isolates hosts; an MCP server reached over HTTP needs to know which client is calling.
Module 7 gives an agent its own identity, with short-lived, narrowly scoped credentials from a mock identity provider, and works through delegation: an agent acting on a person's behalf rather than on its own authority. All of that rests on tokens, and on whether the software that receives one checks it properly.
This lesson builds both sides of the most common token format, the JSON Web Token: an issuer that signs claims and a validator that refuses anything it should.
An assistant writes them to a contract, and the check throws eleven forgeries and mistakes at the validator, from a token with no signature to one whose scope only resembles the one required. Two shortcuts that real code takes are measured, and the lesson ends with the difference between an agent acting as itself and an agent acting for someone.
In a token exchange the agent presents the user’s token and its own credential, and gets back a token whose act claim names the agent, so the API can tell who asked from who acted.
What a Token Is
Readable by anyone, trustworthy only when verifiedA JWT is three parts separated by dots, each base64url-encoded: a header, a payload of claims, and a signature over the first two. Here is one, issued by the lab's draft and taken apart.
$ cp records/tokens-0.7.py lab/foundations/tokens.py
$ python3 decode.py
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2l...
header
alg HS256
typ JWT
payload
iss https://idp.lab.example
sub svc-hunt-agent
aud api://lab-store
exp 2000
nbf 900
scope hosts.read process.read
signature 4fCi0s-K_hEqiYpubIVNpRVar8NdxY8msUZer2kPsT4
Anyone holding the token can read its claims; base64url is an encoding, not encryption. What makes the claims trustworthy is the signature: it was computed over the header and payload with a key, and only a holder of that key could have produced it. Change one character of the payload and the signature no longer matches.
That readability has consequences. A token should carry nothing its holder, or anyone who sees it in transit or in a log, should not read: no secrets, no personal data beyond what the receiving API needs.
Tokens end up in places their designers did not intend, in proxy logs, crash reports, browser history when they travel in URLs, and pasted into support tickets, and every copy is readable and, until it expires, usable by whoever holds it. Encrypted tokens exist for the cases that need them; most do not, and the safer habit is to keep claims minimal and lifetimes short.
Each claim answers a question the receiving API must ask. The issuer, iss, says who vouches for the token. The subject, sub, says who it identifies, here a service identity for the hunting agent. The audience, aud, says which API it is for.
The expiry and not-before claims, exp and nbf, bound when it is valid, as seconds since 1970. The scope says what it permits. A validator that checks the signature but not the claims accepts a genuine token used somewhere it was never meant to go.
The time claims are compared with the validator's own clock, and clocks differ. Validators commonly allow a small leeway, seconds or a few minutes, so that a token issued by a server whose clock runs slightly ahead is not refused as not yet valid.
The leeway is a trade: every second of it is a second a stolen expired token still works. The contract here allows none, so the check can test the boundary exactly.
RFC 8725, the IETF's best current practices for JWTs, sets out what a validator must do. It requires libraries to let the caller specify which algorithms are allowed and to use no others, and says the algorithm called none, which means no signature at all, should only be accepted when the token is protected by other means.
It requires the issuer's keys to be the ones that signed the token. And where one issuer serves several APIs, it requires an audience claim that each API validates, rejecting a token whose audience is missing or does not match.
The subject deserves a moment, because for agents it is easy to get wrong. A service identity should name one workload: the hunting agent, not every agent the team runs.
When several agents share an identity, the logs cannot say which one acted, a permission granted for one is granted to all, and revoking a compromised agent revokes the others with it. One identity per agent, named for its job, is cheap at the start and very expensive to retrofit.
The Contract
One algorithm, every claimThe exercise file states what the issuer and validator must do.
⋯ 13 lines folded14 parts joined by '.'. JSON is compact (no spaces).1516 validate(token, key, audience, issuer, now, scope=None) -> {'ok': bool, 'reason': str, 'claims': dict, 'actor': str}17 ok only if all of these hold: the token has three parts that decode; the header's alg is exactly HS256; the18 signature verifies (compared in constant time); iss equals issuer; aud equals audience or is a list containing it;19 exp is present and now < exp; nbf, if present, is <= now; and, if scope is given, it is one of the20 space-separated values of the 'scope' claim. reason names the first check that failed ('' when ok). claims is21 the payload only when ok, else {}. actor is the 'sub' of the 'act' claim when the token is delegated, else ''.⋯ 9 lines folded
The contract fixes the order of trust. Nothing in a token is believed until the signature over it verifies, and the algorithm used to verify comes from the validator, not from the token.
A header that names an algorithm is a claim like any other, written by whoever made the token; a validator that lets the header choose how it is checked has let the attacker choose. The contract allows exactly one algorithm, HS256, a keyed hash with a shared secret, chosen so the lab needs only Python's standard library.
How the agent obtains its token in the first place is the other half of software identity, and it is where most real compromises start. The simplest arrangement gives the agent a client secret, a password for software, which it presents to the identity provider for a token.
Secrets leak: into repositories, environment dumps and the logs of the tools that read them. The stronger arrangements remove the long-lived secret, letting the platform the agent runs on vouch for it with a short-lived credential the identity provider trusts. Module 7 sets up both against its mock identity provider and measures what each exposes.
Run the check against the file as shipped.
$ python3 -m lab check f07
f07 0.7 Identity for Software: lab/foundations/tokens.py
FAIL the functions are written
lesson 0.7: write issue
FAIL
The check's list of refusals is a catalog of the ways token validation goes wrong in practice: a token with no signature, a payload edited after signing, a token signed by someone else, a genuine token for a different API or from a different issuer, a token used too late or too early, one with no expiry, one without the scope the call needs, one whose scope merely begins with the right word, and input that is not a token at all.
Each maps to a rule. The unsigned token tests the algorithm allowlist, and the edited and foreign-key tokens test the signature. The other audience and other issuer test that a genuine token is accepted only where it was meant to be used, which is the confusion between APIs that RFC 8725's audience rule exists to stop.
The time tests check both edges and the missing expiry, because a token with no expiry is valid forever. The scope tests check that permission is granted by exact name. The last checks that garbage is refused rather than crashing the API.
Before the brief, here is the procedure the contract describes, drawn as the steps and decisions the code has to make.
Each check runs only after the one before it passed, and the first failure is the reason given. The algorithm is fixed by the validator, never taken from the token.
Keep it open while reading the draft: each decision in the diagram should appear as a condition in the code, and each side branch as a case the check can test.
Session: The Brief
Refuse, never raise; trust nothing firstThe brief points at the contract and adds two rules of conduct.
Write issue() and validate() in tokens.py to the contract in its docstring, standard library only. The validator is the only thing between a forged token and an API, so it must refuse anything malformed rather than raise, and must not trust anything in the token before the signature is verified, including the algorithm the header names.
A validator that raises an exception on malformed input fails in a way the caller may not expect, and an API that catches the exception badly may let the request through. The brief requires every bad token to come back as a refusal with a reason.
The second rule, trust nothing before the signature verifies, is the one that matters most and is easy to get subtly wrong: reading the expiry or the audience from an unverified payload to decide whether to bother verifying leaks information and invites mistakes.
The algorithm is the hardest case, because the validator has to look at the header to know what the token claims to be; the rule is that it compares what it reads against the one value it allows, and uses nothing else from it.
In production, token validation belongs to a well-maintained library, configured with an explicit list of allowed algorithms, issuers and audiences, not to code written for the occasion. This exercise writes the validator by hand for the same reason lesson 0.1 wrote the agent loop by hand: to know exactly what each check does, so that a library's configuration can be read and judged.
An assistant asked for token validation in a real project should be asked for the library and its configuration, and its draft read for every check this lesson's contract names.
The Draft
Decode, allow, verify, checkThe reply was the file. Here is the code below the docstring.
23import base6424import binascii25import hashlib26import hmac27import json2829HEADER = {'alg': 'HS256', 'typ': 'JWT'}303132def _enc(data):33 return base64.urlsafe_b64encode(data).rstrip(b'=').decode('ascii')343536def _dec(part):37 return base64.urlsafe_b64decode(part + '=' * (-len(part) % 4))383940def _json(obj):41 return json.dumps(obj, separators=(',', ':')).encode('utf-8')424344def _sign(signing_input, key):45 return _enc(hmac.new(key, signing_input.encode('ascii'), hashlib.sha256).digest())464748def issue(claims, key):49 signing_input = _enc(_json(HEADER)) + '.' + _enc(_json(claims))50 return signing_input + '.' + _sign(signing_input, key)515253def _refuse(reason):54 return {'ok': False, 'reason': reason, 'claims': {}, 'actor': ''}555657def validate(token, key, audience, issuer, now, scope=None):58 parts = token.split('.') if isinstance(token, str) else []59 if len(parts) != 3:60 return _refuse('not three parts')61 try:62 header = json.loads(_dec(parts[0]))63 claims = json.loads(_dec(parts[1]))64 except (binascii.Error, ValueError, UnicodeDecodeError):65 return _refuse('header or payload does not decode')66 if not isinstance(header, dict) or not isinstance(claims, dict):67 return _refuse('header or payload is not an object')68 if header.get('alg') != 'HS256':69 return _refuse(f"algorithm {header.get('alg')!r} is not allowed")70 expected = _sign(parts[0] + '.' + parts[1], key)71 if not hmac.compare_digest(expected, parts[2]):72 return _refuse('signature does not verify')73 if claims.get('iss') != issuer:74 return _refuse('wrong issuer')75 aud = claims.get('aud')76 if not (aud == audience or (isinstance(aud, list) and audience in aud)):77 return _refuse('wrong audience')78 exp = claims.get('exp')79 if not isinstance(exp, (int, float)) or not now < exp:80 return _refuse('expired or no expiry')81 nbf = claims.get('nbf')82 if nbf is not None and (not isinstance(nbf, (int, float)) or nbf > now):83 return _refuse('not yet valid')84 if scope is not None and scope not in str(claims.get('scope', '')).split():85 return _refuse(f'missing scope {scope}')86 act = claims.get('act')87 actor = act.get('sub', '') if isinstance(act, dict) else ''88 return {'ok': True, 'reason': '', 'claims': claims, 'actor': actor}
Issuing encodes a fixed header and the claims as compact JSON, base64url-encodes both without padding, and signs the two joined by a dot. Validation splits the token, decodes the header and payload, refusing anything that does not decode to JSON objects, compares the header's algorithm with the one allowed value, and recomputes the signature with the validator's own key, comparing in constant time.
Only after that does it read the claims: issuer, audience as a string or a list, expiry, not-before, and scope as a list of space-separated values. A delegated token's actor is returned separately.
The reasons are specific on purpose, and where they go matters. A validator's reason belongs in the API's own log, where it tells an engineer which check failed and tells a detection which forgeries are being tried.
The response to the caller should say little more than that the token was refused: telling an attacker that the signature verified but the audience was wrong tells them they hold a genuine token and only need to find the right API.
Run the check against the draft.
$ cp records/tokens-0.7.py lab/foundations/tokens.py
$ python3 -m lab check f07
f07 0.7 Identity for Software: lab/foundations/tokens.py
ok a correct token with the needed scope is accepted
ok
ok refused: alg none, no signature
algorithm 'none' is not allowed
ok refused: payload changed after signing
signature does not verify
ok refused: signed with another key
signature does not verify
ok refused: issued for another audience
wrong audience
ok refused: from another issuer
wrong issuer
ok refused: expired
expired or no expiry
ok refused: not yet valid
not yet valid
ok refused: no exp claim
expired or no expiry
ok refused: missing the scope asked for
missing scope hosts.isolate
ok refused: scope that only starts the same
missing scope hosts.read
ok refused: not a JWT at all
not three parts
ok issue() signs header.payload with HMAC-SHA256, base64url, no padding
ok a delegated token reports its actor
sub r.ahmed, actor svc-ir-agent
PASS
The correct token is accepted with the scope it carries, and every one of the eleven bad tokens is refused, each with the reason of the first check it failed.
The order of the reasons is the order of trust: the token that is not a token fails at the first check, the unsigned one at the algorithm, the edited and foreign ones at the signature, and only genuine tokens ever reach the claim checks, which is where the wrong audience, issuer, time and scope are caught.
The delegated token is accepted and reports both identities: the person it is for, and the agent acting.
Decoding Is Not Validating, Measured
Reading claims without the signatureMany JWT libraries offer a decode call that returns the claims without verifying anything, for debugging. Code that uses it in place of validation is a recurring token bug. Here is the draft with the algorithm and signature checks removed, which is what that mistake amounts to.
67 return _refuse('header or payload is not an object')- if header.get('alg') != 'HS256':- return _refuse(f"algorithm {header.get('alg')!r} is not allowed")- expected = _sign(parts[0] + '.' + parts[1], key)- if not hmac.compare_digest(expected, parts[2]):- return _refuse('signature does not verify')68 if claims.get('iss') != issuer:
Run the check and read the first refusals.
$ cp records/tokens-decode.py lab/foundations/tokens.py
$ python3 -m lab check f07 | sed -n "4,9p"
FAIL refused: alg none, no signature
FAIL refused: payload changed after signing
FAIL refused: signed with another key
ok refused: issued for another audience
wrong audience
ok refused: from another issuer
$ python3 -m lab check f07 | tail -n 1
FAIL
A token with no signature, a token whose payload was edited to grant a write scope, and a token signed with an attacker's key were all accepted. Every claim check still ran, and every one passed, because the attacker wrote the claims. Without the signature, the issuer, audience, expiry and scope checks are checking the attacker's own statements about themselves.
Decode-only validation usually creeps in through architecture rather than carelessness. A gateway validates tokens at the edge, and a service behind it decodes the claims to read the user, trusting that the gateway already checked.
Then a second path to the service appears, an internal route or a new deployment that skips the gateway, and the service is accepting unverified tokens without any line of its own code having changed. Each service that makes a decision from a token's claims should verify the token itself.
A Scope That Resembles, Measured
Substring against membershipThe second shortcut is smaller and survives code review more often. The scope claim is a space-separated list; the shortcut checks whether the required scope appears anywhere in it as text.
- if scope is not None and scope not in str(claims.get('scope', '')).split():84+ if scope is not None and scope not in str(claims.get('scope', '')):
Run the check and read the scope line.
$ cp records/tokens-substr.py lab/foundations/tokens.py
$ python3 -m lab check f07 | grep -A1 "only starts"
FAIL refused: scope that only starts the same
ok refused: not a JWT at all
A token whose scope is hosts.readall was granted hosts.read, because the text hosts.read appears inside it. In a real system the granted scope might be one the API never meant to define, or one an attacker could get issued for a different purpose; either way, a permission was granted by resemblance. Splitting the claim into its values and testing membership, as the draft does, grants only what was named.
Scopes are also where an agent's least privilege is written down. A hunting agent needs hosts.read and process.read and nothing else; a response agent needs hosts.isolate, and arguably only for the duration of an approved action.
Designing scopes narrowly enough to express that, and issuing each agent only the ones its job needs, is the same principle as lesson 0.4's single tool and Module 1's read-only hunt, enforced by the API rather than by the agent's own code.
Acting As, and Acting For
Application and delegated tokensAn agent can hold two kinds of token, and the difference decides what it can do and what the audit trail says. This script issues both for the same scope and validates them.
$ cp records/tokens-0.7.py lab/foundations/tokens.py
$ python3 delegate.py
application token ok True sub svc-ir-agent actor -
delegated token ok True sub r.ahmed actor svc-ir-agent
The application token identifies the agent itself: its subject is the agent's service identity, and anything it does is done on its own authority. The delegated token identifies a person, r.ahmed, with an act claim naming the agent as the party acting for her.
RFC 8693, OAuth 2.0 Token Exchange, defines that claim and the exchange that produces it: a client presents the token of the party it acts for, and its own, to the identity provider and receives a new one.
The RFC distinguishes impersonation, where the acting party becomes indistinguishable from the person within the token's scope, from delegation, where it keeps its own identity and every action is visibly taken by the agent on the person's behalf.
For agents the difference is not academic. An application token's permissions are the agent's, granted once, used for every request, whoever asked for it; an agent with broad application permissions that is steered by injected text acts with all of them. A delegated token carries the person's permissions, usually narrowed further, and the API can see both who asked and who acted.
Impersonation is the riskier of the two for the same reason it is convenient. A token that makes the agent indistinguishable from the person lets the agent do anything the person can, with nothing in the API's records to say a person did not do it.
If the agent is steered into a harmful action, the logs blame the person. Delegation keeps both names on every action, which is what an investigation needs, and what lesson 0.5's ledger needed too: who decided, and who acted, recorded separately.
Module 7 decides between the two on evidence, case by case, and the default it argues for is the narrowest token that does the job, delegated where a person is in the loop.
One rule about tokens is specific to agents and easy to break. A token belongs to the code that calls the API, never to the model. If an agent's token appears anywhere in the model's context, in a system prompt, a tool result or an error message, then any injected instruction that can make the model repeat its context can make it reveal the token.
The tool layer holds the credential and attaches it to outgoing calls; the model asks for an action and never sees what authorizes it. Lesson 0.1's inventory of every message the model receives is where to check that this holds.
From the Validator to Module 7
What the review carries forwardThe session record keeps what held, the two shortcuts and what each accepted, and what the lab simplified.
1# Session 0.7: a token issuer and validator23Assistant: Claude Opus 5.5 (claude-opus-5-5), the SEC410 build session, 2026-11-1845## Held6- The header's alg is compared with the one allowed value7 before anything else in the token is used.8- Signature verified in constant time before any claim is read.9- iss, aud, exp, nbf and scope checked in that order; malformed10 input refused with a reason, never raised.11- check f07: PASS, eleven forgeries and mistakes refused.1213## Measured14- Decode without verifying: alg none, a changed payload and a15 foreign key were all accepted.16- Scope as a substring: hosts.readall granted hosts.read.1718## For Module 719- One shared key signs and verifies: anything that can check a20 token can mint one. Real identity providers sign with a21 private key and publish the public one.
The shared key is the simplification that matters. With HS256, the same key signs and verifies, so every API that can validate a token can also mint one, and a leaked key from any of them forges tokens for all.
Real identity providers sign with a private key that never leaves them and publish the matching public key, so APIs can verify without being able to issue. Module 7's mock identity provider works that way, with keys that rotate and tokens that live minutes, and the practice's stretch goal adds asymmetric signing to this validator.
Keys also change. An identity provider rotates its signing keys, publishing new public keys before it starts using them, and a token's header names which key signed it so the validator can pick the right one.
That header field is another unverified claim: the validator uses it only to choose among keys it already trusts, never to fetch a key from wherever the token says. Module 7's validator handles rotation, and its tests include a token pointing at a key the validator has never seen.
Practice
A token issuer and validator the labBrief your assistant with the contract and the rules of conduct, check the draft, take a token apart, then reproduce both shortcuts and record what each one let through.
1# Practice 0.7: a token issuer and validator23## Done when4- [ ] lab/foundations/tokens.py meets its docstring's contract5- [ ] python -m lab check f07 prints PASS6- [ ] decode.py run: every claim in the payload explained7- [ ] both shortcuts reproduced; what each accepted recorded8- [ ] records/0.7-<assistant>.md: brief, draft, runs, review910## Constraints11- Nothing in a token is used before its signature verifies.12- The allowed algorithm comes from the caller, never the token.1314## Stretch15- Add RS256 with the cryptography package: sign with a private16 key, validate with the public one, and refuse HS256.
A JWT carries claims about who a piece of software is, which API the token is for, what it permits and until when, signed so a receiver can tell it was not altered. A validator allows only the algorithm it chose, verifies the signature before reading anything else, and then checks the issuer, audience, time limits and scope.
Decoding without verifying accepted forged and unsigned tokens; checking scope as a substring granted a permission by resemblance. An agent acting as itself and an agent acting for a person hold different tokens, and the difference decides both its reach and its audit trail.