mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* chore(coherence): adopt Coherence with specs, invariants and a PR report Install @posthog/coherence as a frontend dev dependency and wire its Claude Code hooks into the committed .claude/settings.json, so every agent session in the repo gets the vocabulary, specs, journal and checks. The hooks call the binary under frontend/ through $CLAUDE_PROJECT_DIR. Declare 23 components and the entrances that carry outside trust, and six invariants, each refuted with a deliberate break before it counted: - every /api route requires auth and its scopes, except a named public list (new route sweep in tests/endpoints/test_route_guards.py) - a hidden rom, platform or firmware answers every id route exactly as a missing id would (new sweep over every method of every id route) - the unscoped save, state and screenshot fetches by id are reached only from their own routers (chokepoints) - validate_path never resolves outside its base folder The PR workflow runs in comment mode: one report comment, failing only when Coherence itself breaks. Trunk skips Prettier and markdownlint on *.spec.md and *.practice.md, since Prettier escapes their globs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(routes): satisfy mypy in the route guard sweep Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): record the worktree test database enactment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(roms): answer a hidden rom like a missing one on file routes; tighten route sweeps Addresses Greptile's review on #5584. The rom file delete and reading-progress routes answered "File not found" for a hidden rom but "Rom with id N not found" for a missing one, so a caller could tell them apart. They now raise the same not-found. The route sweeps now reach the checks they claim to test: a protected route with no scopes counts as public (its guard admits anyone), write requests carry a body and upload name so validation can't answer first, RomFile-keyed routes get a real file id, error bodies are compared with the id normalized, and the rom routes are swept with the rom hidden directly, through its platform, and by the unrated filter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(coherence): tighten route guard sweeps and isolate oracle test databases (code-review) - Count a route as protected only when its endpoint is the scope-checking wrapper with non-empty scopes, not just when it declares the bearer scopes. - Treat 401 and 403 like 422 as never reaching the visibility check, and sweep /api/streaming/states/{rom_id}. - Run pytest oracles with a per-run ROMM_TEST_DB_TAG unless one is set. - Use the shared setup-frontend action and ubuntu-24.04 in the workflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(tests): simplify route guard sweeps and path tests (simplify) - Mark scope-guard wrappers with required_scopes so the auth sweep reads a public attribute instead of the private closure. - Derive the entity regex from one segment list, ask each missing id once, and run the three hide scenarios through one sweep helper. - Fold the new validate_path inputs into the existing valid, traversal and absolute path tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): trim workflow comments (review-polish) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(filesystem): restore the validate_path property test the paths invariant cites Filesystem.spec.md names test_validate_path_never_escapes_its_base as the invariant's evidence, and Coherence selects it by name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): run hooks from the local binary instead of npx Each hook calls frontend/node_modules/.bin/coherence directly and exits 0 when it isn't installed, so sessions without frontend deps (fresh worktrees, backend-only setups, cloud setup still installing) don't report a hook error on every tool call, and no hook pays npx's startup. Also commits the journal and run records left by earlier sessions, which .coherence/.gitignore keeps as durable records. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(tests): share the bearer, user token and hide helpers Tests built the same Authorization headers and HiddenEntity rows in about 40 local copies, and two modules imported private helpers from other test files. They now use bearer, user_headers and hide from tests/auth_helpers.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(endpoints): one 404 for a missing or hidden rom, platform or firmware Each route wrote the missing-row 404 and the hidden-row 404 separately and had to keep them identical by hand. visible_rom_or_404, visible_platform_or_404 and visible_firmware_or_404 take the lookup result and raise one answer for both, either the standard not-found or a bespoke detail. Re-reads after a write keep a plain not-found check, so an edit that hides the row doesn't turn into a 404 after it succeeded. The RomFile-keyed routes (/roms/{file_id}/files, .../files/content/{name}, /roms/{file_id}/patch) name their path parameter file_id instead of id, so the route sweep reads which id a route takes from its path and drops its hand-kept list. URLs are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(setup): develop inside WSL on Windows @posthog/coherence installs only on Linux and macOS, so npm install in frontend/ fails on native Windows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): record the whole-repo chokepoint run Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(types): regenerate API types for the file_id patch route Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
8.9 KiB
Python
240 lines
8.9 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.assets import Save, Screenshot, State
|
|
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 visible_rom_or_404[R: (Rom, RomVisibility, RomVisibilityLabel, RomInstallTarget)](
|
|
request: Request, rom: R | None, not_found: int | str
|
|
) -> R:
|
|
"""`rom` when it exists and the caller sees it, else one 404 for both cases.
|
|
|
|
Args:
|
|
not_found: the rom id for the standard not-found, or a bespoke 404 detail.
|
|
"""
|
|
detail = not_found if isinstance(not_found, str) else None
|
|
if rom is None:
|
|
if isinstance(not_found, str):
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=not_found)
|
|
raise RomNotFoundInDatabaseException(not_found)
|
|
assert_rom_visible(request, rom, not_found_detail=detail)
|
|
return rom
|
|
|
|
|
|
def owned_rom_asset_or_404[A: (Save, State, Screenshot)](
|
|
request: Request, asset: A | None, detail: str
|
|
) -> A:
|
|
"""`asset` when the caller owns it and sees its ROM, else 404 with `detail`.
|
|
A detached asset, whose ROM was deleted, answers like a missing one."""
|
|
if not asset or asset.user_id != request.user.id or asset.rom is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=detail)
|
|
assert_rom_visible(request, asset.rom, not_found_detail=detail)
|
|
return asset
|
|
|
|
|
|
def readable_rom_asset_or_404[A: (Save, State)](
|
|
request: Request, asset: A | None, detail: str
|
|
) -> A:
|
|
"""`asset` when the caller owns it, or it is public and its ROM is visible to
|
|
them, else 404 with `detail`. Another user's detached asset has no ROM to check."""
|
|
if not asset or (
|
|
asset.user_id != request.user.id and (not asset.is_public or asset.rom is None)
|
|
):
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=detail)
|
|
if asset.rom is not None:
|
|
assert_rom_visible(request, asset.rom, not_found_detail=detail)
|
|
return asset
|
|
|
|
|
|
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 visible_platform_or_404(
|
|
request: Request, platform: Platform | None, not_found: int | str
|
|
) -> Platform:
|
|
"""`platform` when it exists and the caller sees it, else one 404 for both cases.
|
|
|
|
Args:
|
|
not_found: the platform id for the standard not-found, or a bespoke 404 detail.
|
|
"""
|
|
detail = not_found if isinstance(not_found, str) else None
|
|
if platform is None:
|
|
if isinstance(not_found, str):
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=not_found)
|
|
raise PlatformNotFoundInDatabaseException(not_found)
|
|
assert_platform_visible(request, platform, not_found_detail=detail)
|
|
return platform
|
|
|
|
|
|
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",
|
|
)
|
|
|
|
|
|
def visible_firmware_or_404(
|
|
request: Request, firmware: Firmware | None, firmware_id: int
|
|
) -> Firmware:
|
|
"""`firmware` when it exists and the caller sees its platform, else one 404."""
|
|
if firmware is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Firmware with ID {firmware_id} not found",
|
|
)
|
|
assert_firmware_visible(request, firmware)
|
|
return firmware
|