# Imporre il downscoping nel token exchange per le chiamate tra agenti

> Lab Keycloak per agenti A2A: il token che B ottiene per C segue gli scope di B, non quelli di A, se non imponi il downscoping. Prova, controllo, rimedio.

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

## In breve

- Quando l'agente B chiama l'agente C per conto dell'agente A, B scambia il token di A con uno nuovo. Su Keycloak 26.8.2 lo scope del nuovo token segue gli scope di B, non il token consegnato da A, a meno che si imponga il downscoping.
- Nel mio test A aveva c.read, B aveva c.write come scope opzionale proprio, e lo scambio di B ha restituito un token per A con c.write. L'agente C ha accettato una scrittura che A non aveva mai concesso.
- Non è B che esce dai propri limiti: usa un diritto che ha. Con c.write tolto a B lo stesso scambio fallisce con invalid_scope. È una lezione di configurazione, non una vulnerabilità.
- Una client policy con l'executor downscope-assertion-grant-enforcer limita lo scambio agli scope di A. L'agente C dovrebbe anche richiedere il claim act e controllare lo scope per ogni skill.
- Ho provato solo Keycloak. A2A 1.0.0 lascia l'autorizzazione all'implementazione e l'Agent Card non ha un campo per il token exchange.

A2A 1.0.0 è la versione corrente del protocollo Agent2Agent. Dice che un server deve autenticare ogni richiesta e che l'autorizzazione spetta all'implementazione. Non dice cosa succede quando l'agente B chiama l'agente C per conto dell'agente A. Quella parte è OAuth semplice, e lo strumento abituale è il token exchange ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693)). Ho costruito una piccola catena su un Keycloak locale e mi sono posto una sola domanda: il token che B ottiene per C resta dentro ciò che A ha consegnato?

No, a meno che si chieda a Keycloak di imporlo. Questo articolo parla di quell'impostazione. Se hai letto il [primo lab sul token exchange con Keycloak](https://iamops.dev/it/keycloak-token-exchange-rfc-8693/), questo riparte dal punto dell'insidia "nessun claim act" e aggiunge la delega.

## Cosa mostra questo lab

Tre agenti e un server di autorizzazione, tutti su localhost.

- **A** è il chiamante. Ha un token con scope `agent-b c.read`. Un claim `may_act` in quel token indica B come parte autorizzata ad agire per lui.
- **B** è un agente nel mezzo. Riceve la chiamata di A, poi chiede a Keycloak un token per chiamare C, usando il token di A come `subject_token` e il proprio come `actor_token`.
- **C** è un piccolo agente di note con una skill di lettura e una di scrittura. Accetta solo token delegati e controlla lo scope per ogni skill.

| Client | Ruolo | Scope che può chiedere in uno scambio |
| --- | --- | --- |
| `agent-a` | Chiamante, service account | `agent-b` di default, `c.read` se lo chiede |
| `agent-b` | Agente intermedio, esegue lo scambio | `c.read` e `c.write`, entrambi opzionali |
| `agent-c` | Agente di note, solo audience | nessuno |

![Diagramma di sequenza: l'agente A legge l'Agent Card di B, ottiene un token da Keycloak, chiama B, e B lo scambia con un token delegato con claim act prima di chiamare C.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/00-flow.webp)

*La catena. I passi da 1 a 4 sono A che chiama B. I passi da 5 a 7 sono B che trasforma il token di A in un token delegato. I passi da 8 a 10 sono la chiamata a C.*

Ogni agente pubblica una Agent Card in `/.well-known/agent-card.json` con uno schema di sicurezza `oauth2` e gli scope per skill. Lo schema può dire `clientCredentials` e nulla di più vicino al token exchange: un oggetto `OAuthFlows` contiene esattamente un flusso e non esiste un flusso di scambio. Per questo la card di C lo dice nel testo della descrizione, e chi chiama deve leggerlo.

## Configurazione

