> For the complete documentation index, see [llms.txt](https://rosemary-2.gitbook.io/rosemary-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rosemary-2.gitbook.io/rosemary-docs/tutorials/token-scope-mapping.md). Agents can also search and read this documentation through its [MCP server](https://rosemary-2.gitbook.io/rosemary-docs/~gitbook/mcp).

# Token Scopes & Endpoint Mapping

***

*Advanced · 20 minutes*

Rosemary's REST API is gated by three permission scopes - `read`, `write`, `admin`. This tutorial maps every `/api/v1/...` endpoint to the exact scope it requires, shows how tokens are created with multiple scopes, and how `admin` acts as a superset.

***

### How the Middleware Decides

Two rules worth understanding upfront:

* A token holding `admin` passes **every** scope check, even on `read`-only endpoints. There is no "least privilege" override - `admin` is a superset.
* A token is created with a **list** of permissions, not a single scope. `["read","write"]` is a perfectly valid combination that gives the same access as a write token, plus the explicit ability to read.

Expired tokens are evicted on the first request that arrives after `expires_at`. `last_used_at` is updated on every successful authentication - useful for spotting tokens that have gone cold.

***

### Token Fields

Every token carries:

| Field          | Meaning                                                        |
| -------------- | -------------------------------------------------------------- |
| `id`           | Short opaque identifier; use this to revoke or look up a token |
| `token`        | The raw Bearer value; only returned on creation, never on list |
| `name`         | Human label, max 64 chars                                      |
| `created_at`   | ISO timestamp                                                  |
| `last_used_at` | ISO timestamp of last successful auth                          |
| `expires_at`   | ISO timestamp; absent means no expiry                          |
| `permissions`  | Array of scopes (`read`, `write`, `admin`)                     |

***

### Full Endpoint → Scope Table

| Endpoint                              | Method          | Required Scope |
| ------------------------------------- | --------------- | -------------- |
| `/api/v1/auth`                        | POST            | none (key)     |
| `/api/v1/status`                      | GET             | `read`         |
| `/api/v1/agents`                      | GET             | `read`         |
| `/api/v1/agents/{id}` (and sub-paths) | GET             | `read`         |
| `/api/v1/agents/{id}/...`             | POST            | `write`        |
| `/api/v1/routes`                      | GET             | `read`         |
| `/api/v1/routes`                      | PATCH           | `write`        |
| `/api/v1/forwards`                    | GET/POST/DELETE | `write`        |
| `/api/v1/rforwards`                   | GET/POST/DELETE | `write`        |
| `/api/v1/socks`                       | GET/POST/DELETE | `write`        |
| `/api/v1/connect-bind`                | POST            | `admin`        |
| `/api/v1/cli`                         | POST            | `admin`        |
| `/api/v1/settings`                    | GET/PATCH       | `admin`        |
| `/api/v1/tokens`                      | GET/POST        | `admin`        |
| `/api/v1/tokens/revoke`               | POST            | `admin`        |
| `/api/v1/shutdown`                    | POST            | `admin`        |
| `/api/dashboard-data`                 | GET             | `read`         |

Notes:

* `/api/v1/auth` is the only unauthenticated path. It exchanges the server key for a bootstrap token that already has all scopes.
* `/api/v1/routes` is mixed-method: a read-scope token can list routes but not toggle them.
* Per-agent control endpoints (`/api/v1/agents/{id}/ping`, `/discover`, `/portscan`, `/disconnect`, etc.) require `write` because they POST.
* The `/api/v1/cli` escape hatch needs `admin` even for an innocuous-looking REPL command. Treat it like shell access.

***

### Bootstrap: From Server Key to a Working Token

`/api/v1/auth` is your entry point. The returned token carries every scope.

```bash
SERVER=http://operator.local:1024
KEY="xK9mP2qL...base64...=="

BOOTSTRAP=$(curl -s -X POST $SERVER/api/v1/auth \
  -H "Content-Type: application/json" \
  -d "{\"key\":\"$KEY\"}" | jq -r .token)
```

Treat this like the root password. The next step should be to mint scoped tokens and stop using the bootstrap.

***

### Creating Scoped Tokens

`POST /api/v1/tokens` requires `admin`. Body shape:

```json
{
  "name": "ci-pipeline",
  "permissions": ["read", "write"],
  "ttl_hours": 24
}
```

Field rules:

* `name` - required, max 64 chars
* `permissions` - array; invalid entries silently dropped; if empty after filtering, defaults to `["read"]`
* `ttl_hours` - integer; if `<= 0`, token never expires

Read-only token for an inventory script:

```bash
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" \
  -H "Content-Type: application/json" \
  -d '{"name":"inventory-poller","permissions":["read"],"ttl_hours":168}' | jq
```

Read + write for a CI deployment script (no admin):

```bash
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" \
  -H "Content-Type: application/json" \
  -d '{"name":"ci-deploy","permissions":["read","write"],"ttl_hours":8}' | jq
```

Admin for a short-lived migration job (1 hour):

```bash
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" \
  -H "Content-Type: application/json" \
  -d '{"name":"migration-2026-05","permissions":["admin"],"ttl_hours":1}' | jq
```

Response:

```json
{
  "id": "Hd71xCqK",
  "token": "tun_abc123...",
  "name": "migration-2026-05",
  "created_at": "2026-05-15T10:00:00Z",
  "expires_at": "2026-05-15T11:00:00Z",
  "permissions": ["admin"]
}
```

Capture both `token` (used as Bearer) and `id` (used to revoke).

***

### Listing and Revoking

```bash
curl -s -H "Authorization: Bearer $BOOTSTRAP" $SERVER/api/v1/tokens | jq
```

The list omits the raw token string - you only see id, name, scopes, timestamps. This is intentional: a leaked admin token cannot be re-discovered by listing.

Revoke by id:

```bash
curl -s -X POST $SERVER/api/v1/tokens/revoke \
  -H "Authorization: Bearer $BOOTSTRAP" \
  -H "Content-Type: application/json" \
  -d '{"id":"Hd71xCqK"}'
```

Server logs:

```
[API] Token revoked: name="migration-2026-05" id=Hd71xCqK
```

***

### Failure Modes by Scope

The middleware returns specific JSON errors. Use them to debug.

**No / wrong token:**

```
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="tunnel-api"
{"error":"invalid_token"}
```

**Token valid but scope too narrow:**

```
HTTP/1.1 403 Forbidden
{"error":"insufficient_permissions"}
```

**Token expired:** same as "no token" (`401 invalid_token`) - the entry is deleted on the failed lookup.

***

### Worked Example: Three Tokens for One Engagement

A realistic layout for a multi-person red-team operation:

```bash
# 1. Inventory dashboard for the manager - read only, long-lived
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" -H "Content-Type: application/json" \
  -d '{"name":"manager-dashboard","permissions":["read"],"ttl_hours":720}'

# 2. Per-operator working token - read + write, refreshed daily
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" -H "Content-Type: application/json" \
  -d '{"name":"op-alice","permissions":["read","write"],"ttl_hours":24}'

# 3. Break-glass admin - high TTL but stored offline, only used to mint others
curl -s -X POST $SERVER/api/v1/tokens \
  -H "Authorization: Bearer $BOOTSTRAP" -H "Content-Type: application/json" \
  -d '{"name":"break-glass","permissions":["admin"],"ttl_hours":168}'
```

Then **revoke the bootstrap** (look up its id in `tokens` list and call revoke) so the only path to admin from the network is the break-glass token, which lives in a password manager.

***

### Watching Token Activity

A small watchdog can compare `last_used_at` against now and flag tokens that look stale or, conversely, ones that should be dormant but are not:

```bash
curl -s -H "Authorization: Bearer $BOOTSTRAP" $SERVER/api/v1/tokens \
  | jq -r '.[] | [.id, .name, .permissions|join(","), .last_used_at] | @tsv'
```

```
Hd71xCqK  migration-2026-05  admin       2026-05-15T10:42:11Z
8bAcCwTx  ci-deploy          read,write  2026-05-15T10:43:55Z
3oPxK1nW  inventory-poller   read        2026-05-15T10:43:58Z
```

If `ci-deploy` shows recent activity at 03:00 on a Sunday, the token has been borrowed.

***

### Operational Rules of Thumb

* Never use the bootstrap token for anything except minting other tokens. Revoke it after your real tokens are in place.
* `admin` should be break-glass, not daily. Build day-to-day operations on `read` + `write`.
* `ttl_hours` short and rotate, rather than long and forget. The TTL field exists - use it.
* Tokens are arrays of permissions; you do not have to choose between `read` and `write` - you can have both without escalating to `admin`.
* `/api/v1/cli` is admin-gated because anything the REPL can do, it can do. Don't issue admin tokens to scripts that only need it for one specific command - run that command yourself, or wrap it in a thin write-scoped endpoint elsewhere.

***

### Key Points

* Three scopes: `read`, `write`, `admin`. `admin` is a superset.
* Tokens hold a **list** of scopes, not just one.
* Default scope on token create is `["read"]` if you forget to send any.
* `ttl_hours <= 0` means no expiry - explicit choice, not a default.
* The bootstrap token from `/auth` has every scope; rotate to scoped tokens and revoke it.
* Per-endpoint scope is enforced server-side - the client cannot bypass it by changing headers.
