Files
romm/backend/endpoints/permissions.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

567 lines
19 KiB
Python

import asyncio
from typing import Annotated, Any, Final
from fastapi import Body, HTTPException, Request, status
from decorators.auth import protected_route
from endpoints.responses.permission import (
GrantSchemaIO,
HiddenEntityCreate,
HiddenEntitySchema,
OverrideSchemaIO,
PermissionCatalogSchema,
PermissionGroupCreate,
PermissionGroupSchema,
PermissionGroupUpdate,
PermissionsResponse,
UserPermissionsSchema,
UserPermissionsUpdate,
)
from handler.audit_handler import AuditTarget, record
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_admin, get_permissions
from handler.database import (
db_client_token_handler,
db_permission_handler,
db_platform_handler,
db_rom_handler,
db_user_handler,
)
from handler.socket_handler import close_client_token_sockets, socket_handler
from logger.logger import log
from models.audit_event import AuditAction, AuditTargetType
from models.permission import (
OWNABLE_PERM_ENTITIES,
PermAction,
PermEntity,
PermissionGroup,
)
from utils.router import APIRouter
router = APIRouter(
prefix="/permissions",
tags=["permissions"],
)
ADMIN_ONLY_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_403_FORBIDDEN: {"description": "The caller is not an admin."}
}
GROUP_NOT_FOUND_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_404_NOT_FOUND: {"description": "No permission group has this ID."}
}
USER_NOT_FOUND_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_404_NOT_FOUND: {"description": "No user has this ID."}
}
async def _broadcast_permissions_changed(user_id: int) -> None:
try:
await socket_handler.socket_server.emit(
"permissions:changed", {"user_id": user_id}
)
except Exception as e: # noqa: BLE001
log.warning(f"Failed to broadcast permissions:changed for user {user_id}: {e}")
async def emit_permissions_changed(*user_ids: int) -> None:
"""Notify clients that the users' effective permissions changed.
Broadcast (Redis-backed fan-out); the frontend re-fetches `/permissions/me`
only when the affected user is the current user. Call this from any path that
mutates a user's role, group, overrides, hidden entities or age settings.
"""
# The gallery's cached id index, counts and filter values are computed per
# user with visibility applied, so they go stale with it.
db_rom_handler.invalidate_filter_values_cache()
if not user_ids:
return
await asyncio.gather(*(_broadcast_permissions_changed(u) for u in user_ids))
try:
token_ids = db_client_token_handler.get_token_ids_by_users(user_ids)
except Exception: # noqa: BLE001
log.warning(f"Failed to look up the tokens of users {user_ids}", exc_info=True)
return
await close_client_token_sockets(token_ids)
@protected_route(router.get, "/me", [Scope.ME_READ])
def get_my_permissions(request: Request) -> PermissionsResponse:
"""Return the caller's effective permissions for the UI to gate on.
The backend remains the source of truth; this is a UX hint. Includes the
granted action keys and the platform/rom ids hidden from the caller.
"""
return PermissionsResponse.from_resolved(get_permissions(request))
# --- Admin: catalog -----------------------------------------------------------
@protected_route(
router.get, "/catalog", [Scope.USERS_READ], responses=ADMIN_ONLY_RESPONSE
)
def get_permission_catalog(request: Request) -> PermissionCatalogSchema:
"""The entity/action vocabulary the admin UI renders its matrix from."""
assert_admin(request)
return PermissionCatalogSchema(
entities=list(PermEntity),
actions=list(PermAction),
ownable_entities=[e for e in PermEntity if e in OWNABLE_PERM_ENTITIES],
)
# --- Admin: permission groups -------------------------------------------------
def _group_schema(group: PermissionGroup) -> PermissionGroupSchema:
return PermissionGroupSchema(
id=group.id,
name=group.name,
description=group.description,
is_default=group.is_default,
system_key=group.system_key,
color=group.color,
grants=[
GrantSchemaIO(entity=g.entity, action=g.action, own_only=g.own_only)
for g in group.grants
],
member_count=len(db_permission_handler.get_group_member_ids(group.id)),
hidden=[
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id)
for h in db_permission_handler.get_hidden_entities(group_id=group.id)
],
age_limit=group.age_limit,
hide_unrated_roms=group.hide_unrated_roms,
)
def _group_target(group: PermissionGroup) -> AuditTarget:
return AuditTarget(AuditTargetType.PERMISSION_GROUP, group.id, group.name)
def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget | None:
if entity == PermEntity.ROMS:
rom = db_rom_handler.get_rom_visibility_label(entity_id)
return (
AuditTarget.of_rom(rom)
if rom
else AuditTarget(AuditTargetType.ROM, entity_id, None)
)
if entity == PermEntity.PLATFORMS:
platform = db_platform_handler.get_platform(entity_id)
return (
AuditTarget.of_platform(platform)
if platform
else AuditTarget(AuditTargetType.PLATFORM, entity_id, None)
)
return None
def _group_name(group_id: int | None) -> str | None:
group = db_permission_handler.get_group(group_id) if group_id is not None else None
return group.name if group else None
def _principal(user_id: int | None, group_id: int | None) -> dict[str, Any]:
"""Who something was hidden from, named for the audit log."""
if user_id is not None:
user = db_user_handler.get_user(user_id)
return {"type": "user", "id": user_id, "name": user.username if user else None}
return {"type": "group", "id": group_id, "name": _group_name(group_id)}
@protected_route(
router.get, "/groups", [Scope.USERS_READ], responses=ADMIN_ONLY_RESPONSE
)
def list_permission_groups(request: Request) -> list[PermissionGroupSchema]:
"""List all permission groups with their grants."""
assert_admin(request)
return [_group_schema(g) for g in db_permission_handler.get_groups()]
@protected_route(
router.post,
"/groups",
[Scope.USERS_WRITE],
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_400_BAD_REQUEST: {
"description": "A group with this name already exists."
},
**ADMIN_ONLY_RESPONSE,
},
)
async def create_permission_group(
request: Request, body: PermissionGroupCreate
) -> PermissionGroupSchema:
"""Create a permission group."""
assert_admin(request)
if db_permission_handler.get_group_by_name(body.name):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A group with that name already exists",
)
group = db_permission_handler.create_group(
name=body.name,
description=body.description,
is_default=body.is_default,
color=body.color,
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
age_limit=body.age_limit,
hide_unrated_roms=body.hide_unrated_roms,
)
if body.is_default:
await emit_permissions_changed(
*db_permission_handler.get_group_follower_ids(group.id)
)
record(
AuditAction.PERMISSION_GROUP_CREATE,
request,
_group_target(group),
{"grants": len(body.grants), "is_default": body.is_default},
)
return _group_schema(group)
@protected_route(
router.put,
"/groups/{id}",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"Another group has this name, or the request unsets the default"
" group without making another group the default."
)
},
**ADMIN_ONLY_RESPONSE,
**GROUP_NOT_FOUND_RESPONSE,
},
)
async def update_permission_group(
request: Request,
id: int,
body: PermissionGroupUpdate,
) -> PermissionGroupSchema:
"""Update a permission group (name/description/default/grants)."""
assert_admin(request)
group = db_permission_handler.get_group(id)
if group is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
# Renaming onto an existing name would hit the unique constraint as a 500.
if body.name is not None:
clash = db_permission_handler.get_group_by_name(body.name)
if clash is not None and clash.id != id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A group with that name already exists",
)
# Don't leave the system without a default group; reassign first.
if body.is_default is False and group.is_default:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Set another group as default first",
)
updated = db_permission_handler.update_group(
id,
name=body.name,
description=body.description,
is_default=body.is_default,
color=body.color,
grants=(
[(g.entity, g.action, g.own_only) for g in body.grants]
if body.grants is not None
else None
),
set_age_settings=body.set_age_settings,
age_limit=body.age_limit,
hide_unrated_roms=body.hide_unrated_roms,
)
if updated is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
await emit_permissions_changed(*db_permission_handler.get_group_follower_ids(id))
# Age settings apply only with the flag, so only the flag reports them.
age_fields = {"set_age_settings", "age_limit", "hide_unrated_roms"}
changed = set(body.model_dump(exclude_none=True)) - age_fields
if body.set_age_settings:
changed |= {"age_limit", "hide_unrated_roms"}
record(
AuditAction.PERMISSION_GROUP_EDIT,
request,
_group_target(updated),
{"changed": sorted(changed)},
)
return _group_schema(updated)
@protected_route(
router.delete,
"/groups/{id}",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {"description": "The group is the default group."},
**ADMIN_ONLY_RESPONSE,
**GROUP_NOT_FOUND_RESPONSE,
},
)
async def delete_permission_group(
request: Request,
id: int,
) -> None:
"""Delete a permission group. Members fall back to the default group."""
assert_admin(request)
group = db_permission_handler.get_group(id)
if group is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
if group.is_default:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete the default group; set another default first",
)
member_ids = db_permission_handler.get_group_member_ids(id)
db_permission_handler.delete_group(id)
record(
AuditAction.PERMISSION_GROUP_DELETE,
request,
_group_target(group),
{"members": len(member_ids)},
)
await emit_permissions_changed(*member_ids)
# --- Admin: per-user assignment ----------------------------------------------
def _user_permissions(
user_id: int,
*,
group_id: int | None,
age_limit: int | None,
hide_unrated_roms: bool | None,
) -> UserPermissionsSchema:
overrides = db_permission_handler.get_user_overrides(user_id)
hidden = db_permission_handler.get_hidden_entities(user_id=user_id)
return UserPermissionsSchema(
user_id=user_id,
permission_group_id=group_id,
overrides=[
OverrideSchemaIO(
entity=o.entity,
action=o.action,
granted=o.granted,
own_only=o.own_only,
)
for o in overrides
],
hidden=[
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id) for h in hidden
],
age_limit=age_limit,
hide_unrated_roms=hide_unrated_roms,
)
@protected_route(
router.get,
"/users/{user_id}",
[Scope.USERS_READ],
responses={**ADMIN_ONLY_RESPONSE, **USER_NOT_FOUND_RESPONSE},
)
def get_user_permissions(
request: Request,
user_id: int,
) -> UserPermissionsSchema:
"""A user's group membership, per-user overrides and hidden entities."""
assert_admin(request)
user = db_user_handler.get_user(user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
return _user_permissions(
user_id,
group_id=user.permission_group_id,
age_limit=user.age_limit,
hide_unrated_roms=user.hide_unrated_roms,
)
@protected_route(
router.put,
"/users/{user_id}",
[Scope.USERS_WRITE],
responses={**ADMIN_ONLY_RESPONSE, **USER_NOT_FOUND_RESPONSE},
)
async def update_user_permissions(
request: Request,
user_id: int,
body: UserPermissionsUpdate,
) -> UserPermissionsSchema:
"""Assign a user's group and/or replace their per-user overrides."""
assert_admin(request)
user = db_user_handler.get_user(user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
group_id = user.permission_group_id
if body.set_group:
group_id = body.permission_group_id
db_permission_handler.set_user_group(user_id, group_id)
if body.overrides is not None:
db_permission_handler.replace_user_overrides(
user_id,
[(o.entity, o.action, o.granted, o.own_only) for o in body.overrides],
)
age_limit, hide_unrated_roms = user.age_limit, user.hide_unrated_roms
if body.set_age_settings:
age_limit, hide_unrated_roms = body.age_limit, body.hide_unrated_roms
db_user_handler.update_user(
user_id,
{"age_limit": age_limit, "hide_unrated_roms": hide_unrated_roms},
)
await emit_permissions_changed(user_id)
record(
AuditAction.USER_PERMISSIONS_EDIT,
request,
AuditTarget.of_user(user),
lambda: {
"group": _group_name(group_id),
"group_changed": body.set_group and group_id != user.permission_group_id,
"overrides": len(body.overrides) if body.overrides is not None else None,
"age_settings_changed": body.set_age_settings,
},
)
return _user_permissions(
user_id,
group_id=group_id,
age_limit=age_limit,
hide_unrated_roms=hide_unrated_roms,
)
# --- Admin: hidden entities ---------------------------------------------------
@protected_route(
router.post,
"/hidden",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"The request does not set exactly one of `user_id` and `group_id`,"
" or the entity is not a platform or a rom."
)
},
**ADMIN_ONLY_RESPONSE,
},
)
async def add_hidden_entity(
request: Request, body: HiddenEntityCreate
) -> HiddenEntitySchema:
"""Hide an entity from a user OR a group (exactly one principal)."""
assert_admin(request)
if (body.user_id is None) == (body.group_id is None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Exactly one of user_id or group_id must be set",
)
# Only platforms and roms are honored by the resolver (firmware is hidden via
# its platform cascade), so reject other entity types instead of storing a
# row the visibility filter would silently ignore. The id itself is a
# denylist entry, so a not-yet-present id is a harmless no-op, not an error.
if body.entity not in (PermEntity.PLATFORMS, PermEntity.ROMS):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Only platforms and roms can be hidden",
)
db_permission_handler.add_hidden_entity(
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_id
)
record(
AuditAction.VISIBILITY_HIDE,
request,
lambda: _hidden_target(body.entity, body.entity_id),
lambda: {
"from": _principal(body.user_id, body.group_id),
"entity": body.entity,
"entity_id": body.entity_id,
},
)
await _emit_for_principal(body.user_id, body.group_id)
return HiddenEntitySchema(entity=body.entity, entity_id=body.entity_id)
@protected_route(
router.delete,
"/hidden",
[Scope.USERS_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_400_BAD_REQUEST: {
"description": "The request does not set exactly one of `user_id` and `group_id`."
},
**ADMIN_ONLY_RESPONSE,
},
)
async def remove_hidden_entity(
request: Request,
entity: Annotated[PermEntity, Body(embed=True)],
entity_id: Annotated[int, Body(embed=True)],
user_id: Annotated[
int | None,
Body(
embed=True,
description=(
"The user it was hidden from. Set exactly one of `user_id` and"
" `group_id`."
),
),
] = None,
group_id: Annotated[
int | None,
Body(
embed=True,
description=(
"The group it was hidden from. Set exactly one of `user_id` and"
" `group_id`."
),
),
] = None,
) -> None:
"""Un-hide an entity for a user OR a group."""
assert_admin(request)
if (user_id is None) == (group_id is None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Exactly one of user_id or group_id must be set",
)
db_permission_handler.remove_hidden_entity(
entity, entity_id, user_id=user_id, group_id=group_id
)
record(
AuditAction.VISIBILITY_UNHIDE,
request,
lambda: _hidden_target(entity, entity_id),
lambda: {
"from": _principal(user_id, group_id),
"entity": entity,
"entity_id": entity_id,
},
)
await _emit_for_principal(user_id, group_id)
async def _emit_for_principal(user_id: int | None, group_id: int | None) -> None:
if user_id is not None:
await emit_permissions_changed(user_id)
elif group_id is not None:
await emit_permissions_changed(
*db_permission_handler.get_group_follower_ids(group_id)
)