Keycloak 26.8.2 dallo zip, Java 21, modalità sviluppo. Lo standard token exchange è attivo di default nella 26.8. La delega, cioè i claim `act` e `may_act`, no. Servono due funzioni in anteprima.

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

Keycloak stampa all'avvio le funzioni in anteprima attivate. Le ho attivate insieme e non le ho provate una per una. Senza di esse la mia catena fallisce: Keycloak rifiuta in uno scambio semplice qualsiasi subject token che porti `may_act`, con "Subject token with a delegation claim is not allowed for standard token exchange".

![Output del terminale: Keycloak 26.8.2 si avvia con le funzioni in anteprima parameterized-scopes e token-exchange-delegation attive, poi lo script del realm segnala realm a2a ready.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/01-features.webp)

*Funzioni e realm. Keycloak 26.8.2 con due funzioni in anteprima attive, poi lo script del realm.*

Lo script del realm crea i tre client con service account, gli scope `agent-b`, `c.read` e `c.write` (ciascuno con un audience mapper) e un mapper `may_act` fisso su `agent-a`. Attiva anche lo Standard Token Exchange per `agent-b` e dà a `agent-b` gli scope `c.read` e `c.write` come client scope opzionali. Ricorda quest'ultimo punto. Tutto l'articolo gira attorno a questo.

## La catena funziona

A legge la card di B, chiede a Keycloak esattamente gli scope elencati dalla skill e invia `message:send`. B scambia il token e chiama C. Il token delegato decodificato mantiene A come `sub`, restringe `aud` a C, porta solo `c.read` e aggiunge `act` per B.

![Output del terminale: l'agente A legge l'Agent Card di B, chiede gli scope agent-b e c.read e riceve da B una risposta 200 che riassume due note custodite da C.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/02-chain.webp)

*Il percorso legittimo. A chiede a B di riassumere le note. B scambia il token di A e le legge da C.*

## Lo scambio che A non aveva concesso

Ora B chiede `c.write`. Il token di A non ha `c.write`. Ecco la richiesta, con segnaposto:

