# Token exchange

> An agent swaps a user's token for one that names both the user and the agent, so every API can see who acts for whom.

Token exchange lets an agent act for a user without ever signing in as them. The agent trades the user's token for a
new one that still names the user as its subject and names the agent as the actor, so every API it reaches can see
both: who the request is for, and which agent is making it. The new token is always narrower than the user's, and it
ends when theirs does.

Use it when an agent must call an API for a user and the API needs to know both parties. Nothing is allowed until you
open two locks: a delegation from the user to the agent, and a policy that allows it. When an exchange needs the
agent's owner to approve it first, see [agent guardrails](../../../../gateway/guardrails/agent-guardrails/).

## Before you begin

- **Who can do it:** a realm administrator (a group holding `RealmOwner`) turns the grant on, links the agent to the
  user and writes the delegation policy; `RealmViewer` can read all three. The agent then exchanges tokens itself.
- **Where:** today this is done through the API ([Call the API](/develop/api/) shows how to get
  `$CVYUH_SESSION`).
- **First:** the agent is registered with its client ([Register an agent](../../../guides/agents/register-an-agent/)).

## How it works

A user signs in to an app and holds a token. An agent the user allows to act for them sends that token to the token
endpoint. The agent's client authenticates as usual, proves its DPoP key, and names the API it wants the token for
with `resource`, or with `audience` naming the same registered API:

```sh
curl https://foobar.cvyuh.com/oauth2/token \
  -H "DPoP: eyJ…" \
  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
  -d subject_token=eyJ… \
  -d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
  --data-urlencode resource=https://api.example.com/invoices \
  -d scope=invoices.read \
  -d client_id=invoice-agent-client \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion=eyJ…
```

```json
{
  "access_token": "eyJ…",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "DPoP",
  "expires_in": 300
}
```

The new token's claims name both:

```json
{
  "sub": "2b7e4f10-8c3a-4d1e-9f6b-5a0c7d2e9b13",
  "principal_type": "user",
  "mode": "delegated",
  "act": {
    "sub": "6f1c2a9e-4b7d-4e3a-9c51-2d8f0b7a1e44",
    "principal_type": "agent",
    "risk_class": "high",
    "autonomy_tier": 2,
    "business_owner": "maya"
  },
  "scope": "invoices.read"
}
```

| Claim | What it says |
|---|---|
| `sub` | Still the user |
| `act` | The agent, and any agent before it, outermost first. When the user's token already named an agent, that agent's `act` is nested inside the new one |
| `mode` | `delegated`, so an API knows a user is behind the request |

The subject can also be another agent: an agent can act for an agent in the same way.

The new token's scopes lie within the user's token, the delegation, the agent client's and the realm's. It never
outlives the user's token, and ends when the user's session or refresh family ends, or when any token it was exchanged
from is revoked.

### The request's parameters

- **`subject_token_type`** is `urn:ietf:params:oauth:token-type:access_token` or
  `urn:ietf:params:oauth:token-type:jwt`.
- **`actor_token` and `actor_token_type`** are optional. When sent, the actor token must be this client's own token
  for its agent.
- **`requested_token_type`**, if sent, must name an access token.
- **`audience`** names the target as `resource` does, and is held to the same registration: it must be an API the
  client may ask for. Sending both is fine only when they name the same API. The
  [identity assertion](../identity-assertion-issuing/) and [cross-domain chaining](../cross-domain-chaining/)
  exchanges use other shapes.
- **The new token is bound to the exchanging client's DPoP key**, never to the user's.

### Two locks, both closed by default

1. **A delegation**: an `actsFor` link from the agent to the user, optionally limited in time (`validFrom`,
   `validTo`) and scopes (`scopes`).
2. **A policy** in the realm's delegation policy set that allows `delegate` (and, for impersonation, `impersonate`).
   The set starts empty, so nothing is allowed until you write one. The policy is asked about the resource
   `delegation://user/<user id>` (or `delegation://agent/<agent id>` when the subject is an agent), with the agent as
   the subject and its token's claims in `properties.claims`.

### Impersonation and audience swaps

**Impersonation** gives a token that looks like the user's own, naming no exchanging agent in `act` (any `act` the
user's token already carried stays). It is possible only when the realm, the delegation and a policy all allow it,
and it is off by default.

**An audience swap** is the other kind of exchange: a gateway's client, not an agent's, trades a token meant for it
for one meant for an upstream, about the same subject and naming no actor of its own. Only a confidential client
marked `exchangesAudience` may, and the delegation locks don't apply to it: see
[token swap](/gateway/protect-apis/token-swap/). Every exchange's trail row names which kind it
was (`kind`: `delegation` or `audience`).

