"""Security and permission helpers.""" from __future__ import annotations from backend.dto.common import ApiError, ErrorCode from core.identity import RequestContext def require_authenticated(ctx: RequestContext) -> None: if not ctx.is_authenticated: raise ApiError( ErrorCode.UNAUTHORIZED, "ImageStudio \u9700\u8981 AstrBot WebUI \u767b\u5f55\u6001", ) def require_permission(ctx: RequestContext, permission: str) -> None: require_authenticated(ctx) if not ctx.has_permission(permission): raise ApiError( ErrorCode.FORBIDDEN, "\u5f53\u524d\u7528\u6237\u6ca1\u6709\u6267\u884c\u8be5\u64cd\u4f5c\u7684\u6743\u9650", {"permission": permission}, ) def require_write(ctx: RequestContext) -> None: require_permission(ctx, "can_write") def require_task_retry(ctx: RequestContext) -> None: require_write(ctx) require_permission(ctx, "can_retry_tasks") def require_config_manager(ctx: RequestContext) -> None: require_permission(ctx, "can_manage_config") def can_access_owned_resource(owner_user_id: str | None, ctx: RequestContext) -> bool: """Whether ``ctx`` may act on a resource owned by ``owner_user_id``. Single source of truth for ownership. ``ProfileService._require_owner`` and ``ResourceAccessService._can_access`` used to disagree -- the former ignored ``can_manage_all_profiles`` entirely -- so the same actor could reach a profile through the chat chain and be refused through the web route. Any elevation rule belongs here and nowhere else. """ if ctx.has_permission("can_manage_all_profiles") or ctx.has_permission("*"): return True return bool(ctx.actor_id and owner_user_id and ctx.actor_id == owner_user_id) def enforce_route_permission(ctx: RequestContext, permission: str) -> None: """Apply a route's declared ``PERMISSION_MATRIX`` entry. ``PERMISSION_MATRIX`` used to be documentation only: the dispatcher never read ``RouteMatch.permission``, so a route's real protection was whichever ``require_*`` call its handler happened to contain. Declaration and enforcement could drift silently, and a handler that simply forgot the call was wide open. Enforcing here makes the manifest the contract. Handlers keep their own ``require_*`` calls -- they run inside ``handle_request`` and produce the same errors -- so this is an additional gate, never a replacement. """ # Imported lazily: backend.route_registry imports nothing from core, and # keeping it that way avoids a core -> backend import cycle at module load. from backend.route_registry import permission_requirement requirement = permission_requirement(permission) if requirement.get("auth_required", True): require_authenticated(ctx) required = requirement.get("required_permissions") or ( [requirement["required_permission"]] if requirement.get("required_permission") else [] ) for name in required: if name: require_permission(ctx, name)