feat(perm): 项目 PM 共管接口权限与监控并细化 PM 写权限边界

- deps 新增 list_active_pm_study_ids、is_active_project_pm 与
  require_admin_or_any_project_pm 依赖,用于把 PM 项目范围带进鉴权与
  监控。get_cra_site_scope 内部延后导入 site CRUD,避免循环依赖。
- system_permissions API 改用 PM/ADMIN 双角色入口,permissions/monitoring
  系统级权限新增 PM 配额,并细化访问日志、告警、监控指标的可见范围。
- members API 调整:项目 PM 仅可管理低于 PM 的项目角色,禁止互相
  改写或授予 PM。
- api_permissions API 增加 GET /api-permissions/me,返回当前用户在该
  项目的有效权限矩阵;保存权限矩阵时校验 PM 行为不被篡改。
- core/api_permissions:新增立项配置接口键、PM 默认拥有的监控/权限
  系统级条目,并在权限元信息中标注 PM 共享角色。
- core/project_permissions:role_has_api_permission 命中默认角色矩阵;
  replace_api_endpoint_permissions 改为部分更新且永不持久化 ADMIN/PM。
- studies setup-config 各端点改用接口级权限装饰器,与新的 setup_config
  权限键对齐。permission_monitor 新增 get_metrics 摘要供 PM 视图调用。
- 测试:新增 test_admin_pm_permissions 覆盖 PM 系统级权限、监控范围和
  成员管理边界;conftest 兼容 SA_UUID 列;权限相关用例同步移除已失效
  的 module_permission 链路。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Cheng Zhou