## Set it up

These steps use the admin API; [Call the API](../../../../develop/api/) shows how to get a session.

1. Add `urn:ietf:params:oauth:grant-type:token-exchange` to the realm's `grantTypes`
   (`PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings`) and to the agent's client
   (`https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client`). Read the realm's settings first with `GET` on the same address, and send back the whole list with the new value
   added: **a list you send replaces the realm's list.**
2. Link the agent to the user with an `actsFor` link on the `agent` object.
3. Write a policy in the realm's delegation policy set that allows `delegate`.

| Where | Setting | What it does |
|---|---|---|
| Realm and client | `grantTypes` include `urn:ietf:params:oauth:grant-type:token-exchange` | Off by default |
| `agent` object | `actsFor` link to the user | The delegation, with optional `validFrom`, `validTo`, `scopes` and `impersonate` |
| Realm | a `policy` in the set `delegationPolicySet` names | Who may delegate. The set is `delegation` by default |
| Realm | `maxActDepth` | How many agents may stack (default 4; from 1 to 16) |
| Realm | `tokenExchangeImpersonation` | Allows impersonation at all (default off) |
| A gateway's `oauth2Client` | `exchangesAudience` | Swaps for another audience, with no actor (default off) |

## What the user sees

Nothing at the exchange itself. The user sees each agent acting for them on their **AI Agents** page, and can remove
it there; after that, the agent's exchanges for them are refused.

## Limits and defaults

| Setting or limit | Default | Range |
|---|---|---|
| `maxActDepth`: agents stacked in one chain | 4 | 1 to 16 |
| `tokenExchangeImpersonation` | off | on or off |
| `delegationPolicySet` | `delegation` | any policy set |
| The exchanged token's life | no longer than the user's token | fixed |
| Token types | access tokens in, access tokens out | fixed |

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| `invalid_request` with an `actsFor` link in place | No policy in the delegation set allows `delegate`, or the link's `validTo` has passed | Write the policy; check the link's dates |
| `invalid_request` for a user's valid token | The token wasn't issued to this client, nor for an API it serves | Send a token meant for the exchanging client |
| `invalid_scope` | The agent asked for more than the user's token, the link's `scopes` or the client allows | Ask for a subset |
| A chain stops at a new hop | It would pass `maxActDepth`, or repeat an agent | Shorten the chain |

## Audit record

Every exchange, allowed or refused, is a `TOKEN_EXCHANGED` record keyed by the user it is about, with the agents in
the chain (`principals`), the kind (`delegation` or `audience`), the parent token's id and, for a refusal, its
`reason`. It's on the user's trail and the agent's
([Read a user's or agent's trail](/audit-reports/audit-trail/read-a-trail/)), and in **Audit → Authentication**.

## Good to know

- **Every agent in the chain must still stand.** A quarantined or killed agent can't be carried forward.
- **The user's token must still be active, and meant for the exchanging client:** issued to it, or for a resource it
  serves.
- **No loops.** An agent can't act for itself, and can't appear twice in one chain.
- **Chains are limited in depth** by `maxActDepth`, 4 by default.
- **Only an access token is exchanged**, never a refresh token.
- **Every exchange is recorded.** Allowed or refused, it is on the user's
  [audit trail](../../../../audit-reports/audit-trail/).
- **Users stay in control.** A user can see and remove each agent acting for them, on their **AI agents** page.

## Reference

### Errors

| Error | When |
|---|---|
| `invalid_request` | The subject token is missing, invalid, not meant for this client, inactive or expired, or not about a user or an agent. The actor token isn't this client's agent's. The agent would act for itself, is already in the chain, or the chain would pass `maxActDepth`. There's no open delegation, the realm has no delegation policy, or the policies refuse. `requested_token_type` isn't an access token. A client with no agent that isn't marked `exchangesAudience`. `audience` and `resource` name different APIs |
| `invalid_target` | A `resource` or an `audience` the client may not ask for |
| `invalid_scope` | A scope beyond the user's token, the delegation, the client or the realm |

For an audience swap, a public client is refused `unauthorized_client`, and a user's consent to the client that no
longer stands is `invalid_grant`: see [token swap](/gateway/protect-apis/token-swap/).

## Related

- [Let an agent act for a user](../../../guides/agents/agent-acts-for-a-person/): the task, start to finish.
- [Let users remove agents](../../../guides/agents/people-remove-agents/): how users take an agent's access back.
- [Backchannel authentication](../../../agents/backchannel-authentication/): the agent asks its owner and waits.
- [Token swap](/gateway/protect-apis/token-swap/): the audience swap in detail.
- [Transaction tokens](../transaction-tokens/): carry a request's identity inside your services.
