mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
* fix(auth): bound new client tokens by the caller's scopes and stop delegates removing admins - Creating a client token, approving a device, and regenerating or pairing an existing token now check against the scopes of the credential making the request rather than the whole account's. A narrow client token can no longer mint, or recover the secret of, a broader one. Session and basic auth carry the account's scopes, so they behave as before. - Deleting an admin requires the caller to be an admin, mirroring the existing rule for creating one, since users.write can be delegated. - Editing another user requires the users.write scope on top of the admin role, so an admin's me.write-only token can't change other accounts. - own_only is rejected (422) on grants and overrides for entities with no owner (platforms, roms, firmware, users, tasks, logs), where it silently meant "all". The catalog exposes the ownable entities and the permission matrices only offer "own" on those. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(permissions): keep owner-less own_only grants' access on save Addresses Greptile review on #5346: - An own_only delete grant on an entity with no owner allows nothing today (delete has no coarse scope and the fine check runs with owned=False), so it is now dropped from group grants, or turned into a revoke for overrides, instead of being saved as full delete access. The matrices show it the same way. - The group dialog no longer saves when the permission catalog failed to load, which would have stripped every own_only grant. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(auth): require users.write in the credential to act on another user (pr-ready: code-review) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(auth): share client token effective scopes and canOwn (pr-ready: simplify) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(permissions): tighten grantEffect docstring and matrix comment (pr-ready: review-polish) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(auth): make user, token and streaming admin rules consistent - Acting on another user (edit, delete, RA refresh) needs users.write in the credential, and only admins may target an admin or grant the admin role. One assert_admin_for_admin helper now backs add_user, invite links, update, delete and admin token revocation. - Re-issuing a client token's secret (regenerate, pair) needs every scope it stores; deleting one needs every scope it currently grants, so a narrow token can't remove a broader sibling. - Streaming admin overrides need users.read or users.write in the credential, not just the admin role. - Migration 0154 rewrites stored own_only grants and overrides on owner-less entities to the access they already gave, so the frontend normalisation and the catalog save gate are gone. - own_only is no longer rejected on revoke overrides. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
484 lines
16 KiB
Python
484 lines
16 KiB
Python
import asyncio
|
|
from typing import Annotated, Any
|
|
|
|
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.audit_handler import AuditTarget, record
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import assert_admin, get_permissions
|
|
from handler.database import (
|
|
db_client_token_handler,
|
|
db_permission_handler,
|
|
db_platform_handler,
|
|
db_rom_handler,
|
|
db_user_handler,
|
|
)
|
|
from handler.socket_handler import close_client_token_sockets, socket_handler
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction, AuditTargetType
|
|
from models.permission import (
|
|
OWNABLE_PERM_ENTITIES,
|
|
PermAction,
|
|
PermEntity,
|
|
PermissionGroup,
|
|
)
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter(
|
|
prefix="/permissions",
|
|
tags=["permissions"],
|
|
)
|
|
|
|
|
|
async def _broadcast_permissions_changed(user_id: int) -> None:
|
|
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}")
|
|
|
|
|
|
async def emit_permissions_changed(*user_ids: int) -> None:
|
|
"""Notify clients that the users' 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, hidden entities or age settings.
|
|
"""
|
|
# The gallery's cached id index, counts and filter values are computed per
|
|
# user with visibility applied, so they go stale with it.
|
|
db_rom_handler.invalidate_filter_values_cache()
|
|
if not user_ids:
|
|
return
|
|
await asyncio.gather(*(_broadcast_permissions_changed(u) for u in user_ids))
|
|
try:
|
|
token_ids = db_client_token_handler.get_token_ids_by_users(user_ids)
|
|
except Exception: # noqa: BLE001
|
|
log.warning(f"Failed to look up the tokens of users {user_ids}", exc_info=True)
|
|
return
|
|
await close_client_token_sockets(token_ids)
|
|
|
|
|
|
@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),
|
|
ownable_entities=[e for e in PermEntity if e in OWNABLE_PERM_ENTITIES],
|
|
)
|
|
|
|
|
|
# --- 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,
|
|
system_key=group.system_key,
|
|
color=group.color,
|
|
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)),
|
|
hidden=[
|
|
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id)
|
|
for h in db_permission_handler.get_hidden_entities(group_id=group.id)
|
|
],
|
|
age_limit=group.age_limit,
|
|
hide_unrated_roms=group.hide_unrated_roms,
|
|
)
|
|
|
|
|
|
def _group_target(group: PermissionGroup) -> AuditTarget:
|
|
return AuditTarget(AuditTargetType.PERMISSION_GROUP, group.id, group.name)
|
|
|
|
|
|
def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget | None:
|
|
if entity == PermEntity.ROMS:
|
|
rom = db_rom_handler.get_rom_visibility_label(entity_id)
|
|
return (
|
|
AuditTarget.of_rom(rom)
|
|
if rom
|
|
else AuditTarget(AuditTargetType.ROM, entity_id, None)
|
|
)
|
|
if entity == PermEntity.PLATFORMS:
|
|
platform = db_platform_handler.get_platform(entity_id)
|
|
return (
|
|
AuditTarget.of_platform(platform)
|
|
if platform
|
|
else AuditTarget(AuditTargetType.PLATFORM, entity_id, None)
|
|
)
|
|
return None
|
|
|
|
|
|
def _group_name(group_id: int | None) -> str | None:
|
|
group = db_permission_handler.get_group(group_id) if group_id is not None else None
|
|
return group.name if group else None
|
|
|
|
|
|
def _principal(user_id: int | None, group_id: int | None) -> dict[str, Any]:
|
|
"""Who something was hidden from, named for the audit log."""
|
|
if user_id is not None:
|
|
user = db_user_handler.get_user(user_id)
|
|
return {"type": "user", "id": user_id, "name": user.username if user else None}
|
|
return {"type": "group", "id": group_id, "name": _group_name(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
|
|
)
|
|
async 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,
|
|
color=body.color,
|
|
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
|
|
age_limit=body.age_limit,
|
|
hide_unrated_roms=body.hide_unrated_roms,
|
|
)
|
|
if body.is_default:
|
|
await emit_permissions_changed(
|
|
*db_permission_handler.get_group_follower_ids(group.id)
|
|
)
|
|
record(
|
|
AuditAction.PERMISSION_GROUP_CREATE,
|
|
request,
|
|
_group_target(group),
|
|
{"grants": len(body.grants), "is_default": body.is_default},
|
|
)
|
|
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)
|
|
group = db_permission_handler.get_group(id)
|
|
if group is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
|
|
|
# Renaming onto an existing name would hit the unique constraint as a 500.
|
|
if body.name is not None:
|
|
clash = db_permission_handler.get_group_by_name(body.name)
|
|
if clash is not None and clash.id != id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="A group with that name already exists",
|
|
)
|
|
|
|
# Don't leave the system without a default group; reassign first.
|
|
if body.is_default is False and group.is_default:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Set another group as default first",
|
|
)
|
|
|
|
updated = db_permission_handler.update_group(
|
|
id,
|
|
name=body.name,
|
|
description=body.description,
|
|
is_default=body.is_default,
|
|
color=body.color,
|
|
grants=(
|
|
[(g.entity, g.action, g.own_only) for g in body.grants]
|
|
if body.grants is not None
|
|
else None
|
|
),
|
|
set_age_settings=body.set_age_settings,
|
|
age_limit=body.age_limit,
|
|
hide_unrated_roms=body.hide_unrated_roms,
|
|
)
|
|
if updated is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
|
|
await emit_permissions_changed(*db_permission_handler.get_group_follower_ids(id))
|
|
# Age settings apply only with the flag, so only the flag reports them.
|
|
age_fields = {"set_age_settings", "age_limit", "hide_unrated_roms"}
|
|
changed = set(body.model_dump(exclude_none=True)) - age_fields
|
|
if body.set_age_settings:
|
|
changed |= {"age_limit", "hide_unrated_roms"}
|
|
record(
|
|
AuditAction.PERMISSION_GROUP_EDIT,
|
|
request,
|
|
_group_target(updated),
|
|
{"changed": sorted(changed)},
|
|
)
|
|
return _group_schema(updated)
|
|
|
|
|
|
@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)
|
|
record(
|
|
AuditAction.PERMISSION_GROUP_DELETE,
|
|
request,
|
|
_group_target(group),
|
|
{"members": len(member_ids)},
|
|
)
|
|
await emit_permissions_changed(*member_ids)
|
|
|
|
|
|
# --- Admin: per-user assignment ----------------------------------------------
|
|
|
|
|
|
def _user_permissions(
|
|
user_id: int,
|
|
*,
|
|
group_id: int | None,
|
|
age_limit: int | None,
|
|
hide_unrated_roms: bool | 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=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
|
|
],
|
|
age_limit=age_limit,
|
|
hide_unrated_roms=hide_unrated_roms,
|
|
)
|
|
|
|
|
|
@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,
|
|
group_id=user.permission_group_id,
|
|
age_limit=user.age_limit,
|
|
hide_unrated_roms=user.hide_unrated_roms,
|
|
)
|
|
|
|
|
|
@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],
|
|
)
|
|
age_limit, hide_unrated_roms = user.age_limit, user.hide_unrated_roms
|
|
if body.set_age_settings:
|
|
age_limit, hide_unrated_roms = body.age_limit, body.hide_unrated_roms
|
|
db_user_handler.update_user(
|
|
user_id,
|
|
{"age_limit": age_limit, "hide_unrated_roms": hide_unrated_roms},
|
|
)
|
|
|
|
await emit_permissions_changed(user_id)
|
|
record(
|
|
AuditAction.USER_PERMISSIONS_EDIT,
|
|
request,
|
|
AuditTarget.of_user(user),
|
|
lambda: {
|
|
"group": _group_name(group_id),
|
|
"group_changed": body.set_group and group_id != user.permission_group_id,
|
|
"overrides": len(body.overrides) if body.overrides is not None else None,
|
|
"age_settings_changed": body.set_age_settings,
|
|
},
|
|
)
|
|
return _user_permissions(
|
|
user_id,
|
|
group_id=group_id,
|
|
age_limit=age_limit,
|
|
hide_unrated_roms=hide_unrated_roms,
|
|
)
|
|
|
|
|
|
# --- 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",
|
|
)
|
|
|
|
# Only platforms and roms are honored by the resolver (firmware is hidden via
|
|
# its platform cascade), so reject other entity types instead of storing a
|
|
# row the visibility filter would silently ignore. The id itself is a
|
|
# denylist entry, so a not-yet-present id is a harmless no-op, not an error.
|
|
if body.entity not in (PermEntity.PLATFORMS, PermEntity.ROMS):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Only platforms and roms can be hidden",
|
|
)
|
|
|
|
db_permission_handler.add_hidden_entity(
|
|
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_id
|
|
)
|
|
record(
|
|
AuditAction.VISIBILITY_HIDE,
|
|
request,
|
|
lambda: _hidden_target(body.entity, body.entity_id),
|
|
lambda: {
|
|
"from": _principal(body.user_id, body.group_id),
|
|
"entity": body.entity,
|
|
"entity_id": body.entity_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
|
|
)
|
|
record(
|
|
AuditAction.VISIBILITY_UNHIDE,
|
|
request,
|
|
lambda: _hidden_target(entity, entity_id),
|
|
lambda: {
|
|
"from": _principal(user_id, group_id),
|
|
"entity": entity,
|
|
"entity_id": entity_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:
|
|
await emit_permissions_changed(
|
|
*db_permission_handler.get_group_follower_ids(group_id)
|
|
)
|