"""数据权限引擎。 需求是"同一个人,在项目列表看全公司、在结算列表只看本部门、在预算列表看本部门及下级 但把大额项目藏掉"。所以不能只在角色上挂一个 scope 字段,要做成可组合的策略: 求值顺序 ======== 1. **粗筛主体**:命中"全部人 / 我的任一角色 / 我本人 / 我任一部门 / 我任一岗位"的策略; 2. **allow 之间取并集**:每条 = ``范围谓词 AND 自定义条件``,多条 OR; 3. **deny 取并集后整体排除**:``AND NOT (deny1 OR deny2 ...)``; 4. **一条 allow 都没命中**时退回兜底范围 ``self``,不把人锁死; 5. 系统管理员直接返回"不加限制"。 范围谓词怎么落到列上,由 :class:`ModuleSpec` 声明,模块注册一次就够,业务查询只要 ``session.query(...).where(*scope_conditions)``,看不到任何权限细节。 自定义条件用 JSON 条件树而不是拼 SQL 字符串:字段名要过白名单,值走绑定参数, 这样"自定义"不会变成注入入口。 """ from __future__ import annotations import json from dataclasses import dataclass, field from typing import Any, Callable from sqlalchemy import and_, false, or_, select, true from sqlalchemy.orm import Session from ..models import ( FALLBACK_SCOPE, Account, AccountIdentity, Effect, OrgUnit, PermDataPolicy, Project, ProjectMember, ScopeType, ) from . import permissions @dataclass class ModuleSpec: """一个业务模块怎么接数据权限。""" module: str label: str entity: Any org_column: str = "org_unit_id" # 数据归属部门列 owner_column: str = "creator_id" # 数据归属人列 # 口径组的族代表:留空表示这个模块自己就是一个口径。概算/预算/结算/决算填 "project", # 意思是"这一族共用挂在 project 上的那条策略",见 :func:`_policies_for_module`。 family: str = "" # 需要 join 才能判定的范围(如"我参与的"),返回一个 EXISTS 子句 participant_predicate: Callable[[int], Any] | None = None # 允许出现在自定义条件里的字段白名单:对外的名字 -> 实体属性 filterable: dict[str, str] = field(default_factory=dict) # 金额类字段,条件里按数值比 numeric: tuple[str, ...] = () #: 字段名 -> 操作符 -> 生成 SQL 表达式 OPERATORS = { "eq": lambda column, value: column == value, "ne": lambda column, value: column != value, "gt": lambda column, value: column > value, "gte": lambda column, value: column >= value, "lt": lambda column, value: column < value, "lte": lambda column, value: column <= value, "in": lambda column, value: column.in_(value if isinstance(value, (list, tuple)) else [value]), "not_in": lambda column, value: column.not_in(value if isinstance(value, (list, tuple)) else [value]), "contains": lambda column, value: column.like(f"%{value}%"), "not_contains": lambda column, value: ~column.like(f"%{value}%"), "is_null": lambda column, value: column.is_(None), "is_not_null": lambda column, value: column.isnot(None), } #: 条件树里的动态变量,运行期换成当前人的上下文 DYNAMIC_VALUES = ("$account_id", "$org_unit_ids", "$org_unit_ids_with_children", "$account_name") _REGISTRY: dict[str, ModuleSpec] = {} def register(spec: ModuleSpec) -> ModuleSpec: _REGISTRY[spec.module] = spec return spec def spec_for(module: str) -> ModuleSpec | None: return _REGISTRY.get(module) def registered_modules() -> list[dict[str, str]]: return [{"module": item.module, "label": item.label, "family": item.family} for item in _REGISTRY.values()] def policy_covers(module: str) -> list[str]: """在 ``module`` 上配一条策略,实际管到哪几个模块。 族代表上的策略是整族的默认口径;成员模块上配的策略只管它自己。界面靠这句话说明 一条策略的作用面,省得管理员以为"超级管理员 - budget"只管预算那一页。 """ spec = spec_for(module) if spec is None or (spec.family and spec.family != module): return [module] return [item.module for item in _REGISTRY.values() if item.module == module or item.family == module] # --------------------------------------------------------------------------- # 模块注册 # --------------------------------------------------------------------------- def _project_participant(account_id: int): """EXISTS (SELECT 1 FROM project_member ...):数据权限的"我参与的"。""" return ( select(ProjectMember.id) .where(ProjectMember.project_id == Project.id, ProjectMember.account_id == account_id) .exists() ) #: 项目这一族(项目列表 + 概算/预算/结算/决算)查的是同一张 Project 表、同一套归属列, #: 条件白名单也必须是同一份。白名单不一致时族策略会出事:在 project 上写好的条件换到 #: 预算那一侧,会因为字段不在白名单里被 :func:`_condition_tree` 静默丢掉,于是同一条策略 #: 在项目列表收着、在预算列表放开——那是最没人查得出来的放宽。 _PROJECT_FILTERABLE = { "name": "name", "project_no": "project_no", "type": "type", "stage": "stage", "customer": "customer", "org_unit_id": "org_unit_id", "creator_id": "creator_id", "principal_id": "principal_id", "underwritten_mode": "underwritten_mode", "contract_amount": "contract_amount", "contribution_profit_rate": "contribution_profit_rate", "created_at": "created_at", } _PROJECT_NUMERIC = ("contract_amount", "contribution_profit_rate", "gross_profit") register(ModuleSpec( module="project", label="项目列表", entity=Project, org_column="org_unit_id", owner_column="creator_id", participant_predicate=_project_participant, filterable=dict(_PROJECT_FILTERABLE), numeric=_PROJECT_NUMERIC, )) # 概算/预算/结算/决算都挂在项目上,数据权限直接沿用项目那套归属: # 能看到项目,才能看到它下面的各版本。这样不会出现"列表看得见、详情 403"。 # 口径既然相同,这四个成员模块就不需要各自一条策略:族策略管的就是它们。从前那种 # "每个模块种一条一模一样的"只会长出三五条重复授权,还会种漏——内置角色"公司领导" # 就漏了预算那条,他一进预算列表直接掉进 self 兜底。 for _alias, _label in (("estimate", "项目立项(概算)"), ("budget", "项目预算"), ("settlement", "月度结算"), ("final", "项目决算")): register(ModuleSpec( module=_alias, label=_label, entity=Project, org_column="org_unit_id", owner_column="creator_id", participant_predicate=_project_participant, family="project", filterable=dict(_PROJECT_FILTERABLE), numeric=_PROJECT_NUMERIC, )) # --------------------------------------------------------------------------- # 上下文 # --------------------------------------------------------------------------- @dataclass class ScopeContext: account: Account role_ids: list[int] org_unit_ids: list[int] # 本人全部身份所在部门 position_ids: list[int] primary_org_id: int | None org_unit_ids_with_children: list[int] = field(default_factory=list) _db: Any = None # 供条件树里展开部门下级用,不参与序列化 def build_scope_context(db: Session, account: Account) -> ScopeContext: identities = db.execute( select(AccountIdentity).where(AccountIdentity.account_id == account.id) ).scalars().all() org_ids = sorted({row.org_unit_id for row in identities}) or ([account.org_unit_id] if account.org_unit_id else []) position_ids = sorted({row.position_id for row in identities if row.position_id}) if account.position_id and account.position_id not in position_ids: position_ids.append(account.position_id) primary = account.org_unit_id if identities: default_row = next((row for row in identities if row.is_default), identities[0]) primary = primary or default_row.org_unit_id return ScopeContext( account=account, role_ids=[role.id for role in permissions.account_roles(db, account.id)], org_unit_ids=org_ids, position_ids=position_ids, primary_org_id=primary, org_unit_ids_with_children=descendant_unit_ids(db, org_ids), ) def _context_with_db(db: Session, context: ScopeContext) -> ScopeContext: context._db = db return context def _descendant_prefix(unit: OrgUnit) -> str: """把部门路径收成"能安全当 LIKE 前缀"的形状:一定以 ``/`` 开头、也以 ``/`` 结尾。 两个真实的坑,都朝越权那边倒: * ``org_unit.path`` 的列默认值是 ``"/"``(脚本直插、没跑过路径重算的部门就是这个值), 拿它当前缀等于 ``LIKE '/%'``,整棵组织树都算"我的下级",本部门及下级当场变成全部数据; * 少写结尾斜杠的路径(``/1/2``)会把同级的 ``20/21/…29`` 一起前缀匹配进来。 所以宁可按 ``/{id}/`` 兜底:宁可少给几部门,不能多给一整棵树。 """ path = (unit.path or "").strip().rstrip("/") return f"{path}/" if path and path != "/" else f"/{unit.id}/" def descendant_unit_ids(db: Session, unit_ids: list[int]) -> list[int]: """按 ``org_unit.path`` 前缀匹配取自身 + 全部下级。 用 path 前缀而不是递归 CTE:组织树很深时递归查询每页都要跑一遍,前缀索引一次扫完。 """ if not unit_ids: return [] units = db.execute(select(OrgUnit).where(OrgUnit.id.in_(unit_ids))).scalars().all() prefixes = [_descendant_prefix(unit) for unit in units] rows = db.execute( select(OrgUnit.id).where( or_(OrgUnit.id.in_(unit_ids), *[OrgUnit.path.like(f"{prefix}%") for prefix in prefixes]) ) ).scalars().all() return sorted(set(rows)) # --------------------------------------------------------------------------- # 谓词构造 # --------------------------------------------------------------------------- class ScopeDecision: """一次数据权限求值的结果,带人类可读的说明,界面上要能告诉用户"你为什么看不到"。""" def __init__(self, condition: Any, summary: list[str], *, unlimited: bool = False) -> None: self.condition = condition self.summary = summary self.unlimited = unlimited def apply_to(self, query: Any) -> Any: return query if self.unlimited or self.condition is None else query.where(self.condition) def describe(self) -> str: return ";".join(self.summary) if self.summary else "全部数据" def to_dict(self) -> dict[str, Any]: return {"unlimited": self.unlimited, "description": self.describe()} def evaluate(db: Session, module: str, context: ScopeContext) -> ScopeDecision: _context_with_db(db, context) spec = spec_for(module) if spec is None: # 没注册的模块一律不给看,而不是放行——漏注册应当是个 bug,不能变成越权 return ScopeDecision(false(), [f"模块 {module} 未登记数据权限,默认拒绝"]) if context.account.is_system_admin: return ScopeDecision(None, [], unlimited=True) policies = permissions.data_policies_for( db, context.account.id, context.role_ids, context.org_unit_ids, context.position_ids ) module_policies, inherited = _policies_for_module(policies, spec, module) allows: list[Any] = [] denies: list[Any] = [] summary: list[str] = [] if inherited: summary.append(f"沿用「{spec_for(spec.family).label}」的口径") for policy in module_policies: condition = _policy_condition(db, spec, policy, context) if condition is None: continue if policy.effect == Effect.DENY: denies.append(condition) summary.append(f"排除:{policy.name}") else: allows.append(condition) summary.append(f"{policy.name}({ScopeType.label(policy.scope_type)})") entity = spec.entity if any(_is_unlimited(item) for item in module_policies if item.effect == Effect.ALLOW): # 有"全部数据"的 allow 且没有任何 deny 时,等价于不加限制 if not denies: return ScopeDecision(None, summary, unlimited=True) if not allows: fallback = _scope_predicate(None, spec, FALLBACK_SCOPE, [], context, entity) condition = fallback if fallback is not None else false() summary.append(f"未配置生效策略,按默认范围「{ScopeType.label(FALLBACK_SCOPE)}」") else: condition = allows[0] if len(allows) == 1 else or_(*allows) if denies: condition = and_(condition, ~or_(*denies)) if condition is not None else ~or_(*denies) if condition is None: return ScopeDecision(None, summary, unlimited=True) return ScopeDecision(condition, summary) def _policies_for_module(policies: list[PermDataPolicy], spec: ModuleSpec, module: str) -> tuple[list[PermDataPolicy], bool]: """这次查询该用哪几条策略,返回 ``(策略, 是否沿用族口径)``。 规则只有一句:**本模块的专属策略优先,一条都没有才回落到族策略**。是"优先"不是 "并集"——项目上配了全部数据、预算想收窄成本部门,单独配一条预算策略就得真的收窄, 不能被项目那条族策略又撑回去。族内各模块的归属列与条件白名单完全一致,同一条族策略 在族内任何模块上编译出来的谓词都一样。 """ own = [item for item in policies if item.module == module and _in_valid_window(item)] if own or not spec.family or spec.family == module: return own, False inherited = [item for item in policies if item.module == spec.family and _in_valid_window(item)] return inherited, bool(inherited) def _is_unlimited(policy: PermDataPolicy) -> bool: return policy.scope_type == ScopeType.ALL and not (policy.conditions_json or "").strip() def _in_valid_window(policy: PermDataPolicy) -> bool: from datetime import date today = date.today().isoformat() if policy.valid_from and policy.valid_from > today: return False if policy.valid_to and policy.valid_to < today: return False return True def _policy_condition(db: Session | None, spec: ModuleSpec, policy: PermDataPolicy, context: ScopeContext) -> Any: entity = spec.entity target_ids = _json_list(policy.target_ids_json) scope = _scope_predicate(db, spec, policy.scope_type, target_ids, context, entity, include_children=policy.include_children) condition = None if scope is None else true() if scope is not None: condition = scope tree = _json_dict(policy.conditions_json) if tree: node = _condition_tree(spec, tree, context) condition = and_(condition, node) if condition is not None else node if condition is None: # CUSTOM 且没写条件、或 ALL:视为不加范围限制 return None return condition def _scope_predicate( db: Session | None, spec: ModuleSpec, scope_type: str, target_ids: list[int], context: ScopeContext, entity: Any, *, include_children: bool = True, ) -> Any: """把范围类型翻成 SQL。返回 None 表示"这一层不加限制"。""" org_column = getattr(entity, spec.org_column, None) owner_column = getattr(entity, spec.owner_column, None) if scope_type == ScopeType.ALL: return None if scope_type == ScopeType.SELF: return owner_column == context.account.id if scope_type == ScopeType.UNIT: ids = context.org_unit_ids or ([-1]) return org_column.in_(ids) if scope_type == ScopeType.UNIT_AND_BELOW: ids = context.org_unit_ids_with_children or [-1] return org_column.in_(ids) if scope_type == ScopeType.IDENTITY_UNITS: return org_column.in_(context.org_unit_ids or [-1]) if scope_type == ScopeType.ORG_LIST: ids = target_ids if include_children and db is not None: ids = descendant_unit_ids(db, target_ids) return org_column.in_(ids or [-1]) if scope_type == ScopeType.ACCOUNT_LIST: return owner_column.in_(target_ids or [-1]) if scope_type == ScopeType.PARTICIPANT: predicate = spec.participant_predicate(context.account.id) if spec.participant_predicate else None mine = owner_column == context.account.id return or_(mine, predicate) if predicate is not None else mine if scope_type == ScopeType.DEPT_OF_RECORD: ids = context.org_unit_ids_with_children or [-1] return org_column.in_(ids) if scope_type == ScopeType.CUSTOM: return None return owner_column == context.account.id def _condition_tree(spec: ModuleSpec, tree: dict[str, Any], context: ScopeContext) -> Any: op = str(tree.get("op") or "and").lower() if op in ("and", "or"): children = [_condition_tree(spec, item, context) for item in tree.get("items") or []] children = [item for item in children if item is not None] if not children: return None return and_(*children) if op == "and" else or_(*children) field_name = str(tree.get("field") or "") attribute = spec.filterable.get(field_name) if not attribute: # 白名单外的字段直接忽略这一条,不报错也不放宽 return None column = getattr(spec.entity, attribute) operator = str(tree.get("operator") or "eq").lower() builder = OPERATORS.get(operator) if builder is None: return None value = _resolve_value(tree.get("value"), context) if field_name in spec.numeric and isinstance(value, str): try: value = float(value) except ValueError: return None return builder(column, value) def _resolve_value(value: Any, context: ScopeContext) -> Any: if isinstance(value, str) and value in DYNAMIC_VALUES: if value == "$account_id": return context.account.id if value == "$account_name": return context.account.display_name if value == "$org_unit_ids": return context.org_unit_ids or [-1] if value == "$org_unit_ids_with_children": return context.org_unit_ids_with_children or [-1] if isinstance(value, list): return [_resolve_value(item, context) for item in value] return value def _json_list(raw: str) -> list[int]: try: data = json.loads(raw or "[]") except json.JSONDecodeError: return [] return [int(item) for item in data if str(item).strip().isdigit()] def _json_dict(raw: str) -> dict[str, Any]: if not (raw or "").strip(): return {} try: data = json.loads(raw) except json.JSONDecodeError: return {} return data if isinstance(data, dict) else {} def explain(db: Session, module: str, account: Account) -> dict[str, Any]: """给管理界面用:"如果以这个人的身份打开这个模块,会看到什么范围"。""" context = build_scope_context(db, account) return evaluate(db, module, context).to_dict()