# Enforce downscoping in token exchange for agent-to-agent calls

> A Keycloak lab for A2A agents: the token B gets for C follows B's own scopes, not A's, unless you enforce downscoping. Stock run, control run and the fix.

- URL: https://iamops.dev/enforce-downscoping-token-exchange-a2a/
- Language: en
- Author: Argo
- Published: 2026-11-20
- Category: Labs
- Topics: Token Exchange, Keycloak, A2A, RFC 8693, AI agents

## TL;DR

- When agent B calls agent C for agent A, B swaps A's token for a new one. On Keycloak 26.8.2 the scope of that new token follows B's own scopes, not the token A handed over, unless you enforce downscoping.
- In my run A held c.read, B held c.write as an optional scope of its own, and B's exchange returned a token for A with c.write. Agent C accepted a write that A never granted.
- That is B using a right it has, not B breaking out. With c.write removed from B the same exchange fails with invalid_scope. This is a configuration lesson, not a vulnerability.
- One client policy with the executor downscope-assertion-grant-enforcer bounds the exchange to A's scopes. Agent C should also require an act claim and check scope per skill.
- I only tested Keycloak. A2A 1.0.0 leaves authorization to the implementation, and the Agent Card has no field for token exchange.

A2A 1.0.0 is the current release of the Agent2Agent protocol. It says a server must authenticate every request and that authorization is up to the implementation. It does not say what happens when agent B calls agent C on behalf of agent A. That part is plain OAuth, and the usual tool is token exchange ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693)). I built a small chain on a local Keycloak and asked one question: does the token B gets for C stay inside what A handed over?

