Files
romm/backend/utils/auth.py
Georges-Antoine Assi 4159710e79 docs(api): document the error responses routes raise (#5693)
* docs(api): document error responses for roms routes

Describe every 4xx and 5xx the rom routes and their helpers raise in each
decorator's responses=, so the OpenAPI schema lists them. A hidden rom,
platform or file is described like a missing one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for saves routes

Describe every 4xx/5xx the saves, states, screenshots, snapshots,
play-sessions and sync routes raise in their responses=, and rewrite the
states identifiers docstring that carried Args/Returns blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for devices routes

Describe the 4xx/5xx statuses that the device, device auth, install,
client token, notification, notification channel, sync channel and
heartbeat routes raise, and fill the empty install route entries.
Rewrite the setup and heartbeat docstrings that published Args and
Returns blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for streaming routes

Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for admin routes

Describe the 4xx and 5xx statuses the config, permissions, user, auth,
tasks, logs, activity and export routes raise, and rewrite their
Args/Returns docstrings as plain operation descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error responses for library routes

Describe the 400/403/404/409/500 statuses the collection, feed, firmware,
platform, music, playlist and search routes raise, and replace route
docstrings that carried Args/Returns blocks with plain sentences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): describe private collections and playlists as missing

Matches #5686, where another user's private collection or playlist
answers 404 and a play session on a hidden rom answers like a missing
one. The read routes drop their 403, and the write 403 now covers only
a public resource another user owns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): address Greptile review on route error docs

Fold the nine multi-paragraph route docstrings into one line, and keep
the device-scope 403 descriptions in utils/auth.py next to
resolve_device, which raises them, instead of in both saves.py and
states.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): plain-prose pass on route error descriptions

Spell out clipped error descriptions, replace internal slang (picked,
taken, live, moved past), name the parameter an ID comes from, and split
the long save conversion 400s into sentences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:11:20 -05:00

183 lines
6.3 KiB
Python

import uuid
from datetime import datetime, timezone
from http.cookies import SimpleCookie
from typing import Any, cast
from fastapi import HTTPException, Request, status
from starlette.requests import HTTPConnection
from ua_parser import Result as UAResult
from ua_parser import parse as parse_ua
from handler.auth.constants import SESSION_COOKIE_NAME, Scope
from handler.database import db_device_handler
from handler.redis_handler import async_cache
from logger.formatter import CYAN
from logger.formatter import highlight as hl
from logger.logger import log
from models.device import KNOWN_DEVICES, Device
from models.user import User
from utils import json_module
def token_device_id(conn: HTTPConnection) -> str | None:
"""The device the request's client token is bound to, if any."""
return getattr(conn.state, "device_id", None)
def token_reaches_device(conn: HTTPConnection, device_id: str | None) -> bool:
"""Whether the request's client token may act on this device; unbound ones reach all."""
return token_device_id(conn) in (None, device_id)
def require_token_device(conn: HTTPConnection, device_id: str) -> None:
"""Hide every other device from a client token bound to one, as a 404."""
if not token_reaches_device(conn, device_id):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
def require_device(
request: Request, device_id: str, device_only: bool = False
) -> Device:
"""The caller's device, 404 when not theirs and 403 under ``device_only`` for another caller."""
require_token_device(request, device_id)
device = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
if device is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
if device_only and token_device_id(request) != device_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only the device itself can do this",
)
return device
def resolve_device(
request: Request,
device_id: str | None,
required_scope: Scope | None = None,
) -> Device | None:
"""The caller's device a sync request names, None when it names none."""
if not device_id:
return None
scopes = request.auth.scopes
if required_scope and scopes and required_scope not in scopes:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
return require_device(request, device_id)
# The 403 descriptions for a `device_id` that resolve_device refuses.
DEVICE_READ_FORBIDDEN = (
f"The request sets `device_id` without the `{Scope.DEVICES_READ}` scope."
)
DEVICE_WRITE_FORBIDDEN = (
f"The request sets `device_id` without the `{Scope.DEVICES_WRITE}` scope."
)
def request_client_token_id(conn: HTTPConnection) -> int | None:
"""The id of the client token that authenticated the request, if any."""
return getattr(conn.state, "client_token_id", None)
def current_device_id(conn: HTTPConnection) -> str | None:
"""The device a request comes from: its client token's, else its web session's."""
return token_device_id(conn) or (conn.scope.get("session") or {}).get("device_id")
async def get_session_from_environ(environ: dict[str, Any]) -> dict[str, Any]:
"""Resolve the auth session for a socket handshake.
Tries the session the middleware attached to the ASGI scope first; if it's
absent (scope not propagated to the mounted socket app), falls back to
parsing the session cookie and reading the session straight from Redis —
the same lookup RedisSessionMiddleware performs.
"""
scope = environ.get("asgi.scope", {})
session = scope.get("session")
if session:
return cast(dict[str, Any], session)
raw_cookie = environ.get("HTTP_COOKIE", "")
if not raw_cookie:
return {}
cookie: SimpleCookie = SimpleCookie()
cookie.load(raw_cookie)
morsel = cookie.get(SESSION_COOKIE_NAME)
if morsel is None:
return {}
session_data = await async_cache.get(f"session:{morsel.value}")
if not session_data:
return {}
try:
session = json_module.loads(session_data)
except Exception: # noqa: BLE001 - malformed session is "no session"
return {}
# The middleware adds the same key on the scope path.
return {**session, "session_id": morsel.value}
def _get_device_name(user_agent: UAResult) -> str | None:
"""Extract stable browser + OS family from a User-Agent string.
Returns something like "Chrome on Mac OS X" or "Firefox on Windows"
which won't change across browser version updates.
"""
browser = user_agent.user_agent.family if user_agent.user_agent else None
os = user_agent.os.family if user_agent.os else None
if browser and os:
return f"{browser} on {os}"
if browser:
return browser
return os or "Web Browser"
def create_or_find_web_device(request: Request, user: User) -> Device:
"""Find or create a web browser device for the given user.
Uses parsed browser/OS family + client IP as fingerprint to avoid
creating duplicate devices for the same browser.
"""
device_type = KNOWN_DEVICES["web"]
user_agent = parse_ua(request.headers.get("user-agent", ""))
client_version = user_agent.user_agent.major if user_agent.user_agent else None
ip_address = request.client.host if request.client else None
existing = db_device_handler.get_device_by_fingerprint(
user_id=user.id,
ip_address=ip_address,
platform=device_type.platform,
)
if existing:
db_device_handler.update_last_seen(device_id=existing.id, user_id=user.id)
return existing
device = Device(
id=str(uuid.uuid4()),
user_id=user.id,
name=_get_device_name(user_agent),
platform=device_type.platform,
client=device_type.client,
client_version=client_version,
sync_mode=device_type.sync_mode,
ip_address=ip_address,
last_seen=datetime.now(timezone.utc),
)
device = db_device_handler.add_device(device)
log.info(
f"Auto-created web device {device.id} for user {hl(user.username, color=CYAN)}"
)
return device