mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 18:11:16 +01:00
* fix(backend): make type ignores match what mypy reports Third in the staged series clearing the errors #4655 made visible. Whole-project mypy: 91 errors in 26 files -> 64 in 23. Twenty `# type: ignore[assignment]` comments in endpoints/responses/rom.py never suppressed anything. The request-scoped values `from_orm_with_request` attaches to a Rom (rom_user, has_notes, user_saves and the rest) are not declared on the model, so mypy reports `attr-defined`; it does so under 1.19 as well as 2.3, so the code was wrong when the comments were written rather than drifting since. They now name the error they were meant to silence. Seventy-nine ignores across 24 files suppressed nothing at all under `--warn-unused-ignores`, and are removed. One of them, `utils/zip_cache.py`, keeps its `attr-defined` code for the private `zipfile._get_compressor` and drops only `assignment`. The unused set is identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error count unchanged under both, so none was quietly needed. The two `filter` helpers typed as `[QueryT: Select | Update | Delete]` bound the TypeVar to the union, so `query.filter(...)` returned the union and could not be assigned back to `QueryT`. Constraining it to the three types lets mypy check each one separately, and the callers are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp * fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy does not read them, so the 13 on mypy findings were all still errors to `mypy .` and would fail a whole-project check. Each now has a fix. endpoints/tasks.py: `common_data` was a plain dict literal unpacked into eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not match its keys. It holds exactly the fields of BaseTaskStatusResponse and is now annotated as one, so the unpacking is checked. handler/metadata/gamelist_handler.py: both media maps were inferred as `dict[str, str]`, so indexing the TypedDict with their keys was unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of the TypedDict's fields. A misspelt map key is now an error at the entry; before, only the index site could have noticed, and it was suppressed. handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs guard narrows it to the five lookup attributes, and the frozenset is derived from that Literal so the names live in one place. mypy now checks that each name is a real PlaymatchRomMatch key. It does not check that each takes an int, since mypy is lenient about value types on a union key; that still rests on which five names are listed. endpoints/search.py: the per-source tuples mixed ROM-list and handler types, which mypy joined to `object`. The dict is now annotated with what the loop uses: Mapping rows and the MetadataHandler base. tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an async test (ASYNC240) now goes through `anyio.Path`, as the rest of the codebase already does. Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under 2.3.0 and 2.3.1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp * fix(backend): keep gamelist media keys in one place Review pointed out that `GamelistMediaKey` repeated all fourteen fields of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a TypedDict's keys is a second declaration of them, and a field added to the TypedDict would be left out of it without any error. The three index sites go back to suppressing `literal-required`, now as `# type: ignore[literal-required]` so plain mypy reads it as well as Trunk. The TypedDict stays the only declaration of the key set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
201 lines
6.6 KiB
Python
201 lines
6.6 KiB
Python
"""Per-request permission resolution and the coarse ``oauth_scopes`` projection.
|
||
|
||
This is the authoritative source the auth layer consults. ``resolve_permissions``
|
||
computes a user's effective grants (group ∪ overrides, admin bypass) plus the set
|
||
of entity ids hidden from them; ``compute_oauth_scopes`` projects the grants onto
|
||
the legacy coarse ``Scope`` vocabulary so the existing scope-based enforcement,
|
||
client tokens and OAuth flow keep working unchanged.
|
||
|
||
Precedence: admin bypass > per-user override > group grant > legacy default.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
|
||
from config import KIOSK_MODE
|
||
from decorators.database import begin_session
|
||
from handler.auth.constants import FULL_SCOPES, READ_SCOPES, Scope
|
||
from handler.auth.permissions_map import (
|
||
grants_to_scopes,
|
||
order_scopes,
|
||
)
|
||
from models.permission import PermAction, PermEntity
|
||
from models.user import Role, User
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ResolvedGrant:
|
||
entity: PermEntity
|
||
action: PermAction
|
||
own_only: bool
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ResolvedPermissions:
|
||
is_admin: bool
|
||
user_id: int | None
|
||
grants: frozenset[ResolvedGrant]
|
||
hidden_platform_ids: frozenset[int]
|
||
hidden_rom_ids: frozenset[int]
|
||
|
||
def allows(
|
||
self, entity: PermEntity, action: PermAction, *, owned: bool | None = None
|
||
) -> bool:
|
||
if self.is_admin:
|
||
return True
|
||
for g in self.grants:
|
||
if g.entity != entity or g.action != action:
|
||
continue
|
||
# own_only grants only satisfy a check on an owned resource.
|
||
if g.own_only and owned is not True:
|
||
continue
|
||
return True
|
||
return False
|
||
|
||
def can_see_platform(self, platform_id: int) -> bool:
|
||
return self.is_admin or platform_id not in self.hidden_platform_ids
|
||
|
||
def can_see_rom(self, rom_id: int, platform_id: int) -> bool:
|
||
if self.is_admin:
|
||
return True
|
||
return (
|
||
platform_id not in self.hidden_platform_ids
|
||
and rom_id not in self.hidden_rom_ids
|
||
)
|
||
|
||
|
||
def _effective_group_id(user: User, *, session) -> int | None:
|
||
"""The group a non-admin user follows: their own, else the server default.
|
||
|
||
Used by both the grant map and the hidden-entity lookup so a user with no
|
||
explicit group still inherits the default group's grants AND its hides.
|
||
"""
|
||
|
||
from handler.database import db_permission_handler
|
||
|
||
if user.permission_group_id is not None:
|
||
return user.permission_group_id
|
||
default_group = db_permission_handler.get_default_group(session=session)
|
||
return default_group.id if default_group else None
|
||
|
||
|
||
def _resolve_grant_map(
|
||
user: User, *, session
|
||
) -> dict[tuple[PermEntity, PermAction], bool]:
|
||
"""Effective ``(entity, action) -> own_only`` map for a non-admin user."""
|
||
|
||
from handler.database import db_permission_handler
|
||
|
||
base: dict[tuple[PermEntity, PermAction], bool] = {}
|
||
group_id = _effective_group_id(user, session=session)
|
||
if group_id is not None:
|
||
for g in db_permission_handler.get_group_grants(group_id, session=session):
|
||
base[(g.entity, g.action)] = g.own_only
|
||
|
||
# Per-user overrides win over the group: grant adds, revoke removes.
|
||
# Override identity is (entity, action) only, so a grant override fully
|
||
# replaces the group's own_only for that key rather than merging. Both
|
||
# directions are admin-initiated and the narrowing case fails closed, so
|
||
# this is a granularity limit, not a privilege leak.
|
||
if user.id is not None:
|
||
for ov in db_permission_handler.get_user_overrides(user.id, session=session):
|
||
if ov.granted:
|
||
base[(ov.entity, ov.action)] = ov.own_only
|
||
else:
|
||
base.pop((ov.entity, ov.action), None)
|
||
|
||
return base
|
||
|
||
|
||
def resolve_permissions(
|
||
user: User,
|
||
*,
|
||
session=None,
|
||
) -> ResolvedPermissions:
|
||
# Admins bypass everything -- no DB access needed.
|
||
if user.role == Role.ADMIN:
|
||
return ResolvedPermissions(
|
||
is_admin=True,
|
||
user_id=user.id,
|
||
grants=frozenset(),
|
||
hidden_platform_ids=frozenset(),
|
||
hidden_rom_ids=frozenset(),
|
||
)
|
||
return _resolve_non_admin(user, session=session)
|
||
|
||
|
||
@begin_session
|
||
def _resolve_non_admin(
|
||
user: User,
|
||
*,
|
||
session=None,
|
||
) -> ResolvedPermissions:
|
||
from handler.database import db_permission_handler
|
||
|
||
grant_map = _resolve_grant_map(user, session=session)
|
||
grants = frozenset(
|
||
ResolvedGrant(entity, action, own_only)
|
||
for (entity, action), own_only in grant_map.items()
|
||
)
|
||
# Cap the anonymous visitor at the fine layer too, so a mutating route gated
|
||
# only by `assert_can` (no coarse scope) stays blocked for them.
|
||
if KIOSK_MODE and user.is_kiosk_guest:
|
||
grants = frozenset(g for g in grants if g.action == PermAction.READ)
|
||
|
||
# Resolve the effective group (own or default) so hides assigned to the
|
||
# default group apply to group-less users too, not just their grants.
|
||
group_id = _effective_group_id(user, session=session)
|
||
hidden_platforms = db_permission_handler.get_hidden_entity_ids(
|
||
PermEntity.PLATFORMS, user.id, group_id, session=session
|
||
)
|
||
hidden_roms = db_permission_handler.get_hidden_entity_ids(
|
||
PermEntity.ROMS, user.id, group_id, session=session
|
||
)
|
||
|
||
return ResolvedPermissions(
|
||
is_admin=False,
|
||
user_id=user.id,
|
||
grants=grants,
|
||
hidden_platform_ids=frozenset(hidden_platforms),
|
||
hidden_rom_ids=frozenset(hidden_roms),
|
||
)
|
||
|
||
|
||
def compute_oauth_scopes(
|
||
user: User,
|
||
*,
|
||
session=None,
|
||
) -> list[Scope]:
|
||
"""Project a user's effective grants onto the coarse legacy ``Scope`` set.
|
||
|
||
Admins get the full set; the anonymous ``KIOSK_MODE`` visitor is capped to
|
||
read-only (the public-display lockdown).
|
||
"""
|
||
|
||
# Admins bypass everything -- no DB access needed. Keep the canonical
|
||
# FULL_SCOPES order (same as the non-admin path) to avoid token churn.
|
||
if user.role == Role.ADMIN:
|
||
return order_scopes(FULL_SCOPES)
|
||
return _compute_non_admin_scopes(user, session=session)
|
||
|
||
|
||
@begin_session
|
||
def _compute_non_admin_scopes(
|
||
user: User,
|
||
*,
|
||
session=None,
|
||
) -> list[Scope]:
|
||
grant_map = _resolve_grant_map(user, session=session)
|
||
scopes = set(
|
||
grants_to_scopes(
|
||
(entity, action, own_only)
|
||
for (entity, action), own_only in grant_map.items()
|
||
)
|
||
)
|
||
# Kiosk mode is an anonymous-visitor lockdown, not an account-wide cap: a
|
||
# user someone deliberately logged into keeps the grants they were given.
|
||
if KIOSK_MODE and user.is_kiosk_guest:
|
||
scopes &= set(READ_SCOPES)
|
||
return order_scopes(scopes)
|