# Workload identity

Run a job without storing an API key where it runs.

1. [Name the provider you trust](#1-name-the-provider-you-trust).
2. [Take the job's own token](#2-take-the-jobs-own-token).
3. [Trade it for an access token](#3-trade-it-for-an-access-token).
4. [Call models with the access token](#4-call-models-with-the-access-token).
5. [Trade again when it ends](#5-trade-again-when-it-ends).

A CI job or a cloud function already has an identity: its platform signs a short token that says which job it is. OpenDunes trades that token for an access token that acts as one of your API keys. The job never holds the key, and a leaked access token is dead in 15 minutes at most.

| | Sign in with OpenDunes | Workload identity |
|---|---|---|
| who proves who they are | a user, in a browser | a job, with a token its platform signed |
| what you get | an API key on the user's balance | an access token that acts as one of your own keys |
| charged to | the user's balance | your balance, within the key's cap |
| guide | [Sign in with OpenDunes](/docs/sign-in-with-opendunes) | this page |

## 1. Name the provider you trust

The trust is set up on OpenDunes' side, not through the API. Until it is, every trade answers 401. One trust, called a policy, holds six things:

| The policy holds | What it is |
|---|---|
| id | the policy id, a UUID: the job sends it with every trade |
| issuer | the value of `iss` in the provider's tokens |
| key address | where the provider publishes the public keys that check its signatures |
| audience | the value of `aud` the job's tokens must carry |
| subject | the value of `sub` the job's tokens may carry; `*` stands for any characters, and no subject means any |
| key | the API key of yours the access token acts as: it must be live |

The provider signs its tokens with RS256. OpenDunes reads its public keys from the key address and keeps them ten minutes.

<div class="good-to-know">
<p>A policy is the only thing a trade evaluates: the trade names its policy id, and a token is checked against that policy and no other.</p>
</div>

## 2. Take the job's own token

Ask the platform for a token for the audience of your policy. In a CI job the platform hands it to the job, and the job reads it from its environment; this page calls it `WORKLOAD_TOKEN`. The token must be unexpired and no longer than 16 384 characters.

## 3. Trade it for an access token

Send the token and the policy id to [`POST /v1/oauth/token`](/docs/reference/oauth-token). It takes no key: the signed token is the proof.

| You send | Holds |
|---|---|
| `grant_type` | `urn:ietf:params:oauth:grant-type:token-exchange` |
| `subject_token` | the job's own token |
| `subject_token_type` | `urn:ietf:params:oauth:token-type:jwt` |
| `federation_policy_id` | the policy id |

The samples trade the token and print the access token as an `export` line, with the seconds it lives. The policy id is read from `POLICY_ID`.

```python
import json
import os
import urllib.parse
import urllib.request

ADDRESS = "https://opendunes.com/v1/oauth/token"
WORKLOAD_TOKEN = os.environ["WORKLOAD_TOKEN"]
POLICY_ID = os.environ["POLICY_ID"]

form = urllib.parse.urlencode(
    {
        "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
        "subject_token": WORKLOAD_TOKEN,
        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
        "federation_policy_id": POLICY_ID,
    }
).encode()
with urllib.request.urlopen(urllib.request.Request(ADDRESS, form)) as r:
    answer = json.load(r)

print("export OPENDUNES_API_KEY=" + answer["access_token"])
print("# lives", answer["expires_in"], "seconds")
```

```javascript
const ADDRESS = "https://opendunes.com/v1/oauth/token";
const WORKLOAD_TOKEN = process.env.WORKLOAD_TOKEN;
const POLICY_ID = process.env.POLICY_ID;

const response = await fetch(ADDRESS, {
  method: "POST",
  body: new URLSearchParams({
    grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
    subject_token: WORKLOAD_TOKEN,
    subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
    federation_policy_id: POLICY_ID,
  }),
});
const answer = await response.json();

console.log(`export OPENDUNES_API_KEY=${answer.access_token}`);
console.log("# lives", answer.expires_in, "seconds");
```

```go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
)

const address = "https://opendunes.com/v1/oauth/token"

func main() {
	form := url.Values{}
	form.Set("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange")
	form.Set("subject_token", os.Getenv("WORKLOAD_TOKEN"))
	form.Set("subject_token_type", "urn:ietf:params:oauth:token-type:jwt")
	form.Set("federation_policy_id", os.Getenv("POLICY_ID"))

	res, err := http.PostForm(address, form)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}

	fmt.Println("export OPENDUNES_API_KEY=" + answer.AccessToken)
	fmt.Println("# lives", answer.ExpiresIn, "seconds")
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/oauth/token"
GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange"
TOKEN_TYPE="urn:ietf:params:oauth:token-type:jwt"

curl -s "$ADDRESS" \
  --data-urlencode "grant_type=$GRANT_TYPE" \
  --data-urlencode "subject_token=$WORKLOAD_TOKEN" \
  --data-urlencode "subject_token_type=$TOKEN_TYPE" \
  --data-urlencode "federation_policy_id=$POLICY_ID"
```

The answer carries `access_token`, `expires_in`, `token_type` (`Bearer`) and `scope` (`inference`); [Workload tokens](/docs/reference/oauth-token) lists them all.

### When a trade is refused

| Status | Why |
|---|---|
| 400 | a field is missing or has a value the route does not take, or `subject_token` is over 16 384 characters |
| 401 | no policy is set up, the policy id is not one, or the token fails: its issuer is not the policy's, its signature does not verify, it is not for the policy's audience, its subject is not the policy's, or it has expired |
| 401 | the policy's key is not live: it was paused or deleted |
| 503 | access tokens cannot be issued right now; the answer carries `Retry-After` |

## 4. Call models with the access token

The access token works wherever an API key does, in `Authorization: Bearer` or in `x-api-key`. Set `OPENDUNES_API_KEY` to it and every sample in these docs runs unchanged: [Client SDKs](/docs/client-sdks) sends a request with the OpenAI and the Anthropic library this way.

The access token acts as the policy's key. A request is charged to your balance, counted against that key's cap, and stops at once if the key is paused or deleted. The token carries no scope but inference.

## 5. Trade again when it ends

An access token lives 900 seconds at most, and never past the job's own token: a job token with two minutes left gives an access token with two minutes. `expires_in` says how many. A job that runs longer trades again before the seconds run out, with a token its platform signed again.

To check an access token on your own side, read its signing key from [`GET /v1/oauth/jwks`](/docs/reference/oauth-token): the key is an ES256 P-256 key, and the access token's header names it in `kid`.
