> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# API keys

> Every request carries an API key. Create one, limit it to some areas, to one sandbox or to a lifetime, list and revoke keys, and what each error means.

An **API key** is how Fibre knows who is making a request. Every request you send includes a key, in the
`Authorization` header, and Fibre uses it to decide which account the request belongs to and what it is allowed
to do.

A key does not have to be all-powerful. You can create keys that can only do certain things, keys that only work
on one sandbox, and keys that stop working after a set time. This page shows how, and why you would want to.

## Use your key

Create your first key in the dashboard, under **API keys**. It starts with `fb_live_`. **Copy it as soon as it is
created: Fibre shows it only once** and keeps only a fingerprint of it, so it cannot be shown again. If you lose
it, create a new one.

Send the key as a bearer token. The SDKs read it from the `FIBRE_API_KEY` environment variable, or you can
pass it in yourself:

```bash title="curl" norun reason="shows the header; every example on these docs sends it" theme={null}
curl -sS "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY"
```

```bash title="CLI" norun reason="shows where the CLI takes its key" theme={null}
# the CLI uses FIBRE_API_KEY when it is set, else the key you saved with `fibre login`; or pass one
fibre list --api-key "$MY_FIBRE_KEY"
```

```typescript title="TypeScript" norun reason="shows the client options" theme={null}
import { Fibre, Sandbox } from "@fibre-dev/sdk";

// reads FIBRE_API_KEY by default; or pass a key
const fibre = new Fibre({ apiKey: process.env.MY_FIBRE_KEY });
const sbx = await Sandbox.create({}, fibre);
```

```python title="Python" norun reason="shows the client options" theme={null}
import os

from fibre import Fibre, Sandbox

# reads FIBRE_API_KEY by default; or pass a key
fibre = Fibre(api_key=os.environ["MY_FIBRE_KEY"])
sbx = Sandbox.create(client=fibre)
```

A key from the dashboard can do everything your account can do. That is convenient on your own machine, but risky
anywhere else. For a CI job, a script or an agent, it is much safer to create **a key that can do only what that
job needs**. If such a key leaks, the damage is limited to what it was allowed to do.

## A key for one job

**1. Create it with scopes and an expiry**

Two settings narrow a key down:

