API keys¶
Every data endpoint in Canopy is gated by an API key. This page is the operator's runbook: how to mint, list, and revoke keys, and how the two credential layers behind the scenes fit together.
How keys work¶
Every key carries three independent scopes:
read— GET requests and WebSocket connections, plus the handful of POSTs that only read (Converter's conversions, Formula Engine's evaluate/validate).write— endpoints that change something: setting a PV, saving a snapshot, storing a config.admin— key management (this page's own HTTP surface) and other operational-not-data actions, such as dropping a Vole ring buffer.
admin is orthogonal, not a level above read/write — an admin key that
cannot itself read a PV is a better credential for a provisioning tool than one
that can do everything. A write key cannot mint or revoke keys; only admin
can.
Independently, every key also carries a module scope and a facility scope — see Module scoping and Facility scoping below.
Clients send the token in the X-API-Key header. WebSocket endpoints also
accept ?api_key=<token> for browsers that cannot set headers on a WebSocket
handshake — that parameter exists purely as a compatibility workaround and is
not a convention to extend to other endpoints.
Two credential layers¶
Keys resolve from two places, checked in order:
- Env (
CANOPY_API_KEYS) — a small, long-lived, statically-stable set. Parsed once at startup, so it keeps working even if Postgres is completely unreachable, including on a cold start when there is nothing cached yet. Checked first, so the highest-volume credential in the system — the read key baked into every display — never makes a database round trip. - Database — every other key: per-tool, per-user, and CI keys, and any
writekey. Minted and revoked without a deploy, cached briefly for latency, with revocation therefore not quite instant (see Revocation).
A deployment's env layer typically holds exactly two keys — one read key for
displays, one admin key for ops — and manages everything else in the
database. The env key is not an emergency-only credential: because the display
key ends up inlined into a public JS bundle at build time (via react-trace's
.env), it was never going to be a fast-revocation secret regardless of where
it lived, so it's simplest to keep it as a permanent, statically-stable floor
rather than a special break-glass case.
Unset means locked, not open
If both layers are empty, no keys exist and every gated endpoint returns
401. Startup logs the loaded env count — see Verifying.
Running without a database
An env key works with no Postgres at all. An unknown token, however,
falls through to the database registry, so with no database reachable it
returns 503 key_store_unavailable rather than 401 — the store
genuinely cannot say whether the token is valid.
Provisioning a key¶
Local development / Docker Compose¶
.env / docker/.env carry CANOPY_API_KEYS; docker-compose.yml defaults it
to dev:read+write@* when unset. Fine for a laptop, never for a shared host.
Everything else — the working set of keys for local testing — is easiest to
manage through the CLI once CANOPY_DATABASE_URL points somewhere real:
# Mint. -r/-w/-a add scopes; at least one is required.
uv run python scripts/create_key.py trace -r
uv run python scripts/create_key.py operator-tools -r -w
uv run python scripts/create_key.py ops-cli -a
# List (add -a for active-only).
uv run python scripts/list_keys.py
# Revoke.
uv run python scripts/deactivate_key.py <key-id>
create_key.py prints the plaintext token once — it is not recoverable, only
its hash is stored. These scripts talk to the database directly, so they work
with only CANOPY_DATABASE_URL set: no existing key is needed to bootstrap the
first one, which is what makes them the right tool for a fresh instance.
Without a local uv environment, run the same commands inside the api
container instead: docker compose run --rm api python scripts/create_key.py ....
Production instances¶
The env layer's two long-lived keys live in the instance's CANOPY_API_KEYS,
in the .env beside the production compose file (see
configuration):
CANOPY_API_KEYS=<display-read-token>:read@*,<ops-admin-token>:admin@*
Everything else for that instance — per-tool keys, CI keys — is minted with
the CLI against the instance's database, not through .env. The CLI ships
in the image (Dockerfile.prod copies scripts/), so run it in the running
api container rather than from a workstation — the instance's Postgres is
often bound to the host's 127.0.0.1 and isn't reachable from outside it:
docker compose run --rm api python scripts/create_key.py "<app>" -r
Rotating an env key is still a deploy; rotating anything else is a CLI call.
Managing keys over HTTP¶
The same operations are available at /v1/api-keys on the parent app, gated on
admin (never write — see Scope design below):
| Method | Path | Purpose |
|---|---|---|
POST |
/v1/api-keys |
Mint a key. Body: appName, any of read/write/admin, and optionally modules/facilities. Returns the plaintext token once. |
GET |
/v1/api-keys |
List keys (?activeOnly=true, ?appName=<name> to filter). Never returns a token. |
GET |
/v1/api-keys/count |
Count keys (?activeOnly=true to filter). |
DELETE |
/v1/api-keys/{id} |
Deactivate a key. |
curl -X POST -H "X-API-Key: <admin-token>" -H "Content-Type: application/json" \
-d '{"appName": "trace", "read": true}' \
http://localhost:<API_PORT>/v1/api-keys
Deactivating the key you're using
DELETE /v1/api-keys/{id} refuses to deactivate the key that authenticated
the request itself — 400 api_key_self_deactivation — since doing so
would lock that session out mid-use. Pass ?force=true to override, or use
scripts/deactivate_key.py, which has no such guard (it isn't a request
that can lock itself out).
Module scoping¶
A key can be restricted to one or more mounted sub-apps — mole, hare,
raccoon, vole, formula-engine, squirrel, magpie, jobs, converter, elog
— or core, for the parent app's own routes (/health, /v1/api-keys).
Minting a key via the CLI or POST /v1/api-keys without naming any modules
grants every module, an explicit default of ["*"] at that layer. There is no
such default for the env layer — see below.
This constrains which surface a key can call, not which data it can
see through that surface — a squirrel-scoped key can reach every route
squirrel exposes, the same as an unscoped key would. Restricting which
facility's data a key can see is a separate mechanism — see
Facility scoping below.
Set it with -m/--module (repeatable) on scripts/create_key.py, or the
modules field on POST /v1/api-keys:
uv run python scripts/create_key.py trace -r -m formula-engine -m vole
curl -X POST -H "X-API-Key: <admin-token>" -H "Content-Type: application/json" \
-d '{"appName": "trace", "read": true, "modules": ["formula-engine", "vole"]}' \
http://localhost:<API_PORT>/v1/api-keys
For an env-layer key, always give the @<module>[+<module>] suffix. An entry
with no @ at all still works for now: it is treated as @* (every module)
and logs a deprecation warning at startup. This fallback will eventually be
removed. Use @* to apply permissions to every module:
CANOPY_API_KEYS="trace:read@formula-engine+vole,ops:admin@*"
A key that resolves but isn't scoped to the module a route belongs to gets
403 insufficient_module_access — checked before the read/write/admin
scope check, so an out-of-scope, no-access key is still reported as
out-of-scope, not out-of-read.
Facility scoping¶
A key can also be restricted to one or more core.facility slugs — a global
attribute of the key, independent of module scope. Naming a facility grants
that facility and everything beneath it in the hierarchy, the same "itself
plus descendants" rule ?facility= filtering itself uses.
A ?facility= naming a facility that doesn't exist is a 404 facility_not_found
— for any key, restricted or not. The slug is resolved before it's intersected
with the key's own grant, so an unrestricted key gets the same 404 a restricted
one does.
The grant itself is defined and validated here; nothing yet consults it. A data-serving module (Squirrel) reading and enforcing this scope on its own reads and writes is separate, not-yet-merged work — until it lands, a facility-scoped key authenticates and passes module/read/write checks normally, but every module ignores its facility grant.
Unlike module scope, an empty facility list is valid and meaningful — it's
the default for a newly minted key, and means "provisioned but not yet
assigned to a facility" (or "data access suspended without revoking the
credential entirely"). Minting without any -f/facilities value leaves this
empty; there is no implicit "every facility" default the way module scope
defaults to ["*"]. Pass the wildcard explicitly (-f '*' or
"facilities": ["*"]) for a key that should see every facility's data.
Keys configured via CANOPY_API_KEYS are always granted every facility. There
is no env syntax for facility scope and deliberately won't be: env keys are the
statically stable floor that has to keep working through a database outage, and
resolving a facility grant requires reading the hierarchy from the database.
Restrict by facility with a database-backed key.
The rest of this section calls a key unrestricted if it is granted * or
comes from CANOPY_API_KEYS, and restricted otherwise — including a key
with an empty grant. Facility scope is independent of read/write/admin:
those are flags on the key as a whole, and a key's one facility list applies to
all of them. There is no "write here, read-only there."
Set it with -f/--facility (repeatable) on scripts/create_key.py, or the
facilities field on POST /v1/api-keys:
uv run python scripts/create_key.py trace -r -f lcls -f lcls-sc
curl -X POST -H "X-API-Key: <admin-token>" -H "Content-Type: application/json" \
-d '{"appName": "trace", "read": true, "facilities": ["lcls", "lcls-sc"]}' \
http://localhost:<API_PORT>/v1/api-keys
Every slug named in a grant must already exist — a mistyped one is a 400 naming
it. A typo'd grant resolves to "matches nothing" at request time, so the key would
authenticate normally and then see and write nothing, with no error to point at the
mistake. Define the facility first (see
Defining facilities). * names no slug, so it
needs nothing defined.
For the same reason, a facility that any active key grants cannot be deleted:
DELETE /v1/facilities/{slug} is refused with facility_in_use until the grants
are gone. Deactivating a key releases its grants.
Reads are filtered, not refused. Every PV and snapshot read a restricted key makes is filtered; there is no unfiltered read for it to fall back on:
- PV lists (
GET /v1/pvs,/paged,/search) return only PVs assigned to a facility the key holds. - The snapshot list (
GET /v1/snapshots) returns only snapshots filed under a facility the key holds. - A single snapshot or a comparison (
GET /v1/snapshots/{id},/{id1}/compare/{id2}) is a404if a snapshot is filed under a facility the key doesn't hold, so it can't be read by id either.
A request's own ?facility= filter is intersected with the key's grant, so it
can narrow results but never widen them. A key with an empty grant gets zero
rows, and asking for a facility the key isn't granted returns nothing rather
than everything. Tags, the device list, and meta-PVs (see below) are global
and not filtered.
Writes are refused, with a 403 insufficient_facility_access — a filtered
write would silently do nothing, which is worse than an error. The rules:
- Updating or deleting a PV requires the key to hold every facility
affected. For any PV update, the key must hold all of the PV's current
facilities and, when changing its facility list, all of the requested
facilities too. This covers both facilities being added and facilities being
removed. Deleting a PV requires access to all its current facilities. A key
scoped to only one facility cannot update or delete a PV also assigned to
another one; holding one shared facility is not enough to reach the rest
of the row. (A snapshot has at most one facility, so updating or deleting it
requires membership in that facility — but unlike a PV, a snapshot outside
the key's grant is a
404, not a403naming its facility: a snapshot's existence is already hidden from a key that can't reach it (see below), so naming the facility on update/delete would leak it to a caller that merely guessed the id.) - A row with no facility assignment is writable only by an unrestricted
key. No grant can cover a row that names no facility, so a restricted key —
even one holding every facility that currently exists — is refused, the same
way it's refused a row assigned to a facility it doesn't hold. This also
means a restricted key can't strip a row's last facility and un-assign it:
that write is refused outright, not silently let through because the key
held everything the row used to be assigned to. Update and delete report
this as
403(the row's own facility check runs, not the read-masking one reads use), unlike restore and read, which report an unreachable row as404instead. - Creating a new PV requires a facility-restricted key to hold at least one of the PV's requested facilities. A PV assigned to multiple facilities may therefore include facilities outside the creator's grant, but each row in a bulk create must independently include at least one facility the key holds. A restricted key cannot create an unassigned PV: that row would not be reachable under the "unassigned requires unrestricted" rule for later writes.
- Creating a snapshot requires a facility-restricted key to hold the snapshot's facility. The facility is singular; a restricted key cannot create an unassigned snapshot that captures every registered PV.
- Restoring a snapshot is gated on the snapshot's facility, the same as viewing
it: a snapshot the key can't see is a
404, including an unassigned one for a restricted key. Within a visible snapshot, a PV is included in the restore if the key holds any one of its facilities — the same rule capture and listing use, not the full-containment rule update/delete use. Restore only writes the value captured under this snapshot's own facility; it never touches the PV's other facilities, so it isn't mutating the shared row the way update/delete do, and doesn't need to require every facility on it. A PV with no facility assignment left, or whose facility was reassigned after capture to one the key holds none of, is skipped and reported in the job result'sskippedPvIds; if every PV is skipped, the restore is a403.
A 403 insufficient_facility_access names the facilities the key lacks. A refused
POST /v1/pvs/multi or POST /v1/pvs/import names every one the import needs,
and lists the refused rows, since one bad row refuses the whole batch.
POST /v1/pvs/import applies the create rule above to every row before it
looks up which addresses are already registered, as POST /v1/pvs/multi does.
So a row naming no facility the key holds gets the same 403 whether or not its
address exists. With onConflict=skip, a registered PV is left alone whatever its
facilities, and the response only repeats the skipped rows' own addresses. That
tells the key no more than the 409 from POST /v1/pvs/multi already does. With
onConflict=update, the key must hold all of the facilities of every registered
PV the import matches, as PUT /v1/pvs/{id} requires. Otherwise the whole import
is refused. That refusal lists the rows, but it doesn't name the facilities of a
PV the key can't write, since the key only supplied an address. An import never
changes a registered PV's facilities: a matched row's facilities only has to
pass the create rule above, and PUT /v1/pvs/{id} is how a PV moves between
facilities.
Checking access ahead of a write. GET /v1/facilities/access returns the
calling key's own reach, so a client can check before writing instead of finding
out from a 403 (an import preview, or a facility picker that shows only what the
key can use):
{"unrestricted": false, "facilities": ["lcls", "lcls-nc", "lcls-sc"]}
facilities lists every reachable slug, with a parent grant expanded to its
descendants, so a client tests membership directly. An unrestricted key gets
{"unrestricted": true, "facilities": []}. An admin key reports its own grant
like any other. It's read-gated like GET /v1/facilities and needs the core
module, so a key scoped only to squirrel gets a 403 here. It's under
/v1/facilities rather than /v1/api-keys because key management is admin-only,
and the keys that need this answer aren't admin keys.
Where facilities come from. Both are set by the user. A PV's facilities (it
can have several) are assigned when it's created or edited, through facilities
on POST/PUT /v1/pvs. A snapshot has at most one facility, chosen when it's
taken through facility on POST /v1/snapshots, and that choice decides what it
captures: only the PVs assigned to that facility or one of its descendants, the
same set GET /v1/pvs?facility=<slug> returns. An lcls snapshot holds the
lcls, lcls-sc, and lcls-nc PVs, never facet's. PVs with no facility are
left out. A snapshot with no facility captures every registered PV, and only
an unrestricted key can create one.
Snapshot reads and restore can disagree on an old snapshot. A snapshot
taken before facility scoping existed holds every PV's values as of capture.
If a PV held then is later reassigned to a facility the key holds none of,
that key can still read the old values in the snapshot (the snapshot's own
facility gate is what's checked, not each PV's current one) but restore
skips that PV, since restore checks each PV's current facility membership —
any one shared facility, same as capture and listing. The read is correct as
history; only a future restore follows today's assignment.
This check and a concurrent mint aren't serialized against each other — each runs in its own transaction with no lock between them — so a delete and a mint of a key granted the same facility, racing within the same narrow window, could each see the other's not-yet-committed state. In practice this needs two admin actions targeting the same facility at nearly the same instant, which is far outside normal operation; it isn't a guarantee against that specific race.
A related race exists between deleting a facility and a snapshot job already
queued against it: the in-use check only looks at PVs and snapshots that exist
when the facility is deleted, not jobs already in Redis. A snapshot job
enqueued for a facility that's deleted before the worker picks it up resolves
an empty capture scope and produces a zero-PV snapshot whose facility_id no
longer exists in core.facility — visible and repairable only by an
unrestricted key, since a restricted key's facility-filtered reads can't match
an id with no corresponding row. This is the same class of narrow,
admin-action-timed race as the one above, not a routine occurrence.
Meta-PVs are exempt. Which PVs are meta-PVs (shown as summary columns on every
snapshot), their display names, and whether they're active are global settings, not
facility data. Any write-scoped key can add, rename, enable, disable, or remove one,
and GET /v1/pvs/meta lists all of them regardless of the key's facility scope. The
meta-PV values shown on a snapshot follow that snapshot's own facility gate.
Why admin, not write¶
Gating key management on write would let any write-capable client — every
tool that can set a live setpoint — mint credentials that outlive rotation of
its own key. write is the largest, least-controlled population of keys in
Canopy, and the wrong one to trust with provisioning. admin is a separate,
narrowly-held scope for exactly this and other operational actions — for the
same reason, POST /vole/v1/_debug/evict/{pv} (dropping a ring buffer) is
gated on admin too, not write: it's an operational action, not a data
write.
Rotation¶
Overlapping keys make rotation zero-downtime:
- Mint the new key (
scripts/create_key.pyorPOST /v1/api-keys). Both old and new tokens are now valid. - Roll clients over to the new token.
- Deactivate the old key (
scripts/deactivate_key.pyorDELETE /v1/api-keys/{id}).
last_used_at (visible via GET /v1/api-keys) is what turns "is it safe to
deactivate the old key yet?" from a guess into a query — check it before step 3
rather than picking an arbitrary overlap window.
Rotating an env key is still the old process: add the new token to
CANOPY_API_KEYS, deploy, roll clients, remove the old token, deploy again.
Keep the env layer's population small (the two long-lived keys) specifically
so this stays rare.
Revocation¶
Deactivating a database-backed key (CLI or HTTP) takes effect once its cached
entry expires — the cache TTL is the revocation latency (CANOPY_API_KEY_CACHE_TTL_S,
default 60s). If Postgres itself is unreachable when you deactivate a key, the
cached entry may still be served stale for up to CANOPY_API_KEY_MAX_STALE_S
(default 1h) — bounded so an outage cannot keep a revoked key alive forever,
but worth knowing if a leak coincides with a database outage.
Revoking an env key is a deploy, same as rotation: the practical exposure window is the length of your deploy pipeline.
Production hygiene¶
Before declaring an instance provisioned:
- [ ]
CANOPY_API_KEYSdoes not contain thedev:read+write@*default. - [ ] Tokens are freshly generated per instance — not shared between DEV and a facility, and not shared with another SLAC app.
- [ ] Only one
adminkey exists in the env layer (for ops), and it is not also used as aread/writecredential anywhere else. - [ ]
CANOPY_DEBUGisfalse(verbose errors otherwise). - [ ] The env tokens are recorded in a secrets manager; database-backed tokens are recorded wherever the owning team tracks its own credentials.
Verifying a deployment¶
The startup log reports what the env layer loaded, without ever printing a token:
Registered 2 API key(s) from CANOPY_API_KEYS (1 read, 0 write, 1 admin, 0 module-scoped)
An empty env layer is not itself a problem — it just means every key comes
from the database — and logs an INFO line saying so rather than a warning. A
malformed entry, an empty token, or an unrecognized scope (read+wrote, say)
each warn and name their position, never their content:
# docker-compose.prod.yml sets no container_name; `compose logs` resolves the
# service name for you rather than requiring you to guess the container's.
docker compose logs api --since 10m | grep CANOPY_API_KEYS
The container's healthcheck hits /health every 10s, so a plain --tail 50
scrolls the startup summary out of view within minutes of boot — use
--since (anchored to the deploy time) instead, or reach for Actions ->
Container Host Maintenance -> app-logs (raise log_tail) if you're
working from CI rather than the host.
Then confirm end to end, from a client's point of view:
# Ungated — proves the process is up, says nothing about keys:
curl http://localhost:<API_PORT>/health
# Read-gated — 200 means the key is valid and has read scope:
curl -H "X-API-Key: <token>" http://localhost:<API_PORT>/hare/v1/health/summary
# Expect 401 {"code": "invalid_api_key", ...}:
curl -H "X-API-Key: not-a-real-token" http://localhost:<API_PORT>/hare/v1/health/summary
# Admin-gated key management — 200 with the admin token, 403 with anything else:
curl -H "X-API-Key: <admin-token>" http://localhost:<API_PORT>/v1/api-keys
A key with the wrong scope returns 403 with code insufficient_read_access,
insufficient_write_access, insufficient_admin_access, or (see
Module scoping) insufficient_module_access —
distinguishing "unknown token" (401) from "known token, not allowed here"
(403).
Keys file and closed meta routes¶
Both are off by default.
A keys file instead of CANOPY_API_KEYS¶
CANOPY_API_KEYS_FILE names a file that replaces CANOPY_API_KEYS as the
static tier. The database tier still chains behind it, and, like an env key, a
file key grants every facility.
- Entries use the
CANOPY_API_KEYSgrammar, one per line or comma-separated. - The file is read strictly. Every entry carries
readand an@<module>suffix, and the file has no comments. - A file that cannot be read, holds no key or holds one bad entry stops startup. The error names the entry's position, never its content.
- When both settings are set, the file wins and the startup log warns that
CANOPY_API_KEYSis ignored. - The file is read once, at startup. After rotating it (a Kubernetes Secret mounted as a file, say), restart the API: a removed key stays valid until then.
- Canopy does not check the file's permissions. Make it readable only by the user the API runs as.
Closed meta routes¶
With CANOPY_CLOSED_META=true, every route except GET /health needs a key
scoped to the module it targets. That includes /, /docs, /openapi.json,
/metrics, and each module's docs, OpenAPI and /v1/health/watchdog.
- The gate checks only that the key is known and scoped to the module. Each
route still checks
read,writeoradminitself, so write-only and admin-only keys work as they do without the gate. - Refusals are
401 invalid_api_key,403 insufficient_module_accessor503 key_store_unavailable, with CORS headers, so a browser client can read them. - A CORS preflight needs no key.
GET /healthstays open behind a path prefix (uvicorn --root-path) too.
Before turning it on:
- Probes. Point liveness and readiness probes at
GET /health; the per-module watchdogs need a key. - Prometheus. A scrape of
/metricsmust send a key scoped tocorein theX-API-Keyheader. The bundleddocker/observability/prometheus.ymlsends none, so its scrape fails with401. - Analytics. Anonymous
POST /analytics/v1/eventsis refused; clients send a key scoped toanalytics. - Browser clients. Send the key on every request, docs included.
Known limitations¶
- Keys have no expiration (
expires_at) — nothing enforces one today.