```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 emette il token. `sub` è A, `act` indica B, `scope` è `c.write`. C controlla firma, audience, il claim `act` e lo scope richiesto dalla sua skill di scrittura, e aggiunge la nota.

![Output del terminale su Keycloak standard: l'agente B elenca c.write tra i suoi scope opzionali, il token di A ha scope agent-b c.read, il token ottenuto da B per l'agente C ha scope c.write con act agent-b e C risponde che la nota è stata aggiunta.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/03-stock.webp)

*Keycloak standard. Il token di A dice c.read. Il token per C dice c.write. C aggiunge la nota. Gli id sono sostituiti da segnaposto.*

Ho eseguito l'intera sequenza quattro volte su un Keycloak 26.8.2 nuovo, due con gli script del lab e due con quelli di questo articolo, e il risultato è stato sempre lo stesso.

## Il controllo: B possiede c.write

Prima di chiamarla escalation ho verificato di chi è il diritto usato. Nel mio realm B ha `c.write` come scope opzionale proprio. L'ho messo io. Quindi B non ha ottenuto qualcosa che non gli era mai stato permesso. Ho tolto `c.write` dagli scope opzionali di B e ho ripetuto lo stesso scambio.

![Output del terminale della prova di controllo: dopo aver eliminato c.write dai client scope opzionali dell'agente B, lo stesso scambio è rifiutato con invalid_scope, Invalid scopes: c.write.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/04-control.webp)

*Il controllo. Senza c.write su B non viene emesso nulla. B resta dentro i propri diritti.*

Questo chiarisce una cosa. B non può andare oltre ciò che possiede, e qui non c'è un bug nel senso di un aggiramento. Quello che è andato perso è altro: lo scope del nuovo token è limitato dall'insieme di scope di B e non dal token di A. A aveva detto "lettura", e un passaggio dopo questo non significava più nulla. L'RFC 8693 lascia la scelta al server: `scope` è "the desired scope of the requested security token" e i suoi valori sono "service specific" ([sezione 2.1](https://www.rfc-editor.org/rfc/rfc8693#section-2.1)). Nulla impone che il risultato sia un sottoinsieme del subject token.

Per gli agenti conta perché C registra `sub` A e `act` B. Chi legge il log vede "A ha scritto una nota". A non aveva mai accettato.

## Limitare lo scambio con la policy di downscope

Keycloak ha un executor per le client policy fatto apposta: `downscope-assertion-grant-enforcer`. Limita gli scope del nuovo token a quelli già presenti nel subject token e risponde `invalid_scope` negli altri casi. Non richiede configurazione. L'ho applicato a tutti i client del realm con una sola policy.

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

Con `c.write` di nuovo su B e la policy attiva, lo scambio viene rifiutato. Lo scambio legittimo con `c.read` funziona ancora.

![Output del terminale con la policy di downscope attiva: lo scambio con c.write è rifiutato perché c.write non è presente nel token di accesso iniziale, mentre lo scambio con c.read restituisce ancora un token delegato che C accetta.](https://iamops.dev/media/enforce-downscoping-token-exchange-a2a/05-enforcer.webp)

*Con la policy. c.write è rifiutato perché il token di A non lo porta. c.read funziona ancora. C elenca anche la nota della prova standard.*

L'ultima riga di quell'output è la nota aggiunta dalla prova standard. Resta finché non riavvii C.

## Cosa deve controllare anche C

La policy vive sul server di autorizzazione. C non dovrebbe dipendere solo da quella.

- Richiedi il claim `act` e confronta `act.client_id` con gli agenti che ti aspetti. Il mio C risponde 403 senza.
- Controlla lo scope per skill. Il mio C richiede `c.read` per leggere e `c.write` per scrivere.
- Controlla `aud`. Un token per B viene rifiutato da C con 401.
- Non trattare `may_act` come una prova. Quando B ha presentato il token di C come attore, Keycloak ha rifiutato con un messaggio sull'audience. Non ho verificato se confronti l'attore con `may_act`.

## Insidie

- **L'enforcer e un audience mapper a livello di client.** Nella mia prima configurazione l'audience di C stava in un mapper sul client B. Con l'enforcer attivo ogni scambio falliva con "Requested audience not available: agent-c". Spostare il mapper sugli scope `c.read` e `c.write` ha risolto. Non so perché. Provalo nel tuo realm.
- **L'audience tramite scope ha un effetto collaterale.** `c.read` porta l'audience di C, quindi il token di A ha `aud` B e C. Ciò che impedisce ad A di usarlo su C è il requisito `act`, non l'audience.
- **L'errore sull'attore sbagliato è vago.** Il client vede `access_denied` e "Client is not within the token audience". Il log eventi di Keycloak nomina l'attore.
- **`may_act` è fisso nel mio realm.** In un sistema reale dovrebbe derivare da una policy e vivere insieme al token.

## Cosa non ho eseguito

Ho eseguito solo Keycloak 26.8.2. Non ho provato Entra on-behalf-of, Okta né Auth0, quindi non dico nulla su come limitino lo scope in uno scambio. Un solo passaggio di delega: nessuna catena `act` annidata. Nessun task, streaming o Agent Card firmata, nessun TLS e nessun token vincolato al mittente. Nessun utente nella catena: il soggetto è il service account dell'agente A. Gli agenti sono miei programmi Flask e i loro client secret sono valori statici di laboratorio.

*Le immagini del terminale sono state ricostruite dall'output salvato delle esecuzioni, con gli id sostituiti da segnaposto. Niente di quanto vedi è una credenziale reale.*

Per gli standard alla base, vedi [ID-JAG spiegato](https://iamops.dev/it/id-jag-explained/) e [perché un server MCP non deve inoltrare i token](https://iamops.dev/it/mcp-server-no-token-passthrough/).

## Ripeti questo lab

Circa 40 minuti su un portatile: un Keycloak locale con due funzioni in anteprima, uno script per il realm, tre piccoli agenti in Python e tre scambi: standard, di controllo e con la policy di downscope. Apri ogni passo, copia i blocchi e confronta il tuo output con quello atteso.

Ogni valore tra parentesi angolari è un segnaposto per il tuo ambiente di test. Nulla in questa pagina è un identificativo o un segreto reale.

**Imposta le variabili una sola volta** `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>'
```

### Passo 1: Avvia Keycloak con le funzioni di delega

**Obiettivo.** Esegui un server di autorizzazione locale con token-exchange-delegation e parameterized-scopes, le due funzioni in anteprima che aggiungono il claim act.

**Prerequisiti**

- Keycloak 26.8.2 scompattato e un JDK 21; curl e Python 3.10 o successivo
- Porta 8080 libera; lascia aperto questo terminale e usane un secondo per i passi successivi

`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
```

**Output atteso**

```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
```

### Passo 2: Crea il realm, i client e il claim may_act

**Obiettivo.** Crea il realm a2a: tre client con service account, tre scope con audience e un mapper che mette may_act nel token di A. B riceve c.read e c.write come scope opzionali.

**Prerequisiti**

- Il blocco env impostato in questo terminale; Keycloak del passo precedente ancora in esecuzione
- Lo script richiede circa un minuto perché riduce gli scope predefiniti di ogni 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"
```