2026-05-25 12:38:07 +08:00
parent dd2973c429
commit 747dd55225
22 changed files with 973 additions and 415 deletions
+107 -2
View File
@@ -671,6 +671,37 @@ API_ENDPOINT_PERMISSIONS = {
"description": "搜索参与者历史",
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW"],
},
# 立项配置管理
"setup_config:read": {
"module": "setup_config",
"action": "read",
"description": "查询立项配置",
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
},
"setup_config:update": {
"module": "setup_config",
"action": "write",
"description": "保存立项配置草稿",
"default_roles": ["PM"],
},
"setup_config:publish": {
"module": "setup_config",
"action": "write",
"description": "发布立项配置",
"default_roles": ["PM"],
},
"setup_config:rollback": {
"module": "setup_config",
"action": "write",
"description": "回滚立项配置版本",
"default_roles": ["PM"],
},
"setup_config:delete_version": {
"module": "setup_config",
"action": "write",
"description": "删除立项配置版本",
"default_roles": ["PM"],
},
# 项目里程碑管理
"project_milestones:read": {
"module": "project_milestones",
@@ -1125,6 +1156,17 @@ OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
"project_milestones:update",
],
},
"setup_config": {
"read": [
"setup_config:read",
],
"write": [
"setup_config:update",
"setup_config:publish",
"setup_config:rollback",
"setup_config:delete_version",
],
},
}
# 项目级权限角色列表
@@ -1179,7 +1221,8 @@ OPERATION_PREREQUISITES: dict[str, list[str]] = {
}
# 系统级权限定义
# 描述管理后台各模块操作,当前全部由 ADMIN 角色持有
# 描述管理后台各模块操作的权限归属
# PM 角色的系统级权限限定在其所负责的项目范围内
SYSTEM_PERMISSIONS: dict[str, dict] = {
# 账号管理
"system:users:list": {
@@ -1256,11 +1299,17 @@ SYSTEM_PERMISSIONS: dict[str, dict] = {
"roles": ["ADMIN"],
},
# 权限管理
"system:permissions:read": {
"module": "system_permissions",
"action": "read",
"description": "查看系统级权限定义",
"roles": ["ADMIN", "PM"],
},
"system:permissions:project_config": {
"module": "system_permissions",
"action": "update",
"description": "配置项目接口权限",
"roles": ["ADMIN"],
"roles": ["ADMIN", "PM"],
},
"system:permissions:templates": {
"module": "system_permissions",
@@ -1268,6 +1317,61 @@ SYSTEM_PERMISSIONS: dict[str, dict] = {
"description": "管理权限模板",
"roles": ["ADMIN"],
},
# 权限监控
"system:monitoring:metrics": {
"module": "system_monitoring",
"action": "read",
"description": "查看权限监控指标",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:cache_stats": {
"module": "system_monitoring",
"action": "read",
"description": "查看缓存统计",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:alerts": {
"module": "system_monitoring",
"action": "read",
"description": "查看权限告警",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:health": {
"module": "system_monitoring",
"action": "read",
"description": "查看权限系统健康状态",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:access_logs": {
"module": "system_monitoring",
"action": "read",
"description": "查看权限访问日志",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:trends": {
"module": "system_monitoring",
"action": "read",
"description": "查看权限趋势数据",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:reset_metrics": {
"module": "system_monitoring",
"action": "update",
"description": "重置监控指标",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:clear_alerts": {
"module": "system_monitoring",
"action": "update",
"description": "清除告警",
"roles": ["ADMIN", "PM"],
},
"system:monitoring:security_logs": {
"module": "system_monitoring",
"action": "read",
"description": "查看安全访问日志",
"roles": ["ADMIN"],
},
# 审计日志
"system:audit_logs:read": {
"module": "system_audit",
@@ -1288,5 +1392,6 @@ SYSTEM_MODULE_LABELS: dict[str, str] = {
"system_users": "账号管理",
"system_projects": "项目管理",
"system_permissions": "权限管理",
"system_monitoring": "权限监控",
"system_audit": "审计日志",
}
+54 -5
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Annotated, AsyncGenerator, Callable, Iterable
import time
import uuid
@@ -10,10 +12,11 @@ from app.core.exceptions import AppException
from app.core.security import decode_token, oauth2_scheme
from app.crud import user as user_crud
from app.crud import member as member_crud
from app.crud import site as site_crud
from app.core.project_permissions import role_has_api_permission, get_missing_prerequisites
from app.db.session import SessionLocal
from app.models.study_member import StudyMember
from app.schemas.user import TokenPayload
from sqlalchemy import select
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
@@ -65,12 +68,56 @@ def require_roles(roles: Iterable[str]) -> Callable:
return dependency
def _role_value(user) -> str:
return user.role.value if hasattr(user.role, "value") else str(user.role)
async def list_active_pm_study_ids(db: AsyncSession, user_id: uuid.UUID) -> set[uuid.UUID]:
result = await db.execute(
select(StudyMember.study_id).where(
StudyMember.user_id == user_id,
StudyMember.is_active.is_(True),
StudyMember.role_in_study == "PM",
)
)
return set(result.scalars().all())
async def is_active_project_pm(db: AsyncSession, user_id: uuid.UUID, study_id: uuid.UUID) -> bool:
result = await db.execute(
select(StudyMember.id).where(
StudyMember.study_id == study_id,
StudyMember.user_id == user_id,
StudyMember.is_active.is_(True),
StudyMember.role_in_study == "PM",
)
)
return result.scalar_one_or_none() is not None
def require_admin_or_any_project_pm() -> Callable:
async def dependency(
current_user=Depends(get_current_user),
db: AsyncSession = Depends(get_db_session),
):
if _role_value(current_user) == "ADMIN":
return current_user
if await list_active_pm_study_ids(db, current_user.id):
return current_user
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="权限不足",
)
return dependency
async def get_study_member(
study_id: uuid.UUID,
current_user=Depends(get_current_user),
db: AsyncSession = Depends(get_db_session),
):
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
role_value = _role_value(current_user)
if role_value == "ADMIN":
return None
return await member_crud.get_member(db, study_id, current_user.id)
@@ -82,7 +129,7 @@ def require_study_member():
current_user=Depends(get_current_user),
db: AsyncSession = Depends(get_db_session),
):
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
role_value = _role_value(current_user)
if role_value == "ADMIN":
return current_user
membership = await member_crud.get_member(db, study_id, current_user.id)
@@ -105,7 +152,7 @@ def require_study_roles(roles: Iterable[str], *, allow_system_admin: bool = True
current_user=Depends(get_current_user),
db: AsyncSession = Depends(get_db_session),
):
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
role_value = _role_value(current_user)
if allow_system_admin and role_value == "ADMIN":
return current_user
membership = await member_crud.get_member(db, study_id, current_user.id)
@@ -136,7 +183,7 @@ def require_api_permission(endpoint_key: str, *, allow_system_admin: bool = True
db: AsyncSession = Depends(get_db_session),
):
from app.core.permission_monitor import get_permission_monitor
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
role_value = _role_value(current_user)
if allow_system_admin and role_value == "ADMIN":
_enqueue_permission_log(
study_id, current_user.id, endpoint_key, "ADMIN", True, 0.0, request
@@ -226,6 +273,8 @@ async def get_cra_site_scope(
study_id: uuid.UUID,
current_user,
) -> tuple[set[uuid.UUID], set[str]] | None:
from app.crud import site as site_crud
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
if role_value == "ADMIN":
return None
+6
View File
@@ -122,6 +122,12 @@ class PermissionMonitor:
"cache_metrics": self.metrics.cache_metrics.to_dict(),
}
def get_metrics(self) -> dict[str, Any]:
return {
"cache_metrics": self.metrics.cache_metrics.to_dict(),
"uptime_seconds": self.metrics.uptime_seconds,
}
def reset_metrics(self) -> None:
self.metrics.reset()
+33 -16
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import uuid
from sqlalchemy import delete, select
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.api_endpoint_permission import ApiEndpointPermission
@@ -48,13 +48,21 @@ async def role_has_api_permission(
check_prerequisites: bool = True,
) -> bool:
"""检查角色是否有权访问特定接口"""
if role == "ADMIN" or role == "PM":
if role == "ADMIN":
return True
permissions = await _get_project_permission_overrides(db, study_id)
if role == "PM":
override = permissions.get("PM", {}).get(endpoint_key)
if override is not None:
return override
return True
allowed = permissions.get(role or "", {}).get(endpoint_key)
if allowed is None:
return False
config = API_ENDPOINT_PERMISSIONS.get(endpoint_key)
allowed = bool(config and role in config.get("default_roles", []))
if not allowed:
return False
@@ -78,7 +86,7 @@ async def get_missing_prerequisites(
endpoint_key: str,
) -> list[str]:
"""获取缺失的前置权限列表"""
if role == "ADMIN" or role == "PM":
if role == "ADMIN":
return []
missing = []
@@ -131,27 +139,36 @@ async def replace_api_endpoint_permissions(
study_id: uuid.UUID,
payload: dict[str, dict[str, bool]],
) -> dict[str, dict[str, dict[str, bool]]]:
"""替换项目的接口级权限矩阵"""
await db.execute(
delete(ApiEndpointPermission).where(
ApiEndpointPermission.study_id == study_id,
)
)
"""更新 payload 中指定的角色权限项。未提交的权限项保持不变。
ADMIN 与 PM 权限不会被持久化:ADMIN 始终拥有全部权限,PM 默认拥有
全部项目权限,应当通过专门的渠道而不是项目权限矩阵调整。
"""
for role, endpoints in payload.items():
if role in ("ADMIN", "PM"):
continue
for endpoint_key, allowed in endpoints.items():
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
continue
db.add(
ApiEndpointPermission(
study_id=study_id,
role=role,
endpoint_key=endpoint_key,
allowed=allowed,
result = await db.execute(
select(ApiEndpointPermission).where(
ApiEndpointPermission.study_id == study_id,
ApiEndpointPermission.role == role,
ApiEndpointPermission.endpoint_key == endpoint_key,
)
)
existing = result.scalar_one_or_none()
if existing:
existing.allowed = allowed
else:
db.add(
ApiEndpointPermission(
study_id=study_id,
role=role,
endpoint_key=endpoint_key,
allowed=allowed,
)
)
await db.commit()