openwrt-iac / uapi / docs / 4.0.1 / Tokens and scopes
uapi authenticates every request (except /healthz, /openapi.json, and
/schema/*) with a bearer token. Tokens are created on the router (or
over HTTP once a token with uapi:tokens:rw exists), hashed at rest, and
authorized against a hierarchical scope tree.
uapi-token create --name <label> --scope <scope> [--scope <scope>...] \
[--expires-in <N>[smhd]] [--allowed-cidr <CIDR>...] \
[--rate <N>] [--burst <N>] [--force]
--name: human-readable label. Must be unique: a name that another section of
/etc/config/uapi already holds is refused. Must match [A-Za-z0-9_]+ (uci
section-name charset; use underscores instead of hyphens). Surfaces in the
audit log on every authed request. POST /uapi/tokens takes at most 63
characters, and the CLI takes any length. A longer name keeps its rate-limit
bucket and its last-used marker in a file named by the sha256 of the name,
because a file name holds 255 bytes. A name longer than 238 characters gets no
series in /uapi/metrics, whose files are named by their labels.--scope: at least one. May repeat. Validated against the known scope tree
(see below); --force bypasses.--rate, --burst: optional per-token rate limit, see
Per-token rate limit.--expires-in: optional duration. Suffix is one of s/m/h/d. The token
returns 401 invalid_token with message: "Token expired" after the deadline
passes.--allowed-cidr: optional source-IP allowlist (IPv4 or IPv6 CIDRs; may
repeat). When set, the token returns 401 invalid_token with message:
"Source IP not permitted for this token" from any other source. Bad CIDR
shape rejected at mint time.The router stores only the salt + sha256(salt + ":" + bearer). The cleartext
cannot be recovered.
The token store is re-read from /etc/config/uapi on every request (uci read is
millisecond-scale; the fork-per-request model means no cross-request cache
anyway). Newly created tokens take effect immediately; no uhttpd reload is
needed.
uapi-token list # short summary: name, scopes, expiry (if set), allowed_cidrs (if set)
uapi-token show <name> # detailed view (scopes, expiry, cidrs, last_used_at/ip; no secret)
uapi-token revoke <name> # delete a token
uapi-token scopes [--json] # the known scope paths, one per line or as a JSON array
uapi-token create and revoke take the locks that an HTTP write of the token
store takes, the global lock shared and the lock of the uapi package
exclusive, so that a write of the CLI and one of the HTTP path to
/etc/config/uapi cannot lose each other. An HTTP write holds these locks for
milliseconds, and the CLI waits up to 10 s for them. A non-uci write, such as an
apk run through /packages/installed, can hold the global lock for longer.
When a lock is still held after 10 s, the command names it and exits 75
(EX_TEMPFAIL), having written nothing, so a retry is safe.
A token holding uapi:tokens:rw (or *:rw) can mint other tokens over the
wire:
curl -H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
-X POST https://router/api/v4/uapi/tokens \
-d '{
"name": "ci_bot",
"scopes": ["firewall:rules:rw"],
"expires_in_seconds": 3600,
"allowed_cidrs": ["10.0.0.0/24"]
}'
# response: { "bearer": "<cleartext-once>", "name": "ci_bot" }
allowed_cidrs takes prefixes of either family, and a list may mix them. A
caller is matched
against entries of its own family only, so 0.0.0.0/0 does not admit an IPv6
caller and ::/0
does not admit an IPv4 one: a dual-stack router that means "any" has to say
both. A caller
arriving as an IPv4-mapped IPv6 address is matched against the IPv4 entries. An
IPv6 prefix length
is 1 to 3 digits: an entry such as fd00::/0x40, which 3.1 read as /0, is
refused at mint time,
and a stored one admits no caller. The validation sweep does not cover tokens,
so
uapi-token list is where a stored entry shows.
Each requested scope must be in the scope tree below, as for uapi-token
create, and the HTTP mint has no --force. A typo, a scope that a release
removed such as dhcp:leases6, or a malformed scope returns 422
validation_failed with code not_in_enum on its entry, such as scopes[1].
This check runs before the escalation check, so an unknown scope never returns
scope_escalation_blocked.
The caller's scopes must cover the requested scopes, equal or narrower.
Escalation
returns 403 scope_escalation_blocked. A name that a token or another
section of the token store already holds returns 409 conflict.
A mint removes the rate-limit buckets and the last-used markers of the tokens
that no longer
authenticate, and folds their metric series into token_id="-retired", before
it commits the
new token. A request that uhttpd kills during that cleanup has committed
nothing, so it cannot
lose the bearer of a token that exists. uapi-token create cleans up the same
way, then
commits, then prints the bearer.
uapi keeps no cleartext bearer, with one exception. A POST /uapi/tokens that
carries an
Idempotency-Key is cached with its response, bearer included, for 24 h, in a
file of mode 0600
that only root can read. A retry by the same token with the same key and body
gets that
response back, so for such a client a request killed after the cache write loses
no bearer
either.
curl -H "Authorization: Bearer $ADMIN" https://router/api/v4/uapi/tokens
curl -H "Authorization: Bearer $ADMIN" https://router/api/v4/uapi/tokens/ci_bot
curl -H "Authorization: Bearer $ADMIN" -X DELETE https://router/api/v4/uapi/tokens/ci_bot
GET responses never include salt or hash.
curl -H "Authorization: Bearer $TOKEN" https://router/api/v4/uapi/whoami
Returns {token_id, scopes, source_ip, expires_at, allowed_cidrs,
last_used_at, last_used_ip}. No scope check (any authed token can read
its own metadata).
Authorization: Bearer <bearer string>
Common failure responses:
| HTTP | code | Cause | Header |
|---|---|---|---|
| 401 | unauthorized |
missing or malformed Authorization header | WWW-Authenticate: Bearer |
| 401 | invalid_token |
bearer not in store, or expired, or wrong source IP | WWW-Authenticate: Bearer |
| 403 | insufficient_scope |
token's scopes don't cover the request | - |
| 403 | scope_escalation_blocked |
POST /uapi/tokens requested scopes outside caller's |
- |
| 429 | too_many_requests |
per-token rate limit exceeded | Retry-After: <seconds> |
<segment>[:<segment>...]:(rw|ro)
Up to three segments (<domain>:<subresource>:<verb> for curated,
raw:<package>:<verb> for raw). rw implies ro. * is allowed as any
segment for wildcards:
*:rw / *:ro - top-level wildcard, matches everything.firewall:*:ro - mid-tree wildcard, matches every firewall subresource
(rules, zones, redirects, nat, forwardings, defaults) but NOT the bare domain.*:rules:ro - also valid; matches the rules subresource of every domain
that has one.At equal depth, an exact segment beats a wildcard segment
(firewall:rules:rw wins over firewall:*:ro for /firewall/rules).
The authoritative source is src/lib/scope.uc KNOWN_PATHS.
| Domain | Subresources |
|---|---|
* |
any |
network |
interfaces, devices, routes, rules, bridge_vlans, wireguard_peers, wireguard_kernel_peers |
wireless |
devices, interfaces |
firewall |
zones, rules, redirects, nat, forwardings, defaults |
dhcp |
hosts, leases, servers, dnsmasq, odhcpd |
system |
(singleton), timeservers, password, authorized_keys, cron_jobs |
dropbear |
instances |
uhttpd |
instances, certs |
unbound |
server, srv, ext |
sqm |
queues |
snmpd |
agents, com2secs, groups, accesses, system |
lldpd |
config |
prometheus_node_exporter_lua |
config |
vnstat |
config, interfaces (raw only) |
mwan3 |
globals, interfaces, members, policies, rules |
usteer |
config |
packages |
installed, feeds |
uapi |
tokens, metrics, diagnostics, services |
raw |
<any-package> (composes with the curated domain tree) |
The tree also holds the paths that /raw/ checks for a package outside it. A
scope on all of such a package, such as ddns:rw, is in the tree while the
package exists in /etc/config. *:<package> is in the tree because it
matches raw:<package>. A path below such a package, such as ddns:service,
is not: /raw/ checks each of its sections against the package alone.
POST /uapi/services/<name>/recover passes with uapi:services:rw, or with
rw on a domain whose writes reload the service, as such a write would reload
it, for example dhcp:rw for dnsmasq or system:rw for sysntpd. uapi
derives them from the services that the writes of each resource reload, and
the description of the operation in the spec lists every domain of each
service. A scope below the domain,
such as dhcp:hosts:rw, does not pass.
When multiple scopes match a request, the one with the longest matching
prefix decides. rw and ro at the same depth: rw wins.
Examples (assume the request targets /firewall/rules/r_01HX...):
| Token scopes | Result |
|---|---|
*:rw |
permits |
firewall:rw |
permits |
firewall:rules:rw |
permits |
firewall:zones:rw |
denies |
*:rw, firewall:rules:ro (PUT) |
denies (deepest match is ro) |
*:rw, firewall:rules:ro (GET) |
permits |
firewall:ro, firewall:rules:rw (PUT) |
permits (deeper rw wins) |
/raw/<package>/<id> requires both trees to permit, independently:
raw / raw:<package> matches.firewall.rule
-> firewall:rules, network.interface -> network:interfaces, etc.A token with raw:rw but only firewall:rules:ro can read firewall rules
via /raw/firewall/... but cannot write them. The domain-tree override
always wins. This is intentional: granting raw:rw should not be a
backdoor around carefully-crafted curated scopes.
A section type that the type map of src/raw.uc does not hold, such as a
firewall nat section or any mwan3 section, is checked against the package
alone, [<package>]. Granting *:rw or that package scope covers it.
Tokens carry optional rate (requests/second) and burst (token-bucket
capacity) overrides that beat the global rate-limit default (100 req/s, burst
200). Absent options inherit the global.
Set at mint time via CLI:
uapi-token create --name ci_bot --scope '*:rw' --rate 10 --burst 20
Or via HTTP:
curl -H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
-X POST https://router/api/v4/uapi/tokens \
-d '{
"name": "ci_bot",
"scopes": ["firewall:rules:rw"],
"rate": 10,
"burst": 20
}'
Both values must be positive integers; non-positive or non-integer values return
422 validation_failed. The uci options on the token's section are option rate
'<N>' and option burst '<N>'; setting them directly via uci set is also
supported and takes effect on the next request.
| Use case | Scopes | Flags |
|---|---|---|
| Terraform admin | *:rw |
--expires-in 90d |
| Terraform per-domain | firewall:rw |
--expires-in 90d |
| Read-only dashboard | *:ro |
--allowed-cidr <office> |
| Monitoring (Prometheus scrape) | uapi:metrics:ro, uapi:diagnostics:ro |
--allowed-cidr <prom-host>/32 |
| Agent that starts again a stopped daemon | uapi:diagnostics:ro, uapi:services:rw |
--expires-in 30d |
| Short-lived CI job | firewall:rules:rw, network:routes:rw |
--expires-in 1h --allowed-cidr <ci> |
| Operator that mints other tokens | uapi:tokens:rw, plus the scopes it needs to delegate |
--expires-in 30d |
Long-tail via /raw/ |
*:rw (or raw:rw + the specific domain scopes) |
- |