Files
romm/backend/handler/auth/dependencies.py
Sam Dornan bba15f95f4 perf(backend): resolve roms without the related load in the file and props routes (#4590)
* perf(backend): resolve roms without the related load in the file and props routes

Eleven routes opened with `get_rom(id)` to reach two scalars: `id` for the
404 and `id` plus `platform_id` for `assert_rom_visible`. `get_rom` runs the
whole `with_details` eager load, so each request paid for the platform,
files, metadata, saves, states, screenshots, rom_users, siblings,
collections and notes of the rom. The bulk delete was worse: it ran inside a
per-id loop, so an N-id delete ran the graph N times.

Three narrow projections replace it, alongside the `get_rom_visibility` that
#4587 added for the rom-note routes:

  `get_rom_visibility`        id, platform_id
  `get_rom_visibility_label`  the above plus the name pair the file-delete
                              log lines print
  `get_rom_deletion_target`   the above plus fs_path and the joined platform
                              label the bulk delete logs when a rom's file is
                              already missing from disk

`assert_rom_visible` accepts either narrow row as well as a full `Rom`, so
the check itself is unchanged for every other caller.

Statement counts per request, captured with the `executed_statements`
fixture in `tests/endpoints/roms/test_visibility_loads.py`:

  PUT  /api/roms/{id}/props                       19 ->  9
  GET  /api/roms/{id}/soundtracks/metadata        15 ->  5
  GET  /api/roms/{rom_id}/files/{file_id}/progress 20 ->  8
  DELETE manuals / walkthroughs / screenshots /
         soundtracks files                         20 ->  8 each
  DELETE /api/roms/{rom_id}/files/{file_id}        20 ->  8
  GET  /api/roms/{id}/files (hidden 404)           25 -> 13
  GET  /api/roms/{id}/files/content/{name}         25 -> 13
  POST /api/roms/delete, 1 id                      16 ->  6
  POST /api/roms/delete, 5 ids                     64 -> 14

The marginal cost of each extra id in a bulk delete falls from 12 statements
to 2.

The upload handlers on the same routers are left alone: `receive_rom_file`
hands the rom to `prepare_upload_destination`, so they need the full entity.
`Rom.fs_resources_path` moves its format string into a module-level function
so `RomDeletionTarget` can compute the same value.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(backend): trim the change rationale out of the new docstrings

Greptile flagged the module docstring in the new test file, `_rom_lookup` and
`RomDeletionTarget` for carrying the reasoning behind the change rather than
describing what the code does. The rationale lives in the commit message and
the PR body, so the docstrings keep only the one sentence a reader needs.

The `assert_rom_visible` docstring loses the paragraph added alongside the
widened type union, which restated what the signature already shows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(roms): share one rom factory in the visibility-load guard

Step 3 of the pr-ready gauntlet (simplify). The bulk-delete test built its
three roms from an inline `Rom(...)` literal; `test_random.py` already keeps a
module-local `_add_rom(platform, name)` for exactly this, so the guard grows
the same helper instead of a second copy of the field list.

`_flat` had one caller, so it folds into `_rom_lookup`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 12:18:22 -05:00

155 lines
5.3 KiB
Python

"""Fine-grained, DB-backed permission checks for endpoint handlers.
The coarse ``@protected_route(..., [Scope.X])`` gate stays the first line of
defense (and is what client tokens / kiosk rely on). These helpers add the
authoritative per-entity / per-action / ownership / visibility decisions on top,
resolved once per request and cached on ``request.state``.
Typical use inside a handler::
perms = get_permissions(request)
assert_can(perms, PermEntity.ROMS, PermAction.DELETE) # library-wide
assert_can(perms, PermEntity.COLLECTIONS, PermAction.WRITE,
owner_id=collection.user_id) # own-data ok
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from fastapi import HTTPException, Request, status
from exceptions.endpoint_exceptions import (
PlatformNotFoundInDatabaseException,
RomNotFoundInDatabaseException,
)
from handler.auth.permissions import ResolvedPermissions, resolve_permissions
from models.permission import PermAction, PermEntity
if TYPE_CHECKING:
from models.firmware import Firmware
from models.platform import Platform
from models.rom import Rom, RomVisibility, RomVisibilityLabel
def get_permissions(request: Request) -> ResolvedPermissions:
"""Resolve (and cache for the request) the caller's effective permissions."""
cached = getattr(request.state, "permissions", None)
if cached is not None:
return cached
perms = resolve_permissions(request.user)
request.state.permissions = perms
return perms
def can_access(
perms: ResolvedPermissions,
entity: PermEntity,
action: PermAction,
*,
owner_id: int | None = None,
) -> bool:
"""Whether ``perms`` may perform ``action`` on ``entity``.
Admins bypass. A user may always act on a resource they own (``owner_id``
matches). Otherwise a library-wide (non ``own_only``) grant is required.
"""
if perms.is_admin:
return True
if owner_id is not None and owner_id == perms.user_id:
return True
return perms.allows(entity, action, owned=False)
def assert_can(
perms: ResolvedPermissions,
entity: PermEntity,
action: PermAction,
*,
owner_id: int | None = None,
) -> None:
"""Raise 403 unless ``perms`` may perform ``action`` on ``entity``."""
if not can_access(perms, entity, action, owner_id=owner_id):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions",
)
def require_permission(entity: PermEntity, action: PermAction):
"""FastAPI dependency factory for library-wide gating of a route.
Returns the resolved permissions so the handler can reuse them.
"""
def _dependency(request: Request) -> ResolvedPermissions:
perms = get_permissions(request)
assert_can(perms, entity, action)
return perms
return _dependency
def assert_admin(request: Request) -> ResolvedPermissions:
"""Raise 403 unless the caller is an admin. For permission-management routes."""
perms = get_permissions(request)
if not perms.is_admin:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Administrator privileges required",
)
return perms
# 404-masking helpers: a hidden entity must read as non-existent, not forbidden,
# so its existence isn't leaked. The auth guard skips the check on unauthenticated
# download endpoints, which carry no permission context to resolve.
def assert_rom_visible(
request: Request,
rom: Rom | RomVisibility | RomVisibilityLabel,
*,
not_found_detail: str | None = None,
) -> None:
"""Raise 404 (not 403) when the rom is hidden from the caller.
Defaults to the standard ``RomNotFoundInDatabaseException`` message; pass
``not_found_detail`` for endpoints with a bespoke 404 (metadata-id / hash
lookups) so the masked response is indistinguishable from their not-found.
"""
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
rom.id, rom.platform_id
):
if not_found_detail is not None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
)
raise RomNotFoundInDatabaseException(rom.id)
def assert_platform_visible(
request: Request, platform: Platform, *, not_found_detail: str | None = None
) -> None:
"""Raise 404 (not 403) when the platform is hidden from the caller.
Pass ``not_found_detail`` to match an endpoint's bespoke 404 message.
"""
if request.user.is_authenticated and not get_permissions(request).can_see_platform(
platform.id
):
if not_found_detail is not None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=not_found_detail
)
raise PlatformNotFoundInDatabaseException(platform.id)
def assert_firmware_visible(request: Request, firmware: Firmware) -> None:
"""Raise 404 when the firmware's platform is hidden (firmware inherits it)."""
if request.user.is_authenticated and not get_permissions(request).can_see_platform(
firmware.platform_id
):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Firmware with ID {firmware.id} not found",
)