14 — Service tokens (headless auth)
Issue: #185. Implementation: src/auth/service_token.rs, src/transport/auth_middleware.rs.
The browser SSO flow (04 — Auth & SSO) assumes a human with a browser. A headless client — a CI job, an agent runner, another service — has neither. This spec adds the second credential kind: the service token, a static bearer that authenticates a named service identity with its own permissions group and audit attribution.
Decisions
Token type
Opaque static bearer, shape dbmcp_svc_<64 hex chars> (32 bytes of CSPRNG
entropy), minted operator-side by db-mcp-gateway mint-service-token <name> (in the image; bin/mint-service-token wraps it in a checkout).
The prefix is enforced at boot, and it is load-bearing, not cosmetic:
- Leak detection — a self-identifying token is scannable;
dbmcp_svc_in a log, a paste, or a repo is unambiguous. - Fail-loud misconfiguration — an operator who pastes a session JWT or a DB password into the token slot gets a boot error naming the mistake, instead of a credential that silently authenticates as nothing.
Comparison is constant-time (auth::pkce::ct_eq, the same primitive PKCE
verification uses), and the boot path rejects anything other than the exact
dbmcp_svc_ + 64 lowercase hex shape — short, overlong, missing prefix,
non-hex, or mixed-case tokens abort boot with a WeakToken error naming the
mint verb. Token material never appears in Debug/Display/errors — same
discipline as config::secret::Password, with tests pinning the redaction.
Permissions group — mandatory, exactly one
Every service account names one group in permissions:. That is the whole
scope model: the token inherits exactly that group's grants, evaluated by the
same authz engine (YAML grants merged most-restrictively, deny-by-default)
that IdP-backed identities use. There is no per-token scope on top of the
group — a second scope language would be a second authz surface to review.
Boot validation makes the group real rather than aspirational:
- the group must exist in
permissions:— a typo'd group name would otherwise authenticate cleanly and silently reach nothing (an emptygrants:list is the explicit way to recognize a group that grants nothing); - the group must not be the admin group — the admin middleware
(
transport/admin/middleware.rs) gates on group membership alone and is deliberately not widened or otherwise changed, so this boot gate is what keeps service tokens off/admin/*.
Convention (not enforced): name service groups svc-<name> so they read
distinct from IdP-sourced groups (devs / devops / cto) in permissions
reviews. The mint verb prints the stanza that way.
Audit identity
Every headless call attributes to the service identity, through the same
Identity the audit layer already consumes:
user_sub=service:<name>— theservice:scheme keeps service principals unambiguous next to IdP subjects inaudit_calls. The prefix is reserved (case-insensitively): an IdP login whosesubstarts with it is refused, and a session or refresh chain minted for one before that check existed no longer authenticates or rotates. Otherwise an SSO user could read the service account's query history and be audited as it;user_email=<name>@service-accounts.invalid— the audit column isNOT NULL, and the.invalidTLD (RFC 2606) marks the address as synthesized;groups= the single configured group, snapshotted per call like any other identity.
Names are boot-validated to ^[a-z0-9][a-z0-9-]{0,62}$ so audit fields stay
clean and greppable. There is no session row behind a service identity: no
revocation bitmap, no expiry, no refresh chain — and the
sessions_created_total / sessions_revoked_total counters are untouched.
Upstream attribution
Many agents share one token — a fleet of coding agents, a devops runner working for many people — so the identity alone says which token acted, not which run or for whom. Two request headers carry that:
| Header | Audit column | Meaning |
|---|---|---|
x-dbmcp-run-id | audit_calls.upstream_run_id | The agent's task / run / job id |
x-dbmcp-on-behalf-of | audit_calls.upstream_actor | The person or system the run acts for |
- Claimed, never verified. The gateway cannot check either value: it
stores them, logs them on the dispatch line and span, copies them onto the
intent row (so an
abandonedrow keeps them) — and never uses them for authz. The audit subject staysservice:<name>; the four properties of the service-identity exception (CLAUDE.md) are untouched. - Capped. Each is one header value of 1–128 characters from
[A-Za-z0-9._:@/+=-]. A repeated, empty, overlong or out-of-charset value refuses the callinvalid_arguments(audited) rather than being dropped, so a claim is never silently lost. - Service tokens only. On an SSO session both headers are ignored — the identity is already verified — and nothing is stored.
require_upstream: trueon the account refuses any call that lacks either header withinvalid_arguments(audited, nothing runs). Use it when every call must be attributable to a run and a requester.- History is per run.
get_query_historycalled withx-dbmcp-run-idreturns only rows recorded with that run id, so agents sharing a token do not read each other's history by default (03). - Activity and cancel are per run.
db_activityandcancel_querycalled withx-dbmcp-run-idsee and touch only statements whose intent row recorded that run id; another run'srequest_idanswerscancel_queryexactly like an unknown one (forbidden, same message). Without the header the call keeps the account-wide view only whererequire_upstreamis off andrun_scopedisfalseor absent; otherwise it is refused. The run id only narrows the caller's own requests; it never reaches past theservice:<name>identity (03). run_scoped: truefails closed. Without the header, whererequire_upstreamis off, the two tools answer for the whole account unless the call says otherwise, so a client whose header was lost (a proxy strips it, a bug drops it) would list or cancel other runs' statements without noticing.run_scoped: trueondb_activity/cancel_queryrefuses that call (invalid_arguments, audited, nothing listed or cancelled); SSO sessions, which have no run, are always refused. It is a precondition on the unverified run id, checks only that one was claimed, and never widens an answer (03).require_upstreamis the operator's version for every tool and is checked first; the argument is the client's own, per call, and needs only the run id.run_scopedacross versions. Sendrun_scoped: truetogether with the run header on every call that must stay within the run. A gateway that predates the argument rejects it as an unknown field — the sameinvalid_arguments(-32602), also before any target call — so one request gives one answer: scoped, or nothing happened. No version check is needed, and none would be safe during a rolling upgrade, when the replica that answeredtools/listneed not be the one that serves the call. On the refusal do not retry without the argument: run scoping itself only exists from 2.5.0, and an older gateway ignores the run header on these two tools.- This is a filter, not isolation. The gateway does not verify the run id: whoever holds the bearer can claim another run's id, or omit the header where it is optional. It keeps well-behaved runs out of each other's way. Runs that must not see or cancel each other's statements need separate service accounts.
- The request id to cancel. Every response carries the gateway's
x-request-idheader and every error body itsrequest_id; while a statement is still running,db_activitywith the run's header lists itsrequest_id— the idcancel_querytakes.
Per-account concurrency
max_concurrent_requests (≥ 1) replaces the per-identity cap (default 16)
for that token, so a fleet behind one token is not throttled as one user.
The global cap still applies; a change takes effect on the next request after
a reload.
Scope
Group-bounded. Per-database and per-action scope is expressed as grants on
the service's group (server/database/action/constraints, including
row_limit, statement_timeout_ms, require_reason), identical to human
groups. Per-table scope remains what it is for humans: out of scope.
Service identities resolve grants from YAML only, enforced twice. The
resolver never reads the permissions store for a service identity, so even a
DB grant planted for service:<name> by direct database access is inert
(tests/it_db/service_tokens_e2e.rs). And POST /admin/v1/users rejects any
service:* subject with 400, so the audited admin API cannot create one.
That is deliberate: every grant a service token can exercise is reviewed by
PR.
Mint / rotate / revoke
There is no in-band lifecycle API. The admin API is not widened, and nothing about tokens is callable over HTTP — the lifecycle is GitOps:
- Mint — a human operator runs
bin/mint-service-token <name>, stores the value in the org secret store, and PRs theservice_accounts:stanza (name + group + secret reference — never the value). The gateway refuses to boot on a stanza whose ref does not resolve. In production,service_accounts[].tokencarries a${ENV:…}or${FILE:…}reference, identical to thepassword:policy documented in config-reference.md § ServiceAccount. Undergateway.env: productionan inline literal token is rejected at boot (the error names the field, never the value); the defaultdevelopmentaccepts one for dev/test parity withDatabase.password. Committed config is also guarded at the CI layer: thesecret-scanjob in.github/workflows/ci.ymlrunsbin/secret-scanover the git index — every tracked file's contents (not just YAML), every tracked file name and every symlink target — and FAILS on any literaldbmcp_svc_<64hex>token (test fixtures undertests/**are excluded);.githooks/pre-commitruns the same script over the staged change. It is ADVISORY — it fails the job on every PR, but does not by itself block a merge until made a required branch-protection check (#190 follow-up). - Rotate — same name, overlap window, no audit-identity change. An
account carries either one
token:or atokens:list (setting both, neither, or an empty list aborts boot); every entry of the list follows thetokenrules (secret reference, shape, production literal ban) and authenticates as the sameservice:<name>, group,max_concurrent_requestsandrequire_upstream— so audit rows across the rotation window all attribute toservice:<name>. A value repeated inside the list, or shared with another account, aborts boot. Sequence: (1) mint a new value (bin/mint-service-token <name>) and store it in the secret store; (2) turn the stanza'stoken:intotokens: ["<old ref>", "<new ref>"]— each${ENV:…}/${FILE:…}ref quoted, since unquoted braces are invalid inside a YAML flow list (or use a block list, one-per ref); (3)kill -HUPevery pod (or roll the deployment) and wait until it completes — a reload rebuilds the token store, but a${ENV:…}ref reads the pod's environment, which only changes on a restart, so a value delivered as a new env var needs a roll, while one delivered as a mounted file (${FILE:…}) is picked up bySIGHUP; (4) move every client to the new value; (5) drop the old ref (back totoken: <new ref>, or a one-entrytokens:) and roll orSIGHUPagain — from then on the old value gets 401. Both values share the account's concurrency cap: they are one identity. - Revoke — remove the complete
service_accounts:stanza (the name, the group, and the token reference together) andkill -HUPevery pod (or roll). A reload rebuilds the token store in the same swap as the config, so the removed token gets 401 on its next call. Emptying or unsetting the secret is not a valid revocation: unresolved or empty secret references abort boot (SecretError::EnvNotSet/SecretError::FileUnreadablefor unreadable / missing files, andSecretError::FileEmptyfor a present-but-empty file), and a gateway that refuses to start on a misconfigured stanza is a feature, not a bypass — on reload the same failure keeps the old store, token included. There is no instant revocation; the exposure window is the time to merge and signal. That is the honest price of a stateless compare, and it is documented rather than papered over.
/auth/logout with a service token is a harmless no-op (204) and does not
revoke anything — there is no session row to revoke.
Storage path
Two homes, both pre-existing conventions:
- Record of truth: the org secret store (an operator-held password-manager item), because the gateway cannot recover the value — it is shown once at mint.
- Delivery to the gateway: the same secret-reference mechanism DB
passwords already use —
${ENV:VAR}(env from a k8s Secret/SealedSecret) or${FILE:/run/secrets/…}(mounted file). The YAML carries onlyname,group, and the reference, so the committed config stays credential-free and PR-reviewable.
The per-machine ~/.config/db-mcp-gateway/token cache that interactive
clients use today is a client-side session cache and stays exactly that —
a fleet client's deployment manifests are the analogue of it.
Why not OAuth client-credentials
The standards-shaped answer is an IdP-issued machine token (client credentials / JWT-profile) introspected or JWKS-verified per call. It buys automatic expiry at the cost of an IdP dependency on the headless hot path, clock-skew and cache-staleness handling, and IdP-side service-user provisioning machinery — to end at the same group + audit model. The static token behind the existing secret-ref mechanism is boring, reviewable, and revocable by PR. If the IdP story matures, a client-credentials grant can land as a third credential kind without changing anything here.
Request path
bearer_auth tries the service-token store first — a constant-time scan over
the boot-resolved values — and falls through to the session-JWT path
unchanged on no match. A presented token that matches nothing is not an
auth failure by itself; it just takes the JWT path, whose failure produces
the same 401 contract as before (unauthenticated + login_url). Anonymous
requests are untouched.
Downstream nothing changes: the resolved Identity flows into authz, the
per-identity concurrency limiter (a service gets its own bucket keyed by
service:<name>, sized by its max_concurrent_requests when set), and the
synchronous audit write — failure of which still
fails the request.
What this is not
- Not a user impersonation path. A service identity cannot hold the admin group (boot-enforced) and cannot mint sessions.
- Not a second permissions source. Grants stay in
permissions:YAML. - Not a replacement for SSO. Humans log in exactly as before.