It does not, unless you ask Keycloak to enforce it. This post is about that setting. If you read my [first Keycloak token exchange lab](https://iamops.dev/keycloak-token-exchange-rfc-8693/), this one picks up where its "no act claim" gotcha left off and adds delegation.

## What this lab shows

Three agents and one authorization server, all on localhost.

- **A** is the caller. It holds a token with scope `agent-b c.read`. A `may_act` claim in that token names B as the party that may act for it.
- **B** is an agent in the middle. It receives A's call, then asks Keycloak for a token to call C, using A's token as `subject_token` and its own token as `actor_token`.
- **C** is a small notes agent with a read skill and a write skill. It accepts only delegated tokens and checks the scope per skill.

| Client | Role | Scopes it can ask for in an exchange |
| --- | --- | --- |
| `agent-a` | Caller, service account | `agent-b` by default, `c.read` when it asks |
| `agent-b` | Middle agent, performs the exchange | `c.read` and `c.write`, both optional |
| `agent-c` | Notes agent, audience only | none |

![Sequence diagram: agent A reads the Agent Card of B, gets a token from Keycloak, calls B, and B swaps it for a delegated token with an act claim before calling C.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/00-flow.webp)

*The chain. Steps 1 to 4 are A calling B. Steps 5 to 7 are B turning A's token into a delegated token. Steps 8 to 10 are the call to C.*

Each agent publishes an Agent Card at `/.well-known/agent-card.json` with an `oauth2` security scheme and the scopes per skill. The scheme can say `clientCredentials` and nothing closer to token exchange: an `OAuthFlows` object holds exactly one flow, and there is no exchange flow. So C's card says it in the description text, and a caller has to read it.

## Setup

Keycloak 26.8.2 from the zip, Java 21, development mode. Standard token exchange is on by default in 26.8. Delegation, meaning the `act` and `may_act` claims, is not. It needs two preview features.

```bash
"$KC_HOME/bin/kc.sh" start-dev --http-port 8080 --features=token-exchange-delegation,parameterized-scopes
```

Keycloak prints the preview features it enabled at startup. I enabled the two together and did not test them one by one. Without them my chain fails: Keycloak refuses any subject token that carries `may_act` in a plain exchange, with "Subject token with a delegation claim is not allowed for standard token exchange".

![Terminal output of Keycloak 26.8.2 starting with the preview features parameterized-scopes and token-exchange-delegation enabled, followed by the realm script reporting realm a2a ready.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/01-features.webp)

*Features and realm. Keycloak 26.8.2 with two preview features on, then the realm script.*

The realm script creates the three clients with service accounts, the scopes `agent-b`, `c.read` and `c.write` (each with an audience mapper), and a hard-coded `may_act` mapper on `agent-a`. It also switches on Standard Token Exchange for `agent-b` and gives `agent-b` the scopes `c.read` and `c.write` as optional client scopes. Remember that last part. The whole post turns on it.

## The call chain works

A reads B's card, asks Keycloak for exactly the scopes the skill lists and sends `message:send`. B exchanges the token and calls C. The decoded delegated token keeps A as `sub`, narrows `aud` to C, carries only `c.read` and adds `act` for B.

![Terminal output of agent A reading the Agent Card of B, requesting the scopes agent-b and c.read, and getting a 200 answer from B that summarises two notes held by C.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/02-chain.webp)

*The legitimate path. A asks B to summarise the notes. B exchanges A's token and reads them from C.*

## The exchange that A never granted

Now B asks for `c.write`. A's token has no `c.write`. This is the request, with placeholders:

```bash
curl -s "$KC_URL/realms/a2a/protocol/openid-connect/token" \
  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
  -d client_id=agent-b -d "client_secret=$AGENT_B_SECRET" \
  -d subject_token="$A_TOKEN" -d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
  -d actor_token="$B_TOKEN" -d actor_token_type=urn:ietf:params:oauth:token-type:access_token \
  -d audience=agent-c -d scope=c.write
```

Keycloak issues the token. `sub` is A, `act` names B, `scope` is `c.write`. C checks signature, audience, the `act` claim and the scope its write skill needs, and adds the note.

![Terminal output on stock Keycloak: agent B lists c.write among its optional scopes, A's token has scope agent-b c.read, the token B gets for agent C has scope c.write with act agent-b, and C answers that the note was added.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/03-stock.webp)

*Stock Keycloak. A's token says c.read. The token for C says c.write. C adds the note. Ids are replaced by placeholders.*

I ran the whole sequence four times on a fresh Keycloak 26.8.2, twice with the lab scripts and twice with the ones in this post, and got the same result each time.

## The control: B holds c.write

Before calling this an escalation I checked whose right is being used. In my realm B holds `c.write` as an optional scope of its own. I put it there. So B did not get something it was never allowed to have. I removed `c.write` from B's optional scopes and ran the same exchange.

![Terminal output of the control run: after c.write is deleted from the optional client scopes of agent B, the same exchange is refused with invalid_scope, Invalid scopes: c.write.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/04-control.webp)

*The control. Without c.write on B, nothing is issued. B stays inside its own rights.*

That settles one thing. B cannot go beyond what it holds itself, and nothing here is a bug in the sense of a bypass. What went missing is something else: the scope of the new token is bounded by B's scope pool and not by A's token. A said "read", and that stopped meaning anything one hop later. RFC 8693 leaves this to the server: `scope` is "the desired scope of the requested security token" and its values are "service specific" ([section 2.1](https://www.rfc-editor.org/rfc/rfc8693#section-2.1)). Nothing requires the result to be a subset of the subject token.

It matters for agents because C logs `sub` A and `act` B. Whoever reads the log sees "A wrote a note". A never agreed to that.

## Bound the exchange with the downscope policy

Keycloak has a client policy executor for exactly this: `downscope-assertion-grant-enforcer`. It limits the scopes of the new token to those already in the subject token and answers `invalid_scope` otherwise. It takes no configuration. I applied it to every client in the realm with one policy.

```json
{"profiles":[{"name":"downscope-only","description":"exchange can narrow, never widen",
  "executors":[{"executor":"downscope-assertion-grant-enforcer","configuration":{}}]}]}
```

With `c.write` back on B and the policy on, the exchange is refused. The legitimate `c.read` exchange still works.

![Terminal output with the downscope policy active: the c.write exchange is refused because c.write is not present in the initial access token, and the c.read exchange still returns a delegated token that C accepts.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/05-enforcer.webp)

*With the policy. c.write is refused because A's token does not carry it. c.read still works. C lists the note from the stock run too.*

The last line of that output is the note that the stock run added. It stays until you restart C.

## What C should check as well

The policy lives on the authorization server. C should not depend on it alone.

- Require the `act` claim and check `act.client_id` against the agents you expect. My C answers 403 without it.
- Check the scope per skill. My C needs `c.read` to read and `c.write` to write.
- Check `aud`. A token for B is refused at C with 401.
- Do not treat `may_act` as proof. When B presented C's token as the actor, Keycloak refused with an audience message. I did not isolate whether it compares the actor with `may_act`.

## Gotchas

- **The enforcer and a client-level audience mapper.** My first setup put C's audience in a mapper on client B. With the enforcer on, every exchange then failed with "Requested audience not available: agent-c". Moving the mapper to the `c.read` and `c.write` scopes fixed it. I do not know why. Test it in your own realm.
- **Audience by scope has a side effect.** `c.read` carries C's audience, so A's own token gets `aud` B and C. The thing that stops A from using it at C is the `act` requirement, not the audience.
- **The wrong-actor error is vague.** The client sees `access_denied` and "Client is not within the token audience". The Keycloak event log names the actor.
- **`may_act` is hard-coded in my realm.** In a real system it should come from policy and live with the token.

## What was not run

I only ran Keycloak 26.8.2. I did not test Entra on-behalf-of, Okta or Auth0, so I make no claim about how they bound scope in an exchange. One hop of delegation only: no nested `act` chain. No tasks, streaming or signed Agent Cards, no TLS and no sender-constrained tokens. No user in the chain: the subject is agent A's service account. The agents are my own Flask programs, and their client secrets are static lab values.

*Terminal images were rendered from the saved output of the runs, with ids replaced by placeholders. Nothing here is a real credential.*

For the standards behind it, see [ID-JAG explained](https://iamops.dev/id-jag-explained/) and [why an MCP server must not pass tokens through](https://iamops.dev/mcp-server-no-token-passthrough/).

## Repeat this lab

About 40 minutes on a laptop: a local Keycloak with two preview features, one realm script, three small agents in Python, and three exchanges: stock, control and with the downscope policy. Open each step, copy the blocks and compare your output with the expected output.

Every value in angle brackets is a placeholder for your own test environment. Nothing on this page is a real identifier or secret.

**Set your variables once** `env.sh` (bash)

```bash
# Paste into every terminal you use for this lab. Replace each <PLACEHOLDER> with a throwaway value of your own.
export KC_HOME='<KEYCLOAK_DIR>'          # the unpacked keycloak-26.8.2 folder
export JAVA_HOME='<JDK_DIR>'             # a JDK 21
export KC_URL="http://localhost:8080"
export KC_ADMIN_USER="admin"
export KC_ADMIN_PASSWORD='<ADMIN_PASSWORD>'
export AGENT_A_SECRET='<AGENT_A_SECRET>'
export AGENT_B_SECRET='<AGENT_B_SECRET>'
export AGENT_C_SECRET='<AGENT_C_SECRET>'
```

### Step 1: Start Keycloak with the delegation features

**Goal.** Run a local authorization server with token-exchange-delegation and parameterized-scopes, the two preview features that add the act claim.

**Prerequisites**

- Keycloak 26.8.2 unpacked and a JDK 21; curl and Python 3.10 or newer
- Port 8080 free; keep this terminal open and use a second one for the next steps

`start-keycloak.sh` (bash)

```bash
export KC_BOOTSTRAP_ADMIN_USERNAME="$KC_ADMIN_USER" KC_BOOTSTRAP_ADMIN_PASSWORD="$KC_ADMIN_PASSWORD"
"$KC_HOME/bin/kc.sh" start-dev --http-port 8080 --features=token-exchange-delegation,parameterized-scopes
```

**Expected output**

```text
INFO  [org.keycloak.common.Profile] (main) Preview features enabled: parameterized-scopes:v1, token-exchange-delegation:v1
WARN  [org.keycloak.common.Profile] (main) Deprecated features identity-brokering-api:v1, twitter-broker:v1 enabled by default. Check the upgrading guide for steps to use later versions if available.
INFO  [io.quarkus] (main) Keycloak 26.8.2 on JVM (powered by Quarkus 3.40.1.1) started in 16.223s. Listening on: http://localhost:8080
```

### Step 2: Create the realm, the clients and the may_act claim

**Goal.** Build realm a2a: three clients with service accounts, three scopes with audiences, and a mapper that puts may_act in A’s token. B gets c.read and c.write as optional scopes.

**Prerequisites**

- The env block set in this terminal; Keycloak from the previous step still running
- The script takes about a minute because it trims the default scopes of each client

`kc-realm.sh` (bash)

```bash
#!/usr/bin/env bash
# Realm "a2a": three agents as clients with service accounts, scopes with audiences, and a may_act claim that names the actor.
set -euo pipefail
: "${KC_HOME:?}" "${JAVA_HOME:?}" "${KC_ADMIN_PASSWORD?}" "${AGENT_A_SECRET:?}" "${AGENT_B_SECRET:?}" "${AGENT_C_SECRET:?}"
KCADM="$KC_HOME/bin/kcadm.sh"
$KCADM config credentials --server "${KC_URL:-http://localhost:8080}" --realm master --user "${KC_ADMIN_USER:-admin}" --password "$KC_ADMIN_PASSWORD" >/dev/null
$KCADM create realms -s realm=a2a -s enabled=true -s sslRequired=none >/dev/null
scope() { # name audience
  $KCADM create client-scopes -r a2a -s name="$1" -s protocol=openid-connect -s 'attributes."include.in.token.scope"=true' >/dev/null
  local id; id=$($KCADM get client-scopes -r a2a --fields id,name --format csv --noquotes | awk -F, -v n="$1" '$2==n{print $1}')
  $KCADM create client-scopes/$id/protocol-mappers/models -r a2a -s name="aud-$2" -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper \
    -s "config.\"included.client.audience\"=$2" -s 'config."access.token.claim"=true' -s 'config."id.token.claim"=false' >/dev/null
  echo "$id"
}
S_B=$(scope agent-b agent-b); S_CR=$(scope c.read agent-c); S_CW=$(scope c.write agent-c)
agent() { # client id, secret
  $KCADM create clients -r a2a -s clientId="$1" -s secret="$2" -s publicClient=false -s serviceAccountsEnabled=true \
    -s standardFlowEnabled=false -s directAccessGrantsEnabled=false >/dev/null
  $KCADM get clients -r a2a -q clientId="$1" --fields id --format csv --noquotes
}
A=$(agent agent-a "$AGENT_A_SECRET"); B=$(agent agent-b "$AGENT_B_SECRET"); C=$(agent agent-c "$AGENT_C_SECRET")
# keep the tokens small: drop the default profile, email and roles scopes from every agent
for CID in $A $B $C; do
  for SN in roles profile email web-origins acr basic; do
    SID=$($KCADM get client-scopes -r a2a --fields id,name --format csv --noquotes | awk -F, -v n="$SN" '$2==n{print $1}')
    [ -n "$SID" ] && $KCADM delete clients/$CID/default-client-scopes/$SID -r a2a >/dev/null 2>&1 || true
  done
done
# agent-b performs the exchange
$KCADM update clients/$B -r a2a -s 'attributes."standard.token.exchange.enabled"=true' >/dev/null
SA_B=$($KCADM get clients/$B/service-account-user -r a2a --fields id --format csv --noquotes)
# agent-a: may call agent-b by default, may add c.read when it asks for it
$KCADM update clients/$A/default-client-scopes/$S_B -r a2a >/dev/null
$KCADM update clients/$A/optional-client-scopes/$S_CR -r a2a >/dev/null
# the claim value is JSON, so pass the mapper as a file; kcadm -s cannot carry nested quotes
MAP=$(mktemp)
cat > "$MAP" <<JSON
{"name":"may-act-agent-b","protocol":"openid-connect","protocolMapper":"oidc-hardcoded-claim-mapper",
 "config":{"claim.name":"may_act","claim.value":"{\"sub\":\"$SA_B\",\"client_id\":\"agent-b\"}","jsonType.label":"JSON",
           "access.token.claim":"true","id.token.claim":"false"}}
JSON
$KCADM create clients/$A/protocol-mappers/models -r a2a -f "$MAP" >/dev/null; rm -f "$MAP"
# agent-b: its own token is the actor token; c.read and c.write are optional scopes it can ask for in an exchange
$KCADM update clients/$B/optional-client-scopes/$S_CR -r a2a >/dev/null
$KCADM update clients/$B/optional-client-scopes/$S_CW -r a2a >/dev/null
echo "realm a2a ready"
```

`create-realm.sh` (bash)

```bash
chmod +x kc-realm.sh
./kc-realm.sh 2>&1 | grep -v "^Created\|^Logging"
```

**Expected output**

```text
realm a2a ready
```

### Step 3: Save and start agent B and agent C

**Goal.** Four small Python files: a shared library, agent C (notes, accepts delegated tokens only), agent B (does the exchange) and agent A (the caller). Start B and C and read C’s Agent Card.

**Prerequisites**

- Python 3.10 or newer; ports 19402 and 19403 free
- Save the four files in one folder, the same folder as kc-realm.sh

`a2alib.py` (python)

```python
import json, os, urllib.error, urllib.parse, urllib.request, uuid
import jwt
from flask import Flask, Response, request

KC_URL = os.environ.get("KC_URL", "http://localhost:8080")
ISS = f"{KC_URL}/realms/a2a"
TOKEN_URL = f"{ISS}/protocol/openid-connect/token"
JWKS = jwt.PyJWKClient(f"{ISS}/protocol/openid-connect/certs")
MEDIA = "application/a2a+json"
AT = "urn:ietf:params:oauth:token-type:access_token"


class Reject(Exception):
    def __init__(self, http, status, reason, message):
        self.http, self.status, self.reason, self.message = http, status, reason, message


def error_body(r):
    return {"error": {"code": r.http, "status": r.status, "message": r.message,
                      "details": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": r.reason, "domain": "a2a-protocol.org"}]}}


def verify(auth_header, my_audience):
    if not auth_header or not auth_header.lower().startswith("bearer "):
        raise Reject(401, "UNAUTHENTICATED", "MISSING_TOKEN", "bearer token required")
    token = auth_header[7:].strip()
    try:
        key = JWKS.get_signing_key_from_jwt(token).key
        return jwt.decode(token, key, algorithms=["RS256"], audience=my_audience, issuer=ISS,
                          options={"require": ["exp", "iss", "aud", "sub"]})
    except jwt.InvalidAudienceError:
        raise Reject(401, "UNAUTHENTICATED", "WRONG_AUDIENCE", f"token is not meant for {my_audience}")
    except jwt.PyJWTError as e:
        raise Reject(401, "UNAUTHENTICATED", "INVALID_TOKEN", f"token rejected: {type(e).__name__}")


def scopes(claims):
    return set((claims.get("scope") or "").split())


def secret_of(client_id):
    return os.environ[client_id.upper().replace("-", "_") + "_SECRET"]


def post_form(data):
    req = urllib.request.Request(TOKEN_URL, data=urllib.parse.urlencode(data).encode())
    try:
        with urllib.request.urlopen(req) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        return {"http_status": e.code, **json.load(e)}


def client_credentials(client_id, scope=None):
    d = {"grant_type": "client_credentials", "client_id": client_id, "client_secret": secret_of(client_id)}
    if scope:
        d["scope"] = scope
    return post_form(d)


def exchange(client_id, subject_token, actor_token, audience, scope):
    d = {"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", "client_id": client_id,
         "client_secret": secret_of(client_id), "subject_token": subject_token, "subject_token_type": AT,
         "audience": audience, "scope": scope}
    if actor_token:
        d.update(actor_token=actor_token, actor_token_type=AT)
    return post_form(d)


def fetch_card(base):
    with urllib.request.urlopen(f"{base}/.well-known/agent-card.json") as r:
        return json.load(r)


def send_message(base, token, text):
    body = {"message": {"messageId": str(uuid.uuid4()), "role": "ROLE_USER", "parts": [{"text": text}]}}
    h = {"Content-Type": MEDIA, "A2A-Version": "1.0"}
    if token:
        h["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(f"{base}/message:send", data=json.dumps(body).encode(), headers=h, method="POST")
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)


def reply(text):
    return {"message": {"messageId": str(uuid.uuid4()), "role": "ROLE_AGENT", "parts": [{"text": text}]}}


def claims_unverified(token):
    import base64
    p = token.split(".")[1]
    return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))


def serve(name, port, card, handle):
    app = Flask(name)
    out = lambda obj, status=200: Response(json.dumps(obj), status=status, mimetype=MEDIA)
    app.get("/.well-known/agent-card.json")(lambda: out(card))

    @app.post("/message:send")
    def send():
        try:
            return out(reply(handle(request)))
        except Reject as r:
            print(f"AUDIT {name}: DENIED {r.http} {r.reason}", flush=True)
            return out(error_body(r), r.http)
    app.run(port=port)
```

`agent_c.py` (python)

```python
import os
from a2alib import *

PORT = int(os.environ.get("C_PORT", "19403"))
NOTES = ["note 1: quarterly review is on Thursday", "note 2: renew the staging certificate"]
need = lambda s: [{"schemes": {"keycloak": {"list": [s]}}}]
CARD = {
    "name": "agent-c notes", "description": "Keeps a short list of notes. Reads and writes need a delegated token.", "version": "1.0.0",
    "supportedInterfaces": [{"url": f"http://localhost:{PORT}", "protocolBinding": "HTTP+JSON", "protocolVersion": "1.0"}],
    "capabilities": {"streaming": False, "pushNotifications": False},
    "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"],
    "securitySchemes": {"keycloak": {"oauth2SecurityScheme": {
        "description": "Tokens come from Keycloak via RFC 8693 token exchange, with an actor token. The scheme types below cannot say that, so this text does.",
        "oauth2MetadataUrl": f"{ISS}/.well-known/oauth-authorization-server",
        "flows": {"clientCredentials": {"tokenUrl": TOKEN_URL, "scopes": {"c.read": "read notes", "c.write": "add notes"}}}}}},

    "skills": [
        {"id": "read-notes", "name": "Read notes", "description": "Say 'read' to get all notes.", "tags": ["notes"], "securityRequirements": need("c.read")},
        {"id": "add-note", "name": "Add a note", "description": "Say 'write: <text>' to add one.", "tags": ["notes"], "securityRequirements": need("c.write")}],
}

def handle(req):
    c = verify(req.headers.get("Authorization"), "agent-c")
    act = c.get("act") or {}
    if act.get("client_id") != "agent-b":
        raise Reject(403, "PERMISSION_DENIED", "ACTOR_REQUIRED", "a delegated token from agent-b is required")
    text = req.get_json(force=True)["message"]["parts"][0]["text"].strip()
    skill = "c.write" if text.startswith("write:") else "c.read"
    if skill not in scopes(c):
        raise Reject(403, "PERMISSION_DENIED", "INSUFFICIENT_SCOPE", f"skill needs scope {skill}")
    print(f"AUDIT c: sub={c['sub'][:8]} actor={act['client_id']} scope='{c.get('scope')}' skill={skill}", flush=True)
    if skill == "c.write":
        NOTES.append(text[6:].strip())
        return f"added, {len(NOTES)} notes now"
    return "\n".join(NOTES)

serve("c", PORT, CARD, handle)
```

`agent_b.py` (python)

```python
import os
from a2alib import *

PORT, C_BASE = int(os.environ.get("B_PORT", "19402")), os.environ.get("C_BASE", "http://localhost:19403")
need = lambda *s: [{"schemes": {"keycloak": {"list": list(s)}}}]
CARD = {
    "name": "agent-b summariser", "description": "Reads the notes through agent C and sums them up.", "version": "1.0.0",
    "supportedInterfaces": [{"url": f"http://localhost:{PORT}", "protocolBinding": "HTTP+JSON", "protocolVersion": "1.0"}],
    "capabilities": {"streaming": False, "pushNotifications": False},
    "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"],
    "securitySchemes": {"keycloak": {"oauth2SecurityScheme": {
        "oauth2MetadataUrl": f"{ISS}/.well-known/oauth-authorization-server",
        "flows": {"clientCredentials": {"tokenUrl": TOKEN_URL, "scopes": {"agent-b": "call agent B", "c.read": "allow B to read notes for you"}}}}}},

    "skills": [{"id": "summarize", "name": "Summarise notes", "description": "Say 'summarize'.", "tags": ["notes"], "securityRequirements": need("agent-b", "c.read")}],
}

def handle(req):
    bearer = req.headers.get("Authorization")
    c = verify(bearer, "agent-b")
    for s in ("agent-b", "c.read"):
        if s not in scopes(c):
            raise Reject(403, "PERMISSION_DENIED", "INSUFFICIENT_SCOPE", f"skill needs scope {s}")
    actor = client_credentials("agent-b")["access_token"]
    ex = exchange("agent-b", bearer[7:].strip(), actor, audience="agent-c", scope="c.read")
    if "access_token" not in ex:
        raise Reject(502, "UNAVAILABLE", "EXCHANGE_FAILED", f"token exchange refused: {ex.get('error_description')}")
    print(f"AUDIT b: exchanged for sub={c['sub'][:8]} scope='{ex['scope']}'", flush=True)
    code, body = send_message(C_BASE, ex["access_token"], "read")
    if code != 200:
        raise Reject(502, "UNAVAILABLE", "DOWNSTREAM_REFUSED", f"agent C said {code}")
    notes = body["message"]["parts"][0]["text"].splitlines()
    return f"{len(notes)} notes. First: {notes[0]}"

serve("b", PORT, CARD, handle)
```

`agent_a.py` (python)

```python
import json, sys
from a2alib import *

B = "http://localhost:19402"
card = fetch_card(B)
skill = card["skills"][0]
want = skill["securityRequirements"][0]["schemes"]["keycloak"]["list"]
flow = card["securitySchemes"]["keycloak"]["oauth2SecurityScheme"]["flows"]["clientCredentials"]
print(f"card says: skill '{skill['id']}' needs scopes {want}, token endpoint {flow['tokenUrl'].split('/realms/')[1]}")
tok = client_credentials("agent-a", " ".join(want))
claims = claims_unverified(tok["access_token"])
print(f"token: aud={claims['aud']} scope='{claims['scope']}' may_act={claims['may_act']['client_id']}")
code, body = send_message(B, tok["access_token"], sys.argv[1] if len(sys.argv) > 1 else "summarize")
print(code, body["message"]["parts"][0]["text"] if code == 200 else json.dumps(body))
```

`start-agents.sh` (bash)

```bash
python3 -m venv .venv && . .venv/bin/activate
pip install -q "PyJWT==2.15.1" "Flask==3.1.3" "cryptography==50.0.2"
nohup python3 agent_c.py > c.log 2>&1 &
nohup python3 agent_b.py > b.log 2>&1 &
sleep 3
curl -s localhost:19403/.well-known/agent-card.json | python3 -c "import sys,json;c=json.load(sys.stdin);print(c['name']);print(list(c['securitySchemes']));print(c['skills'][0]['securityRequirements'])"
```

**Expected output**

```text
agent-c notes
['keycloak']
[{'schemes': {'keycloak': {'list': ['c.read']}}}]
```

### Step 4: Call the chain as agent A

**Goal.** A reads B’s card, asks Keycloak for the scopes the skill lists and sends one message. B swaps A’s token for a token for C and reads the notes.

**Prerequisites**

- Steps 1 to 3 done, in the same virtual environment

`call-chain.sh` (bash)

```bash
python3 agent_a.py
```

**Expected output**

```text
card says: skill 'summarize' needs scopes ['agent-b', 'c.read'], token endpoint a2a/protocol/openid-connect/token
token: aud=['agent-c', 'agent-b'] scope='agent-b c.read' may_act=agent-b
200 2 notes. First: note 1: quarterly review is on Thursday
```

### Step 5: Ask for c.write on stock Keycloak

**Goal.** B exchanges A’s token and asks for c.write. A’s token only has c.read. Read B’s optional scopes first, then watch what Keycloak issues and what C does with it.

**Prerequisites**

- Steps 1 to 4 done; this is the stock configuration, no policy yet
- Save escal.py from the block below next to the other files

`escal.py` (python)

```python
import json, sys
from a2alib import *

scope = sys.argv[1]
KEYS = ("aud", "scope", "azp", "sub", "may_act", "act")
show = lambda t: json.dumps({k: claims_unverified(t)[k] for k in KEYS if k in claims_unverified(t)}, indent=1)
a = client_credentials("agent-a", "agent-b c.read")["access_token"]
b = client_credentials("agent-b")["access_token"]
print("## A's token\n" + show(a))
ex = exchange("agent-b", a, b, "agent-c", scope)
if "access_token" not in ex:
    sys.exit(f"exchange refused: {ex['error']} - {ex['error_description']}")
print("## token B got for C\n" + show(ex["access_token"]))
text = "write: evidence note" if scope == "c.write" else "read"
code, body = send_message("http://localhost:19403", ex["access_token"], text)
print("C says:", body["message"]["parts"][0]["text"] if code == 200 else f"{code} {body['error']['details'][0]['reason']}")
```

`stock-exchange.sh` (bash)

```bash
KCADM="$KC_HOME/bin/kcadm.sh"
$KCADM config credentials --server "$KC_URL" --realm master --user "$KC_ADMIN_USER" --password "$KC_ADMIN_PASSWORD"
B_ID=$($KCADM get clients -r a2a -q clientId=agent-b --fields id --format csv --noquotes)
CW_ID=$($KCADM get client-scopes -r a2a --fields id,name --format csv --noquotes | awk -F, '$2=="c.write"{print $1}')
$KCADM get clients/$B_ID/optional-client-scopes -r a2a --fields name --format csv --noquotes | tr '\n' ' '; echo
python3 escal.py c.write
```

**Expected output**

```text
address delegation:user phone offline_access organization delegation:client microprofile-jwt c.read c.write 
## A's token
{
 "aud": [
  "agent-c",
  "agent-b"
 ],
 "scope": "agent-b c.read",
 "azp": "agent-a",
 "sub": "<A-ID>",
 "may_act": {
  "sub": "<B-ID>",
  "client_id": "agent-b"
 }
}
## token B got for C
{
 "aud": "agent-c",
 "scope": "c.write",
 "azp": "agent-b",
 "sub": "<A-ID>",
 "act": {
  "sub": "<B-ID>",
  "client_id": "agent-b"
 }
}
C says: added, 3 notes now
```

### Step 6: Control: take c.write away from B

**Goal.** Remove c.write from B’s optional scopes and repeat the same exchange. If it fails, B was using a right it holds. Then put the scope back.

**Prerequisites**

- Step 5 done
- The commands log in again, so any terminal with the env block works

`control.sh` (bash)

```bash
KCADM="$KC_HOME/bin/kcadm.sh"
$KCADM config credentials --server "$KC_URL" --realm master --user "$KC_ADMIN_USER" --password "$KC_ADMIN_PASSWORD"
B_ID=$($KCADM get clients -r a2a -q clientId=agent-b --fields id --format csv --noquotes)
CW_ID=$($KCADM get client-scopes -r a2a --fields id,name --format csv --noquotes | awk -F, '$2=="c.write"{print $1}')
$KCADM delete clients/$B_ID/optional-client-scopes/$CW_ID -r a2a
python3 escal.py c.write
$KCADM update clients/$B_ID/optional-client-scopes/$CW_ID -r a2a
```

**Expected output**

```text
exchange refused: invalid_scope - Invalid scopes: c.write
```

### Step 7: Turn on the downscope policy

**Goal.** Add one client policy with the executor downscope-assertion-grant-enforcer, then repeat the c.write exchange and the legitimate c.read exchange.

**Prerequisites**

- Step 6 done, with c.write back on B

`kc-downscope.sh` (bash)

```bash
#!/usr/bin/env bash
# Client policy: every token exchange in realm a2a may only carry scopes that were already in the subject token.
set -euo pipefail
: "${KC_HOME:?}" "${JAVA_HOME:?}" "${KC_ADMIN_PASSWORD?}"
KCADM="$KC_HOME/bin/kcadm.sh"
$KCADM config credentials --server "${KC_URL:-http://localhost:8080}" --realm master --user "${KC_ADMIN_USER:-admin}" --password "$KC_ADMIN_PASSWORD" >/dev/null
TMP=$(mktemp)
cat > "$TMP" <<'JSON'
{"profiles":[{"name":"downscope-only","description":"exchange can narrow, never widen",
  "executors":[{"executor":"downscope-assertion-grant-enforcer","configuration":{}}]}]}
JSON
$KCADM update client-policies/profiles -r a2a -f "$TMP"
cat > "$TMP" <<'JSON'
{"policies":[{"name":"all-clients-downscope","description":"applies to every client in the realm","enabled":true,
  "conditions":[{"condition":"any-client","configuration":{}}],"profiles":["downscope-only"]}]}
JSON
$KCADM update client-policies/policies -r a2a -f "$TMP"; rm -f "$TMP"
echo "downscope policy active"
```

`downscope.sh` (bash)

```bash
chmod +x kc-downscope.sh
./kc-downscope.sh
python3 escal.py c.write
python3 escal.py c.read
```

**Expected output**

```text
downscope policy active
## A's token
{
 "aud": [
  "agent-c",
  "agent-b"
 ],
 "scope": "agent-b c.read",
 "azp": "agent-a",
 "sub": "<A-ID>",
 "may_act": {
  "sub": "<B-ID>",
  "client_id": "agent-b"
 }
}
exchange refused: invalid_scope - Scopes [c.write] not present in the initial access token [agent-b, c.read]
## A's token
{
 "aud": [
  "agent-c",
  "agent-b"
 ],
 "scope": "agent-b c.read",
 "azp": "agent-a",
 "sub": "<A-ID>",
 "may_act": {
  "sub": "<B-ID>",
  "client_id": "agent-b"
 }
}
## token B got for C
{
 "aud": "agent-c",
 "scope": "c.read",
 "azp": "agent-b",
 "sub": "<A-ID>",
 "act": {
  "sub": "<B-ID>",
  "client_id": "agent-b"
 }
}
C says: note 1: quarterly review is on Thursday
note 2: renew the staging certificate
evidence note
```

### Step 8: Clean up

**Goal.** Stop the agents and Keycloak, delete the Keycloak data folder and the logs, and unset the lab secrets.

**Prerequisites**

- Press Ctrl+C in the terminal that runs Keycloak first
- The Keycloak folder is the one you unpacked for this lab only

`cleanup.sh` (bash)

```bash
pkill -f "agent_[abc].py"
rm -rf "$KC_HOME/data" c.log b.log __pycache__ .venv
unset AGENT_A_SECRET AGENT_B_SECRET AGENT_C_SECRET KC_ADMIN_PASSWORD
pgrep -f "agent_[abc].py" > /dev/null || echo "agents stopped"
```

**Expected output**

```text
agents stopped
```


## Sources

- [A2A Protocol specification 1.0.0](https://a2a-protocol.org/latest/specification/)
- [RFC 8693: OAuth 2.0 Token Exchange](https://www.rfc-editor.org/rfc/rfc8693)
- [Keycloak documentation: Configuring and using token exchange](https://www.keycloak.org/securing-apps/token-exchange)
- [RFC 6749: The OAuth 2.0 Authorization Framework, client credentials grant](https://www.rfc-editor.org/rfc/rfc6749#section-4.4)