**Output atteso**

```text
realm a2a ready
```

### Passo 3: Salva e avvia l’agente B e l’agente C

**Obiettivo.** Quattro piccoli file Python: una libreria comune, l’agente C (note, accetta solo token delegati), l’agente B (fa lo scambio) e l’agente A (il chiamante). Avvia B e C e leggi l’Agent Card di C.

**Prerequisiti**

- Python 3.10 o successivo; porte 19402 e 19403 libere
- Salva i quattro file in una cartella, la stessa di 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'])"
```

**Output atteso**

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

### Passo 4: Chiama la catena come agente A

**Obiettivo.** A legge la card di B, chiede a Keycloak gli scope elencati dalla skill e invia un messaggio. B scambia il token di A con un token per C e legge le note.

**Prerequisiti**

- Passi da 1 a 3 completati, nello stesso ambiente virtuale

`call-chain.sh` (bash)

```bash
python3 agent_a.py
```

**Output atteso**

```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
```

### Passo 5: Chiedi c.write su Keycloak standard

**Obiettivo.** B scambia il token di A e chiede c.write. Il token di A ha solo c.read. Leggi prima gli scope opzionali di B, poi guarda cosa emette Keycloak e cosa ne fa C.

**Prerequisiti**

- Passi da 1 a 4 completati; è la configurazione standard, ancora senza policy
- Salva escal.py dal blocco qui sotto accanto agli altri file

`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
```

**Output atteso**

```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
```

### Passo 6: Controllo: togli c.write a B

**Obiettivo.** Rimuovi c.write dagli scope opzionali di B e ripeti lo stesso scambio. Se fallisce, B stava usando un diritto che possiede. Poi rimetti lo scope.

**Prerequisiti**

- Passo 5 completato
- I comandi rifanno il login, quindi va bene qualsiasi terminale con il blocco env

`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
```

**Output atteso**

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

### Passo 7: Attiva la policy di downscope

**Obiettivo.** Aggiungi una client policy con l’executor downscope-assertion-grant-enforcer, poi ripeti lo scambio con c.write e quello legittimo con c.read.

**Prerequisiti**

- Passo 6 completato, con c.write di nuovo su 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
```

**Output atteso**

```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
```

### Passo 8: Pulizia

**Obiettivo.** Ferma gli agenti e Keycloak, elimina la cartella dei dati di Keycloak e i log, e rimuovi i segreti del lab dalle variabili.

**Prerequisiti**

- Premi prima Ctrl+C nel terminale che esegue Keycloak
- La cartella di Keycloak è quella che hai scompattato solo per questo lab

`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"
```

**Output atteso**

```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)
