Files
romm/backend/handler/auth/dependencies.py
Georges-Antoine Assi 26dff477d7 fix(auth): bound new client tokens by the caller's scopes and stop delegates removing admins (#5346)
* fix(auth): bound new client tokens by the caller's scopes and stop delegates removing admins

- Creating a client token, approving a device, and regenerating or pairing
  an existing token now check against the scopes of the credential making
  the request rather than the whole account's. A narrow client token can no
  longer mint, or recover the secret of, a broader one. Session and basic
  auth carry the account's scopes, so they behave as before.
- Deleting an admin requires the caller to be an admin, mirroring the
  existing rule for creating one, since users.write can be delegated.
- Editing another user requires the users.write scope on top of the admin
  role, so an admin's me.write-only token can't change other accounts.
- own_only is rejected (422) on grants and overrides for entities with no
  owner (platforms, roms, firmware, users, tasks, logs), where it silently
  meant "all". The catalog exposes the ownable entities and the permission
  matrices only offer "own" on those.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(permissions): keep owner-less own_only grants' access on save

Addresses Greptile review on #5346:
- An own_only delete grant on an entity with no owner allows nothing
  today (delete has no coarse scope and the fine check runs with
  owned=False), so it is now dropped from group grants, or turned into
  a revoke for overrides, instead of being saved as full delete access.
  The matrices show it the same way.
- The group dialog no longer saves when the permission catalog failed
  to load, which would have stripped every own_only grant.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): require users.write in the credential to act on another user (pr-ready: code-review)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(auth): share client token effective scopes and canOwn (pr-ready: simplify)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(permissions): tighten grantEffect docstring and matrix comment (pr-ready: review-polish)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): make user, token and streaming admin rules consistent

- Acting on another user (edit, delete, RA refresh) needs users.write in
  the credential, and only admins may target an admin or grant the admin
  role. One assert_admin_for_admin helper now backs add_user, invite
  links, update, delete and admin token revocation.
- Re-issuing a client token's secret (regenerate, pair) needs every scope
  it stores; deleting one needs every scope it currently grants, so a
  narrow token can't remove a broader sibling.
- Streaming admin overrides need users.read or users.write in the
  credential, not just the admin role.
- Migration 0154 rewrites stored own_only grants and overrides on
  owner-less entities to the access they already gave, so the frontend
  normalisation and the catalog save gate are gone.
- own_only is no longer rejected on revoke overrides.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 09:35:17 -04:00

167 lines
6.0 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, cast
from fastapi import HTTPException, Request, status
from exceptions.endpoint_exceptions import (
PlatformNotFoundInDatabaseException,
RomNotFoundInDatabaseException,
)
from handler.auth.constants import Scope
from handler.auth.permissions import ResolvedPermissions, resolve_permissions
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from models.permission import PermAction, PermEntity
from models.user import Role
if TYPE_CHECKING:
from models.firmware import Firmware
from models.platform import Platform
from models.rom import Rom, RomInstallTarget, 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 cast(ResolvedPermissions, cached)
perms = resolve_permissions(request.user)
request.state.permissions = perms
return perms
def get_rom_visibility_filter(request: Request) -> RomVisibilityFilter:
"""The caller's ROM visibility; unrestricted when unauthenticated, as there is
no caller to scope it to."""
if not request.user.is_authenticated:
return UNRESTRICTED
return get_permissions(request).rom_visibility
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 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
def is_scoped_admin(request: Request, scope: Scope) -> bool:
"""Whether the caller is an admin whose credential also carries ``scope``."""
return (
getattr(request.user, "role", None) == Role.ADMIN
and scope in request.auth.scopes
)
def assert_admin_for_admin(request: Request, role: str | None, detail: str) -> None:
"""Raise 403 when a non-admin targets or grants the admin role.
``USERS_WRITE`` can be delegated to non-admins, so it alone never reaches admins.
"""
if role == Role.ADMIN and getattr(request.user, "role", None) != Role.ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=detail)
# 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 | RomInstallTarget,
*,
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 not get_rom_visibility_filter(request).allows(rom):
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",
)