# Authentication

API keys of a Router space, how to send them, their limits, expiry and rotation.

Every request to `/api/v1` except `GET /api/v1/models` needs an API key in the `Authorization` header:

```http
Authorization: Bearer sk-nr-...
```

## API keys

An API key belongs to one Router space. Members with the right role create keys on the **API keys** page of the space in the cabinet. A key looks like `sk-nr-<prefix>-<secret>`:

- the secret is shown **once**, when the key is created; the router stores only a hash and the prefix;
- usage of every key is billed to the payer of its space and appears in the space's logs.

## Key settings

| Setting             | What it does                                                                 |
| ------------------- | ---------------------------------------------------------------------------- |
| Budget              | The most a key may spend, in PnP. A request that would exceed it gets `402`. |
| Budget reset        | Never, daily, weekly or monthly; resets happen at 00:00 Moscow time.         |
| Requests per minute | A lower request rate for this key than the default limit.                    |
| Expiration          | The date after which the key stops working (`401`). It can be extended.      |
| Disable / Enable    | Pauses a key without revoking it. A disabled key gets `401`.                 |
| Revoke              | Deletes the key for good.                                                    |

`GET /api/v1/key` returns the current spend, budget, reset period and expiration of the key that calls it. See [GET /key](/docs/en/api/key).

## Keep keys secret

- Call the API from your server, never from a browser or a mobile app: anyone who can read the page can read the key. The API does not send CORS headers, so browsers on other sites cannot call it anyway.
- Keep keys in environment variables or a secret manager, not in code or repositories.
- Use a separate key per application or environment: you can then set its budget and revoke it on its own.

## Rotate a key

1. Create a new key in the same Router space.
2. Deploy it to your application.
3. Check in the logs that requests use the new key, then revoke the old one.

## Authentication errors

| Status | Message                                                  | What to do                                     |
| ------ | -------------------------------------------------------- | ---------------------------------------------- |
| `401`  | `invalid API key`                                        | Check the header and the key.                  |
| `401`  | `the API key is disabled` / `has expired` / `is revoked` | Enable or extend the key, or create a new one. |
| `402`  | `the API key spending limit is reached`                  | Raise the budget or wait for the reset.        |
| `403`  | `the Router space has no payer Nodul space`              | Choose a payer in the space settings.          |

All error codes: [Errors](/docs/en/errors).
