# Token swap

> The gateway calls each API or MCP server with a fresh token meant for it alone, never the caller's, by exchanging the caller's token at the realm.

A token sent to your gateway is meant for the gateway. Passing it on to the API behind it would let that API replay it
anywhere the gateway is trusted. With token swap, the gateway checks the caller's token, then trades it at the realm
for one meant for the API it's about to call. Each API sees only its own audience, and the caller's token never leaves
the gateway. The MCP specification asks this of every MCP gateway: a server must never receive a token meant for
someone else.

The [gateway](/gateway/) swaps on its own when you give it your API's resource identifier (`UPSTREAM_AUDIENCE`). A proxy
of your own that speaks RFC 8693 can swap for itself, and ask the gateway through its `ext_authz` check before each
call.

## Before you begin

- **A realm administrator** in a group holding `RealmOwner`, to offer token exchange and change the gateway's client,
  with the API. [Call the API](/develop/api/) shows how to get `$CVYUH_SESSION`.
- **The gateway running** with its own client, as in [Run the gateway](/gateway/protect-apis/run-the-gateway/). Its
  image isn't published yet: ask your Cvyūh contact for it.
- **Your API's resource identifier**, here `https://orders.internal.example.com`, served by an active client in the
  realm.

## How it works

The swap is a [token exchange](/workforce-identity/applications/tokens/token-exchange/) by the gateway's own client, naming the
API as its `resource` and no actor. The new token is the caller's, narrowed to one API:

- **The same subject.** It names the caller's `sub`, and any agents already acting in its `act`. The gateway adds no
  actor of its own: it passes the call on and acts for no one.
- **The API's audience.** Its `aud` is the one `resource` (or `audience`) asked, which must be among the gateway
  client's `allowedResources`.
- **Never wider.** Its scopes are the caller's, within what the gateway client and the realm allow, and the realm's
  entitlements and issuance policy judge it as any issuance.
- **Never longer.** It never outlives the caller's token.
- **Never unbound.** When the caller's token is bound to a key, the swap is made only under the gateway's own DPoP
  proof, and the new token is bound to the gateway's key.
- **Revoked with its source.** The new token names the one it came from, so revoking the caller's token revokes
  the swap too, at the realm and at the gateway.
- **On the trail.** Each swap is a `TOKEN_EXCHANGED` record: see [Audit record](#audit-record).

The request, made as the gateway's client under its own DPoP proof (shown on several lines; it's one form body):

```http
POST /oauth2/token HTTP/1.1
Host: foobar.cvyuh.com
Content-Type: application/x-www-form-urlencoded
DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsImFsZyI6IkVTMjU2IiwiandrIjp7…

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9…
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&resource=https://orders.internal.example.com
&client_id=floor
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=eyJhbGciOiJFUzI1NiJ9…
```

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

### When the gateway swaps

- **It replaces the call's credentials.** The caller's `Authorization` and `DPoP` headers are replaced by the new
  token, under `DPoP`, with a fresh proof made with the gateway's own key.
- **It reuses a swap** for the same caller token's next calls, for at most an hour. A restart means fresh swaps.

## Set it up

The gateway swaps as its own client, here `floor`, for the API at `https://orders.internal.example.com`.

1. **Offer token exchange in the realm.** Add `urn:ietf:params:oauth:grant-type:token-exchange` to the realm's
   `oauth2Settings.grantTypes`. A list is replaced whole, so send the grants the realm already offers with it:

   ```sh
   curl -X PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Settings/oauth2Settings \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "grantTypes": ["authorization_code", "refresh_token", "client_credentials",
                         "urn:ietf:params:oauth:grant-type:token-exchange"] }'
   ```

2. **Let the gateway's client swap.** Mark it `exchangesAudience`, give it the exchange grant, name the gateway's own
   audience in `servesResources`, and each API it may swap for in `allowedResources`, beside the realm's two:

   ```sh
   curl -X PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/oauth2Client/floor \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
     -H "Content-Type: application/json" \
     -d '{ "exchangesAudience": true,
           "grantTypes": ["client_credentials", "urn:ietf:params:oauth:grant-type:token-exchange"],
           "servesResources": ["https://api.example.com"],
           "allowedResources": ["https://foobar.cvyuh.com/policies/v1", "https://foobar.cvyuh.com/access/v1",
                                "https://orders.internal.example.com"] }'
   ```

   The client must authenticate confidentially: `floor` uses `private_key_jwt`.

