# Workload tokens

`POST /v1/oauth/token` trades a token your own identity provider signed for a short-lived
access token that works as one of your API keys; `GET /v1/oauth/jwks` answers the keys that
sign access tokens.

## Request

Neither route takes a key: the signed token is the proof. Use them where a job runs under an
identity of its own, a CI job or a cloud function, so that no API key is stored there. For a
key a user approves for your app, see [Sign in with OpenDunes](/docs/sign-in-with-opendunes).

| Route | Key | Does |
|---|---|---|
| `POST /v1/oauth/token` | no key | trades a signed token for an access token |
| `GET /v1/oauth/jwks` | no key | answers the public keys that sign access tokens |

OpenDunes trusts an identity provider through a policy: its id, the provider's issuer and key
address, the audience its tokens carry, the subject they may name, and the API key they act as.
A policy is set up on OpenDunes' side; until one is, every exchange answers 401. [Workload
identity](/docs/workload-identity) takes you through it.

### Trade a token

`POST /v1/oauth/token` takes a form, `application/x-www-form-urlencoded`, or JSON. The token
you send carries the trusted issuer in `iss`, the trusted audience in `aud`, and a `sub` the
policy trusts. It is signed with RS256.

| Field | Needed | You send |
|---|---|---|
| `grant_type` | yes | `urn:ietf:params:oauth:grant-type:token-exchange` |
| `subject_token` | yes | the token your identity provider signed, up to 16 384 characters |
| `subject_token_type` | yes | `urn:ietf:params:oauth:token-type:jwt`, or `urn:ietf:params:oauth:token-type:id_token` |
| `federation_policy_id` | yes | the id of the policy that trusts the provider: only that policy is checked |
| `requested_token_type` | no | `urn:ietf:params:oauth:token-type:access_token`, the only one |
| `scope` | no | `inference`, the only one |

Souk Bot's nightly job reads the token its CI gave it from `WORKLOAD_TOKEN`, trades it, then
reads the key the access token acts as with [This key](/docs/reference/key), a route that
charges nothing.

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

ADDRESS = "https://opendunes.com/v1/oauth/token"
KEY_ADDRESS = "https://opendunes.com/v1/key"
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:
    access_token = json.load(r)["access_token"]

check = urllib.request.Request(
    KEY_ADDRESS,
    headers={"Authorization": "Bearer " + access_token},
)
with urllib.request.urlopen(check) as response:
    print(json.load(response)["data"])
```

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

const exchange = 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 { access_token } = await exchange.json();

const check = await fetch(KEY_ADDRESS, {
  headers: { Authorization: `Bearer ${access_token}` },
});
console.log((await check.json()).data);
```

```go
package main

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

const (
	address    = "https://opendunes.com/v1/oauth/token"
	keyAddress = "https://opendunes.com/v1/key"
)

func main() {
	workloadToken := os.Getenv("WORKLOAD_TOKEN")

	form := url.Values{}
	form.Set("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange")
	form.Set("subject_token", workloadToken)
	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 exchange struct {
		AccessToken string `json:"access_token"`
	}
	if err := json.NewDecoder(res.Body).Decode(&exchange); err != nil {
		panic(err)
	}

	req, err := http.NewRequest("GET", keyAddress, nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+exchange.AccessToken)

	check, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer check.Body.Close()

	var answer struct {
		Data map[string]any `json:"data"`
	}
	if err := json.NewDecoder(check.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.Data)
}
```

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

ACCESS_TOKEN=$(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" \
  | jq -r .access_token)

curl "$KEY_ADDRESS" \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

### The signing keys

`GET /v1/oauth/jwks` takes no field. Read it to check an access token's signature on your own
side.

```python
import json
import urllib.request

ADDRESS = "https://opendunes.com/v1/oauth/jwks"

with urllib.request.urlopen(ADDRESS) as response:
    for key in json.load(response)["keys"]:
        print(key["kid"], key["alg"])
```

```javascript
const ADDRESS = "https://opendunes.com/v1/oauth/jwks";

const response = await fetch(ADDRESS);
const { keys } = await response.json();

for (const key of keys) console.log(key.kid, key.alg);
```

```go
package main

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

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

func main() {
	res, err := http.Get(address)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var set struct {
		Keys []struct {
			Kid string `json:"kid"`
			Alg string `json:"alg"`
		} `json:"keys"`
	}
	if err := json.NewDecoder(res.Body).Decode(&set); err != nil {
		panic(err)
	}
	for _, key := range set.Keys {
		fmt.Println(key.Kid, key.Alg)
	}
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/oauth/jwks"

curl "$ADDRESS"
```

## Response

`POST /v1/oauth/token` answers `200 OK`:

| Field | Holds |
|---|---|
| `access_token` | the access token: send it as `Authorization: Bearer <access_token>`, or as `x-api-key`, on any route an API key calls |
| `token_type` | `Bearer` |
| `issued_token_type` | `urn:ietf:params:oauth:token-type:access_token` |
| `expires_in` | seconds until the access token stops working: 900 at most, and never past the token you traded |
| `scope` | `inference` |

The access token acts as the API key the provider is trusted for: it spends that key's cap and
your balance, and it stops the moment that key is paused or deleted.

`GET /v1/oauth/jwks` answers `200 OK`:

| Field | Holds |
|---|---|
| `keys` | the keys that sign access tokens; an empty list when none is set up |
| `kty` | `EC` |
| `crv` | `P-256` |
| `use` | `sig` |
| `alg` | `ES256` |
| `kid` | the key's id, as the `kid` in an access token's header |
| `x` · `y` | the public key's coordinates, in base64url |

Both answers, *illustrative*:

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im9w…",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "Bearer",
  "expires_in": 900,
  "scope": "inference"
}
```

```json
{
  "keys": [
    {
      "kty": "EC",
      "crv": "P-256",
      "use": "sig",
      "alg": "ES256",
      "kid": "opendunes-1",
      "x": "SAT6302t0ZCuZ4jU6tMwhmd0mdNAkSDCZRQmBGqQiyY",
      "y": "HTj_S_2fHlYA5QwzEBa1nHc1PVhqvUAMjRt-VU9Br-s"
    }
  ]
}
```

## What it cost

Free. Trading a token and reading the signing keys are never charged. A request sent with the
access token is charged in DA to your balance, and to the cap of the key it acts as.

## Errors

`error.code` carries the status, and `error.message` says why.

| Status | When |
|---|---|
| 400 | `grant_type`, `subject_token`, `subject_token_type` or `federation_policy_id` is missing, or a field is not one of the values above; `error.metadata.errors` names the field |
| 401 | no policy is set up, the policy id is not one, the token's issuer is not the policy's, the token does not verify against the provider's keys, its audience or its subject is not the policy's, or the key it would act as is not active |
| 503 | no access token can be issued right now; `Retry-After` says when to ask again |
