Authentication: OAuth 2.1, API keys, multi-user
ToolMesh provides a production-ready authentication system with multiple modes, from simple single-user setups to full multi-user OAuth. Without any credential configured, every request is rejected (see No credential configured).
Authentication Modes
Section titled “Authentication Modes”Simple (Single-User)
Section titled “Simple (Single-User)”Start quickly with environment variables:
TOOLMESH_AUTH_PASSWORD=changeme # Single-user OAuth passwordTOOLMESH_API_KEY=sk-my-key # Static API keyMulti-User OAuth 2.1
Section titled “Multi-User OAuth 2.1”Full OAuth 2.1 with PKCE S256 for interactive login:
- Users defined in
config/users.yaml(bcrypt-hashed passwords) - Each user has: username, company, plan, roles
- Dynamic Client Registration (DCR), limited to 5 registrations per hour from one client address
- A login page that names where the authorization goes and asks the user to confirm it (see The login page)
- Redis/KeyDB for state persistence (tokens, auth codes, client registrations)
users: - username: alice password_hash: "$2a$12$..." # bcrypt hash company: acme plan: pro roles: [admin]ToolMesh reads users.yaml at startup: changes to it take effect after a restart (see Tokens).
API Keys
Section titled “API Keys”For programmatic access. Each entry names its key by the SHA-256 of the key, or by a bcrypt hash:
keys: - key_sha256: "<SHA-256 of the key, 64 hex characters>" user_id: ci-bot company_id: acme plan: standard roles: [read] caller_id: github-actionsGenerate a key and the value for key_sha256:
KEY="tm_$(openssl rand -hex 32)"printf '%s' "$KEY" | sha256sum | cut -d' ' -f1Each API key carries its own identity (user, company, plan, roles) that flows through the entire pipeline.
key_sha256 is looked up in a table from the first request on and is meant for randomly generated keys of 128 bits or more; a key a person chose, or a short one, could be guessed from a leaked file far faster than through bcrypt, so keep such a key as key_hash or replace it. Files with bcrypt key_hash entries, as earlier versions wrote them, keep working unchanged: such an entry is compared with bcrypt the first time its key is presented after startup and found by lookup from then on. Until then, every bearer credential that nothing else recognizes costs one comparison per such entry, which is why ToolMesh logs a warning at startup while a file has key_hash-only entries. Add key_sha256 to an entry to remove that cost; key_hash may stay next to it.
A bearer credential is checked in this order: the lookup table of the API keys (or the single TOOLMESH_API_KEY), then the access tokens in the token store, and only then, by bcrypt comparison, the key_hash-only entries not seen yet. A valid access token never costs a bcrypt comparison, and an API key does not depend on the token store being reachable. Failed API keys are limited per client address (see API key throttling).
The keys of approvers, who grant kits, are separate from these: an approver key works only on the approver API, and an MCP credential never approves.
Identity Flow
Section titled “Identity Flow”The authenticated identity flows through every step:
Authentication → CallerID → OpenFGA AuthZ → Credential Store → Audit TrailThis ensures full traceability: every tool call is attributed to a specific user, with a specific plan, from a specific client.
Unauthenticated requests
Section titled “Unauthenticated requests”A request to /mcp without a valid credential is answered 401 Unauthorized with a WWW-Authenticate: Bearer challenge that points to the OAuth protected resource metadata of the endpoint (/.well-known/oauth-protected-resource/mcp), as the MCP authorization specification asks. MCP clients act on the status: they start the OAuth flow, or refresh an expired token and retry. The body is the JSON-RPC error -32001. Set TOOLMESH_ISSUER to the public URL clients use, as the metadata names it. A reverse proxy must pass the 401 and the WWW-Authenticate header through unchanged, and for origins in TOOLMESH_CORS_ORIGINS the header is exposed to browsers.
A request whose credential could not be checked right now, because the token store failed or because no password hash comparison could be started, is answered 503 Service Unavailable with Retry-After instead. That says nothing about the credential; a 401 would make a client discard a token that is still good. /files/upload and DELETE /blobs/… answer 401 and 503 in the same cases.
Rejected requests are logged at INFO (mcp request rejected: unauthorized) and counted in toolmesh_logins_total{method="anonymous"}.
No credential configured
Section titled “No credential configured”A server without any credential configured (no TOOLMESH_AUTH_PASSWORD, TOOLMESH_API_KEY, users.yaml or apikeys.yaml) rejects every request to /mcp, /files/upload and DELETE /blobs/… with 401. Where no password is configured, /authorize answers 403 instead of showing a login form, and no tokens are issued or honored.
The login page
Section titled “The login page”The login page at /authorize names the host of the client’s redirect_uri, which is where the authorization goes, and the name the client gave itself at registration, marked as not verified by ToolMesh. Before signing in, the user ticks I trust <host> with access to my ToolMesh tools; the button reads Authorize <host>. The box is never ticked in advance. A login without the confirmation is refused before the password is looked at and does not count as a failed login.
- Scripted logins, such as smoke tests with
curl, sendconfirm_host=<redirect host>along with the username and password. - Restricting redirect hosts. Any client can register itself with any https
redirect_uri. On a server that serves only known clients, setTOOLMESH_OAUTH_REDIRECT_HOSTS:claude.ai,claude.comfor Claude,chatgpt.comfor ChatGPT. It is checked at/registerand again at/authorize, so it also covers clients registered earlier. Loopback redirect URIs of native clients such as Claude Code are always accepted. - Refused redirect URIs. A redirect URI with a fragment, without a host (
https:host/callback) or with a non-ASCII host is refused at/registerand/authorize; a host with non-ASCII characters works in its punycode form. A client registered earlier with such a URI has to register again.
Refused logins are logged as login failed with the reason consent_not_confirmed (no confirmation) or redirect_host_not_allowed (host not in TOOLMESH_OAUTH_REDIRECT_HOSTS).
Tokens
Section titled “Tokens”An access token lives one hour, a refresh token seven days; every refresh issues a new pair. A refresh token is refused once its seven days are over, also after a restart.
- Checked against the current users. Every access token and every refresh is checked against the user configuration in force:
users.yamlwhen it is loaded, the single password otherwise. A user who was removed fromusers.yaml, or whosepassword_hashis no longer usable (for example"!"), loses access with the next request, running sessions included, and no refresh succeeds for it. Changed roles, plan and company apply to existing tokens. In single-password mode the same holds whenTOOLMESH_AUTH_USERchanges. - Changes apply after a restart.
users.yamland theTOOLMESH_AUTH_*variables are read at startup. To end a session before the restart, revoke its tokens. - A password change ends sessions. Tokens are bound to a fingerprint of the credential the user logged in with. After a password change, and the restart that loads it, the sessions issued for the old password end with their next request or refresh.
- Revocation.
POST /revoke(RFC 7009) takestoken=<access or refresh token>and revokes both tokens of the pair. It answers200also for an unknown token. Holding a token is enough to revoke it; the OAuth metadata advertises the endpoint asrevocation_endpoint.
Tokens from before the upgrade
Section titled “Tokens from before the upgrade”Tokens issued by a version before 0.6.0 carry no fingerprint yet. They are accepted and bound to the credential in force at their next refresh. Such a token therefore survives a password change made after the upgrade: it is renewed and bound to the new password. A later release will close this. Until then, if you suspect misuse of a session that predates the upgrade, revoke its tokens with POST /revoke (this needs the token value), or end every session by clearing the stored tokens while ToolMesh is stopped:
- Without Redis: delete
oauth-state.jsonin the data directory. It also holds the registered OAuth clients, so clients register again and every user signs in again. - With Redis: delete the Redis keys
oauth:token:*andoauth:refresh:*andoauth-state.jsonin the data directory. Clearing only one of them is not enough: at startup ToolMesh copies the tokens fromoauth-state.jsonback into Redis, and while running it reads Redis first. The registered clients stay in Redis.
redis-cli --scan --pattern 'oauth:token:*' | xargs -r redis-cli delredis-cli --scan --pattern 'oauth:refresh:*' | xargs -r redis-cli delWith the shipped Compose file, run keydb-cli inside the keydb service instead.
Login throttling
Section titled “Login throttling”The password login at /authorize limits failed attempts: by default 5 for one account from one client address, 20 for one account from all addresses together and 50 from one address across all accounts, each within 15 minutes. Once a limit is reached, the attempts it covers are answered 429 with Retry-After, without the password being checked, until the window that began with the first counted failure has passed. The variables are listed under Configuration.
- An unknown username is counted and locked out like a real one, and costs the same password-hash comparison, so neither the lockout nor the response time shows which accounts exist.
- A wrong password re-renders the login form with
401. A request naming an unregistered client or redirect URI is rejected with400before the password is looked at and does not count; neither does a login without the confirmation of the redirect host. - Only new password logins are refused. Access and refresh tokens already issued keep working, and so do API keys, which have a limit of their own.
- The counters live in Redis when it is connected, so the limits hold across replicas and survive a restart, and in process memory otherwise. A Redis error falls back to process memory with a warning instead of lifting the limits.
- The per-address limits count the client address. With a password that many people share on purpose, set the per-account limit to
0and keep the per-address ones.
Every failed login is logged at WARN (login failed, with the submitted username, the client address and a reason; never the password) and counted in toolmesh_logins_total{method="password",result="failure"}.
API key throttling
Section titled “API key throttling”Failed bearer credentials on /mcp, /files/upload and DELETE /blobs/… are limited per client address: by default 50 within the window of the login limits (TOOLMESH_APIKEY_MAX_FAILURES_PER_IP; 0 switches the limit off). A credential reserves its slot before it is checked, so concurrent attempts cannot all pass before the first failure is counted; an accepted credential hands the slot back. Once the limit is reached, every bearer credential from that address, the right one included, is answered 429 with Retry-After until the window ends, and logged at INFO as bearer authentication throttled. Clients behind one shared address share this limit.
The counters live in Redis when it is connected, which costs each API key request two short Redis operations, and in process memory otherwise. Values in the form of an access token issued by ToolMesh (64 lowercase hex characters) reserve no slot up front: they cannot be guessed, and expired ones arrive routinely, often from the shared addresses of hosted clients. When their address is throttled they are answered 401 like any unknown token, so a client with an expired token can still refresh it. An API key of that form (openssl rand -hex 32 without the recommended tm_ prefix) is therefore not throttled either, which is safe only because such a key is random.
Client address
Section titled “Client address”The client address counts for the login, API key and registration limits and appears as remote in the request log. ToolMesh takes it from the connection, and from X-Forwarded-For only when the connection comes from a trusted proxy (TOOLMESH_TRUSTED_PROXIES, by default loopback only). It then reads the header from the right: the first entry that is not a trusted proxy itself is the client. Entries with a port (203.0.113.7:51234, [2001:db8::7]:51234) or in brackets count as addresses. An entry that is no address (unknown, empty) ends the evaluation, and the last trusted proxy read so far counts as the client. IPv6 addresses are counted per /64.
TOOLMESH_TRUSTED_PROXIES lists the addresses your reverse proxies connect from, not the networks your clients are in. A client whose own address is listed can choose the address it is counted under.
| Setup | What to set |
|---|---|
| Reverse proxy on the same host (Caddy, nginx, Traefik as a host service) | Nothing |
| Reverse proxy in a container in the same Compose network | The proxy container’s own address, fixed in the Compose file, for example TOOLMESH_TRUSTED_PROXIES=172.18.0.10. Not the Compose network; see Proxy in a container. |
| Proxy or CDN on other machines (a load balancer, Cloudflare) | Its addresses or published ranges |
| No proxy, ports published directly with rootful Docker on Linux | Nothing: Docker keeps the client’s source address |
| No proxy with Docker Desktop, rootless Docker or a userland proxy | Every connection comes from a gateway address, so all clients share one address’s limits. Put a reverse proxy in front, or raise the per-address limits. |
Behind a proxy that is not listed, every client is counted under the proxy’s address. That fails safe, but a lockout then hits everyone, and ToolMesh logs X-Forwarded-For from an address that is not a trusted proxy is ignored at WARN, at most once an hour. The startup log names the trusted addresses (X-Forwarded-For honored from ...), and the remote field of the request log shows the address ToolMesh uses. The proxy closest to ToolMesh must append the client’s address to X-Forwarded-For, as common reverse proxies do. none honors no X-Forwarded-For at all.
Proxy in a container
Section titled “Proxy in a container”A reverse proxy that runs as a container next to ToolMesh is listed with its own address, not with the Compose network. The network contains its gateway (for example 172.18.0.1), and with Docker Desktop, rootless Docker or a userland proxy, direct connections to ToolMesh’s published port arrive from that gateway. With the network listed, they count as coming from a trusted proxy.
Give the proxy a fixed address and list that address alone. The proxy reaches ToolMesh over the Compose network, so ToolMesh’s port needs to be published on 127.0.0.1 only, or not at all:
# docker-compose.yml, the parts that changeservices: proxy: image: caddy:2 ports: - "443:443" networks: default: ipv4_address: 172.18.0.10 toolmesh: ports: - "127.0.0.1:${TOOLMESH_PORT:-8123}:8080"
networks: default: ipam: config: - subnet: 172.18.0.0/24 # a subnet no other Docker network uses ip_range: 172.18.0.128/25 # automatic addresses for the other containersTOOLMESH_TRUSTED_PROXIES=172.18.0.10The ip_range keeps Docker from giving the proxy’s address to another container. The proxy forwards to http://toolmesh:8080.
On an existing installation, changing the network’s ipam makes docker compose up -d create the network anew, but it re-creates only the services whose configuration changed. The others are attached to the new network without their service name: ToolMesh then no longer finds Redis as keydb, logs Redis not reachable and runs with its file token store only. After such a change, run docker compose up -d --force-recreate and check that the start log shows Redis connected.
Password hash comparisons
Section titled “Password hash comparisons”bcrypt keeps one core busy for tens of milliseconds per comparison. The number of comparisons running at the same time is bounded for the whole process (TOOLMESH_BCRYPT_MAX_CONCURRENT, default half of the CPUs available, at least one); the bound covers password logins and the remaining comparisons for key_hash-only API keys. A request that cannot get a comparison in time is answered 503 with Retry-After; it is not a failed login. Requests that need a comparison for a bearer credential are admitted one at a time, so they use at most one core and cannot keep password logins waiting.
Migration Path
Section titled “Migration Path”Start with TOOLMESH_AUTH_PASSWORD for quick prototyping. When you need multiple users, switch to users.yaml — no architecture change required. The same pipeline handles both modes.
Upgrading an existing installation to v0.6.0 changes the login page, token handling and the client address; see Upgrading to v0.6.0.