Authentication and authorization
The backend turns browser sessions, API credentials, and kiosk access into one request identity. It then uses that identity to apply broad access scopes and target-level rules before an endpoint performs protected work. See Identity and access for the wider identity model and User and device administration for user and device flows.
Authentication model
Request identity
Each request receives a user and a set of effective scopes. An administrator bypasses the permission matrix. A regular user receives grants from a permission group and user-specific changes. The same request identity supports route guards, ownership checks, hidden-library filtering, and user activity updates.
When an endpoint returns the current user, its response can include the device ID resolved from the request. This lets clients relate the session to the active device without trusting a client-supplied device value.
The backend also uses this identity for WebSocket connections. A socket stores the server-resolved user at connect time, then activity and private notification events use that stored identity rather than a client-supplied user ID. This keeps real-time actions tied to the account that opened the connection.
References: backend/…/identity.py• L20-50 backend/…/activity.py• L9-14 backend/…/activity.py• L46-72 backend/…/logs.py• L36-67
Authentication paths
The hybrid authentication layer checks credentials in a fixed order. A valid browser session takes priority over an Authorization header. Without a session, the backend accepts Basic credentials, an rmm_ client token, or an OAuth access token. Kiosk mode is the final fallback for anonymous read-only access.
Session login and OIDC callback login create the browser session and associate it with a web device. The OAuth token endpoint issues short-lived access tokens and one-time refresh tokens after it confirms that the requested scopes are within the user's current grants. Client tokens are user-owned bearer credentials with their own expiry and scope set. The hybrid layer resolves them against the owner's current enabled state and effective scopes, so a token does not outlive the owner's access. OAuth access tokens receive only the scopes that still overlap with the user's current grants.
OpenID Connect login is a separate identity-provider path. It requires an email and configured username claim, accepts only verified email claims when the provider supports that check, and can create an account when registration is enabled. A configured provider role must map to the local administrator or user role. The legacy editor and viewer provider role names now map to the local user role. A provider identity without an allowed role cannot sign in. Existing accounts match by the provider issuer and subject; an email match cannot replace a different subject from the same provider.
The following diagram shows how the credential paths produce one request identity.
flowchart TD
A[Incoming request] --> B{Valid session cookie?}
B -- Yes --> C[Session user and scopes]
B -- No --> D{Authorization header?}
D -- Basic --> E[Check username and password]
D -- Client token --> F[Check token, owner, expiry, and scopes]
D -- OAuth access token --> G[Check access claims]
E --> H[Enabled user and user scopes]
F --> I[Live token and user scopes]
G --> I
D -- No --> J{Kiosk mode?}
J -- Yes --> K[Read-only kiosk identity]
J -- No --> L[Unauthenticated request]
M[OpenID Connect login] --> N[Match or provision enabled user]
Basic authentication is useful for direct API calls and does not create a browser session. Password verification runs outside the event loop because it is costly and some clients send Basic credentials on every request. Bearer credentials cannot grant more than the owning user can currently use. A refresh token is not accepted as a resource credential. Refresh tokens are single-use and produce a new access identity only after their server-side record is consumed.
The hybrid layer also records recent use for client tokens and their linked devices without writing on every request. An expired token, a disabled owner, or an invalid credential leaves the request unauthenticated rather than creating a partial identity.
References: backend/…/hybrid_auth.py• L31-50 backend/…/hybrid_auth.py• L53-60 backend/…/hybrid_auth.py• L63-152 backend/…/auth.py• L118-327 backend/…/auth.py• L330-420 backend/…/base_handler.py• L453-579 backend/…/base_handler.py• L616-801 backend/…/permissions.py• L184-216
Device authorization
The device authorization flow lets a device obtain a client token without holding credentials at startup. The device opens a short-lived request, the user reviews it in an authenticated browser, and the device polls until the user approves or denies it.
The flow moves through these states:
- The device receives a secret device code and a shorter user code.
- The user opens the verification path and sees the device details and the scopes that the user may approve.
- The user approves a permitted scope set or denies the request.
- On approval, the backend creates or updates the user's device and binds a client token to it.
- The device's next permitted poll receives the token. Pending, denied, expired, and over-fast polls return distinct outcomes.
The following diagram shows the separate device and user sides of the approval flow.
sequenceDiagram
participant D as Device
participant B as Backend
participant U as User browser
D->>B: Start authorization
B-->>D: Device code and user code
U->>B: Read pending request
U->>B: Approve or deny scopes
B-->>U: Approval result
D->>B: Poll with device code
B-->>D: Access token or flow status
The device start and poll endpoints are open because the device has no credential yet. The pending, approve, and deny operations require the user's self-service read or write scope. The approved scopes must be a subset of both the requested scopes and the user's current OAuth scopes.
References: backend/…/auth.py• L69-108 backend/…/auth.py• L111-183 backend/…/auth.py• L185-270 backend/…/auth.py• L273-357
Browser sessions
Browser login uses a session layer that can store session data in Redis behind an opaque cookie or serialize it in a signed cookie. Both forms expose session state to HTTP and WebSocket authentication, apply expiry rules, and use HttpOnly cookies with the configured same-site and secure flags.
The Redis session middleware renews a record only while that record still exists. This prevents a request that started before revocation from writing the session back. It tracks all session keys for each user, so credential changes can clear every active browser session. Clearing sessions also closes the associated login sockets.
References: backend/…/redis_session_middleware.py• L13-45 backend/…/redis_session_middleware.py• L46-116 backend/…/session_middleware.py• L17-78 backend/…/session_middleware.py• L80-143
Cross-site request protection
Cookie-authenticated state-changing requests require a matching signed token in the CSRF cookie and x-csrftoken header. Basic and Bearer requests do not use this check when no browser session is present because their credentials are not ambient browser cookies. If a valid session is present, it remains the selected identity and the CSRF check applies even when the request also has an Authorization header. WebSocket and selected public pairing or token routes remain exempt.
References: backend/…/csrf_middleware.py• L19-96 backend/…/csrf_middleware.py• L98-200 backend/main.py• L135-165
Account recovery and invitations
Password reset and invite links use signed, short-lived tokens with a one-time server-side record in Redis. A reset link can be emailed or logged for an administrator to pass on. An invite link carries the role for the new account and is consumed as part of registration, so concurrent reuse does not create multiple accounts.
Credential changes clear the user's tracked sessions before the account write and try to clear them again after the write. A failure to clear sessions before the write stops the update; a failure after the write is logged because the account change has already committed.
References: backend/…/base_handler.py• L192-310 backend/…/base_handler.py• L312-371 backend/…/base_handler.py• L373-461 backend/…/auth.py• L423-487
Authorization model
Coarse scopes
Scopes are the first route-level gate. A scope names a broad resource area and action. The protected_route contract rejects a request before the endpoint runs when its effective scopes do not include the required scope.
| Scope area | Main decision |
|---|---|
me.* | Manage the current user's profile and self-managed data |
roms.*, platforms.*, firmware.* | Read or change library content |
assets.*, devices.*, collections.*, playlists.* | Manage library support data and personal media state |
users.* | View users and manage access policy |
tasks.run, logs.read | Run backend work or view backend logs |
Non-admin users keep self-service scopes. Permission groups and user overrides supply the other scopes. A missing scope produces 401 for an unauthenticated request and 403 for a known user.
References: backend/…/auth.py• L35-45 backend/…/auth.py• L75-151 backend/…/constants.py• L12-74
Granular permissions
Granular permissions refine a broad scope with an entity, action, and optional own-only limit. A permission group supplies a base policy. A user override changes one entity-action pair without changing the group for other users. Users without a selected group use the default group.
The resolver applies the rules in this order:
- An administrator bypasses the database permission matrix.
- A user override replaces the group result for its entity-action pair.
- The user's group supplies the remaining grants.
- The default group supplies grants when no group is assigned.
The resolved result is cached on the request. Endpoint helpers reuse it for action checks, ownership checks, and visibility checks. An own-only grant can manage a caller-owned resource. A library-wide grant is required for resources outside that ownership boundary.
Kiosk mode applies an extra read-only cap to the anonymous kiosk identity. It does not reduce the grants of a user who deliberately signs in while kiosk mode is enabled.
References: backend/…/permission.py• L20-44 backend/…/permission.py• L63-137 backend/…/permissions.py• L40-69 backend/…/permissions.py• L90-181 backend/…/permissions.py• L184-216 backend/…/dependencies.py• L38-116
Permission map projection
The permission map keeps fine-grained grants compatible with the coarse scope contract. Read and write grants project to matching scopes. Delete remains a fine-grained decision because the scope model has no delete scope. The stored role model has only admin and user; older access tiers are represented by permission groups and projected scopes.
The /permissions/me response projects effective grants into the action names used by the client. It helps the client choose controls, but endpoint checks remain authoritative.
References: backend/…/permissions_map.py• L1-16 backend/…/permissions_map.py• L76-127 backend/…/permissions.py• L48-65 backend/…/permission.py• L23-148
Visibility rules
Visibility is separate from permission to act. Administrators can see all library objects. For other authenticated users, the effective visibility filter combines hidden platform IDs, hidden ROM IDs, and optional age rules. Firmware follows its platform's visibility.
The filter removes hidden IDs from list queries and checks the loaded parent object on direct reads. An age limit hides ROMs rated above the user's limit. A group can also hide unrated ROMs when an age rule applies. A user's age settings replace the group settings when they are set. A hidden object appears as 404, not 403, so its existence is not exposed.
The backend applies the same boundary to child resources such as files and user assets. ROM response shaping also removes hidden siblings from detail payloads. Response models expose the caller's own saves, states, screenshots, and notes, plus data that other users marked public. Shared save and state records hide private fields from other users while retaining the data needed to show a public entry.
References: backend/…/rom_visibility.py• L34-117 backend/…/permissions.py• L71-87 backend/…/permissions.py• L147-181 backend/…/dependencies.py• L48-55 backend/…/dependencies.py• L118-166 backend/…/__init__.py• L463-571 backend/…/__init__.py• L738-814 backend/…/rom.py• L514-529 backend/…/rom.py• L620-748 backend/…/files.py• L40-69
Endpoint decisions
Endpoint authorization uses two layers. The route guard checks the broad scope. The handler then checks the target resource, ownership, fine-grained action, or administrator role that the route needs.
The request path is therefore:
flowchart LR
A[Session or credential] --> B[Resolve request identity]
B --> C[Check coarse scope]
C --> D{Target-specific rule?}
D -- No --> E[Run endpoint action]
D -- Yes --> F[Resolve grant, ownership, and visibility]
F --> G{Allowed and visible?}
G -- Yes --> E
G -- No --> H[403 or masked 404]
Important endpoint boundaries include the following:
| Endpoint concern | Authorization decision |
|---|---|
| Configuration | Reads hide parse details and network credentials from anonymous callers. Platform configuration writes require platform write scope. |
| ROM and file access | ROM read scope is followed by a parent-ROM visibility check. ROM file deletion also needs the ROM delete grant. |
| Metadata search | ROM read scope protects provider search. A hidden ROM returns no results and is not sent to providers. |
| Music and playlists | Track browsing uses ROM visibility. Playlist reads include the owner's private playlists and other users' public playlists. Playlist changes require ownership. |
| Streaming | Read scope covers status and joining. Session creation and controls use the user-write scope. Owner checks stop a joiner from controlling the host's session. |
| Tasks and scans | REST task routes and scan sockets use the server-resolved tasks.run scope. Client payload fields do not grant access. |
| Logs and activity | Only administrators enter the log room. Activity events use the user stored on the socket instead of a payload user ID. |
| User administration | User creation may be delegated after bootstrap, but creating an administrator stays administrator-only. Self-edit and cross-user edit rules remain separate. |
| Client tokens | Users manage their own tokens with self-service write access. Administrators can list or revoke any token with user-management access. Pairing and exchange create or use a token only for the owning flow. |
| Device authorization | Device start and polling are open but rate-limited. Reading and approving a pending request require the user's self-service scopes, and approved scopes cannot exceed the user's current grants. |
These layers protect work before side effects begin. For example, hidden ROM checks run before file bytes are served, metadata is fetched, a streaming broker is launched, or a scan is queued. Response shapes preserve these boundaries by omitting hidden data and declaring outcomes such as pending streaming decisions or task cleanup variants.
References: backend/…/configs.py• L118-170 backend/…/configs.py• L186-318 backend/…/music.py• L69-215 backend/…/music_playlists.py• L59-237 backend/…/search.py• L99-143 backend/…/streaming.py• L255-288 backend/…/streaming.py• L635-672 backend/…/streaming.py• L1000-1072 backend/…/tasks.py• L187-345 backend/…/scan.py• L1414-1514 backend/…/logs.py• L36-67 backend/…/user.py• L39-182 backend/…/user.py• L343-504 backend/…/identity.py• L20-50 backend/…/rom.py• L514-748 backend/…/client_tokens.py• L60-192 backend/…/auth.py• L69-183 backend/…/auth.py• L273-357
Real-time authorization
Socket connections use server-side identity but not every socket event has the same access boundary. The main socket connect flow stores authenticated users and places them in private user rooms. The log stream adds administrators to an admin-only room. Scan events resolve the stored user and require tasks.run before queue or stop work.
Sync notifications are sent to a user room selected by the server-side user ID. Netplay room membership is controlled by room state and password checks rather than the HTTP permission map, so its room and signaling contract must be treated as a separate real-time boundary.
Client-token revocation and regeneration also close sockets that use the affected token. This keeps a live connection from retaining access after the token's credential has changed.
References: backend/…/logs.py• L36-67 backend/…/scan.py• L1414-1514 backend/…/sync.py• L25-127 backend/…/netplay.py• L24-111 backend/…/client_tokens.py• L97-131 backend/…/client_tokens.py• L182-192
Permission administration
Group and user policy changes
Administrators manage the permission catalog, reusable groups, group grants, user assignment, user overrides, and hidden library entities. A hidden entry targets exactly one principal: a user or a group. Only platforms and ROMs are stored as hidden entities because firmware inherits platform visibility.
The default group remains available as the fallback for users without an explicit group. It cannot be removed while it is the default. Group changes affect every member, while user changes affect one user's effective policy.
References: backend/…/permissions.py• L58-191 backend/…/permissions.py• L194-327
Permission change notifications
Permission writes emit a permissions:changed event for each affected user. The client re-reads /permissions/me when the affected user is the current user. This event keeps controls fresh, but the backend resolves permissions again on the next request and remains the access control authority.
Role changes also emit the same event. Credential changes clear the user's tracked sessions before the account update and attempt another clear after it. This prevents a failed session store from allowing the update to commit with old sessions still active, while an after-update failure is logged because the account change has already committed.
References: backend/…/permissions.py• L33-46 backend/…/permissions.py• L152-191 backend/…/permissions.py• L250-327 backend/…/user.py• L477-497 backend/…/base_handler.py• L312-358 backend/…/redis_session_middleware.py• L29-45
Change checklist
When these files or sections are changed, remember to consider these:
- Update both the granular entity-action map and the coarse scope projection when a permission domain changes.
- Keep the route scope and the target-level check aligned. A broad write scope must not reopen a route that needs deletion, ownership, or administrator access.
- Preserve the session cookie name, subject format, expiry rules, and revocation behavior across Redis-backed and signed-cookie sessions, HTTP middleware, WebSocket lookup, and session invalidation.
- When adding a cookie-authenticated state-changing route, confirm that its path is not accidentally exempt from CSRF protection. Also account for the rule that a valid session takes priority over an
Authorizationheader. - When changing hidden-resource queries or response shaping, check direct IDs, child routes, sibling payloads, provider lookups, downloads, and streaming launch paths.
- When changing ROM visibility, keep query filters and loaded-object checks aligned for hidden platforms, hidden ROMs, age limits, and unrated ROMs. Preserve firmware inheritance from platform visibility.
- When changing permission resolution, preserve administrator bypass, default-group fallback, override replacement, and the kiosk read-only cap.
- When changing group, override, role, or hidden-entity writes, notify every affected user and keep
/permissions/meaction names aligned with the client. - When changing socket events, keep identity in server-side connection state. Do not authorize an event from a client-supplied user ID or scope value.
- When changing REST tasks or scan sockets, keep both entry points on the server-resolved
tasks.runscope. - When changing user creation or editing, preserve the bootstrap exception and the rule that only an administrator can create or retain administrator access after bootstrap.
- When changing response models used at an authorization boundary, preserve masked empty or
404results and declared pending or terminal variants. - When changing OIDC identity matching or account registration, keep issuer-and-subject matching, email collision checks, provider role mapping, local role updates, email checks, and the registration-disabled path aligned.
- When changing reset, invite, or refresh tokens, preserve their expiry and one-time server-side consumption rules.
- When changing client-token creation, use, pairing, revocation, or regeneration, keep owner scopes, token expiry, socket closure, and audit records aligned.
- When changing device authorization, keep open device entry points separate from protected approval steps. Preserve the requested-scope intersection, poll states, rate limits, and one-time approved-token consumption.
- When changing session login or OAuth token issuance, keep login activity records, disabled-user checks, scope limits, and web-device association aligned across password, OIDC, and refresh flows.
- When changing hybrid credential resolution, preserve session precedence, the access-token-only check, live client-token owner validation, and debounced token and device activity updates.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Revoked or expired Redis session is written back by an in-flight request | The revoked browser session becomes active again | Session renewal uses an existing-record check before writing |
| Token scopes exceed the user's current grants | The credential uses less access than it requests or is rejected | Bearer authentication intersects credential and user scopes |
| Cookie-authenticated unsafe request lacks a valid CSRF pair | The endpoint returns 403 before its handler runs | CSRF middleware checks the signed cookie and header against the selected session user |
| User lacks a fine-grained action | The endpoint returns 403 even when its broad scope passes | Target checks resolve group, override, ownership, and administrator state |
| Caller addresses a hidden ROM, platform, file, or sibling | The target appears absent and no protected side effect runs | Visibility checks mask direct access as 404 and filter list or detail data |
| An age rule hides a ROM that a query or detail path does not filter | A restricted ROM appears in a list or response | The shared ROM visibility filter supplies both query clauses and loaded-ROM checks |
| Anonymous kiosk access reaches a mutating fine-grained check | A public display identity can perform a write | Permission resolution caps the kiosk guest to read grants |
| Anonymous caller reads protected configuration details | A file path or network credential can be exposed | Configuration response limits sensitive fields to authenticated requests |
| Read scope is reused for streaming controls | A joiner or kiosk visitor can change another session | Session controls use user-write scope and ownership checks |
| Scan socket trusts client permission data | An untrusted socket can queue or stop a scan | Scan authorization resolves the connected user and checks tasks.run |
| Permission change omits a notification | The client can show stale controls until a later refresh | Permission writes broadcast permissions:changed to affected users |
| Client-supplied activity user ID is trusted | A client can publish activity for another account | Activity uses the user stored at socket connect |
| Non-admin creates an administrator after bootstrap | A delegated user can escalate privileges | User creation separates normal delegated creation from admin creation |
| A user changes a username or password without session revocation | Old browser sessions remain usable | Credential changes clear the user's tracked Redis sessions before and after the write |
| OIDC login matches an account only by email after the provider subject changes | A provider identity can take over an existing account | Matching uses issuer and subject, and rejects a different subject already linked at that issuer |
| OIDC registration accepts an identity without a permitted role | An unapproved provider user receives an account or login | Provider role claims are checked before account creation or role update |
| A reset, invite, or refresh token is reused | A one-time security action can be replayed | The token's Redis record is consumed on use |
| Redis is unavailable before a credential update | The account change could commit while old sessions remain live | The pre-update session clear must succeed before the database write |
| A client token expires, is revoked, or belongs to a disabled user | Its request or socket loses access | Token resolution checks token lifetime, owner status, and current owner scopes; revocation and regeneration close token sockets |
| Device approval includes a scope outside the user's current grants | The device receives access the user cannot delegate | Approval accepts only the intersection of requested and user scopes |
| A device polls too fast, after denial, or after approval is consumed | The device receives a temporary, denied, or expired result instead of a token | Poll rate limits and one-time approved-state consumption enforce the flow states |
| A request sends an expired client token or a token owned by a disabled user | The request is treated as unauthenticated instead of using stale access | Client-token resolution checks expiry and the owner's enabled state before returning an identity |
| A refresh token is presented as a resource credential | The token cannot access an endpoint | The hybrid bearer path accepts only OAuth claims with type access |
Key files
| File | Why to read it |
|---|---|
| backend/…/hybrid_auth.py | Shows credential precedence, access-token-only use, live client-token checks, scope intersection, and activity tracking |
| backend/…/auth.py | Shows browser login, OAuth access and refresh issuance, OIDC callback, logout, and recovery entry points |
| backend/…/base_handler.py | Shows password, OIDC identity matching, invite, reset, session revocation, and OAuth token decisions |
| backend/…/client_tokens.py | Shows user and administrator token management, pairing, exchange, and socket invalidation |
| backend/…/auth.py | Shows the device authorization lifecycle and its protected approval boundary |
| backend/…/redis_session_middleware.py | Shows Redis session lookup, renewal, bulk invalidation, and login-socket closure |
| backend/…/session_middleware.py | Shows the signed-cookie session form and its expiry handling |
| backend/…/csrf_middleware.py | Shows when cookie requests need a CSRF pair and how tokens bind to session users |
| backend/…/auth.py | Defines route scope checks and 401 versus 403 behavior |
| backend/…/permissions.py | Resolves effective grants, coarse scopes, kiosk limits, and library visibility settings |
| backend/…/permissions_map.py | Connects fine-grained grants to coarse scopes |
| backend/…/dependencies.py | Provides cached action, ownership, administrator, and visibility checks |
| backend/…/rom_visibility.py | Defines the shared ROM visibility rules for queries and loaded objects |
| backend/…/permission.py | Defines policy entities, actions, groups, overrides, and hidden entries |
| backend/…/permissions.py | Shows policy administration and permission-change events |
| backend/…/user.py | Shows user creation, self-service boundaries, and credential-triggered session revocation |
| backend/…/identity.py | Shows request-aware user and device identity in response data |
| backend/…/__init__.py | Shows library list, direct-read, download, and write authorization |
| backend/…/files.py | Shows parent-ROM checks for file metadata, content, and deletion |
| backend/…/rom.py | Shows visibility filtering for ROM siblings and user-owned or public data |
| backend/…/streaming.py | Shows read versus session-control scopes and owner checks |
| backend/…/music.py and backend/…/music_playlists.py | Show visibility-aware music access and playlist ownership |
| backend/…/search.py | Shows visibility enforcement before external metadata search |
| backend/…/tasks.py and backend/…/scan.py | Show the shared task-run boundary for REST and socket scan control |
| backend/…/logs.py and backend/…/activity.py | Show administrator log rooms and server-resolved socket identity |
| backend/…/sync.py | Shows user-scoped delivery of background sync notifications |