完善项目权限前置依赖保存校验

- 以接口权限定义中的 prerequisite_permissions 作为前置依赖单一事实源,生成运行时前置权限映射\n- 保存项目角色权限前预检缺失前置权限与受影响下游权限,未确认时返回 409 调整详情\n- 确认保存时自动合并补齐前置权限与取消下游权限,并提供有效权限矩阵读取接口\n- 前端角色权限编辑改为保存时执行依赖校验,弹窗展示需补充前置权限和受影响下游权限\n- 新增编辑权限取消按钮,清理权限选择即时确认弹窗残留\n- 补充后端接口测试、前端权限编辑测试与优化设计文档
This commit is contained in:
Cheng Zhou
2026-06-04 16:29:44 +08:00
parent 02f2c6660b
commit d6452e3f9d
13 changed files with 1089 additions and 80 deletions
+46 -48
View File
@@ -36,7 +36,7 @@ API_ENDPOINT_PERMISSIONS = {
"action": "write",
"description": "创建参与者",
"default_roles": ["PM", "CRA"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["subjects:read", "sites:read"],
},
"subjects:read": {
"module": "subjects",
@@ -50,14 +50,14 @@ API_ENDPOINT_PERMISSIONS = {
"action": "write",
"description": "更新参与者",
"default_roles": ["PM", "CRA"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["subjects:read", "sites:read"],
},
"subjects:delete": {
"module": "subjects",
"action": "write",
"description": "删除参与者",
"default_roles": ["PM"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["subjects:read", "sites:read"],
},
# 访视管理 (visits)
"visits:create": {
@@ -94,7 +94,7 @@ API_ENDPOINT_PERMISSIONS = {
"action": "write",
"description": "创建参与者AE",
"default_roles": ["PM", "CRA", "PV", "QA"],
"prerequisite_permissions": ["subjects:read", "sites:read"],
"prerequisite_permissions": ["subject_aes:read", "subjects:read", "sites:read"],
},
"subject_aes:read": {
"module": "subjects",
@@ -123,7 +123,7 @@ API_ENDPOINT_PERMISSIONS = {
"action": "write",
"description": "创建合同费用",
"default_roles": ["PM"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
},
"fees_contracts:read": {
"module": "fees",
@@ -137,14 +137,14 @@ API_ENDPOINT_PERMISSIONS = {
"action": "write",
"description": "更新合同费用",
"default_roles": ["PM"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
},
"fees_contracts:delete": {
"module": "fees",
"action": "write",
"description": "删除合同费用",
"default_roles": ["PM"],
"prerequisite_permissions": ["sites:read"],
"prerequisite_permissions": ["fees_contracts:read", "sites:read"],
},
# 项目成员管理
"project_members:create": {
@@ -384,30 +384,35 @@ API_ENDPOINT_PERMISSIONS = {
"action": "read",
"description": "查询立项配置",
"default_roles": ["PM", "CRA", "PV", "QA", "CTA"],
"prerequisite_permissions": [],
},
"setup_config:update": {
"module": "setup_config",
"action": "write",
"description": "保存立项配置草稿",
"default_roles": ["PM"],
"prerequisite_permissions": ["setup_config:read"],
},
"setup_config:publish": {
"module": "setup_config",
"action": "write",
"description": "发布立项配置",
"default_roles": ["PM"],
"prerequisite_permissions": ["setup_config:read"],
},
"setup_config:rollback": {
"module": "setup_config",
"action": "write",
"description": "回滚立项配置版本",
"default_roles": ["PM"],
"prerequisite_permissions": ["setup_config:read"],
},
"setup_config:delete_version": {
"module": "setup_config",
"action": "delete",
"description": "删除立项配置版本",
"default_roles": ["PM"],
"prerequisite_permissions": ["setup_config:read"],
},
# 项目里程碑管理
"project_milestones:read": {
@@ -640,6 +645,36 @@ API_ENDPOINT_PERMISSIONS = {
},
}
def _operation_read_candidates(operation_key: str) -> list[str]:
prefix = operation_key.split(":", 1)[0]
candidates = []
for read_key in (f"{prefix}:read", f"{prefix}:list"):
canonical_key = canonical_permission_key(read_key)
if canonical_key in API_ENDPOINT_PERMISSIONS and canonical_key not in candidates:
candidates.append(canonical_key)
return candidates
def _normalized_prerequisite_permissions(operation_key: str, config: dict) -> list[str]:
prerequisites = [
canonical_permission_key(key)
for key in config.get("prerequisite_permissions", [])
]
verb = operation_key.split(":")[-1]
if verb in {"create", "update", "delete", "export", "publish", "rollback", "delete_version"}:
for read_key in _operation_read_candidates(operation_key):
if read_key != operation_key and read_key not in prerequisites:
prerequisites.insert(0, read_key)
return list(dict.fromkeys(prerequisites))
for _operation_key, _operation_config in API_ENDPOINT_PERMISSIONS.items():
_operation_config["prerequisite_permissions"] = _normalized_prerequisite_permissions(
_operation_key,
_operation_config,
)
# 向后兼容:业务操作名到接口级权限的映射
# 用于在接口级权限未配置时,回退到模块级权限
OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
@@ -830,48 +865,11 @@ OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
# 项目级权限角色列表
PROJECT_PERMISSION_ROLES = ["PM", "CRA", "PV", "QA", "CTA"]
# 前置权限映射表(用于权限检查)
# 定义每个操作需要的前置权限
# 前置权限映射表(用于权限检查),由权限定义生成,避免展示与运行时不一致。
OPERATION_PREREQUISITES: dict[str, list[str]] = {
# 参与者管理
"subjects:create": ["sites:read"],
"subjects:update": ["sites:read"],
"subjects:delete": ["sites:read"],
# 访视管理
"visits:create": ["subjects:read", "sites:read"],
"visits:update": ["subjects:read", "sites:read"],
"visits:delete": ["subjects:read", "sites:read"],
# 参与者AE
"subject_aes:create": ["subjects:read", "sites:read"],
"subject_aes:update": ["subject_aes:read", "subjects:read", "sites:read"],
"subject_aes:delete": ["subject_aes:read", "subjects:read", "sites:read"],
# 合同费用
"fees_contracts:create": ["sites:read"],
"fees_contracts:update": ["sites:read"],
"fees_contracts:delete": ["sites:read"],
# 药物发货
"drug_shipments:create": ["sites:read"],
"drug_shipments:update": ["sites:read"],
"drug_shipments:delete": ["sites:read"],
# 参与者PD
"subject_pds:create": ["subjects:read", "sites:read"],
"subject_pds:update": ["subject_pds:list", "subjects:read", "sites:read"],
"subject_pds:delete": ["subject_pds:list", "subjects:read", "sites:read"],
# 病史记录
"subject_histories:create": ["subjects:read"],
"subject_histories:update": ["subjects:read"],
"subject_histories:delete": ["subjects:read"],
# 监查访视问题
"monitoring_issues:create": ["sites:read"],
"monitoring_issues:update": ["sites:read"],
"monitoring_issues:delete": ["sites:read"],
key: config["prerequisite_permissions"]
for key, config in API_ENDPOINT_PERMISSIONS.items()
if config["prerequisite_permissions"]
}
# 系统级权限定义
+167 -2
View File
@@ -16,6 +16,14 @@ from app.core.api_permissions import (
from app.core.permission_cache import get_permission_cache
class PrerequisitePermissionConfirmationRequired(ValueError):
"""权限调整需要授权人确认。"""
def __init__(self, adjustments: dict):
super().__init__("需要确认前置权限调整")
self.adjustments = adjustments
async def _get_project_permission_overrides(
db: AsyncSession,
study_id: uuid.UUID,
@@ -48,6 +56,126 @@ async def _get_project_permission_overrides(
return permissions
def _empty_role_adjustment() -> dict[str, dict[str, list[str]]]:
return {"add": {}, "remove": {}}
def _flatten_role_permissions(
matrix: dict[str, dict[str, dict[str, bool]]],
role: str,
) -> dict[str, bool]:
permissions: dict[str, bool] = {
endpoint_key: False
for endpoint_key in API_ENDPOINT_PERMISSIONS.keys()
}
if role in matrix:
for endpoint_key, value in matrix[role].items():
endpoint_key = canonical_permission_key(endpoint_key)
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
continue
permissions[endpoint_key] = bool(value["allowed"] if isinstance(value, dict) else value)
return permissions
def _canonicalize_payload(payload: dict[str, dict[str, bool]]) -> dict[str, dict[str, bool]]:
normalized: dict[str, dict[str, bool]] = {}
for role, endpoints in payload.items():
normalized[role] = {}
for endpoint_key, allowed in endpoints.items():
endpoint_key = canonical_permission_key(endpoint_key)
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
continue
normalized[role][endpoint_key] = bool(allowed)
return normalized
def _add_adjustment(target: dict[str, list[str]], key: str, value: str) -> None:
values = target.setdefault(key, [])
if value not in values:
values.append(value)
async def preview_api_permission_prerequisite_adjustments(
db: AsyncSession,
study_id: uuid.UUID,
payload: dict[str, dict[str, bool]],
) -> dict:
"""预检权限草稿需要授权人确认的前置补齐和下游消除项。"""
normalized_payload = _canonicalize_payload(payload)
matrix = await get_api_endpoint_permissions(db, study_id)
roles: dict[str, dict[str, dict[str, list[str]]]] = {}
for role, endpoints in normalized_payload.items():
if role in ("ADMIN", "PM"):
continue
candidate = _flatten_role_permissions(matrix, role)
explicitly_denied = {
endpoint_key
for endpoint_key, allowed in endpoints.items()
if not allowed
}
for endpoint_key, allowed in endpoints.items():
candidate[endpoint_key] = allowed
role_adjustment = _empty_role_adjustment()
denied_sources = set(explicitly_denied)
changed = True
while changed:
changed = False
for endpoint_key, allowed in list(candidate.items()):
if not allowed or endpoint_key in denied_sources:
continue
for prereq in OPERATION_PREREQUISITES.get(endpoint_key, []):
prereq = canonical_permission_key(prereq)
if prereq in denied_sources:
_add_adjustment(role_adjustment["remove"], prereq, endpoint_key)
candidate[endpoint_key] = False
denied_sources.add(endpoint_key)
changed = True
break
changed = True
while changed:
changed = False
for endpoint_key, allowed in list(candidate.items()):
if not allowed:
continue
for prereq in OPERATION_PREREQUISITES.get(endpoint_key, []):
prereq = canonical_permission_key(prereq)
if candidate.get(prereq, False):
continue
_add_adjustment(role_adjustment["add"], endpoint_key, prereq)
candidate[prereq] = True
changed = True
if role_adjustment["add"] or role_adjustment["remove"]:
roles[role] = role_adjustment
return {
"requires_confirmation": bool(roles),
"roles": roles,
}
def apply_prerequisite_adjustments_to_payload(
payload: dict[str, dict[str, bool]],
adjustments: dict,
) -> dict[str, dict[str, bool]]:
"""把已确认的补齐和消除项合并到待保存 payload。"""
normalized = _canonicalize_payload(payload)
for role, role_adjustment in adjustments.get("roles", {}).items():
role_payload = normalized.setdefault(role, {})
for prerequisites in role_adjustment.get("add", {}).values():
for prereq in prerequisites:
role_payload[canonical_permission_key(prereq)] = True
for dependents in role_adjustment.get("remove", {}).values():
for dependent in dependents:
role_payload[canonical_permission_key(dependent)] = False
return normalized
async def role_has_api_permission(
db: AsyncSession,
study_id: uuid.UUID,
@@ -150,21 +278,58 @@ async def get_api_endpoint_permissions(
return matrix
async def get_effective_api_endpoint_permissions(
db: AsyncSession,
study_id: uuid.UUID,
) -> dict[str, dict[str, dict[str, bool]]]:
"""获取考虑前置权限后的有效权限矩阵。"""
matrix = await get_api_endpoint_permissions(db, study_id)
effective: dict[str, dict[str, dict[str, bool]]] = {}
for role, endpoints in matrix.items():
effective[role] = {}
for endpoint_key in endpoints.keys():
effective[role][endpoint_key] = {
"allowed": await role_has_api_permission(
db,
study_id,
role,
endpoint_key,
check_prerequisites=True,
)
}
return effective
async def replace_api_endpoint_permissions(
db: AsyncSession,
study_id: uuid.UUID,
payload: dict[str, dict[str, bool]],
*,
confirm_prerequisite_adjustments: bool = False,
) -> dict[str, dict[str, dict[str, bool]]]:
"""更新 payload 中指定的角色权限项。未提交的权限项保持不变。
ADMIN 与 PM 权限不会被持久化:ADMIN 始终拥有全部权限,PM 默认拥有
全部项目权限,应当通过专门的渠道而不是项目权限矩阵调整。
"""
for role, endpoints in payload.items():
normalized_payload = _canonicalize_payload(payload)
adjustments = await preview_api_permission_prerequisite_adjustments(
db,
study_id,
normalized_payload,
)
if adjustments["requires_confirmation"]:
if not confirm_prerequisite_adjustments:
raise PrerequisitePermissionConfirmationRequired(adjustments)
normalized_payload = apply_prerequisite_adjustments_to_payload(
normalized_payload,
adjustments,
)
for role, endpoints in normalized_payload.items():
if role in ("ADMIN", "PM"):
continue
for endpoint_key, allowed in endpoints.items():
endpoint_key = canonical_permission_key(endpoint_key)
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
continue
result = await db.execute(