3. **Make sure the API is served.** It needs an active `oauth2Client` whose `servesResources` names
   `https://orders.internal.example.com`.

4. **Tell the gateway.** Restart it with `UPSTREAM_AUDIENCE=https://orders.internal.example.com`: see
   [Gateway configuration](/gateway/configuration/).

## Good to know

- **The realm refuses a swap** from a public client; from a client not marked `exchangesAudience`; from an agent's
  client, whose exchanges are always delegations ([Agents acting for users](/workforce-identity/agents/acting-for-users/)); that
  names an `actor_token`; of a token not issued to the gateway nor meant for a resource it serves; of a token revoked
  or expired; toward an audience no active client serves; or of a user's token without the user's consent to the
  gateway client, unless that client is `consentImplied`.
- **The gateway is trusted** to have checked the caller's token, and its proof when it's bound, before swapping it.
  That trust is why only a confidential client that `exchangesAudience`, and serves the caller's audience, may swap.
- **Behind a proxy that can't sign DPoP, only unbound callers are swapped.** A bound caller is refused, never handed
  a bearer token. The gateway proves DPoP, so it swaps every caller, and every swap is bound.
- **No retry on an API's fresh nonce.** The call's body streams through and can't be sent twice. The gateway keeps
  the nonce, and the caller's next call carries it.
- **The proof to the API names its own address.** Its `htu` is the address the gateway forwards to (`BACKEND`) and
  the request's path. An API that
  checks `htu` against another name for itself refuses it.

## Limits and defaults

| What | Default | Can it change? |
|---|---|---|
| APIs a gateway swaps for | One, its `UPSTREAM_AUDIENCE` | No: run one gateway per API |
| A swap reused for | Until shortly before the new token expires, at most an hour | No |
| The new token's life | Never longer than the caller's token | Lower it with the realm's token lifetimes |

## What callers see

Nothing changes for a caller whose swap succeeds. If the realm refuses the swap, the caller gets
`403 exchange_refused` and nothing reaches your API. If the realm can't be asked, the caller gets `503`. Each
refusal is logged by the gateway with the realm's error.

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Every allowed call is `403 exchange_refused` | The realm doesn't offer token exchange, or the gateway's client isn't marked `exchangesAudience`, or doesn't name your API in `allowedResources` | Do steps 1 and 2 of [Set it up](#set-it-up); the gateway's log names the realm's error |
| Users' calls are `403 exchange_refused`, agents' aren't | The users haven't consented to the gateway's client | Mark the gateway's client `consentImplied`, or have users consent |
| Your API refuses the swapped token's proof | Your API checks the proof's address against another name for itself | Have your API accept the address the gateway forwards to (`BACKEND`) |

## Audit record

Each swap, allowed or refused, is a `TOKEN_EXCHANGED` record on the audit trail, its context naming `kind: audience`.
See [What is recorded](/audit-reports/audit-trail/what-is-recorded/).

## Reference

### Errors

| Where | Error | When |
|---|---|---|
| Token endpoint | `invalid_request` | The client isn't marked `exchangesAudience`, the request names an `actor_token`, the caller's token isn't the gateway's to swap or was revoked or expired, or `audience` and `resource` name different targets |
| Token endpoint | `unauthorized_client` | The client is public |
| Token endpoint | `invalid_target` | No target or more than one, one outside `allowedResources`, or one no active client serves |
| Token endpoint | `invalid_scope` | A scope the caller's token doesn't hold |
| Token endpoint | `invalid_dpop_proof` | The caller's token is bound, and the swap came without the gateway's own proof |
| Token endpoint | `invalid_grant` | The user hasn't consented to the gateway's client, or took that consent back |
| Gateway | `403 exchange_refused` | The realm refused the swap. Nothing is forwarded |
| Gateway | `503` | The realm couldn't be asked, or gave no usable answer. Nothing is forwarded |

## Related

- [Run the gateway](/gateway/protect-apis/run-the-gateway/): where `UPSTREAM_AUDIENCE` is set.
- [Token exchange](/workforce-identity/applications/tokens/token-exchange/): the exchange grant itself.
- [MCP tool calls](/gateway/mcp-servers/mcp-tool-calls/): an MCP server behind the gateway.