* **`scopes`** lists what the key may do. `sandboxes.read`, for example, lets it look at sandboxes but not create or
  change them. All the scopes are listed [further down](#scopes).
* **`expires_in_sec`** sets when the key stops working.

This creates a key that can only read sandboxes, and only for the next hour:

```bash title="CLI" run theme={null}
CI=$(fibre key create ci-read-only --scope sandboxes.read --expires 1h --json)
CI_ID=$(echo "$CI" | jq -r .id)
CI_KEY=$(echo "$CI" | jq -r .key)
```

```typescript title="TypeScript" run theme={null}
import { Fibre, PermissionDeniedError, Sandbox } from "@fibre-dev/sdk";

const fibre = new Fibre();
const ci = await fibre.json<{ id: string; key: string }>("POST", "/v1/auth/api-keys", {
  body: { name: "ci-read-only", scopes: ["sandboxes.read"], expires_in_sec: 3600 },
});
```

```python title="Python" run theme={null}
from fibre import Fibre, PermissionDeniedError, Sandbox

fibre = Fibre()
ci = fibre.json("POST", "/v1/auth/api-keys", json={"name": "ci-read-only", "scopes": ["sandboxes.read"], "expires_in_sec": 3600})
```

```bash title="curl" run capture=KEY=.key theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/auth/api-keys" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "ci-read-only", "scopes": ["sandboxes.read"], "expires_in_sec": 3600}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "name": "ci-read-only",
>   "key": "…",
>   "scopes": ["sandboxes.read"],
>   "resource": null,
>   "expires_at": "…"
> }
> ```

**2. Use it**

Now try the new key. Listing sandboxes is a read, so it works. Starting a sandbox is a write, so Fibre refuses it
and says which scope was missing:

```bash title="CLI" run theme={null}
fibre list --api-key "$CI_KEY"
fibre create --api-key "$CI_KEY" --json || true   # {"error": {"code": "insufficient_scope", …}}
```

```typescript title="TypeScript" run theme={null}
const readOnly = new Fibre({ apiKey: ci.key });
for await (const s of Sandbox.list({}, readOnly)) console.log(s.id);
try {
  await Sandbox.create({}, readOnly);
} catch (e) {
  if (!(e instanceof PermissionDeniedError)) throw e;
  console.log(e.status, e.code); // 403 insufficient_scope
}
```

```python title="Python" run theme={null}
read_only = Fibre(api_key=ci["key"])
for s in Sandbox.list(client=read_only):
    print(s.id)
try:
    Sandbox.create(client=read_only)
except PermissionDeniedError as e:
    print(e.status, e.code)  # 403 insufficient_scope
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "code": "insufficient_scope",
>   "required": "sandboxes.write",
>   "granted": ["sandboxes.read"]
> }
> ```

> [!NOTE]
>
> A key can create other keys only if it has the `keys.write` scope. Even then, it can never create a key that can do
> more than itself, or one that lives longer than itself. So a limited key can never be used to make an unlimited
> one.

## A key for one sandbox

When an agent runs **inside** a sandbox, it often needs to use Fibre itself: to read its own files, start a
background command, or extend its own lifetime. Giving it your main key would let it reach every sandbox you own.

Instead, **bind a key to that one sandbox** with the `resource` field. The bound key works on that sandbox and
nothing else, and it is revoked automatically when the sandbox is deleted. Here is the whole flow:

**1. Start a sandbox**

```bash title="CLI" run theme={null}
SBX=$(fibre create --lifetime 10m --label docs=keys --json | jq -r .id)
```

```typescript title="TypeScript" run theme={null}
const sbx = await Sandbox.create({ lifetime: 600, labels: { docs: "keys" } });
```

```python title="Python" run theme={null}
sbx = Sandbox.create(lifetime=600, labels={"docs": "keys"})
```

```bash title="curl" run capture=SBX=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"lifetime_sec": 600, "labels": {"docs": "keys"}}'
```

**2. Create a key bound to it**

```bash title="CLI" run theme={null}
AGENT_KEY=$(fibre key create "agent-$SBX" --scope 'sandboxes.*' --sandbox "$SBX" --json | jq -r .key)
```

```typescript title="TypeScript" run theme={null}
const agent = await fibre.json<{ key: string }>("POST", "/v1/auth/api-keys", {
  body: { name: `agent-${sbx.id}`, scopes: ["sandboxes.*"], resource: sbx.id },
});
```

```python title="Python" run theme={null}
agent = fibre.json("POST", "/v1/auth/api-keys", json={"name": f"agent-{sbx.id}", "scopes": ["sandboxes.*"], "resource": sbx.id})
```

```bash title="curl" run capture=AGENT_KEY=.key theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/auth/api-keys" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d "{\"name\": \"agent-$SBX\", \"scopes\": [\"sandboxes.*\"], \"resource\": \"$SBX\"}"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "key": "…",
>   "scopes": ["sandboxes.*"],
>   "resource": "…"
> }
> ```

**3. Hand it to the program inside**

Pass the key to the program inside the sandbox as an environment variable of the command that starts it. Only that
command, and the programs it starts, can see it:

```bash title="CLI" run theme={null}
fibre exec "$SBX" --env FIBRE_API_KEY="$AGENT_KEY" -- 'test -n "$FIBRE_API_KEY" && echo has its key'
```

```typescript title="TypeScript" run theme={null}
const { stdout } = await sbx.run('test -n "$FIBRE_API_KEY" && echo has its key', { env: { FIBRE_API_KEY: agent.key } });
console.log(stdout); // has its key
```

```python title="Python" run theme={null}
print(sbx.run('test -n "$FIBRE_API_KEY" && echo has its key', env={"FIBRE_API_KEY": agent["key"]}).stdout)  # has its key
```

**4. It reaches its own sandbox, and nothing else**

```bash title="CLI" run theme={null}
fibre get "$SBX" --api-key "$AGENT_KEY" --json | jq -r .status   # running
fibre create --api-key "$AGENT_KEY" --json || true   # {"error": {"code": "key_resource_bound", …}}
```

```typescript title="TypeScript" run theme={null}
const own = new Fibre({ apiKey: agent.key });
console.log((await Sandbox.get(sbx.id, own)).status); // running
try {
  await Sandbox.create({}, own);
} catch (e) {
  if (!(e instanceof PermissionDeniedError)) throw e;
  console.log(e.code); // key_resource_bound
}
```

```python title="Python" run theme={null}
own = Fibre(api_key=agent["key"])
print(Sandbox.get(sbx.id, client=own).status)  # running
try:
    Sandbox.create(client=own)
except PermissionDeniedError as e:
    print(e.code)  # key_resource_bound
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $AGENT_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["echo", "only this one"]}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "exit_code": 0,
>   "stdout": "only this one\n"
> }
> ```

If the key is used for anything outside its sandbox, such as listing all sandboxes, Fibre refuses it:

```bash title="curl" run theme={null}
curl -sS "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $AGENT_KEY"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "code": "key_resource_bound"
> }
> ```

If the key asks for a different sandbox by its ID, Fibre answers `404 sandbox_not_found`, as if that sandbox did
not exist. The key cannot even learn which other sandboxes you have.

## List and revoke keys

You can list all the keys of your account at any time. The list shows each key's name, its first few characters
(`prefix`, so you can recognise it), its scopes and when it was last used. It never shows the key itself.

To revoke a key, delete it. **A revoked key stops working immediately.**

```bash title="CLI" run theme={null}
fibre key list

fibre key revoke "$CI_ID"
fibre delete "$SBX"   # its bound key goes with it
```

```typescript title="TypeScript" run theme={null}
const { keys } = await fibre.json<{ keys: { id: string; name: string; prefix: string }[] }>("GET", "/v1/auth/api-keys");
console.log(keys.map((k) => `${k.name} ${k.prefix}`));

await fibre.json("DELETE", `/v1/auth/api-keys/${ci.id}`);
await sbx.delete(); // its bound key goes with it
```

```python title="Python" run theme={null}
keys = fibre.json("GET", "/v1/auth/api-keys")["keys"]
print([f"{k['name']} {k['prefix']}" for k in keys])

fibre.json("DELETE", f"/v1/auth/api-keys/{ci['id']}")
sbx.delete()  # its bound key goes with it
```

```bash title="curl" run theme={null}
curl -sS "$FIBRE_API_URL/v1/auth/api-keys" -H "Authorization: Bearer $FIBRE_API_KEY" \
  | jq '.keys[] | {id, name, prefix, scopes, resource, last_used_at}'
```

```bash title="curl: revoke one" run theme={null}
ID=$(curl -sS "$FIBRE_API_URL/v1/auth/api-keys" -H "Authorization: Bearer $FIBRE_API_KEY" \
  | jq -r '.keys[] | select(.name == "ci-read-only") | .id' | head -n 1)
curl -sS -X DELETE "$FIBRE_API_URL/v1/auth/api-keys/$ID" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "deleted": true,
>   "id": "…"
> }
> ```

```bash title="curl: delete the sandbox" run theme={null}
curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY"
```

## Scopes

A scope combines an **area** of the API with what the key may do there:

* `sandboxes.read` lets the key look, for example list sandboxes or read their status. Any `GET` request needs
  `.read`.
* `sandboxes.write` lets the key make changes, for example create, update or delete sandboxes, or run commands.
  Every other request needs `.write`.
* `sandboxes.*` allows both, and `*` on its own allows everything in every area.

These are the areas:

| Area | Covers |
| - | - |
| `sandboxes` | Sandboxes and everything in them: exec, commands, files, browser, desktop |
| `snapshots` | Snapshots |
| `images` | Images |
| `builds` | Image builds |
| `webhooks` | Webhooks |
| `keys` | API keys |
| `secrets` | Stored secrets: set, list and delete them. A sandbox or command that names a secret needs `secrets.read` |
| `billing` | Usage, balance and payments |
| `org` | Your organization's details (`GET /v1/org`) |

## Errors

If a request is refused because of its key, the answer tells you why:

| Status | Code | What happened |
| - | - | - |
| 401 | `missing_credentials` | No `Authorization: Bearer …` header |
| 401 | `invalid_api_key` | The key is wrong, revoked, expired, or its sandbox was deleted |
| 403 | `insufficient_scope` | The key's scopes do not cover this call; the answer names `required` and `granted` |
| 403 | `key_resource_bound` | A key bound to one sandbox was used for something else |
| 403 | `key_broader` | A new key would be able to do more than the key creating it |
| 400 | `unknown_scope` | A scope that does not exist; the answer lists the areas |
| 404 | `key_resource_not_found` | `resource` names no sandbox of yours |
| 404 | `api_key_not_found` | No key with that ID |

## Keep keys safe

A few habits keep your account safe:

* **Keep keys out of your code.** Read them from environment variables or a secret manager, and never commit them
  to a repository.
* **Give each job its own key.** A CI pipeline, a script and an agent should each have a separate key, with only
  the scopes and the lifetime they need. Then one leak affects one job.
* **Inside a sandbox, use a bound key.** It cannot reach anything beyond that sandbox.
* **If a key leaks, revoke it.** Nothing else needs to change: create a new key and carry on.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.