Appearance
Authentication
Gatez issues its own sessions. A user signs in to the Control Plane API with an email and password, receives a short-lived access token and a rotating refresh token, and every backend (Control Plane API, AI Gateway, Agent Gateway) verifies that token itself. No external identity provider is needed to run the platform. An external IdP (Zitadel, Keycloak, Okta, Entra) is an optional add-on for enterprise SSO.
This document describes what ships today. Items that are still on the roadmap are marked.
1. Built-in sessions
Sign-in flow
POST /api/auth/login {email, password} → token pair + user
POST /api/auth/refresh {refresh_token} → new token pair
POST /api/auth/logout bearer (optional) + {refresh_token?} → 204
POST /api/auth/password bearer + {current_password, new_password} → new token pair
GET /api/auth/me bearer → profile, roles, sessionThe login response:
json
{
"access_token": "<EdDSA JWT, 8 h>",
"token_type": "Bearer",
"expires_in": 28800,
"refresh_token": "rt_<43 chars>",
"refresh_expires_in": 604800,
"must_change_password": false,
"user": { "id": "<uuid>", "email": "…", "display_name": "…", "tenant_id": "retail", "roles": ["tenant-admin"] }
}Tokens travel in JSON bodies and the Authorization: Bearer header. Gatez sets no cookies, so there is no CSRF surface; every auth response carries Cache-Control: no-store.
The access token
An Ed25519 (EdDSA) JWT signed by the Control Plane API's STS key. Claims:
| claim | meaning |
|---|---|
iss, aud | aud is gatez; iss is GATEZ_ISSUER (the API's public https URL; http://localhost:4001 locally; the bare gatez when unset on a host). Every verifier pins aud and accepts exactly this deployment's issuer — a session from another deployment, or one minted before GATEZ_ISSUER was set, is refused even under the same key (users sign in again once after the cutover); an STS hop token (issuer https://sts.gatez.internal) can never pass as a session and vice versa |
sub | user id (UUID) |
email | login name; used as the display username in logs and audit rows |
tenant_id | the user's tenant, or absent for platform administrators |
roles | informational only — authorisation uses the stored role key (see below) |
sv | session version at mint time |
pwd_change_required | present and true while a temporary password is in force |
jti, iat, exp | exp = 8 hours |
The public key is published at GET /sts/jwks and its alias GET /.well-known/jwks.json (kty: OKP, crv: Ed25519, kid = first 16 hex of SHA-256(public key)); both answer with Access-Control-Allow-Origin: *. GET /.well-known/openid-configuration reports issuer, jwks_uri, token_signing_alg_values_supported and claims_supported — served only when GATEZ_ISSUER is a URL (and, for the local default, only under a localhost Host), 404 issuer_not_configured otherwise: a metadata document whose issuer is not its own URL would be wrong. Gatez is not an OpenID Provider (no authorization endpoint, no ID tokens) and the RFC 8693 exchange at /sts/token is deliberately not advertised until it is edge-routed and actor-verified (W2-D7-28). /.well-known/oauth-authorization-server and oauth-protected-resource belong to the agent gateway's MCP OAuth metadata. APISIX publishes exactly /.well-known/jwks.json and /.well-known/openid-configuration to the control-plane API without auth, 120 req/min per IP (scripts/setup-routes.sh).
Sessions are only ever signed with an asymmetric key. If the Control Plane API is running with the legacy HS256 STS_SIGNING_KEY instead of STS_ED25519_PRIVATE_DER_B64, login answers 503 login_unavailable rather than mint a token that anyone holding the shared secret could forge.
The refresh token
An opaque 256-bit random value (rt_…), stored only as a SHA-256 hash with a 7-day TTL. It is single-use: each refresh consumes it and returns a new pair. Presenting a consumed token again within 10 seconds is treated as a concurrent tab and simply answered 401; a replay later than that is treated as theft, bumps the user's session version (which invalidates every session), and revokes every refresh token of the account. Portals must therefore single-flight their refresh and share tokens across tabs.
Password rules
- 12 characters minimum, 1024 bytes maximum. Hashes are argon2id (OWASP defaults).
- Five wrong passwords lock the account for 15 minutes (
423 account_locked,Retry-After). The counter is keyed by the email, so unknown addresses lock the same way and the response does not reveal whether an account exists. Password change uses the same counter. must_change_passwordaccounts get a full token pair but may only call/api/auth/*until the password is changed; everything else answers403 password_change_required. A password change clears the flag, revokes every other session and refresh token of the account, and returns a fresh pair.
How a request is authorised on every route
Each backend verifies the signature in-process (Control Plane API) or against GATEZ_JWKS_URL (AI Gateway, Agent Gateway), then re-reads the account state from the shared Redis in one pipelined round trip:
| check | rejection |
|---|---|
jti on the logout denylist | 401 token_revoked |
| credential record missing | 401 invalid_token |
| account disabled | 401 account_disabled |
token sv older than the credential's session_version (password change, theft) | 401 token_revoked |
| tenant no longer in the tenant index | 401 tenant_not_found |
| role key missing or illegal, or user no longer a member of the tenant | 401 role_revoked |
temporary password outside /api/auth/* | 403 password_change_required |
| Redis unreachable or slower than 1.5 s | 503 auth_unavailable (never fail open) |
The stored role key user:{id}:roles:{tenant} is authoritative, so a demotion, disable, tenant move or password change takes effect on the user's next request even though the access token lives for 8 hours. A platform administrator is a user in the reserved platform tenant whose only role is platform-admin; on the AI Gateway an administrator selects the tenant to act on with the X-Tenant-ID header, tenant users cannot.
A bearer that claims to be Gatez-issued but does not verify (expired, forged, signed by a rotated key) is answered 401 invalid_token immediately. It is never forwarded to an identity provider and never reaches the local development bypass.
Roles — what each one gates today (W2-D7-59)
One table, read by both portals (@gatez/auth ROLE_MATRIX: the operator Users page "Roles" drawer and the developer Settings "Your access" panel) and by this document. It states what is enforced now and where; it is not a plan.
| role | source | can | enforced by | status |
|---|---|---|---|---|
platform-admin | a user of the reserved platform tenant, or the master key | Operator Portal; every admin-only route (tenants, users incl. invite/disable/delete, routes, providers, settings, health, service accounts, SCIM); select any tenant with X-Tenant-ID; tool-server registry; approve any tenant's HITL request. Never its own disable/delete, never the last active admin | ADMIN_ONLY_MATRIX, portalAccess, agent-gateway registry gate | enforced |
tenant-admin | assigned per tenant (user:{id}:roles:{tenant}) | everything a tenant user can + write branding and notification delivery; sees the Notifications/Branding tabs | branding.rs (403 tenant_admin_required), Developer Portal tabs | enforced |
tenant-user | assigned per tenant (default for an invite) | Developer Portal for its tenant; its tenant's keys, usage, audit, sessions; approve its own tenant's HITL requests. Pinned to its tenant on every call | require_tenant_id on every tenant-scoped route, portalAccess, agent-gateway hitl_approve tenant check | enforced |
key-manager, api-consumer, agent-operator | assignable per tenant | same as tenant user today | carried in session claims by all three layers, enforced by none | assigned but not enforced |
viewer / demo-viewer (or a login in READ_ONLY_USERS) | role or env list | read everything; every mutating control-plane request is refused (403) | middleware.rs read_only_blocks | enforced (not yet applied to agent-gateway HITL approvals — W2-D7-03) |
hitl-approver | planned | — | — | planned (W2-D7-03): until then any member of the tenant, viewers included, and any platform admin can approve |
Route classes on the Control Plane API
Every authenticated route is in exactly one of two classes (layers/control-plane-api/src/protected_routes.rs):
- Tenant-scoped: the handler reads the verified principal and pins a non-admin caller to its own tenant (tenants, consumers, keys, rate limits, analytics, route reads, audit, usage, SSO settings — a tenant admin may read or write only its own tenant's IdP configuration; notifications and notification preferences — a non-admin always acts on its own tenant and a platform admin names the tenant, or reads the cross-tenant feed; branding — read by the tenant's users, written by its tenant admins or a platform admin). Consumers are tenant objects: the routes a consumer is granted must carry that tenant's label (an unlabelled or another tenant's route is refused, for platform admins too), a tenant user cannot set a consumer's rate limit or token budget above the tenant's plan, and the gateway's consumer-restriction whitelist is patched in place rather than rewriting the route. Pinned does not mean role-checked everywhere: which tenant roles may write guard/prompt config, consumers and keys is a separate item (W2-D6-14).
- Platform-admin only: everything else — route creation, update, deletion and OpenAPI import (a route carries arbitrary APISIX plugin, upstream and priority configuration for the shared gateway), providers and provider tests, settings, webhooks, lifecycle and canary, traffic labels, health, user-management reads, service accounts, the agent registry, SCIM. A router-level gate answers
403 forbidden / platform_admin_requiredto any other principal and401 unauthorized / no_principalwhen no principal was attached, so a handler that never looks at the caller cannot be reached by a tenant session.
A route added to the admin-only class must also be listed in ADMIN_ONLY_MATRIX; a route added to the tenant-scoped class must be declared self-authorising, and the tests parse that handler's signature for the principal extractor, or be an explicit pending-pin exception (today only /api/plans, public pricing data). The tests also parse main.rs: the protected router is built only from the two classes, the public router matches a fixed allowlist, and every protected path is under the prefixes the auth middleware guards. A Redis-backed matrix test sends a tenant-user principal to every admin-only route (writes are only attempted as the refused tenant user, so the run changes nothing).
Provider configuration is additionally constrained: an environment-variable key source must be named <PROVIDER>_API_KEY and may never reference a platform secret (MASTER_KEY, REDIS_PASSWORD, signing keys, anything containing SECRET, PASSWORD or TOKEN), and a provider base_url must be a public http(s) origin (best effort — DNS names resolving to private addresses and redirects are not yet checked; see W2-D7-14) — the connection test sends the resolved key to that URL.
Master key
Service-to-service calls may still use the master key (MASTER_KEY / LITELLM_MASTER_KEY) as a bearer; it is checked before anything else and acts as a platform administrator.
2. SSO federation (external IdP)
Federation is the ability to accept RS256 tokens from an external OIDC provider in addition to Gatez sessions.
GATEZ_SSO_FEDERATION=on|offswitches it explicitly. When unset, federation is on only if an IdP JWKS URL is configured (KEYCLOAK_JWKS_URL); an unrecognised value counts as off and is logged.- With federation off, any bearer that is not a Gatez session or the master key is answered
401 sso_not_configuredbefore any outbound call. - With federation on, the existing IdP path applies: JWKS signature verification (
KEYCLOAK_JWKS_URL, issuers derived fromKEYCLOAK_URL/KEYCLOAK_EXTERNAL_URL, optionalKEYCLOAK_ALLOWED_AUDIENCES), then introspection as a fallback.
Setting up the sso profile
The order matters: a portal started with SSO on and no client id refuses to start.
.env:COMPOSE_PROFILES=sso(orobservability,demo,sso) andGATEZ_SSO_FEDERATION=false;make up. On the first start of an empty Zitadel instance the compose file provisions a service usergatez-setup(IAM owner) and Zitadel writes its personal access token to thezitadel-machinekeyvolume (ZITADEL_FIRSTINSTANCE_PATPATH).scripts/zitadel-setup.sh— reads that token (docker cpfrom the container; distroless image, so no shell; only for a localhost URL), orZITADEL_PAT=<token>for an instance that predates the machine user or lives on a host (create a PAT in the console for a service user with IAM owner; https required), creates thegatez-portalproject, the operator / developer / apisix OIDC apps and the roles, and writesZITADEL_OPERATOR_CLIENT_ID/ZITADEL_DEVELOPER_CLIENT_ID/ZITADEL_APISIX_CLIENT_IDinto.env(ENV_FILEto redirect; it refuses to overwrite different existing ids without--force). Demo accountsoperator/developer(passwordDemo@123, platform-admin and tenant-user) are created only on a developer machine (localhost URL andGATEZ_ENV=local) or with--demo-users; a single-box host talking to localhost hasGATEZ_ENV=staging|productionand gets none unless asked. Re-runs are idempotent (project and apps looked up by name). Because the provisioned token is an IAM-owner credential valid untilZITADEL_SETUP_PAT_EXPIRATION, the script revokes it and deletes the file when it finishes, unless--keep-token; later runs useZITADEL_PAT..env:GATEZ_SSO_FEDERATION=true;make up— the portals read the client ids into their runtime/config.jsonand show the SSO button; the services now verify IdP tokens against the JWKS.
scripts/test-sso-setup.sh --live runs exactly this sequence against a temporary env file and restores the stack (--fresh-idp first removes the local Zitadel volumes so the first-instance token exists).
Federated users do not yet have local accounts, so revocation-by-version, disable and role changes do not apply to their tokens. Roadmap: an OIDC connector configured per deployment, a claim mapping that injects tenant_id, and mapping of federated identities onto local user records.
3. Deployment notes
| variable | service | purpose |
|---|---|---|
STS_ED25519_PRIVATE_DER_B64 | Control Plane API | session/hop-token signing key (required outside GATEZ_ENV=local; an ephemeral key is generated locally, which invalidates sessions on every restart) |
GATEZ_ISSUER | all three | session issuer / discovery URL (W1-D1-05): the API's public https URL. Unset = http://localhost:4001 locally, legacy gatez on a host (discovery disabled, warned at startup). L2/L3 resolve the same value and accept exactly it |
GATEZ_JWKS_URL | AI Gateway, Agent Gateway | where to fetch the session public key; default http://control-plane-api:4001/sts/jwks |
GATEZ_SSO_FEDERATION | all three | explicit federation switch (see §2) |
KEYCLOAK_JWKS_URL, KEYCLOAK_URL, KEYCLOAK_EXTERNAL_URL, KEYCLOAK_ALLOWED_AUDIENCES | all three | external IdP settings, only used when federation is on |
GATEZ_DEV_AUTH_BYPASS | Control Plane API | local development only: accept an unverifiable non-Gatez bearer as an administrator; unreachable when federation is off |
GATEZ_ENV | all three | local / staging / production (trimmed, case-insensitive). Only an explicit local enables the developer conveniences (proxy-header trust, dev auth bypass, default secrets, ephemeral STS key, localhost issuer); unset or unrecognised values fail closed with production rules and are logged as an error at startup (W2-D7-30) |
TRUST_PROXY_AUTH_HEADERS | all three | trust X-Tenant-ID/X-Userinfo from a validating proxy when no bearer is present (default: only in GATEZ_ENV=local) |
READ_ONLY_USERS | Control Plane API, Agent Gateway | comma-separated login local-parts that may not mutate (hosted demo); the Agent Gateway still allows HITL approve/deny |
Generating the signing key (PKCS#8 v2, RFC 8410 — the seed plus the public key; openssl genpkey alone emits v1, which the service rejects with VersionNotSupported):
bash
python3 - <<'PY'
import subprocess, base64
v1 = subprocess.run(["openssl","genpkey","-algorithm","ed25519","-outform","DER"], capture_output=True, check=True).stdout
pub = subprocess.run(["openssl","pkey","-inform","DER","-pubout","-outform","DER"], input=v1, capture_output=True, check=True).stdout
assert len(v1) == 48 and v1.startswith(bytes.fromhex("302e020100300506032b657004220420")), "unexpected openssl v1 layout"
assert len(pub) == 44 and pub.startswith(bytes.fromhex("302a300506032b6570032100")), "unexpected openssl SPKI layout"
v2 = bytes.fromhex("3053020101300506032b657004220420") + v1[-32:] + bytes.fromhex("a123032100") + pub[-32:]
print(base64.b64encode(v2).decode())
PYPut the output in the host's .env (mode 0600) as STS_ED25519_PRIVATE_DER_B64. The prod overlay declares the variable with :?, so on a host without it compose refuses every command that uses the overlay (up, down, ps, logs, run) with a message naming the variable, instead of the control-plane-api panicking later; the sandbox override written by scripts/setup-sandbox.sh does not carry it. Rotating the key invalidates every outstanding session and hop token. scripts/test-prod-build.sh generates a throwaway key the same way for its staging check. (The a1-tagged public-key form is the one ring produces and accepts; other PKCS#8 tools may emit the RFC 5958 implicit 81 tag, which the service does not read.) A control-plane-api --gen-sts-key subcommand writing straight to a 0600 file is the planned replacement for this recipe.
Session state lives in Redis under user:{id}, user:{id}:cred, user:{id}:roles:{tenant}, user:email:{email}, auth:refresh:*, auth:revoked:* and login_fail:*. That Redis runs maxmemory-policy volatile-lru (W1-D4-11): keys without a TTL — users, credentials, the email index, tenant membership, API keys, plan limits, budgets — are never evicted, while keys with a TTL still can be under memory pressure: auth:revoked:* (a logged-out access token then stays valid until its exp, ≤ 8 h), auth:refresh:* (the user is signed out), login_fail:* (the lockout resets). Do not switch the shared instance to noeviction: cache and rate-limit writes would fail with OOM and the limiters, the budget reservation and the STS replay guard fail open. noeviction for the state Redis is only safe after the cache/state split (tracker W2-D7-19), the durable fix; until then keep memory well below maxmemory and alert on evicted_keys.
Deploy the Control Plane API as a single-version swap: a build predating session versions that rewrites a credential record resets its version and revives old tokens.
Portal runtime configuration
The portal images are built once and configured at start. nginx serves /config.json (generated from the container environment, Cache-Control: no-store) and the app awaits it before rendering, so no API origin, IdP URL, client id or feature flag is baked into a bundle. The document is public and must contain no secrets (OIDC client ids are public).
| variable | /config.json key | default | purpose |
|---|---|---|---|
GATEZ_API_URL | api_url | "" (same origin) | Control Plane API origin used by apiFetch |
GATEZ_SSO_ENABLED | sso_enabled | false | show the Sign in with SSO button on the built-in sign-in form |
GATEZ_SSO_PROVIDER | sso_provider | zitadel | zitadel or keycloak; both go through standard OIDC (oidc-client-ts, code flow + PKCE); keycloak's authority is <sso_url>/realms/<sso_realm> |
GATEZ_SSO_URL | sso_url | "" | IdP base URL (OIDC authority); required when SSO is on |
GATEZ_SSO_REALM | sso_realm | gateway | keycloak only |
GATEZ_SSO_CLIENT_ID | sso_client_id | "" | public client id; required for zitadel, defaults to operator-portal / developer-portal for keycloak |
GATEZ_JAEGER_ENABLED | jaeger_enabled | false | gates the Operator Portal's Traces navigation item and /traces route (W2-D7-13) |
GATEZ_AGENT_IDENTITY | agent_identity | false | mount the Agent Identity page (operator) |
The container validates these at start (docker/portal-config.envsh, sourced by the nginx entrypoint): booleans accept true/false, on/off, 1/0, yes/no; URLs must be absolute https (http only for localhost) with no query, fragment or credentials; realm and client id are [A-Za-z0-9._-]. Anything else stops the container with a message naming the variable, so a bad value can never reach nginx or the JSON. The same script derives the CSP connect-src from api_url and sso_url, so the browser may only send the bearer to the configured origins.
The loader in the browser fails closed as well: a missing document (404) is the built-in default; an unreachable, non-JSON or partially invalid document falls back per key and logs one warning. SSO is offered only when sso_url is valid (and a client id is set for zitadel), so a broken config can never send the browser to an IdP nobody configured. Built-in password sign-in is always available; SSO never redirects on its own, and a sign-out ends both the built-in session and any IdP session the tab holds.
VITE_TEST_AUTH=true (the E2E mock login) remains a build-time input and must never be set for a deployed image. The dev servers serve apps/<portal>/public/config.json (built-in defaults); Vite copies the same file into dist/ as the fallback when no nginx sits in front.
Browser session behaviour
Every minted pair — login, refresh and password change — carries the same
userprofile (id,email,display_name,tenant_id,roles), so the portal always shows the server's current claims. On every page load and whenever the tab regains focus (at most once per five minutes) the portal compares its session withGET /api/auth/me: changed roles, tenant or must-change flag force one refresh;token_revokedends the session on every tab with the reason "Your access has changed";invalid_token(a signing-key rotation) is settled by the refresh token, never by ending the session; transient failures are ignored.The built-in session (access + refresh token) lives in
sessionStorage, per tab. A new tab asks open tabs for the session over aBroadcastChannelhandoff; refresh-token rotation is single-flight across tabs under a Web Lock, and a non-secret rotation marker inlocalStoragerecords which token pair is live so a restored stale tab never spends an old refresh token or signs the live tab out.Without
BroadcastChannelor Web Locks (very old browsers, some privacy modes) the portal still works: each tab signs in separately, refresh is single-flight within the tab only, and a sign-out in one tab is not propagated to the others.The two portals use separate storage keys and channels (
gatez.session.operator,gatez.session.developer), so co-hosting both on one origin never mixes sessions; a sign-out in one portal does not sign the other out.
4. What is not built yet
- First-boot administrator and a user-provisioning API for local accounts (roadmap: week 1).
- OIDC connector for federated users (local-account mapping,
amr=sso); today the SSO button signs in against the IdP directly and the backends accept the IdP token only while federation is on (§2). - JWKS well-known aliases; per-request rate limiting on
/api/auth/*at the edge (the application lockout is per account, not per client). - Audit rows for login, lockout and refresh-token theft (only structured logs today).
- OIDC connector and local-account mapping for federated users.