mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 18:43:23 +01:00
feat: Implement fine-grained permission checks and admin CRUD for permission groups
- Added new permission handling in `backend/handler/auth/dependencies.py` to support fine-grained, DB-backed permission checks. - Enhanced user role update logic in `backend/endpoints/user.py` to prevent demotion of the last admin. - Introduced `hidden_platform_ids` and `hidden_rom_ids` parameters in various database handlers to manage visibility based on admin settings. - Created new endpoints for managing permission groups, user memberships, and hidden entities in `backend/tests/endpoints/test_permissions_admin.py`. - Added tests for permissions visibility and CRUD operations in `backend/tests/endpoints/test_permissions_visibility.py` and `backend/tests/endpoints/test_permissions_me.py`. - Updated archive handling in `backend/utils/archives.py` to improve error logging and timeout management during extraction.
This commit is contained in:
@@ -8,6 +8,7 @@ from decorators.auth import protected_route
|
||||
from endpoints.responses import BulkOperationResponse
|
||||
from endpoints.responses.firmware import AddFirmwareResponse, FirmwareSchema
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_can, get_permissions
|
||||
from handler.database import db_firmware_handler, db_platform_handler
|
||||
from handler.filesystem import fs_firmware_handler
|
||||
from handler.scan_handler import scan_firmware
|
||||
@@ -15,6 +16,7 @@ from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.firmware import Firmware
|
||||
from models.permission import PermAction, PermEntity
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
@@ -119,9 +121,13 @@ def get_platform_firmware(
|
||||
Returns:
|
||||
list[FirmwareSchema]: Firmware stored in the database
|
||||
"""
|
||||
perms = get_permissions(request)
|
||||
return [
|
||||
FirmwareSchema.model_validate(f)
|
||||
for f in db_firmware_handler.list_firmware(platform_id=platform_id)
|
||||
for f in db_firmware_handler.list_firmware(
|
||||
platform_id=platform_id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@@ -137,8 +143,10 @@ def get_firmware_identifiers(
|
||||
Returns:
|
||||
list[int]: List of firmware IDs
|
||||
"""
|
||||
perms = get_permissions(request)
|
||||
firmware = db_firmware_handler.list_firmware(
|
||||
only_fields=[Firmware.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
return [f.id for f in firmware]
|
||||
|
||||
@@ -164,6 +172,15 @@ def get_firmware(request: Request, id: int) -> FirmwareSchema:
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
# Firmware inherits its platform's visibility; 404-mask when hidden.
|
||||
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 {id} not found",
|
||||
)
|
||||
|
||||
return FirmwareSchema.model_validate(firmware)
|
||||
|
||||
|
||||
@@ -190,6 +207,15 @@ def head_firmware_content(request: Request, id: int, file_name: str):
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
# Firmware inherits its platform's visibility; 404-mask when hidden.
|
||||
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 {id} not found",
|
||||
)
|
||||
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(
|
||||
@@ -228,6 +254,15 @@ def get_firmware_content(
|
||||
log.error(error)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
||||
|
||||
# Firmware inherits its platform's visibility; 404-mask when hidden.
|
||||
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 {id} not found",
|
||||
)
|
||||
|
||||
firmware_path = fs_firmware_handler.validate_path(firmware.full_path)
|
||||
|
||||
return FileResponse(path=firmware_path, filename=firmware.file_name)
|
||||
@@ -254,6 +289,8 @@ async def delete_firmware(
|
||||
) -> BulkOperationResponse:
|
||||
"""Delete firmware."""
|
||||
|
||||
assert_can(get_permissions(request), PermEntity.FIRMWARE, PermAction.DELETE)
|
||||
|
||||
successful_items = 0
|
||||
failed_items = 0
|
||||
errors = []
|
||||
|
||||
293
backend/endpoints/permissions.py
Normal file
293
backend/endpoints/permissions.py
Normal file
@@ -0,0 +1,293 @@
|
||||
from typing import Annotated
|
||||
|
||||
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.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_admin, get_permissions
|
||||
from handler.database import db_permission_handler, db_user_handler
|
||||
from handler.socket_handler import socket_handler
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity, PermissionGroup
|
||||
from utils.router import APIRouter
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/permissions",
|
||||
tags=["permissions"],
|
||||
)
|
||||
|
||||
|
||||
async def emit_permissions_changed(user_id: int) -> None:
|
||||
"""Notify clients that `user_id`'s 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 or hidden entities.
|
||||
"""
|
||||
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}")
|
||||
|
||||
|
||||
@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])
|
||||
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))
|
||||
|
||||
|
||||
# --- 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,
|
||||
is_system=group.is_system,
|
||||
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)),
|
||||
)
|
||||
|
||||
|
||||
@protected_route(router.get, "/groups", [Scope.USERS_READ])
|
||||
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
|
||||
)
|
||||
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,
|
||||
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
|
||||
)
|
||||
return _group_schema(group)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.put,
|
||||
"/groups/{id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
async def update_permission_group(
|
||||
request: Request, id: int, body: PermissionGroupUpdate
|
||||
) -> PermissionGroupSchema:
|
||||
"""Update a permission group (name/description/default/grants)."""
|
||||
assert_admin(request)
|
||||
if db_permission_handler.get_group(id) is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
||||
|
||||
updated = db_permission_handler.update_group(
|
||||
id,
|
||||
name=body.name,
|
||||
description=body.description,
|
||||
is_default=body.is_default,
|
||||
grants=(
|
||||
[(g.entity, g.action, g.own_only) for g in body.grants]
|
||||
if body.grants is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
# Grant changes alter every member's effective permissions.
|
||||
for member_id in db_permission_handler.get_group_member_ids(id):
|
||||
await emit_permissions_changed(member_id)
|
||||
return _group_schema(updated) # type: ignore[arg-type]
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.delete,
|
||||
"/groups/{id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
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)
|
||||
for member_id in member_ids:
|
||||
await emit_permissions_changed(member_id)
|
||||
|
||||
|
||||
# --- Admin: per-user assignment ----------------------------------------------
|
||||
|
||||
|
||||
def _user_permissions(
|
||||
user_id: int, permission_group_id: int | 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=permission_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
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.get,
|
||||
"/users/{user_id}",
|
||||
[Scope.USERS_READ],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
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, user.permission_group_id)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.put,
|
||||
"/users/{user_id}",
|
||||
[Scope.USERS_WRITE],
|
||||
responses={status.HTTP_404_NOT_FOUND: {}},
|
||||
)
|
||||
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],
|
||||
)
|
||||
|
||||
await emit_permissions_changed(user_id)
|
||||
return _user_permissions(user_id, group_id)
|
||||
|
||||
|
||||
# --- Admin: hidden entities ---------------------------------------------------
|
||||
|
||||
|
||||
@protected_route(router.post, "/hidden", [Scope.USERS_WRITE])
|
||||
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",
|
||||
)
|
||||
|
||||
db_permission_handler.add_hidden_entity(
|
||||
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_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,
|
||||
)
|
||||
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)] = None,
|
||||
group_id: Annotated[int | None, Body(embed=True)] = 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
|
||||
)
|
||||
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:
|
||||
for member_id in db_permission_handler.get_group_member_ids(group_id):
|
||||
await emit_permissions_changed(member_id)
|
||||
@@ -10,12 +10,14 @@ from endpoints.responses.platform import PlatformSchema
|
||||
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_can, get_permissions
|
||||
from handler.database import db_platform_handler
|
||||
from handler.filesystem import fs_platform_handler
|
||||
from handler.scan_handler import scan_platform
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.platform import Platform
|
||||
from utils.platforms import get_supported_platforms
|
||||
from utils.router import APIRouter
|
||||
@@ -61,9 +63,13 @@ def get_platforms(
|
||||
) -> list[PlatformSchema]:
|
||||
"""Retrieve platforms."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
return [
|
||||
PlatformSchema.model_validate(p)
|
||||
for p in db_platform_handler.get_platforms(updated_after=updated_after)
|
||||
for p in db_platform_handler.get_platforms(
|
||||
updated_after=updated_after,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@@ -73,8 +79,10 @@ def get_platform_identifiers(
|
||||
) -> list[int]:
|
||||
"""Retrieve platform identifiers."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
platforms = db_platform_handler.get_platforms(
|
||||
only_fields=[Platform.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
)
|
||||
return [p.id for p in platforms]
|
||||
|
||||
@@ -98,8 +106,10 @@ def get_platform(
|
||||
) -> PlatformSchema:
|
||||
"""Retrieve a platform by ID."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
if not platform:
|
||||
# 404-mask hidden platforms so their existence isn't leaked.
|
||||
if not platform or not perms.can_see_platform(id):
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
return PlatformSchema.model_validate(platform)
|
||||
|
||||
@@ -142,9 +152,11 @@ async def delete_platform(
|
||||
) -> None:
|
||||
"""Delete a platform by ID."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
platform = db_platform_handler.get_platform(id)
|
||||
if not platform:
|
||||
if not platform or not perms.can_see_platform(id):
|
||||
raise PlatformNotFoundInDatabaseException(id)
|
||||
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
|
||||
|
||||
log.info(
|
||||
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
|
||||
|
||||
226
backend/endpoints/responses/permission.py
Normal file
226
backend/endpoints/responses/permission.py
Normal file
@@ -0,0 +1,226 @@
|
||||
"""Response schemas for `/permissions/me`.
|
||||
|
||||
`ActionKey` is the canonical, UI-facing action vocabulary (mirrors the v2
|
||||
`useCan` actions). Exposing it here puts it in the OpenAPI schema so the frontend
|
||||
generates the enum and can delete its hand-authored `actions.ts` / `role-map.ts`.
|
||||
|
||||
The grants returned reflect what the BACKEND actually enforces (the source of
|
||||
truth), resolved from the user's groups + overrides. All scopes are global in
|
||||
this phase; per-resource scoping is reserved for later.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from handler.auth.permissions import ResolvedPermissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
|
||||
class ActionKey(enum.StrEnum):
|
||||
# ROMs
|
||||
ROM_VIEW = "rom.view"
|
||||
ROM_PLAY = "rom.play"
|
||||
ROM_DOWNLOAD = "rom.download"
|
||||
ROM_UPLOAD = "rom.upload"
|
||||
ROM_EDIT = "rom.edit"
|
||||
ROM_DELETE = "rom.delete"
|
||||
ROM_MATCH = "rom.match"
|
||||
ROM_REFRESH = "rom.refresh"
|
||||
ROM_FAVORITE = "rom.favorite"
|
||||
# Platforms
|
||||
PLATFORM_VIEW = "platform.view"
|
||||
PLATFORM_CREATE = "platform.create"
|
||||
PLATFORM_EDIT = "platform.edit"
|
||||
PLATFORM_DELETE = "platform.delete"
|
||||
# Collections
|
||||
COLLECTION_VIEW = "collection.view"
|
||||
COLLECTION_CREATE = "collection.create"
|
||||
COLLECTION_EDIT = "collection.edit"
|
||||
COLLECTION_DELETE = "collection.delete"
|
||||
# Library
|
||||
LIBRARY_SCAN = "library.scan"
|
||||
# Users
|
||||
USER_VIEW = "user.view"
|
||||
USER_CREATE = "user.create"
|
||||
USER_EDIT = "user.edit"
|
||||
USER_DELETE = "user.delete"
|
||||
# App-wide "is admin" hatch.
|
||||
APP_ADMIN = "app.admin"
|
||||
|
||||
|
||||
# (entity, action) a user holds -> the UI action keys it unlocks. One backend
|
||||
# grant fans out to several UI actions. Kept faithful to backend enforcement:
|
||||
# e.g. platform create/delete and rom delete gate on the platform/rom write or
|
||||
# delete grants the legacy editor already held.
|
||||
_ENTITY_ACTION_KEYS: dict[tuple[PermEntity, PermAction], tuple[ActionKey, ...]] = {
|
||||
(PermEntity.ROMS, PermAction.READ): (
|
||||
ActionKey.ROM_VIEW,
|
||||
ActionKey.ROM_PLAY,
|
||||
ActionKey.ROM_DOWNLOAD,
|
||||
ActionKey.ROM_FAVORITE,
|
||||
),
|
||||
(PermEntity.ROMS, PermAction.WRITE): (
|
||||
ActionKey.ROM_UPLOAD,
|
||||
ActionKey.ROM_EDIT,
|
||||
ActionKey.ROM_MATCH,
|
||||
ActionKey.ROM_REFRESH,
|
||||
),
|
||||
(PermEntity.ROMS, PermAction.DELETE): (ActionKey.ROM_DELETE,),
|
||||
(PermEntity.PLATFORMS, PermAction.READ): (ActionKey.PLATFORM_VIEW,),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE): (
|
||||
ActionKey.PLATFORM_CREATE,
|
||||
ActionKey.PLATFORM_EDIT,
|
||||
ActionKey.LIBRARY_SCAN,
|
||||
),
|
||||
(PermEntity.PLATFORMS, PermAction.DELETE): (ActionKey.PLATFORM_DELETE,),
|
||||
(PermEntity.COLLECTIONS, PermAction.READ): (ActionKey.COLLECTION_VIEW,),
|
||||
(PermEntity.COLLECTIONS, PermAction.WRITE): (
|
||||
ActionKey.COLLECTION_CREATE,
|
||||
ActionKey.COLLECTION_EDIT,
|
||||
),
|
||||
(PermEntity.COLLECTIONS, PermAction.DELETE): (ActionKey.COLLECTION_DELETE,),
|
||||
(PermEntity.USERS, PermAction.READ): (ActionKey.USER_VIEW,),
|
||||
(PermEntity.USERS, PermAction.WRITE): (
|
||||
ActionKey.USER_CREATE,
|
||||
ActionKey.USER_EDIT,
|
||||
ActionKey.USER_DELETE,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class PermissionScopeSchema(BaseModel):
|
||||
kind: Literal["global", "platform", "collection", "rom"] = "global"
|
||||
id: int | None = None
|
||||
|
||||
|
||||
class GrantSchema(BaseModel):
|
||||
action: ActionKey
|
||||
scope: PermissionScopeSchema
|
||||
|
||||
|
||||
class HiddenEntitiesSchema(BaseModel):
|
||||
platforms: list[int]
|
||||
roms: list[int]
|
||||
|
||||
|
||||
class PermissionsResponse(BaseModel):
|
||||
is_admin: bool
|
||||
grants: list[GrantSchema]
|
||||
hidden: HiddenEntitiesSchema
|
||||
|
||||
@classmethod
|
||||
def from_resolved(cls, perms: ResolvedPermissions) -> PermissionsResponse:
|
||||
keys = action_keys_for(perms)
|
||||
return cls(
|
||||
is_admin=perms.is_admin,
|
||||
grants=[
|
||||
GrantSchema(action=k, scope=PermissionScopeSchema(kind="global"))
|
||||
for k in keys
|
||||
],
|
||||
hidden=HiddenEntitiesSchema(
|
||||
platforms=sorted(perms.hidden_platform_ids),
|
||||
roms=sorted(perms.hidden_rom_ids),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def action_keys_for(perms: ResolvedPermissions) -> list[ActionKey]:
|
||||
"""The UI action keys a user can perform, in enum order.
|
||||
|
||||
Admins unlock everything (the frontend also short-circuits on `is_admin`).
|
||||
Otherwise each held grant fans out to its UI actions; `owned=True` makes
|
||||
own-only grants (e.g. manage own collections) count as "can do this action".
|
||||
"""
|
||||
if perms.is_admin:
|
||||
return list(ActionKey)
|
||||
|
||||
keys: set[ActionKey] = set()
|
||||
for (entity, action), action_keys in _ENTITY_ACTION_KEYS.items():
|
||||
if perms.allows(entity, action, owned=True):
|
||||
keys.update(action_keys)
|
||||
return [k for k in ActionKey if k in keys]
|
||||
|
||||
|
||||
# --- Admin CRUD schemas -------------------------------------------------------
|
||||
|
||||
|
||||
class GrantSchemaIO(BaseModel):
|
||||
"""A single (entity, action) grant on a group, with the own-only flag."""
|
||||
|
||||
entity: PermEntity
|
||||
action: PermAction
|
||||
own_only: bool = False
|
||||
|
||||
|
||||
class PermissionGroupSchema(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: str
|
||||
is_default: bool
|
||||
is_system: bool
|
||||
grants: list[GrantSchemaIO]
|
||||
member_count: int
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class PermissionGroupCreate(BaseModel):
|
||||
name: str
|
||||
description: str = ""
|
||||
is_default: bool = False
|
||||
grants: list[GrantSchemaIO] = []
|
||||
|
||||
|
||||
class PermissionGroupUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
is_default: bool | None = None
|
||||
grants: list[GrantSchemaIO] | None = None
|
||||
|
||||
|
||||
class OverrideSchemaIO(BaseModel):
|
||||
entity: PermEntity
|
||||
action: PermAction
|
||||
granted: bool
|
||||
own_only: bool = False
|
||||
|
||||
|
||||
class HiddenEntitySchema(BaseModel):
|
||||
entity: PermEntity
|
||||
entity_id: int
|
||||
|
||||
|
||||
class HiddenEntityCreate(BaseModel):
|
||||
entity: PermEntity
|
||||
entity_id: int
|
||||
# Exactly one principal must be set (validated by the endpoint).
|
||||
user_id: int | None = None
|
||||
group_id: int | None = None
|
||||
|
||||
|
||||
class UserPermissionsSchema(BaseModel):
|
||||
"""Admin view of one user's permission assignment."""
|
||||
|
||||
user_id: int
|
||||
permission_group_id: int | None
|
||||
overrides: list[OverrideSchemaIO]
|
||||
hidden: list[HiddenEntitySchema]
|
||||
|
||||
|
||||
class UserPermissionsUpdate(BaseModel):
|
||||
# `permission_group_id` is a tri-state: omit to leave unchanged, null to
|
||||
# clear (fall back to default group), an id to assign.
|
||||
permission_group_id: int | None = None
|
||||
set_group: bool = False
|
||||
overrides: list[OverrideSchemaIO] | None = None
|
||||
|
||||
|
||||
class PermissionCatalogSchema(BaseModel):
|
||||
"""The vocabulary the admin UI renders the group/override matrix from."""
|
||||
|
||||
entities: list[PermEntity]
|
||||
actions: list[PermAction]
|
||||
@@ -46,6 +46,7 @@ from endpoints.responses.rom import (
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from exceptions.fs_exceptions import RomAlreadyExistsException
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_can, get_permissions
|
||||
from handler.database import db_rom_handler, db_save_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from handler.filesystem import fs_resource_handler, fs_rom_handler
|
||||
@@ -63,6 +64,7 @@ from handler.metadata.ss_handler import add_ss_auth_to_url, get_preferred_media_
|
||||
from logger.formatter import BLUE
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.permission import PermAction, PermEntity
|
||||
from models.rom import Rom, RomUserStatus, compute_name_sort_key
|
||||
from utils.background_tasks import fire_and_forget
|
||||
from utils.database import safe_int, safe_str_to_bool
|
||||
@@ -502,6 +504,8 @@ def get_roms(
|
||||
] = False,
|
||||
) -> CustomLimitOffsetPage[SimpleRomSchema]:
|
||||
"""Retrieve roms."""
|
||||
perms = get_permissions(request)
|
||||
|
||||
unfiltered_query, order_by_attr = db_rom_handler.get_roms_query(
|
||||
user_id=request.user.id,
|
||||
order_by=order_by.lower(),
|
||||
@@ -513,6 +517,8 @@ def get_roms(
|
||||
query = db_rom_handler.filter_roms(
|
||||
query=unfiltered_query,
|
||||
user_id=request.user.id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
platform_ids=platform_ids,
|
||||
collection_id=collection_id,
|
||||
virtual_collection_id=virtual_collection_id,
|
||||
@@ -597,6 +603,8 @@ def get_roms(
|
||||
filter_query = db_rom_handler.filter_roms(
|
||||
query=unfiltered_query,
|
||||
user_id=request.user.id,
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
platform_ids=platform_ids,
|
||||
collection_id=collection_id,
|
||||
virtual_collection_id=virtual_collection_id,
|
||||
@@ -678,9 +686,12 @@ def get_rom_identifiers(
|
||||
request: Request,
|
||||
) -> list[int]:
|
||||
"""Retrieve rom identifiers."""
|
||||
perms = get_permissions(request)
|
||||
db_roms = db_rom_handler.get_roms_scalar(
|
||||
user_id=request.user.id,
|
||||
only_fields=[Rom.id],
|
||||
hidden_platform_ids=perms.hidden_platform_ids,
|
||||
hidden_rom_ids=perms.hidden_rom_ids,
|
||||
)
|
||||
|
||||
return [r.id for r in db_roms]
|
||||
@@ -735,6 +746,13 @@ async def download_roms(
|
||||
|
||||
rom_objects = db_rom_handler.get_roms_by_ids(rom_id_list)
|
||||
|
||||
# Drop roms hidden from the caller so they can't be pulled by direct id.
|
||||
if request.user.is_authenticated:
|
||||
perms = get_permissions(request)
|
||||
rom_objects = [
|
||||
rom for rom in rom_objects if perms.can_see_rom(rom.id, rom.platform_id)
|
||||
]
|
||||
|
||||
if not rom_objects:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
@@ -918,6 +936,12 @@ def get_rom_simple(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
# 404-mask roms hidden from the caller (skip when unauthenticated download).
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
return SimpleRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -938,6 +962,12 @@ def get_rom(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
# 404-mask roms hidden from the caller (skip when unauthenticated download).
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
return DetailedRomSchema.from_orm_with_request(rom, request)
|
||||
|
||||
|
||||
@@ -965,6 +995,11 @@ async def head_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
files = rom.files
|
||||
if file_ids:
|
||||
file_id_values = {int(f.strip()) for f in file_ids.split(",") if f.strip()}
|
||||
@@ -1045,6 +1080,11 @@ async def get_rom_content(
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
if request.user.is_authenticated and not get_permissions(request).can_see_rom(
|
||||
rom.id, rom.platform_id
|
||||
):
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
# https://muos.dev/help/addcontent#what-about-multi-disc-content
|
||||
hidden_folder = safe_str_to_bool(request.query_params.get("hidden_folder", ""))
|
||||
|
||||
@@ -1616,6 +1656,9 @@ async def delete_roms(
|
||||
) -> BulkOperationResponse:
|
||||
"""Delete roms."""
|
||||
|
||||
perms = get_permissions(request)
|
||||
assert_can(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
|
||||
successful_items = 0
|
||||
failed_items = 0
|
||||
errors = []
|
||||
@@ -1623,7 +1666,8 @@ async def delete_roms(
|
||||
for id in roms:
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
|
||||
if not rom:
|
||||
# Hidden roms are masked as not-found rather than reported deletable.
|
||||
if not rom or not perms.can_see_rom(rom.id, rom.platform_id):
|
||||
failed_items += 1
|
||||
errors.append(f"ROM with ID {id} not found")
|
||||
continue
|
||||
|
||||
@@ -7,6 +7,7 @@ from fastapi import Request, status
|
||||
|
||||
from decorators.auth import protected_route
|
||||
from endpoints.forms.identity import UserForm
|
||||
from endpoints.permissions import emit_permissions_changed
|
||||
from endpoints.responses.identity import InviteLinkSchema, UserSchema
|
||||
from handler.auth import auth_handler
|
||||
from handler.auth.constants import Scope
|
||||
@@ -359,7 +360,18 @@ async def update_user(
|
||||
|
||||
# You can't change your own role
|
||||
if form_data.role and request.user.id != id:
|
||||
cleaned_data["role"] = Role[form_data.role.upper()] # type: ignore[assignment]
|
||||
new_role = Role[form_data.role.upper()]
|
||||
# You can't demote the last admin (mirrors the delete guard).
|
||||
if (
|
||||
db_user.role == Role.ADMIN
|
||||
and new_role != Role.ADMIN
|
||||
and len(db_user_handler.get_admin_users()) == 1
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="You cannot demote the last admin user",
|
||||
)
|
||||
cleaned_data["role"] = new_role # type: ignore[assignment]
|
||||
|
||||
# You can't disable yourself
|
||||
if form_data.enabled is not None and request.user.id != id:
|
||||
@@ -402,6 +414,10 @@ async def update_user(
|
||||
if cleaned_data:
|
||||
db_user_handler.update_user(id, cleaned_data)
|
||||
|
||||
# A role change alters the user's effective permissions; tell their UI.
|
||||
if "role" in cleaned_data:
|
||||
await emit_permissions_changed(id)
|
||||
|
||||
# Log out the current user if username or password changed
|
||||
creds_updated = cleaned_data.get("username") or cleaned_data.get(
|
||||
"hashed_password"
|
||||
|
||||
88
backend/handler/auth/dependencies.py
Normal file
88
backend/handler/auth/dependencies.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""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 fastapi import HTTPException, Request, status
|
||||
|
||||
from handler.auth.permissions import ResolvedPermissions, resolve_permissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
|
||||
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
|
||||
@@ -33,6 +33,7 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
*,
|
||||
platform_id: int | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Firmware]:
|
||||
query = select(Firmware).order_by(Firmware.file_name.asc())
|
||||
@@ -40,6 +41,11 @@ class DBFirmwareHandler(DBBaseHandler):
|
||||
if platform_id:
|
||||
query = query.filter_by(platform_id=platform_id)
|
||||
|
||||
# Firmware inherits its platform's visibility: hide firmware whose
|
||||
# platform an admin has hidden from the caller.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Firmware.platform_id.not_in(hidden_platform_ids))
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
|
||||
@@ -1,26 +1,34 @@
|
||||
from collections.abc import Sequence
|
||||
from collections.abc import Iterable, Sequence
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy import and_, delete, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.permission import (
|
||||
HiddenEntity,
|
||||
PermAction,
|
||||
PermEntity,
|
||||
PermissionGroup,
|
||||
PermissionGroupGrant,
|
||||
UserPermissionOverride,
|
||||
)
|
||||
from models.user import User
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
|
||||
# (entity, action, own_only)
|
||||
GrantTuple = tuple[PermEntity, PermAction, bool]
|
||||
# (entity, action, granted, own_only)
|
||||
OverrideTuple = tuple[PermEntity, PermAction, bool, bool]
|
||||
|
||||
|
||||
class DBPermissionsHandler(DBBaseHandler):
|
||||
"""Read access to the granular permission model used by the resolver.
|
||||
"""Read and admin-write access to the granular permission model.
|
||||
|
||||
Write/CRUD for the admin UI lands in a later PR; this handler only exposes
|
||||
what ``handler/auth/permissions.py`` needs to resolve a user's effective
|
||||
permissions per request.
|
||||
The read helpers (`get_default_group`, `get_group_grants`,
|
||||
`get_user_overrides`, `get_hidden_entity_ids`) feed the per-request resolver;
|
||||
the rest is the admin CRUD surface for managing groups, memberships,
|
||||
overrides and hidden entities.
|
||||
"""
|
||||
|
||||
@begin_session
|
||||
@@ -79,3 +87,231 @@ class DBPermissionsHandler(DBBaseHandler):
|
||||
)
|
||||
).all()
|
||||
return set(rows)
|
||||
|
||||
# --- Admin CRUD: groups ---------------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_groups(
|
||||
self,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[PermissionGroup]:
|
||||
return (
|
||||
session.scalars(select(PermissionGroup).order_by(PermissionGroup.name))
|
||||
.unique()
|
||||
.all()
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_group(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
return session.get(PermissionGroup, group_id)
|
||||
|
||||
@begin_session
|
||||
def get_group_by_name(
|
||||
self,
|
||||
name: str,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
return session.scalar(select(PermissionGroup).filter_by(name=name).limit(1))
|
||||
|
||||
@begin_session
|
||||
def create_group(
|
||||
self,
|
||||
name: str,
|
||||
description: str = "",
|
||||
is_default: bool = False,
|
||||
grants: Iterable[GrantTuple] = (),
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup:
|
||||
group = PermissionGroup(
|
||||
name=name, description=description, is_default=is_default, is_system=False
|
||||
)
|
||||
session.add(group)
|
||||
session.flush()
|
||||
self._replace_group_grants(group.id, grants, session=session)
|
||||
if is_default:
|
||||
self._clear_other_defaults(group.id, session=session)
|
||||
session.refresh(group)
|
||||
return group
|
||||
|
||||
@begin_session
|
||||
def update_group(
|
||||
self,
|
||||
group_id: int,
|
||||
*,
|
||||
name: str | None = None,
|
||||
description: str | None = None,
|
||||
is_default: bool | None = None,
|
||||
grants: Iterable[GrantTuple] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> PermissionGroup | None:
|
||||
group = session.get(PermissionGroup, group_id)
|
||||
if group is None:
|
||||
return None
|
||||
if name is not None:
|
||||
group.name = name
|
||||
if description is not None:
|
||||
group.description = description
|
||||
if is_default is not None:
|
||||
group.is_default = is_default
|
||||
if is_default:
|
||||
self._clear_other_defaults(group_id, session=session)
|
||||
if grants is not None:
|
||||
self._replace_group_grants(group_id, grants, session=session)
|
||||
session.flush()
|
||||
session.refresh(group)
|
||||
return group
|
||||
|
||||
@begin_session
|
||||
def delete_group(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(delete(PermissionGroup).where(PermissionGroup.id == group_id))
|
||||
|
||||
def _replace_group_grants(
|
||||
self, group_id: int, grants: Iterable[GrantTuple], *, session: Session
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(PermissionGroupGrant).where(
|
||||
PermissionGroupGrant.group_id == group_id
|
||||
)
|
||||
)
|
||||
for entity, action, own_only in grants:
|
||||
session.add(
|
||||
PermissionGroupGrant(
|
||||
group_id=group_id, entity=entity, action=action, own_only=own_only
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
|
||||
def _clear_other_defaults(self, keep_id: int, *, session: Session) -> None:
|
||||
session.execute(
|
||||
update(PermissionGroup)
|
||||
.where(PermissionGroup.id != keep_id, PermissionGroup.is_default.is_(True))
|
||||
.values(is_default=False)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def get_group_member_ids(
|
||||
self,
|
||||
group_id: int,
|
||||
session: Session = None, # type: ignore
|
||||
) -> list[int]:
|
||||
return list(
|
||||
session.scalars(
|
||||
select(User.id).where(User.permission_group_id == group_id)
|
||||
).all()
|
||||
)
|
||||
|
||||
# --- Admin CRUD: user membership + overrides ------------------------------
|
||||
|
||||
@begin_session
|
||||
def set_user_group(
|
||||
self,
|
||||
user_id: int,
|
||||
group_id: int | None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
update(User)
|
||||
.where(User.id == user_id)
|
||||
.values(permission_group_id=group_id)
|
||||
.execution_options(synchronize_session="evaluate")
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def replace_user_overrides(
|
||||
self,
|
||||
user_id: int,
|
||||
overrides: Iterable[OverrideTuple],
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(UserPermissionOverride).where(
|
||||
UserPermissionOverride.user_id == user_id
|
||||
)
|
||||
)
|
||||
for entity, action, granted, own_only in overrides:
|
||||
session.add(
|
||||
UserPermissionOverride(
|
||||
user_id=user_id,
|
||||
entity=entity,
|
||||
action=action,
|
||||
granted=granted,
|
||||
own_only=own_only,
|
||||
)
|
||||
)
|
||||
|
||||
# --- Admin CRUD: hidden entities ------------------------------------------
|
||||
|
||||
@begin_session
|
||||
def get_hidden_entities(
|
||||
self,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[HiddenEntity]:
|
||||
query = select(HiddenEntity)
|
||||
if user_id is not None:
|
||||
query = query.filter_by(user_id=user_id)
|
||||
if group_id is not None:
|
||||
query = query.filter_by(group_id=group_id)
|
||||
return session.scalars(query).all()
|
||||
|
||||
@begin_session
|
||||
def add_hidden_entity(
|
||||
self,
|
||||
entity: PermEntity,
|
||||
entity_id: int,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
# Idempotent: a repeated hide is a no-op rather than a unique violation.
|
||||
existing = session.scalar(
|
||||
select(HiddenEntity)
|
||||
.filter_by(
|
||||
entity=entity,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
group_id=group_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
if existing is None:
|
||||
session.add(
|
||||
HiddenEntity(
|
||||
entity=entity,
|
||||
entity_id=entity_id,
|
||||
user_id=user_id,
|
||||
group_id=group_id,
|
||||
)
|
||||
)
|
||||
|
||||
@begin_session
|
||||
def remove_hidden_entity(
|
||||
self,
|
||||
entity: PermEntity,
|
||||
entity_id: int,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
group_id: int | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> None:
|
||||
session.execute(
|
||||
delete(HiddenEntity).where(
|
||||
and_(
|
||||
HiddenEntity.entity == entity,
|
||||
HiddenEntity.entity_id == entity_id,
|
||||
HiddenEntity.user_id == user_id,
|
||||
HiddenEntity.group_id == group_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -68,12 +68,18 @@ class DBPlatformsHandler(DBBaseHandler):
|
||||
self,
|
||||
updated_after: datetime | None = None,
|
||||
only_fields: Sequence[QueryableAttribute] | None = None,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Platform]:
|
||||
if updated_after:
|
||||
query = query.filter(Platform.updated_at > updated_after)
|
||||
|
||||
# Admin-driven visibility (opt-out): exclude platforms hidden from the
|
||||
# caller. Empty/None (e.g. admins) skips filtering.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Platform.id.not_in(hidden_platform_ids))
|
||||
|
||||
if only_fields:
|
||||
query = query.options(load_only(*only_fields))
|
||||
|
||||
|
||||
@@ -741,6 +741,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
updated_after: datetime | None = None,
|
||||
include_file_stats: bool = False,
|
||||
include_files: bool = False,
|
||||
hidden_platform_ids: Sequence[int] | None = None,
|
||||
hidden_rom_ids: Sequence[int] | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Query[Rom]:
|
||||
from handler.scan_handler import MetadataSource
|
||||
@@ -979,6 +981,14 @@ class DBRomsHandler(DBBaseHandler):
|
||||
or_(RomUser.hidden.is_(False), RomUser.hidden.is_(None))
|
||||
)
|
||||
|
||||
# Admin-driven visibility (opt-out): hide platforms/roms an admin has
|
||||
# hidden from this user/group. Orthogonal to the personal RomUser.hidden
|
||||
# toggle above. Empty sets (e.g. admins) skip filtering entirely.
|
||||
if hidden_platform_ids:
|
||||
query = query.filter(Rom.platform_id.not_in(hidden_platform_ids))
|
||||
if hidden_rom_ids:
|
||||
query = query.filter(Rom.id.not_in(hidden_rom_ids))
|
||||
|
||||
return query
|
||||
|
||||
@begin_session
|
||||
@@ -1096,6 +1106,8 @@ class DBRomsHandler(DBBaseHandler):
|
||||
user_id=kwargs.get("user_id", None),
|
||||
group_by_meta_id=kwargs.get("group_by_meta_id", False),
|
||||
include_files=kwargs.get("include_files", False),
|
||||
hidden_platform_ids=kwargs.get("hidden_platform_ids", None),
|
||||
hidden_rom_ids=kwargs.get("hidden_rom_ids", None),
|
||||
)
|
||||
return session.scalars(roms).all()
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ from endpoints.firmware import router as firmware_router
|
||||
from endpoints.heartbeat import router as heartbeat_router
|
||||
from endpoints.logs import router as logs_router
|
||||
from endpoints.netplay import router as netplay_router
|
||||
from endpoints.permissions import router as permissions_router
|
||||
from endpoints.platform import router as platform_router
|
||||
from endpoints.play_sessions import router as play_sessions_router
|
||||
from endpoints.raw import router as raw_router
|
||||
@@ -173,6 +174,7 @@ app.include_router(firmware_router, prefix="/api")
|
||||
app.include_router(collections_router, prefix="/api")
|
||||
app.include_router(export_router, prefix="/api")
|
||||
app.include_router(netplay_router, prefix="/api")
|
||||
app.include_router(permissions_router, prefix="/api")
|
||||
|
||||
app.mount("/ws", socket_handler.socket_app)
|
||||
app.mount("/netplay", netplay_socket_handler.socket_app)
|
||||
|
||||
194
backend/tests/endpoints/test_permissions_admin.py
Normal file
194
backend/tests/endpoints/test_permissions_admin.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Admin CRUD for groups, memberships, overrides and hidden entities, and the
|
||||
end-to-end effect on a member's /permissions/me."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_user_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import PermissionGroup
|
||||
|
||||
|
||||
def _bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _fresh_user_auth(user_id):
|
||||
# Mint a token from the user's CURRENT (post-change) projected scopes.
|
||||
user = db_user_handler.get_user(user_id)
|
||||
return _bearer(
|
||||
oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": " ".join(user.oauth_scopes),
|
||||
},
|
||||
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _me_actions(client, user_id):
|
||||
body = client.get("/api/permissions/me", headers=_fresh_user_auth(user_id)).json()
|
||||
return {g["action"] for g in body["grants"]}, body
|
||||
|
||||
|
||||
def _cleanup():
|
||||
with sync_session.begin() as s:
|
||||
s.query(PermissionGroup).filter(PermissionGroup.is_system.is_(False)).delete(
|
||||
synchronize_session="evaluate"
|
||||
)
|
||||
|
||||
|
||||
def test_non_admin_forbidden(client, viewer_access_token):
|
||||
h = _bearer(viewer_access_token)
|
||||
assert client.get("/api/permissions/groups", headers=h).status_code == 403
|
||||
assert client.get("/api/permissions/catalog", headers=h).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/permissions/groups", headers=h, json={"name": "x"}
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
|
||||
def test_catalog_lists_vocabulary(client, access_token):
|
||||
body = client.get("/api/permissions/catalog", headers=_bearer(access_token)).json()
|
||||
assert "roms" in body["entities"] and "platforms" in body["entities"]
|
||||
assert set(body["actions"]) == {"read", "write", "delete"}
|
||||
|
||||
|
||||
def test_group_create_assign_and_effective_permissions(
|
||||
client, access_token, viewer_user
|
||||
):
|
||||
try:
|
||||
created = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={
|
||||
"name": "Curators",
|
||||
"description": "roms + platform read",
|
||||
"grants": [
|
||||
{"entity": "roms", "action": "read"},
|
||||
{"entity": "roms", "action": "write"},
|
||||
{"entity": "platforms", "action": "read"},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
group = created.json()
|
||||
assert group["member_count"] == 0
|
||||
assert {(g["entity"], g["action"]) for g in group["grants"]} == {
|
||||
("roms", "read"),
|
||||
("roms", "write"),
|
||||
("platforms", "read"),
|
||||
}
|
||||
gid = group["id"]
|
||||
|
||||
assigned = client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={"set_group": True, "permission_group_id": gid},
|
||||
)
|
||||
assert assigned.status_code == 200
|
||||
assert assigned.json()["permission_group_id"] == gid
|
||||
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
# Group grants -> these actions; nothing from the default viewer matrix.
|
||||
assert {"rom.view", "rom.upload", "platform.view"} <= actions
|
||||
assert "collection.create" not in actions # group grants no collections
|
||||
finally:
|
||||
_cleanup()
|
||||
|
||||
|
||||
def test_user_override_adds_capability(client, access_token, viewer_user):
|
||||
try:
|
||||
gid = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={"name": "RO", "grants": [{"entity": "roms", "action": "read"}]},
|
||||
).json()["id"]
|
||||
client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={
|
||||
"set_group": True,
|
||||
"permission_group_id": gid,
|
||||
"overrides": [{"entity": "roms", "action": "delete", "granted": True}],
|
||||
},
|
||||
)
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
assert "rom.delete" in actions # granted by override on top of read-only group
|
||||
finally:
|
||||
_cleanup()
|
||||
|
||||
|
||||
def test_hide_entity_for_user(client, access_token, viewer_user):
|
||||
resp = client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
_, body = _me_actions(client, viewer_user.id)
|
||||
assert body["hidden"]["platforms"] == [11]
|
||||
|
||||
# Idempotent + removable.
|
||||
client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
removed = client.request(
|
||||
"DELETE",
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "platforms", "entity_id": 11, "user_id": viewer_user.id},
|
||||
)
|
||||
assert removed.status_code == 204
|
||||
_, body = _me_actions(client, viewer_user.id)
|
||||
assert body["hidden"]["platforms"] == []
|
||||
|
||||
|
||||
def test_hidden_requires_exactly_one_principal(client, access_token):
|
||||
resp = client.post(
|
||||
"/api/permissions/hidden",
|
||||
headers=_bearer(access_token),
|
||||
json={"entity": "roms", "entity_id": 1, "user_id": 1, "group_id": 1},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_cannot_delete_default_group(client, access_token):
|
||||
groups = client.get("/api/permissions/groups", headers=_bearer(access_token)).json()
|
||||
default = next(g for g in groups if g["is_default"])
|
||||
resp = client.delete(
|
||||
f"/api/permissions/groups/{default['id']}", headers=_bearer(access_token)
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_delete_group_falls_members_back(client, access_token, viewer_user):
|
||||
gid = client.post(
|
||||
"/api/permissions/groups",
|
||||
headers=_bearer(access_token),
|
||||
json={"name": "Temp", "grants": [{"entity": "roms", "action": "read"}]},
|
||||
).json()["id"]
|
||||
client.put(
|
||||
f"/api/permissions/users/{viewer_user.id}",
|
||||
headers=_bearer(access_token),
|
||||
json={"set_group": True, "permission_group_id": gid},
|
||||
)
|
||||
|
||||
resp = client.delete(
|
||||
f"/api/permissions/groups/{gid}", headers=_bearer(access_token)
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
# FK SET NULL -> user falls back to the default (viewer) matrix.
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
assert user.permission_group_id is None
|
||||
actions, _ = _me_actions(client, viewer_user.id)
|
||||
assert "collection.create" in actions # default viewer behaviour restored
|
||||
95
backend/tests/endpoints/test_permissions_me.py
Normal file
95
backend/tests/endpoints/test_permissions_me.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""`/permissions/me` returns backend-enforced grants in the UI action vocabulary."""
|
||||
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import HiddenEntity, PermEntity
|
||||
|
||||
VIEWER_ACTIONS = {
|
||||
"rom.view",
|
||||
"rom.play",
|
||||
"rom.download",
|
||||
"rom.favorite",
|
||||
"platform.view",
|
||||
"collection.view",
|
||||
"collection.create",
|
||||
"collection.edit",
|
||||
"collection.delete",
|
||||
}
|
||||
|
||||
|
||||
def _actions(payload):
|
||||
return {g["action"] for g in payload["grants"]}
|
||||
|
||||
|
||||
def test_requires_auth(client):
|
||||
assert client.get("/api/permissions/me").status_code == 403
|
||||
|
||||
|
||||
def test_admin_is_admin_and_all_actions(client, access_token):
|
||||
resp = client.get(
|
||||
"/api/permissions/me", headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["is_admin"] is True
|
||||
# Admin unlocks the full vocabulary, incl. user.* and app.admin.
|
||||
assert {"user.delete", "app.admin", "rom.delete"} <= _actions(body)
|
||||
assert body["hidden"] == {"platforms": [], "roms": []}
|
||||
|
||||
|
||||
def test_viewer_matches_read_only_action_set(client, viewer_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert body["is_admin"] is False
|
||||
assert _actions(body) == VIEWER_ACTIONS
|
||||
|
||||
|
||||
def test_editor_adds_write_actions(client, editor_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {editor_access_token}"},
|
||||
).json()
|
||||
assert body["is_admin"] is False
|
||||
actions = _actions(body)
|
||||
assert VIEWER_ACTIONS <= actions
|
||||
# Editor gains library-wide write (and the backend-true delete/create it
|
||||
# always had, which the legacy role-map under-reported).
|
||||
assert {
|
||||
"rom.upload",
|
||||
"rom.edit",
|
||||
"rom.delete",
|
||||
"platform.edit",
|
||||
"platform.create",
|
||||
"platform.delete",
|
||||
"library.scan",
|
||||
} <= actions
|
||||
# Still no user management.
|
||||
assert not {a for a in actions if a.startswith("user.")}
|
||||
|
||||
|
||||
def test_hidden_entities_reported(client, viewer_user, viewer_access_token):
|
||||
with sync_session.begin() as s:
|
||||
s.add(
|
||||
HiddenEntity(
|
||||
entity=PermEntity.PLATFORMS, entity_id=5, user_id=viewer_user.id
|
||||
)
|
||||
)
|
||||
s.add(
|
||||
HiddenEntity(entity=PermEntity.ROMS, entity_id=42, user_id=viewer_user.id)
|
||||
)
|
||||
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert body["hidden"]["platforms"] == [5]
|
||||
assert body["hidden"]["roms"] == [42]
|
||||
|
||||
|
||||
def test_grant_scopes_are_global(client, viewer_access_token):
|
||||
body = client.get(
|
||||
"/api/permissions/me",
|
||||
headers={"Authorization": f"Bearer {viewer_access_token}"},
|
||||
).json()
|
||||
assert all(g["scope"]["kind"] == "global" for g in body["grants"])
|
||||
146
backend/tests/endpoints/test_permissions_visibility.py
Normal file
146
backend/tests/endpoints/test_permissions_visibility.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""End-to-end checks for admin-driven visibility (hiding) and delete enforcement.
|
||||
|
||||
Proves the fine permission layer is actually wired into the endpoints: hidden
|
||||
platforms/roms disappear from lists and 404 on detail, the platform hide cascades
|
||||
to its roms, admins are unaffected, and delete requires a delete grant even when
|
||||
the coarse write scope is present.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi import status
|
||||
|
||||
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
|
||||
from handler.auth import oauth_handler
|
||||
from handler.database import db_user_handler
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.permission import (
|
||||
HiddenEntity,
|
||||
PermAction,
|
||||
PermEntity,
|
||||
PermissionGroup,
|
||||
PermissionGroupGrant,
|
||||
)
|
||||
|
||||
|
||||
def _auth(user):
|
||||
# Re-reads the user's current (projected) scopes each call.
|
||||
token = oauth_handler.create_access_token(
|
||||
data={
|
||||
"sub": user.username,
|
||||
"iss": "romm:oauth",
|
||||
"scopes": " ".join(user.oauth_scopes),
|
||||
},
|
||||
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
|
||||
)
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _hide(entity, entity_id, user_id):
|
||||
with sync_session.begin() as s:
|
||||
s.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user_id))
|
||||
|
||||
|
||||
def _make_group(name, grants):
|
||||
with sync_session.begin() as s:
|
||||
group = PermissionGroup(name=name, is_system=False)
|
||||
s.add(group)
|
||||
s.flush()
|
||||
gid = group.id
|
||||
for entity, action, own_only in grants:
|
||||
s.add(
|
||||
PermissionGroupGrant(
|
||||
group_id=gid, entity=entity, action=action, own_only=own_only
|
||||
)
|
||||
)
|
||||
return gid
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _cleanup_non_system_groups():
|
||||
# HiddenEntity user rows cascade when clear_database deletes users; only the
|
||||
# non-system groups created here need explicit cleanup.
|
||||
yield
|
||||
with sync_session.begin() as s:
|
||||
s.query(PermissionGroup).filter(PermissionGroup.is_system.is_(False)).delete(
|
||||
synchronize_session="evaluate"
|
||||
)
|
||||
|
||||
|
||||
def test_hidden_platform_excluded_from_list_but_visible_to_admin(
|
||||
client, viewer_user, admin_user, platform
|
||||
):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
|
||||
viewer_ids = [
|
||||
p["id"] for p in client.get("/api/platforms", headers=_auth(viewer_user)).json()
|
||||
]
|
||||
assert platform.id not in viewer_ids
|
||||
|
||||
admin_ids = [
|
||||
p["id"] for p in client.get("/api/platforms", headers=_auth(admin_user)).json()
|
||||
]
|
||||
assert platform.id in admin_ids
|
||||
|
||||
|
||||
def test_hidden_platform_detail_is_404_masked(client, viewer_user, platform):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
resp = client.get(f"/api/platforms/{platform.id}", headers=_auth(viewer_user))
|
||||
assert resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_rom_excluded_and_detail_404(client, viewer_user, rom):
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
|
||||
listing = client.get("/api/roms", headers=_auth(viewer_user)).json()
|
||||
assert rom.id not in listing["rom_id_index"]
|
||||
|
||||
detail = client.get(f"/api/roms/{rom.id}", headers=_auth(viewer_user))
|
||||
assert detail.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_hidden_platform_cascades_to_its_roms(client, viewer_user, rom, platform):
|
||||
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
|
||||
listing = client.get("/api/roms", headers=_auth(viewer_user)).json()
|
||||
assert rom.id not in listing["rom_id_index"]
|
||||
|
||||
|
||||
def test_hidden_rom_cannot_be_downloaded_by_id(client, viewer_user, rom):
|
||||
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
|
||||
# Zip download of a hidden rom is masked as not-found.
|
||||
zip_resp = client.get(
|
||||
f"/api/roms/download?rom_ids={rom.id}", headers=_auth(viewer_user)
|
||||
)
|
||||
assert zip_resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
# Direct content stream is masked too (before any file lookup).
|
||||
content_resp = client.get(
|
||||
f"/api/roms/{rom.id}/content/whatever", headers=_auth(viewer_user)
|
||||
)
|
||||
assert content_resp.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_delete_requires_delete_grant_even_with_write_scope(
|
||||
client, viewer_user, platform
|
||||
):
|
||||
# Group can read+write platforms but NOT delete them.
|
||||
gid = _make_group(
|
||||
"platform-writers",
|
||||
[
|
||||
(PermEntity.PLATFORMS, PermAction.READ, False),
|
||||
(PermEntity.PLATFORMS, PermAction.WRITE, False),
|
||||
],
|
||||
)
|
||||
db_user_handler.update_user(viewer_user.id, {"permission_group_id": gid})
|
||||
user = db_user_handler.get_user(viewer_user.id)
|
||||
|
||||
# Coarse PLATFORMS_WRITE is present (projected from the write grant), so the
|
||||
# request passes the scope gate and is rejected by the fine delete check.
|
||||
assert "platforms.write" in {s.value for s in user.oauth_scopes}
|
||||
resp = client.delete(f"/api/platforms/{platform.id}", headers=_auth(user))
|
||||
assert resp.status_code == status.HTTP_403_FORBIDDEN
|
||||
|
||||
|
||||
def test_admin_can_delete_platform(client, admin_user, platform):
|
||||
resp = client.delete(f"/api/platforms/{platform.id}", headers=_auth(admin_user))
|
||||
assert resp.status_code == status.HTTP_200_OK
|
||||
60
backend/tests/handler/auth/test_permissions_dependencies.py
Normal file
60
backend/tests/handler/auth/test_permissions_dependencies.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Pure unit tests for the fine-grained enforcement helpers (no DB needed)."""
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from handler.auth.dependencies import assert_can, can_access
|
||||
from handler.auth.permissions import ResolvedGrant, ResolvedPermissions
|
||||
from models.permission import PermAction, PermEntity
|
||||
|
||||
|
||||
def _perms(*, is_admin=False, user_id=1, grants=()):
|
||||
return ResolvedPermissions(
|
||||
is_admin=is_admin,
|
||||
user_id=user_id,
|
||||
grants=frozenset(grants),
|
||||
hidden_platform_ids=frozenset(),
|
||||
hidden_rom_ids=frozenset(),
|
||||
)
|
||||
|
||||
|
||||
def test_admin_can_do_anything():
|
||||
perms = _perms(is_admin=True)
|
||||
assert can_access(perms, PermEntity.USERS, PermAction.DELETE)
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.WRITE, owner_id=999)
|
||||
|
||||
|
||||
def test_library_wide_grant_allows_any_resource():
|
||||
perms = _perms(grants=[ResolvedGrant(PermEntity.ROMS, PermAction.DELETE, False)])
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
assert can_access(perms, PermEntity.ROMS, PermAction.DELETE, owner_id=999)
|
||||
|
||||
|
||||
def test_missing_grant_is_denied():
|
||||
perms = _perms(grants=[ResolvedGrant(PermEntity.ROMS, PermAction.READ, False)])
|
||||
assert not can_access(perms, PermEntity.ROMS, PermAction.DELETE)
|
||||
|
||||
|
||||
def test_owner_always_allowed_even_without_grant():
|
||||
perms = _perms(user_id=7, grants=())
|
||||
assert can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=7)
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=8)
|
||||
|
||||
|
||||
def test_own_only_grant_does_not_allow_others_resources():
|
||||
# own_only collections.write: may act on own (owner_id match) but not others'.
|
||||
perms = _perms(
|
||||
user_id=7,
|
||||
grants=[ResolvedGrant(PermEntity.COLLECTIONS, PermAction.WRITE, True)],
|
||||
)
|
||||
assert can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=7)
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE, owner_id=8)
|
||||
# No owner context (library-wide attempt) -> own_only is insufficient.
|
||||
assert not can_access(perms, PermEntity.COLLECTIONS, PermAction.WRITE)
|
||||
|
||||
|
||||
def test_assert_can_raises_403():
|
||||
perms = _perms(grants=())
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
|
||||
assert exc.value.status_code == 403
|
||||
62
backend/tests/utils/test_archives.py
Normal file
62
backend/tests/utils/test_archives.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from utils import archives
|
||||
|
||||
|
||||
def _fake_7z_listing(names: list[str]) -> str:
|
||||
"""Build a `7zz l -slt -ba` style listing for the given member names."""
|
||||
return "\n".join(f"Path = {name}\nSize = 10\nAttributes = A\n" for name in names)
|
||||
|
||||
|
||||
def test_stream_7z_chunks_yields_until_eof():
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [b"abc", b"def", b""]
|
||||
on_timeout = MagicMock()
|
||||
|
||||
chunks = list(
|
||||
archives._stream_7z_chunks(
|
||||
process, deadline=time.monotonic() + 1000, on_timeout=on_timeout
|
||||
)
|
||||
)
|
||||
|
||||
assert chunks == [b"abc", b"def"]
|
||||
on_timeout.assert_not_called()
|
||||
process.terminate.assert_not_called()
|
||||
|
||||
|
||||
def test_stream_7z_chunks_timeout_terminates_and_signals_once():
|
||||
process = MagicMock()
|
||||
process.stdout.read.side_effect = [b"abc", b"def", b""]
|
||||
on_timeout = MagicMock()
|
||||
|
||||
# A deadline in the past trips on the first chunk.
|
||||
chunks = list(
|
||||
archives._stream_7z_chunks(process, deadline=0.0, on_timeout=on_timeout)
|
||||
)
|
||||
|
||||
assert chunks == []
|
||||
on_timeout.assert_called_once()
|
||||
process.terminate.assert_called_once()
|
||||
|
||||
|
||||
def test_read_7z_archive_files_timeout_logs_once_without_spam(monkeypatch):
|
||||
"""Once the shared budget is spent, no subprocess is spawned per remaining
|
||||
member and the timeout is logged a single time, not once per entry."""
|
||||
names = [f"file{i:02d}.bin" for i in range(20)]
|
||||
listing = MagicMock(stdout=_fake_7z_listing(names))
|
||||
|
||||
# Force the per-archive deadline to be already in the past.
|
||||
monkeypatch.setattr(archives, "SEVEN_ZIP_TIMEOUT", -1)
|
||||
|
||||
with (
|
||||
patch.object(archives.subprocess, "run", return_value=listing),
|
||||
patch.object(archives.subprocess, "Popen") as popen_patch,
|
||||
patch.object(archives.log, "error") as log_error,
|
||||
):
|
||||
results = list(archives.read_7z_archive_files(Path("/fake.7z"), [], []))
|
||||
|
||||
assert results == []
|
||||
popen_patch.assert_not_called()
|
||||
assert log_error.call_count == 1
|
||||
@@ -282,13 +282,15 @@ def read_tar_archive_files(
|
||||
|
||||
|
||||
def _stream_7z_chunks(
|
||||
process: subprocess.Popen[bytes], deadline: float
|
||||
process: subprocess.Popen[bytes],
|
||||
deadline: float,
|
||||
on_timeout: Callable[[], None],
|
||||
) -> Iterator[bytes]:
|
||||
assert process.stdout is not None
|
||||
while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE):
|
||||
if time.monotonic() > deadline:
|
||||
process.terminate()
|
||||
log.error("7z extraction timed out during multi-file archive read")
|
||||
on_timeout()
|
||||
return
|
||||
yield chunk
|
||||
|
||||
@@ -350,9 +352,21 @@ def read_7z_archive_files(
|
||||
|
||||
entries.sort(key=lambda e: e[0])
|
||||
|
||||
# Single time budget for reading every member of this archive.
|
||||
deadline = time.monotonic() + SEVEN_ZIP_TIMEOUT
|
||||
timed_out = False
|
||||
|
||||
def _mark_timed_out() -> None:
|
||||
nonlocal timed_out
|
||||
timed_out = True
|
||||
|
||||
for name, size in entries:
|
||||
# Once the shared budget is spent, stop spawning a subprocess per
|
||||
# remaining member; otherwise each one trips the deadline and spams
|
||||
# an identical error line for every entry left in the archive.
|
||||
if timed_out or time.monotonic() > deadline:
|
||||
timed_out = True
|
||||
break
|
||||
try:
|
||||
with subprocess.Popen(
|
||||
[SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y"],
|
||||
@@ -362,8 +376,10 @@ def read_7z_archive_files(
|
||||
) as process:
|
||||
if process.stdout is None:
|
||||
continue
|
||||
yield name, size, _stream_7z_chunks(process, deadline)
|
||||
if process.returncode != 0:
|
||||
yield name, size, _stream_7z_chunks(process, deadline, _mark_timed_out)
|
||||
# A timeout terminates the subprocess, so a non-zero return code is
|
||||
# expected then and is covered by the single log below.
|
||||
if not timed_out and process.returncode != 0:
|
||||
log.error(
|
||||
f"7z extraction of {name} failed with code {process.returncode}"
|
||||
)
|
||||
@@ -372,6 +388,9 @@ def read_7z_archive_files(
|
||||
log.error(f"Error extracting {name} from {file_path}: {e}")
|
||||
continue
|
||||
|
||||
if timed_out:
|
||||
log.error(f"7z extraction timed out reading members of {file_path}")
|
||||
|
||||
|
||||
def read_rar_archive_files(
|
||||
file_path: Path,
|
||||
|
||||
Reference in New Issue
Block a user