--- title: "Authorization Guide" version: 3.8.40 lastUpdated: 2026-09-22 --- # Authorization Guide > **Source of truth:** `src/server/authz/`, `src/shared/constants/publicApiRoutes.ts`, `src/lib/api/requireManagementAuth.ts`, `src/shared/utils/apiAuth.ts` OmniRoute has a route-aware authorization pipeline that gates every API request. Classification is **deterministic** and **fail-closed** — anything that cannot be classified ends up as `MANAGEMENT` and demands a session or management-grade token. This page explains the model for engineers maintaining routes or designing new endpoints. ![AuthZ pipeline (3 route classes + policy evaluation)](../diagrams/exported/authz-pipeline.svg) > Source: [diagrams/authz-pipeline.mmd](../diagrams/authz-pipeline.mmd) ## Two Auth Modes ### 1. API Key (Bearer) Used for the OpenAI/Anthropic/Gemini-compatible client APIs and a few management routes when the key has the `manage` scope. ``` Authorization: Bearer ``` Validated by `isValidApiKey()` / `extractApiKey()` in `src/sse/services/auth.ts` and re-exported through `src/shared/utils/apiAuth.ts`. The validator also accepts the `OMNIROUTE_API_KEY` / `ROUTER_API_KEY` env vars as persistent passthrough keys (issue #1350). ### 2. Dashboard Session (auth_token cookie) For dashboard pages and admin operations. ``` Cookie: auth_token= ``` A cookie is a session only when the JWT verifies **and** carries `authenticated: true` (`src/shared/utils/dashboardSessionToken.ts` → `verifyDashboardSessionToken`). Every consumer of the cookie (dashboard route guard (`isDashboardSessionAuthenticated()`), authz pipeline refresh, WebSocket handshake, live server, `/api/settings/require-login`, `/api/auth/status`) goes through that helper. Other JWTs signed with `JWT_SECRET` exist — the Cursor CLI passthrough mints `iss "omniroute" / aud "cursor-cli"` tokens for key holders — and are never sessions (#13298). Verified by `isDashboardSessionAuthenticated()` in `src/shared/utils/apiAuth.ts`. The pipeline auto-refreshes the JWT when it has fewer than 7 days left in its 30-day lifetime. A session can also end before its 30 days are up, because every minter goes through `mintDashboardSessionToken` (an issue time `iat` and an id `jti`) and the verifier checks two settings: `sessionsValidAfter`, set by a password change so every session issued before it stops verifying (the browser that changed the password gets a fresh cookie), and `revokedDashboardSessions`, to which `POST /api/auth/logout` adds the signed-out session's `jti`. Sessions minted by an older release carry neither claim and stay valid until the first password change. If the settings cannot be read, the session is not trusted. Some management routes accept **either** mode: cookie OR `Bearer ` when the API key has the `manage` (or `admin`) scope. This is what enables the "configurable via API calls" workflow added in v3.8. #### Optional OIDC login gate (#6973) The dashboard admin login also supports an **opt-in** OIDC (OpenID Connect) flow alongside the default password login — password login is never removed, only supplemented: - Disabled unless `settings.oidcEnabled === true` **and** `oidcIssuer` / `oidcClientId` / `oidcClientSecret` are all configured (Settings → Auth). `GET /api/auth/oidc/login` returns `400` otherwise. - `GET /api/auth/oidc/login` discovers the `authorization_endpoint` from the issuer's `/.well-known/openid-configuration` (falls back to `/authorize`), builds the redirect URI from the incoming request (`x-forwarded-proto`-aware), and redirects to the IdP with a random `state` stored in an `httpOnly` `oidc_state` cookie. - `GET /api/auth/oidc/callback` validates `state`, exchanges the authorization code, and verifies the ID token's signature via the issuer's JWKS (`jose`'s `createRemoteJWKSet`, cached per JWKS URI) with `issuer`/`audience` checks. Dashboard admission requires a nonempty `oidcAllowedSubjects` list, an `oidcAdmissionClaim` policy, or both. The subject list matches `sub` or `email` only when `email_verified === true`. The optional claim policy takes a dot-separated ID-token claim path (for example, `realm_access.roles`) and an array of accepted values; the resolved claim must be an array of strings containing at least one accepted value. If both policies are configured, both must pass. Missing/malformed claims fail closed, and without either policy the callback refuses login (`not_configured`). Existing subject-only configurations continue unchanged. - Keycloak normally maps realm roles into access tokens, not necessarily ID tokens. To require the realm role `admin`, configure a protocol mapper for this client that includes `realm_access.roles` in its **ID token**, then set `oidcAdmissionClaim` to `{ "path": "realm_access.roles", "values": ["admin"] }`. Check the actual ID-token claim for this client before enabling role-only admission; the application does not read access-token roles. IdP-side token refusal can supplement but does not replace this application-side check. - On success it mints the **exact same** 30-day `auth_token` JWT the password login issues (`src/app/api/auth/login/route.ts`), so the rest of the dashboard session pipeline (auto-refresh, cookie flags) is unchanged — OIDC only replaces how the cookie gets minted, not what it grants. Changes to IdP roles/groups do not invalidate existing OmniRoute sessions; logout, password rotation, or session expiry still govern their lifetime. - Every `oidc*` setting (`oidcEnabled`, `oidcDisablePasswordLogin`, `oidcIssuer`, `oidcClientId`, `oidcClientSecret`, `oidcAllowedSubjects`, `oidcAdmissionClaim`, `oidcRedirectPath`, `oidcScopes`) is in `SECURITY_IMPACTING_SETTINGS_KEYS` (`src/shared/constants/securityImpactingSettings.ts`): `PATCH /api/settings` answers `400 PASSWORD_REQUIRED` unless the body carries the management password as `currentPassword` (`401 PASSWORD_MISMATCH` when it is wrong). `oidcDisablePasswordLogin` refuses password _login_ (`POST /api/auth/login`) but keeps the stored password hash, and re-auth still checks `currentPassword` against it. - `corsOrigins` and `bruteForceProtection` are in `SECURITY_IMPACTING_SETTINGS_KEYS` too: loosening either weakens the login defenses, so they take the same `currentPassword` re-auth (the Security tab asks for it) and the JSON import drops them. - Every security-policy key — the `SECURITY_IMPACTING_SETTINGS_KEYS` entries, every `oidc*` key and the dashboard session state — is **operator-only** on `PATCH /api/settings`: a manage-scoped API key or an `oma_` access token is refused with `403` even when it sends the right `currentPassword`, and the refusal is audited as `settings.update_failed` with `reason: OPERATOR_REQUIRED` (`requireOperatorCredential()` in `src/lib/api/operatorCredential.ts`). Ordinary settings (theme, display preferences) stay writable for a `manage` key or an `admin` access token. Every mutation of `/api/settings` itself (and of `/api/settings/require-login`) also needs the `admin` access-token scope (`ADMIN_MUTATION_EXACT_PATHS` in `src/server/authz/accessScopes.ts`, exact-path match); `GET` stays `read`, and the other `/api/settings/*` sub-routes (proxies, combo defaults, model aliases, compression, purges…) keep the method-inferred `write` scope. - `POST /api/settings/import-json` skips that re-auth, so it drops every key in `IMPORT_STRIPPED_SETTINGS_KEYS` (same file) before writing: the password and `currentPassword`, every `SECURITY_IMPACTING_SETTINGS_KEYS` entry, and the dashboard session state (`sessionsValidAfter`, `revokedDashboardSessions`). Importing an older backup therefore cannot revive a session that a password change or a sign-out already ended. #### Optional TOTP two-factor login (#16619) Enrolled from Settings → Security; off until the operator turns it on (`src/server/auth/dashboardMfa.ts`). - **What it covers:** password login (`POST /api/auth/login`, which then needs `POST /api/auth/mfa/verify`) and `omniroute connect` (`POST /api/cli/connect`, which refuses a password-only exchange and takes the code as `totp`). - **What it does not cover:** OIDC / SSO sign-in (`/api/auth/oidc/callback`) does not ask for the OmniRoute TOTP. It relies on the identity provider's own second factor, so enforce MFA in the IdP if OIDC is enabled. - **Recovery** (lost device, no recovery codes left, or a factor that can no longer be verified, for example after `STORAGE_ENCRYPTION_KEY` changed): 1. Restart the server with `OMNIROUTE_DISABLE_MFA=true`. 2. On the host itself (loopback peer and loopback `Host`, such as `http://localhost:20128`), sign in with the password. The second factor is skipped for that origin only; every other origin still needs the code. 3. In Settings → Security → Disable, enter the password and leave the code blank. `POST /api/auth/mfa/disable` accepts a body without `code` only while the variable is set and the request comes from the host; it still requires the dashboard session and the current password, and is audited as `auth.mfa.disabled` with `secondFactor: "recovery_switch"`. 4. Unset `OMNIROUTE_DISABLE_MFA`, restart, and enroll again if needed. ## Route Classes `src/server/authz/types.ts` defines three classes; any route that cannot be classified deterministically falls back to `MANAGEMENT`. | Class | Description | Auth required | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | `PUBLIC` | Explicitly safe routes — login, logout, status, health, onboarding bootstrap. | None | | `CLIENT_API` | Model-serving endpoints — `/api/v1/*`, `/api/v1beta/*`, plus aliases `/v1/*`, `/v1beta/*`, `/chat/completions`, `/responses`, `/models`, `/codex/*`. | Bearer key when the effective `REQUIRE_API_KEY` feature flag is enabled | | `MANAGEMENT` | Dashboard pages, settings, providers, keys, admin and diagnostics endpoints. | Dashboard session OR Bearer with `manage` scope | A few `MANAGEMENT` actions are **operator-only**: a `manage` key is not enough. Exporting stored credentials (`GET /api/settings/export-json`, `GET /api/db-backups/export`, `GET /api/db-backups/exportAll`), restoring a backup over the live data (`POST /api/db-backups/import` including `dryRun=true`, `POST /api/db-backups` restore by id, `POST /api/settings/import-json`), destroying restore points (`DELETE /api/db-backups` cleanup, and `PATCH /api/db-backups` because the retention it persists drives the automatic pruning after every backup) require a dashboard session, the local CLI subject, or login disabled. Issuing a sync token (`POST /api/sync/tokens`) and minting an `admin` CLI access token (`POST /api/cli/tokens`) require a dashboard session or the local CLI subject in every login mode. API keys of any scope and `oma_` access tokens are not operator credentials: they get `403` whenever one is required. The check lives in `src/lib/api/operatorCredential.ts` (`resolveOperatorCredential()` / `requireOperatorCredential()`). Changing the login settings is operator-only too: `POST /api/settings/require-login` (set the management password / toggle `requireLogin`) accepts only those credentials once a password exists — the first-run bootstrap window (no password yet) is unchanged — and a dashboard session must send `currentPassword` to replace the password (`403` when it is missing or wrong, audited as `settings.update_failed`). The local CLI and an instance with login disabled keep the recovery path and may set a password without it, since both are bound to the host that owns the data directory. ## Pipeline ``` Incoming request → src/proxy.ts → runAuthzPipeline() in src/server/authz/pipeline.ts 1. Strip trusted internal headers (x-omniroute-auth-*, x-omniroute-route-class) 2. Generate request id, classify route via classifyRoute() 3. If pathname == "/" → redirect /dashboard 4. If draining (graceful shutdown) and /api/* → 503 5. If non-GET /api/* → checkBodySize() guard 6. If OPTIONS → CORS preflight 204 7. If options.enforce == false → pass-through with route-class headers 8. Otherwise: POLICIES[routeClass].evaluate(ctx) - allow → stamp x-omniroute-auth-{kind,id,label,scopes} → NextResponse.next() - reject → JSON error w/ correlation_id (dashboard pages → 302 /login) ``` Trusted internal headers (defined in `src/server/authz/headers.ts`) are **stripped from incoming requests** before classification — clients cannot pre-populate `x-omniroute-auth-*` to impersonate a subject. ### Policy contracts Each route class has a policy in `src/server/authz/policies/`: - **`publicPolicy`** (`policies/public.ts`) — always returns `allow({ kind: "anonymous", id: "anonymous" })`. - **`clientApiPolicy`** (`policies/clientApi.ts`) — extracts Bearer, validates via `validateApiKey()`. Falls through to anonymous only when the effective `REQUIRE_API_KEY` feature flag is disabled. The effective flag is resolved through `isRequireApiKeyEnabled()` (`DB feature flag override > process.env.REQUIRE_API_KEY > default`) so Dashboard Feature Flags and environment variables govern `/api/v1/*`, `/api/v1beta/*`, and aliases consistently; resolver failures fail closed. Allows dashboard-session requests on client API routes (including `/api/v1/models`, used by the dashboard model catalog). When Entra ID SSO is enabled, a Bearer that is structurally an Entra token (three base64url segments, `RS*` alg, `kid`) is handled by the SSO branch **before** `validateApiKey()` and its verdict is final — it never falls through to the API-key path or the degrade-to-anonymous branch, so an identity-provider outage cannot become open access. Static API keys are unaffected. See [Entra ID SSO](../security/ENTRA_SSO.md). - **`managementPolicy`** (`policies/management.ts`) — accepts dashboard session, internal model-sync requests (matched against `/api/providers/[name]/(sync-models|models)`), or skips entirely if `isAuthRequired()` returns false. Returns 403 (`AUTH_001`) when a Bearer token is present but invalid, 401 otherwise. Also enforces the route-guard tiers (LOCAL_ONLY / ALWAYS_PROTECTED) before any auth branch — see [Route Guard Tiers](../security/ROUTE_GUARD_TIERS.md). LOCAL_ONLY paths in `LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES` (today: `/api/mcp/`) may be accessed from non-loopback when the Bearer key carries the `manage`/`admin` scope or the narrow `mcp:connect` scope (`hasMcpConnectOrManageScope`), or with an authenticated dashboard session; all other LOCAL_ONLY paths remain strict-loopback regardless of scope. A successful policy returns `AuthSubject` with `kind ∈ { client_api_key, dashboard_session, management_key, anonymous, sso_user }`. Downstream handlers can read it via `assertAuth(request, "CLIENT_API")` in `src/server/authz/assertAuth.ts` instead of re-running auth logic. ## Public Routes List `src/shared/constants/publicApiRoutes.ts` is the explicit allowlist: The list is split by **shape**, and the split is load-bearing (GHSA-74g9-q8f6-793h): a prefix is matched with `startsWith()`, so it also matches every adjacent path sharing its leading characters. `/api/usage/om-usage` as a prefix marked `/api/usage/om-usage` PUBLIC, and Next resolves that to `/api/usage/[connectionId]` — a handler with no auth of its own. ```ts // Genuine subtrees. Every entry MUST end in "/" (asserted by a unit test). PUBLIC_API_ROUTE_PREFIXES = [ "/api/auth/oidc/", "/api/v1/", // treated as CLIENT_API in classify, not as "no-auth public" "/api/oauth/", "/api/codex/connect/", "/api/telegram/", "/api/cursor-cli/", ]; // Single routes, matched EXACTLY (with or without a trailing slash). PUBLIC_API_ROUTES_EXACT = new Set([ "/api/auth/login", "/api/auth/logout", "/api/auth/status", "/api/auth/mfa/verify", // login step 2 for opt-in TOTP; needs the MFA-pending cookie "/api/sync/bundle", "/api/cli/connect", "/api/usage/om-usage", "/api/skills/collect/chaos", ]); // Read-only single routes that also take the CORS origin relaxation. PUBLIC_READONLY_CORS_API_ROUTES = [ "/api/health/ping", "/api/monitoring/health", "/api/settings/require-login", ]; // Read-only single route WITHOUT the CORS relaxation. PUBLIC_READONLY_API_ROUTES_EXACT = new Set(["/api/health"]); PUBLIC_READONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); ``` Read-only routes are public **only** for safe methods. Note: `classifyRoute()` excludes `/api/v1/*` and `/api/v1beta/*` from the PUBLIC fall-through — those are always `CLIENT_API` so the Bearer-key policy still applies. ## Adding a New Route ### Pattern 1 — Public client API endpoint (Bearer-auth) Routes under `/api/v1/` and `/api/v1beta/` are classified `CLIENT_API` automatically. The middleware enforces the Bearer check; route handlers don't need to redo it but can read the subject if useful. ```typescript // src/app/api/v1/your-route/route.ts import { NextRequest, NextResponse } from "next/server"; import { assertAuth } from "@/server/authz/assertAuth"; export async function POST(req: NextRequest) { const subject = assertAuth(req, "CLIENT_API"); // subject.kind === "client_api_key" | "anonymous" | "dashboard_session" // ... handler logic } ``` ### Pattern 2 — Management endpoint (session or Bearer + manage) Use `requireManagementAuth()` from `src/lib/api/requireManagementAuth.ts`: ```typescript import { requireManagementAuth } from "@/lib/api/requireManagementAuth"; export async function POST(request: Request) { const rejection = await requireManagementAuth(request); if (rejection) return rejection; // ... handler logic } ``` `requireManagementAuth()` returns `null` on success or a JSON error `Response`: - 401 `AUTH_001` "Authentication required" — no credentials at all - 403 — invalid Bearer **or** Bearer present but key lacks the `manage` / `admin` scope `hasManageScope(scopes)` returns true for `"manage"` or `"admin"`. ### Pattern 3 — Adding to the public allowlist Pick the set by shape, not by convenience. One route goes in `PUBLIC_API_ROUTES_EXACT` (or `PUBLIC_READONLY_CORS_API_ROUTES` for GET-only); only a genuine subtree goes in `PUBLIC_API_ROUTE_PREFIXES`, and it **must end in `/`**. Putting a single route in the prefix list also publishes every adjacent path that shares its leading characters — including dynamic-segment siblings added later (GHSA-74g9-q8f6-793h). Update unit tests at `tests/unit/public-api-routes.test.ts`, `tests/unit/authz/public-route-exact-match.test.ts` and `tests/unit/authz/classify.test.ts`. ## Scopes Three namespaces. Each checker reads only its own strings. The side-by-side, including why `manage` fails `scopeMatches` for `read:compression` and why a `read` access token cannot `PATCH /api/keys/{id}`, is [Three scope namespaces](../frameworks/MCP-SERVER.md#three-scope-namespaces). API keys carry a `scopes` array (stored as JSON in `api_keys.scopes`, see `src/lib/db/apiKeys.ts`). ### Management scope - `manage` / `admin` — `hasManageScope`. Bearer access to management API routes. - `mcp:connect`, `self:usage`, `self:account-quota`, and `policy:bypass-provider-quota` are additive exact-match scopes. They sit outside `MANAGEMENT_API_KEY_SCOPES`. `mcp:connect` opens only the `/api/mcp/` non-loopback carve-out. ### MCP tool scopes Catalog and matching rules (identical string, or a granted scope ending in `*`): [MCP tool scopes](../frameworks/MCP-SERVER.md#mcp-tool-scopes). `MCP_SCOPE_LIST` in `src/shared/constants/mcpScopes.ts` is the original typed subset, not that full catalog. Enforcement runs in `open-sse/mcp-server/scopeEnforcement.ts` after `resolveCallerScopeContext()` resolves scopes from MCP auth info, request metadata, or `OMNIROUTE_MCP_SCOPES`. `OMNIROUTE_MCP_ENFORCE_SCOPES=true` turns it on globally (default `false`), but it is always enforced for an HTTP/SSE caller whose API key lacks `manage`/`admin` (see `shouldForceScopeEnforcement()` in `open-sse/mcp-server/scopeEnforcement.ts`), regardless of the flag. ### Access-token scopes `read` / `write` / `admin` on `oma_live_…` tokens, ranked by `scopeSatisfies` (`src/lib/accessTokens/scopes.ts`). This rank applies to the access-token credential only. See [Management Authentication](../guides/MANAGEMENT-AUTH.md). ## Auth Required Toggle `isAuthRequired()` in `src/shared/utils/apiAuth.ts` decides whether **any** auth is enforced for a request: - `settings.requireLogin === false` → auth is globally disabled, except for the always-protected tier (see [Route Guard Tiers](../security/ROUTE_GUARD_TIERS.md)) and the calls that hand out a credential it accepts, which need the same credential as with login on: issuing sync tokens, minting CLI access tokens at any scope, and creating an API key with the `manage`/`admin` scope, granting that scope to a key, or regenerating or revealing such a key (`requireCredentialForManagementScopedKey()` in `src/lib/api/requireManagementAuth.ts`). Inference-only keys stay open. Writing a protected feature flag (`REQUIRE_API_KEY`, the other Security flags, and the SSRF / TLS / MCP-scope / sandbox flags listed in [Feature Flags](../reference/FEATURE_FLAGS.md#rest-api)) and saving the PII masking settings (`PUT /api/settings/pii`) also keep needing a credential. - No password configured **and** no `INITIAL_PASSWORD` env var → bootstrap mode allows the onboarding wizard and loopback requests, but exposed network requests still need credentials. Exception: writing a protected feature flag and saving the PII masking settings (`PUT /api/settings/pii`) need a credential even from loopback, so loopback by itself is not enough there. - Any DB error → fails closed (secure-by-default). Client API key enforcement uses `isRequireApiKeyEnabled()` in `src/shared/utils/featureFlags.ts`, not a direct `process.env.REQUIRE_API_KEY` read. This matters for deployed instances: toggling `REQUIRE_API_KEY` in Dashboard → Feature Flags stores a DB override and immediately affects `/v1/*`, `/v1beta/*`, `/models`, `/responses`, `/chat/completions`, `/codex/*`, and other client-API auth checks that share this helper. If the feature flag store cannot be read, client API auth fails closed and requires a key. ## Breaking Change — v3.8.0 The `/api/v1/agents/tasks/*` and `/api/resilience/model-cooldowns` endpoints **now require management auth** (commit `588a0333`). Clients previously sending a normal API key without the `manage` scope receive `403`. Migration: either issue the key the `manage` scope in the API Keys dashboard, or use a logged-in dashboard session. ## Behaviour Change — v3.8.2 `/api/mcp/*` (the remote MCP server) is still LOCAL_ONLY by default but now accepts non-loopback requests when the `Authorization: Bearer ` header carries the `manage` scope. The carve-out is gated explicitly per-path via `LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES` in `src/server/authz/routeGuard.ts`; the sibling LOCAL_ONLY prefix `/api/cli-tools/runtime/*` is intentionally NOT bypassable because it can spawn arbitrary subprocesses. Anonymous requests to `/api/mcp/*` from non-loopback continue to return `403 LOCAL_ONLY` — the default for any new LOCAL_ONLY path remains strict-loopback. See [Route Guard Tiers](../security/ROUTE_GUARD_TIERS.md#manage-scope-carve-out). ## Testing - Unit tests: `tests/unit/authz/` — `classify.test.ts`, `pipeline.test.ts`, `client-api-policy.test.ts`, `management-policy.test.ts`, `public-policy.test.ts`. - Public allowlist: `tests/unit/public-api-routes.test.ts`. - Run focused: `node --import tsx/esm --test tests/unit/authz/classify.test.ts`. ## Debugging The pipeline always stamps responses with: ``` x-request-id: x-omniroute-route-class: PUBLIC | CLIENT_API | MANAGEMENT ``` For authenticated requests the upstream (handler-side) request headers also include: ``` x-omniroute-auth-kind: client_api_key | dashboard_session | management_key | anonymous | sso_user x-omniroute-auth-id: key_ | "dashboard" | "anonymous" | x-omniroute-auth-label: (optional) x-omniroute-auth-scopes: comma-separated list ``` Use `assertAuth(req, expectedClass)` inside handlers — it throws `AuthzAssertionError` with code `AUTHZ_NOT_INITIALIZED` if the middleware was bypassed (helpful for catching configuration regressions in tests). ## See Also - [API_REFERENCE.md](../reference/API_REFERENCE.md) — auth marker per endpoint - [COMPLIANCE.md](../security/COMPLIANCE.md) — audit log for auth events - [MCP-SERVER.md](../frameworks/MCP-SERVER.md#three-scope-namespaces) — three scope namespaces and MCP tool-scope catalog - Source: `src/server/authz/`, `src/lib/api/requireManagementAuth.ts`