# API key rotation

Replace an API key with a new one without dropping a request.

1. [Create the new key](#1-create-the-new-key). It is shown once: copy it now.
2. [Move your apps to it](#2-move-your-apps-to-it).
3. [Check the new key spends](#3-check-the-new-key-spends).
4. [Pause the old key](#4-pause-the-old-key).
5. [Revoke the old key](#5-revoke-the-old-key).
6. [Rotate from a script](#6-rotate-from-a-script).

Rotate on a schedule you set, and at once when a key may have leaked.

<div class="dont">
<p>Keep a leaked key running while your apps move to the new one. Anyone holding it spends your balance until it stops.</p>
</div>

<div class="do">
<p>Revoke it first, in step 5, then create its replacement. Your apps get a 401 until they carry the new key.</p>
</div>

## 1. Create the new key

In the app, open *API Keys* and press *Create API key*. The key is shown once: copy it now.

<div class="buttons">
<a href="/dashboard/keys" class="button primary">API Keys</a>
</div>

Give it the old key's name, cap and cap reset. A cap belongs to one key, so the new key starts on its own. [API keys](/docs/api-keys) sets out each setting.

<div class="watch-out">
<p>An account holds at most 5 keys, paused keys counted, unless raised. With 5, revoke a key you no longer use before you create the new one.</p>
</div>

## 2. Move your apps to it

Put the new key everywhere the old one is set: each server's `OPENDUNES_API_KEY`, your deploy secrets, your `.env` files. Restart what reads the key only when it starts.

Both keys work while you move, and both spend the same balance. Nothing is dropped: a request carries one key or the other.

## 3. Check the new key spends

[`GET /v1/key`](/docs/reference/key) answers the key that sends it, with what it has spent. Run the sample with `OPENDUNES_API_KEY` set to the new key: a `usage` above 0 means your apps send it.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/key"

request = urllib.request.Request(
    ADDRESS,
    headers={"Authorization": "Bearer " + API_KEY},
)
with urllib.request.urlopen(request) as response:
    key = json.load(response)["data"]

print("spent:", key["usage"], "today:", key["usage_daily"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/key";

const response = await fetch(ADDRESS, {
  headers: { Authorization: `Bearer ${API_KEY}` },
});
const { data } = await response.json();

console.log("spent:", data.usage, "today:", data.usage_daily);
```

```go
package main

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

const address = "https://opendunes.com/v1/key"

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

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

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

	var body struct {
		Data struct {
			Usage      float64 `json:"usage"`
			UsageDaily float64 `json:"usage_daily"`
		} `json:"data"`
	}
	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
		panic(err)
	}
	fmt.Println("spent:", body.Data.Usage, "today:", body.Data.UsageDaily)
}
```

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

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY"
```

Then run it twice with the old key, some minutes apart. When its `usage` no longer moves, nothing sends it. Reading a key is free.

## 4. Pause the old key

Open the old key in *API Keys* and choose *Pause this key*. Every request it sends gets a 401 from then on.

If an app you forgot starts failing, choose *Resume this key*, move that app, and pause the key again. Keep it paused until nothing has failed for as long as your slowest job takes to run.

## 5. Revoke the old key

Open it in *API Keys* and choose *Revoke this key*. A revoked key never works again: every request it sends gets a 401.

## 6. Rotate from a script

With a management key, the [Keys](/docs/reference/keys) routes run the same rotation without the app. Set `OPENDUNES_MANAGEMENT_KEY` to it for these calls: an API key gets a 401.

The sample finds the oldest active key named `NAME`, creates its replacement with the same name, cap, cap reset and storage, and prints the new secret, once.

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

MANAGEMENT_KEY = os.environ["OPENDUNES_MANAGEMENT_KEY"]
ADDRESS = "https://opendunes.com/v1/keys"
NAME = "Souk Bot"
HEADERS = {
    "Authorization": "Bearer " + MANAGEMENT_KEY,
    "Content-Type": "application/json",
}


def call(method, body=None):
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(
        ADDRESS, data=data, headers=HEADERS, method=method
    )
    with urllib.request.urlopen(request) as response:
        return json.load(response)


old = next(k for k in call("GET")["data"] if k["name"] == NAME)
created = call("POST", {
    "name": NAME,
    "limit": old["limit"],
    "limit_reset": old["limit_reset"],
    "storage": old["storage"],
})

print("old key:", old["hash"])
print("new key:", created["data"]["hash"])
print("secret, shown once:", created["key"])
```

```javascript
const MANAGEMENT_KEY = process.env.OPENDUNES_MANAGEMENT_KEY;
const ADDRESS = "https://opendunes.com/v1/keys";
const NAME = "Souk Bot";
const HEADERS = {
  Authorization: `Bearer ${MANAGEMENT_KEY}`,
  "Content-Type": "application/json",
};

const listed = await fetch(ADDRESS, { headers: HEADERS });
const { data: keys } = await listed.json();
const old = keys.find((key) => key.name === NAME);

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({
    name: NAME,
    limit: old.limit,
    limit_reset: old.limit_reset,
    storage: old.storage,
  }),
});
const created = await response.json();

console.log("old key:", old.hash);
console.log("new key:", created.data.hash);
console.log("secret, shown once:", created.key);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/keys"
	name    = "Souk Bot"
)

var managementKey = os.Getenv("OPENDUNES_MANAGEMENT_KEY")

type key struct {
	Hash       string   `json:"hash"`
	Name       string   `json:"name"`
	Limit      *float64 `json:"limit"`
	LimitReset *string  `json:"limit_reset"`
	Storage    bool     `json:"storage"`
}

func call(method string, body any, into any) {
	var payload bytes.Buffer
	if body != nil {
		if err := json.NewEncoder(&payload).Encode(body); err != nil {
			panic(err)
		}
	}
	req, err := http.NewRequest(method, address, &payload)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+managementKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	if err := json.NewDecoder(res.Body).Decode(into); err != nil {
		panic(err)
	}
}

func main() {
	var listed struct {
		Data []key `json:"data"`
	}
	call("GET", nil, &listed)

	var old *key
	for i := range listed.Data {
		if listed.Data[i].Name == name {
			old = &listed.Data[i]
			break
		}
	}
	if old == nil {
		panic("no active key named " + name)
	}

	var created struct {
		Key  string `json:"key"`
		Data key    `json:"data"`
	}
	call("POST", map[string]any{
		"name":        name,
		"limit":       old.Limit,
		"limit_reset": old.LimitReset,
		"storage":     old.Storage,
	}, &created)

	fmt.Println("old key:", old.Hash)
	fmt.Println("new key:", created.Data.Hash)
	fmt.Println("secret, shown once:", created.Key)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/keys"
NAME="Souk Bot"

OLD="$(curl -s "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" |
  jq -c --arg name "$NAME" 'first(.data[] | select(.name == $name))')"

echo "old key: $(echo "$OLD" | jq -r .hash)"

curl -s "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d "$(echo "$OLD" | jq -c '{name, limit, limit_reset, storage}')" |
  jq -r '"new key: " + .data.hash, "secret, shown once: " + .key'
```

Steps 2 and 3 stay the same. Then the old key's `hash` pauses it, and deletes it:

| Route | Body | Does |
|---|---|---|
| `PATCH /v1/keys/{hash}` | `{"disabled": true}` | pauses the key; `{"disabled": false}` lets it run again |
| `DELETE /v1/keys/{hash}` | none | deletes the key; a request sent with it gets a 401 from then on |

Every key route is free.
