unis-oa/backend/app/service/hub_perm.py

754 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""统一身份(Hub)权限对接:角色、权限 code 与数据范围。
对应《Hub 权限接口交互文档》(``permission-integration.md``)。那份文档只给查询:Hub
交出"这个人在这个应用里有哪些权限码、多大数据范围",业务资源与最终的数据过滤仍然
由本系统自己判(文档第 9 节)。这里做三件事:
1. **取**:优先用用户自己的 Hub 令牌问 ``/me/permissions`` 与 ``/me/data-scope``
(文档第 3 节推荐的顺序)。免登进来的用户本系统手上没有令牌,就退一步用服务端凭证
代查 ``/admin/users/{id}/roles`` 与 ``/admin/users/{id}/data-scope``(文档第 7、8 节),
角色对应的权限码另存一份进程内缓存,全员共用一次拉取。
2. **缓存**:按人缓存 ``hub_perm_cache_seconds`` 秒。文档第 3 节说得很直白 —— 业务系统
可以自行缓存,但必须自己负责失效。Hub 取不到时不硬等:照本地权限走,并留一小段
冷却,免得每个请求都去撞一次超时。
3. **用**:``shadow`` 只把 Hub 口径显示出来给管理员对账;``enforce`` 让 Hub 的权限码与
数据范围真的参与判定。两种模式都不改本地权限矩阵,关掉开关立刻回到对接前的行为。
刻意不做的事:不把 Hub 角色写成本地角色(本地角色矩阵是管理员手工维护的资产,
同名角色被覆盖一次就回不来了);不落地存储 Hub 的用户令牌;也不拿没有用户 ``sub``
的服务端令牌去问 ``/me/*`` —— 文档第 1 节说那种令牌问不到用户授权接口。
"""
from __future__ import annotations
import logging
import threading
import time
from dataclasses import dataclass
from typing import Any
from .. import cache
from .. import hubconfig
from .. import permissions as perm
from . import hub as hub_api
logger = logging.getLogger("unisoa.hub.perm")
#: 文档第 6 节:数据范围只配在角色上,多角色取最大,SELF < ORG < ORG_AND_CHILDREN < ALL
HUB_SCOPES = {
"SELF": perm.SCOPE_SELF,
"ORG": perm.SCOPE_UNIT,
"ORG_AND_CHILDREN": perm.SCOPE_UNIT_AND_BELOW,
"ALL": perm.SCOPE_ALL,
}
HUB_SCOPE_LABELS = {
"SELF": "仅本人",
"ORG": "本部门",
"ORG_AND_CHILDREN": "本部门及下级",
"ALL": "全部数据",
}
MODE_SHADOW = "shadow"
MODE_ENFORCE = "enforce"
MODE_LABELS = {
MODE_SHADOW: "只对照,不参与判定",
MODE_ENFORCE: "以统一身份为准",
}
SCOPE_MERGE = "merge"
SCOPE_HUB = "hub"
#: Hub 取不到权限后的冷却(秒):这段时间内直接按本地权限走,不再逐个请求去撞超时
FALLBACK_COOLDOWN_SECONDS = 15
#: 登记到 Hub 权限目录时用的 type(文档第 6 节:api / menu / plugin)。本系统的权限码
#: 既是菜单可见性也是接口准入,统一按 api 登记,Hub 管理端绑角色时看 code 就够用。
REGISTER_TYPE = "api"
#: 共享缓存(Redis)里的三段键名。没配 Redis 时这些字符串只是字符串,一次也不会用到
_SHARED_GRANTS = "hubperm:grant"
_SHARED_ROLES = "hubperm:roles"
_SHARED_COOL = "hubperm:cool"
#: 角色 -> 权限码 那张表在共享缓存里的最短停留(秒),与进程内那份同一条命
ROLES_MIN_TTL_SECONDS = 30.0
@dataclass(frozen=True)
class HubGrant:
"""某个人在本系统这个应用里的有效权限(一次查询的结果)。"""
permissions: tuple[str, ...] = ()
#: 本系统口径的数据范围(self / unit / unit_and_below / all),问不到时为空串
scope: str = ""
#: Hub 原样的取值(SELF / ORG / ORG_AND_CHILDREN / ALL),排障时要看原文
hub_scope: str = ""
roles: tuple[str, ...] = ()
version: int = 0
#: 这次问法:me = 用户自己的令牌;admin = 服务端凭证代查
source: str = ""
fetched_at: float = 0.0
@property
def known(self) -> tuple[str, ...]:
"""只留本系统权限目录里有的 code,顺序按目录走。"""
return tuple(perm.clean_codes(self.permissions))
@property
def unknown(self) -> tuple[str, ...]:
"""Hub 给了但本系统目录里没有的 code:不参与判定,只在界面上提醒去补登记。"""
return tuple(code for code in self.permissions if not perm.is_known(code))
@property
def scope_label(self) -> str:
return HUB_SCOPE_LABELS.get(self.hub_scope, self.hub_scope or "无")
def enabled() -> bool:
"""这一层现在生效吗(应急总闸、Hub 开关、这一项自己的开关,三个都开才算开)。"""
return hubconfig.get().perm_on
def application_id() -> str:
"""问 Hub 要哪个应用的权限(文档第 6 节的 ``application_id``)。"""
cfg = hubconfig.get()
return (cfg.hub_perm_application_id or cfg.hub_app_code or "oa").strip()
def _ttl() -> float:
return float(max(0, hubconfig.get().hub_perm_cache_seconds))
# ---------------------------------------------------------------------------
# 缓存:按人一份有效权限,另加一张"角色 -> 权限码"的全局表
# ---------------------------------------------------------------------------
_lock = threading.Lock()
#: person_id -> (过期时刻, 结果)
_grants: dict[str, tuple[float, HubGrant]] = {}
#: person_id -> 冷却到什么时候(Hub 取不到、这段时间按本地权限走)
_cooldown: dict[str, float] = {}
#: (应用编码, permission_version) -> {role_id: (code, ...)},全员共用
_role_codes: dict[tuple[str, int], dict[str, tuple[str, ...]]] = {}
_role_codes_expiry = 0.0
def clear_cache() -> None:
"""界面上改过 Hub 配置之后调一下:应用编码、口径都可能跟着变了。"""
global _role_codes_expiry
with _lock:
_grants.clear()
_cooldown.clear()
_role_codes.clear()
_role_codes_expiry = 0.0
_drop_shared()
cache.publish(cache.TOPIC_HUB_PERM, "clear")
def _drop_shared() -> None:
"""共享缓存里那三段一起清掉(Hub 地址、应用编码、口径都可能跟着配置变了)。"""
for namespace in (_SHARED_GRANTS, _SHARED_ROLES, _SHARED_COOL):
cache.delete_prefix(cache.key(namespace))
def _clear_local(_payload: Any = None) -> None:
"""收到"别的进程改了 Hub 配置"之后的本地清理。幂等:自己发的那条也会收到。"""
global _role_codes_expiry
with _lock:
_grants.clear()
_cooldown.clear()
_role_codes.clear()
_role_codes_expiry = 0.0
def _grant_payload(grant: HubGrant) -> dict:
return {
"permissions": list(grant.permissions), "scope": grant.scope, "hub_scope": grant.hub_scope,
"roles": list(grant.roles), "version": int(grant.version), "source": grant.source,
"fetched_at": float(grant.fetched_at),
}
def _grant_of(payload: dict) -> HubGrant:
return HubGrant(
permissions=tuple(str(code) for code in payload.get("permissions") or ()),
scope=str(payload.get("scope") or ""), hub_scope=str(payload.get("hub_scope") or ""),
roles=tuple(str(name) for name in payload.get("roles") or ()),
version=int(payload.get("version") or 0), source=str(payload.get("source") or ""),
fetched_at=float(payload.get("fetched_at") or 0.0),
)
def cached(person_id: Any) -> HubGrant | None:
"""只回还没过期的那一份;这一步保证不碰网络(共享缓存算网络之外的另一半内存)。
先翻本进程那份,再翻共享那份:另一个副本刚问过的权限,本副本不必再问 Hub 一次。
"""
key = str(person_id or "")
if not key:
return None
with _lock:
slot = _grants.get(key)
if slot:
expires_at, grant = slot
if expires_at > time.monotonic():
return grant
shared = cache.get_json(cache.key(_SHARED_GRANTS, key))
if isinstance(shared, dict):
grant = _grant_of(shared)
with _lock:
_grants[key] = (time.monotonic() + _ttl(), grant)
return grant
return None
def _store(person_id: Any, grant: HubGrant) -> None:
key = str(person_id or "")
if not key:
return
ttl = _ttl()
with _lock:
_grants[key] = (time.monotonic() + ttl, grant)
_cooldown.pop(key, None)
if ttl > 0:
cache.set_json(cache.key(_SHARED_GRANTS, key), _grant_payload(grant), ttl)
cache.delete(cache.key(_SHARED_COOL, key))
def _cooling(person_id: Any) -> bool:
key = str(person_id or "")
with _lock:
until = _cooldown.get(key, 0.0)
if until > time.monotonic():
return True
with _lock:
_cooldown.pop(key, None)
if cache.get(cache.key(_SHARED_COOL, key)):
# 别的副本正在冷却 = Hub 这会儿多半还不通,本副本就别再去撞一次超时了
return True
return False
def _cool(person_id: Any) -> None:
key = str(person_id or "")
if not key:
return
with _lock:
_cooldown[key] = time.monotonic() + FALLBACK_COOLDOWN_SECONDS
cache.set_value(cache.key(_SHARED_COOL, key), "1", FALLBACK_COOLDOWN_SECONDS)
# ---------------------------------------------------------------------------
# 取
# ---------------------------------------------------------------------------
def _scope_pair(raw: Any) -> tuple[str, str]:
"""Hub 的数据范围取值 -> ``(本地口径, 原样取值)``;认不出来的原样带回。"""
value = str(raw or "").strip().upper()
return (HUB_SCOPES.get(value, ""), value)
def _role_rows(payload: Any) -> list[dict[str, Any]]:
"""/me/roles 与 /admin/users/{id}/roles 的下发形状不太一样,这里一次抹平。"""
if isinstance(payload, list):
return [row for row in payload if isinstance(row, dict)]
if isinstance(payload, dict):
rows = payload.get("roles") or payload.get("items") or payload.get("data")
if isinstance(rows, list):
return [row for row in rows if isinstance(row, dict)]
return []
def _role_names(rows: list[dict[str, Any]]) -> tuple[str, ...]:
names: list[str] = []
for row in rows:
if str(row.get("status") or "1") != "1":
continue
name = str(row.get("name") or row.get("code") or "").strip()
if name and name not in names:
names.append(name)
return tuple(names)
def _codes_of_permissions(rows: list[dict[str, Any]], app_id: str) -> tuple[str, ...]:
"""只留归属本应用的启用权限项(目录里 application_id + type + code 才是唯一键)。"""
wanted = app_id.strip().lower()
codes: list[str] = []
for row in rows:
if str(row.get("status") or "1") != "1":
continue
belong = str(row.get("application_id") or "").strip().lower()
if belong and belong != wanted:
continue
code = str(row.get("code") or "").strip()
if code and code not in codes:
codes.append(code)
return tuple(codes)
def _permission_rows(payload: Any) -> list[dict[str, Any]]:
if isinstance(payload, list):
return [row for row in payload if isinstance(row, dict)]
if isinstance(payload, dict):
rows = payload.get("permissions") or payload.get("items") or payload.get("data")
if isinstance(rows, list):
return [row for row in rows if isinstance(row, dict)]
return []
def _version_of(payload: Any) -> int:
if isinstance(payload, dict):
try:
return int(payload.get("permission_version") or 0)
except (TypeError, ValueError):
return 0
return 0
def _role_code_map(hub_client: hub_api.HubClient, token: str, app_id: str) -> dict[str, tuple[str, ...]]:
"""Hub 角色 -> 本应用的权限码。全员共用一张表,按版本与缓存时间换。"""
global _role_codes_expiry
now = time.monotonic()
with _lock:
if _role_codes_expiry > now:
for key, table in _role_codes.items():
if key[0] == app_id:
return table
shared_key = cache.key(_SHARED_ROLES, app_id)
shared = cache.get_json(shared_key)
if isinstance(shared, dict) and isinstance(shared.get("table"), dict):
# 别的副本已经拉过这张表了(一次 admin/roles + 每个角色一次 permissions,
# 角色多的时候是十几跳),本副本直接接手
table = {str(role_id): tuple(codes) for role_id, codes in shared["table"].items()}
with _lock:
_role_codes[(app_id, int(shared.get("version") or 0))] = table
_role_codes_expiry = now + max(ROLES_MIN_TTL_SECONDS, _ttl())
return table
roles_payload = hub_client.admin_roles(token)
version = _version_of(roles_payload)
table: dict[str, tuple[str, ...]] = {}
for row in _role_rows(roles_payload):
role_id = str(row.get("role_id") or row.get("id") or "").strip()
if not role_id or str(row.get("status") or "1") != "1":
continue
table[role_id] = _codes_of_permissions(_permission_rows(hub_client.admin_role_permissions(token, role_id)), app_id)
with _lock:
_role_codes.clear()
_role_codes[(app_id, version)] = table
# 与人的缓存同一条命:过期就整体重拉。版本没变时这步也就两三跳
_role_codes_expiry = now + max(ROLES_MIN_TTL_SECONDS, _ttl())
cache.set_json(shared_key, {"version": int(version),
"table": {role_id: list(codes) for role_id, codes in table.items()}},
max(ROLES_MIN_TTL_SECONDS, _ttl()))
return table
cache.watch(cache.TOPIC_HUB_PERM, _clear_local)
def _via_user(hub_client: hub_api.HubClient, token: str, app_id: str) -> HubGrant:
"""文档第 3 节推荐的问法:拿用户自己的令牌问 me/*。"""
permissions = hub_client.me_permissions(token, app_id)
scope = hub_client.me_data_scope(token)
roles = hub_client.me_roles(token)
local, normalized = _scope_pair(scope.get("data_scope") if isinstance(scope, dict) else "")
return HubGrant(
permissions=_codes_of_permissions(_permission_rows(permissions), app_id),
scope=local,
hub_scope=normalized,
roles=_role_names(_role_rows(roles)),
version=_version_of(permissions) or _version_of(scope),
source="me",
)
def _via_admin(hub_client: hub_api.HubClient, token: str, app_id: str, hub_user_id: int) -> HubGrant:
"""服务端代查:管理员接口按用户问角色与数据范围(文档第 7、8 节)。"""
roles = _role_rows(hub_client.admin_user_roles(token, hub_user_id))
scope = hub_client.admin_user_data_scope(token, hub_user_id)
table = _role_code_map(hub_client, token, app_id)
codes: list[str] = []
for row in roles:
if str(row.get("status") or "1") != "1":
continue
for code in table.get(str(row.get("role_id") or row.get("id") or "")) or ():
if code not in codes:
codes.append(code)
local, normalized = _scope_pair(scope.get("data_scope") if isinstance(scope, dict) else "")
return HubGrant(
permissions=tuple(codes),
scope=local,
hub_scope=normalized,
roles=_role_names(roles),
version=_version_of(scope),
source="admin",
)
def fetch(person: Any, hub_token: str = "") -> HubGrant:
"""问一次 Hub:这个人有哪些权限、多大数据范围。失败抛 :class:`hub_api.HubError`。"""
cfg = hubconfig.get()
app_id = application_id()
hub_client = hub_api.client()
if hub_token:
return _via_user(hub_client, hub_token, app_id)
if not cfg.hub_perm_admin_query:
raise hub_api.HubError(
"这次登录没有可用的统一身份令牌,且没开「没有用户令牌时由服务端代查」",
retryable=False,
)
try:
hub_user_id = int(getattr(person, "hub_user_id", None) or 0)
except (TypeError, ValueError):
hub_user_id = 0
if not hub_user_id:
raise hub_api.HubError("这个账号没有绑定统一身份用户,代查不到权限", retryable=False)
return _via_admin(hub_client, hub_api.service_token(), app_id, hub_user_id)
def grant(person: Any, hub_token: str = "", *, force: bool = False) -> HubGrant | None:
"""这个人当前的有效权限;取不到回 ``None``(调用方按本地权限走)。
这是给每次请求用的热路径:命中缓存时只有一次字典查找,不碰网络。
"""
person_id = getattr(person, "id", person)
if not enabled() or person_id is None:
return None
if not force:
hit = cached(person_id)
if hit is not None:
return hit
if not hub_token and _cooling(person_id):
return None
try:
result = fetch(person, hub_token)
except hub_api.HubError as exc:
_cool(person_id)
logger.info("统一身份权限取不到(%s),本次按本地权限走:%s", person_id, exc.message)
return None
_store(person_id, result)
return result
# ---------------------------------------------------------------------------
# 用
# ---------------------------------------------------------------------------
def merge_scope(local: str, other: str) -> str:
"""两个口径取最宽的一档,只用于展示;生效范围由 CurrentUser.apply_scope 合并。
Hub 只会给 ``self`` / ``unit`` / ``unit_and_below`` / ``all``,本系统的 ``custom``
只能来自本地角色,所以这里永远比不出"自定义比部门宽"这种结论——真要合并部门
集合得走 ``permissions.merge_grant``。
"""
rank = {scope: index for index, scope in enumerate(perm.SCOPES)}
return other if rank.get(other, -1) > rank.get(local, -1) else local
def overlay(user: Any, result: HubGrant | None) -> dict[str, Any]:
"""按配置口径把 Hub 权限合进当前用户,并回一句"这次到底改了没有"。
两条不动手的情况:``shadow`` 模式(只对照)、以及本地管理员(内置超管与应急账号
是 Hub 配错时唯一还能进门的那条路,任何时候都不被外部系统降级)。
"""
cfg = hubconfig.get()
if result is None:
return {"applied": False, "reason": "没问到统一身份权限,按本地权限生效"}
if cfg.hub_perm_mode != MODE_ENFORCE:
return {"applied": False, "reason": "当前是对照模式,统一身份权限只展示不参与判定"}
if user.is_admin:
return {"applied": False, "reason": "本地管理员不受统一身份权限降级"}
codes = result.known
if not codes and cfg.hub_perm_keep_local:
return {"applied": False, "reason": "统一身份没给出本系统可用的权限码,保留本地权限"}
user.permissions = codes
if result.scope:
# 合并模式是"两边的部门都能看",以统一身份为准是整份覆盖(本地自定义部门作废)
user.apply_scope(result.scope, union=cfg.hub_perm_scope_mode != SCOPE_HUB)
if perm.ALL in codes:
user.apply_scope(perm.SCOPE_ALL, union=False)
return {"applied": True, "reason": "权限与数据范围以统一身份为准"}
def resolve_for(user: Any) -> dict[str, Any]:
"""每次构建当前用户时问一次:取缓存里的 Hub 口径,按配置合进判定,回一份展示用的口径。
热路径上只有一次字典查找 —— 真正的网络调用发生在登录时(:func:`prime_on_login`)、
缓存过期后的那一次,以及界面上点「从统一身份刷新」。关掉这一层时更便宜:
一个布尔判断就返回。
"""
cfg = hubconfig.get()
if not cfg.hub_perm_enabled:
return {}
person = getattr(user, "person", None)
if person is None:
return view(user.data_scope, None, applied=False, reason="没有本地人员档案")
result = grant(person)
outcome = overlay(user, result)
return view(user.data_scope, result, applied=outcome["applied"], reason=outcome["reason"])
def prime_on_login(person: Any, hub_token: str = "") -> HubGrant | None:
"""登录后先把这个人在 Hub 上的权限取回来放好,之后每次请求就只读缓存。
只有 Hub 口令登录那条路拿得到用户自己的令牌(文档第 3 节推荐先问 ``/me/*``);
免登与本地应急登录没有令牌,按配置决定要不要用服务端凭证代查。
"""
if not enabled():
return None
return grant(person, hub_token)
def view(user_scope: str, result: HubGrant | None, *, applied: bool = False, reason: str = "") -> dict[str, Any]:
"""统一身份权限口径的出参:界面上的「来源」标签与对账表都读这一份。"""
cfg = hubconfig.get()
payload: dict[str, Any] = {
"enabled": bool(cfg.hub_perm_enabled),
"active": cfg.perm_on,
"mode": cfg.hub_perm_mode,
"mode_label": MODE_LABELS.get(cfg.hub_perm_mode, cfg.hub_perm_mode),
"application_id": application_id(),
"scope_mode": cfg.hub_perm_scope_mode,
"local_scope": user_scope,
"applied": bool(applied),
"reason": reason,
"source": "",
"permissions": [],
"unknown": [],
"roles": [],
"hub_scope": "",
"hub_scope_label": "",
"permission_version": 0,
}
if result is None:
return payload
return {
**payload,
"source": result.source,
"permissions": list(result.known),
"unknown": list(result.unknown),
"roles": list(result.roles),
"hub_permissions": list(result.permissions),
"hub_scope": result.hub_scope,
"hub_scope_label": result.scope_label,
"hub_data_scope": result.scope,
"permission_version": result.version,
}
def refresh(person: Any, hub_token: str = "") -> tuple[HubGrant | None, str]:
"""强制重取某个人的权限(界面上的「从统一身份刷新」)。回 ``(结果, 为什么没取到)``。
与 :func:`grant` 的区别只在这儿要把失败原因原样交给界面:热路径上"回退本地权限"
是对的,但管理员点一下刷新时得知道到底是被拒还是连不上。
"""
try:
result = fetch(person, hub_token)
except hub_api.HubError as exc:
_cool(person_id_of(person))
return None, exc.message
_store(person_id_of(person), result)
return result, ""
def person_id_of(person: Any) -> str:
return str(getattr(person, "id", person) or "")
# ---------------------------------------------------------------------------
# 目录对账与登记(文档第 8 节:业务系统登记权限,管理员再绑角色)
# ---------------------------------------------------------------------------
def catalog_view() -> dict[str, Any]:
"""本系统权限目录 vs Hub 上这个应用的权限目录,差在哪一眼看清。"""
cfg = hubconfig.get()
app_id = application_id()
local = [item.code for item in perm.CATALOG]
payload: dict[str, Any] = {
"application_id": app_id,
"enabled": bool(cfg.hub_perm_enabled),
"local_total": len(local),
"hub_total": 0,
"missing": [],
"extra": [],
"error": "",
}
try:
rows = _permission_rows(hub_api.client().admin_permissions(hub_api.service_token(), app_id))
except hub_api.HubError as exc:
payload["error"] = exc.message
return payload
hub_codes = [str(row.get("code") or "").strip() for row in rows]
hub_codes = [code for code in hub_codes if code]
payload["hub_total"] = len(hub_codes)
payload["missing"] = [code for code in local if code not in hub_codes]
payload["extra"] = [code for code in hub_codes if code not in perm.CODES]
return payload
def register_missing() -> dict[str, Any]:
"""把本系统有、Hub 上还没有的权限码登记进去(文档第 8 节,重复提交是幂等成功)。
需要服务端凭证是 Hub 的管理员:普通集成账号调 ``POST /admin/permissions`` 会被拒。
"""
app_id = application_id()
view_data = catalog_view()
if view_data.get("error"):
raise hub_api.HubError(str(view_data["error"]))
token = hub_api.service_token()
hub_client = hub_api.client()
# 本系统目录里只有 code 与分组,展示名在前端语言包那儿;登记时就把 code 当名字,
# Hub 管理端看着陌生可以改(文档第 8 节:展示名称可编辑,code 一旦用了别再改)
labels = {item.code: item.code for item in perm.CATALOG}
created: list[str] = []
failed: list[str] = []
for code in view_data.get("missing") or []:
try:
hub_client.register_permission(token, application_id=app_id, type_=REGISTER_TYPE, code=code,
name=labels.get(code, code))
created.append(code)
except hub_api.HubError:
failed.append(code)
clear_cache()
return {
"application_id": app_id,
"created": created,
"failed": failed,
"recheck": catalog_view(),
"message": (
f"已登记 {len(created)} 项" + (f",{len(failed)} 项被拒(多半是集成账号不是 Hub 管理员)" if failed else "")
if created or failed
else "本系统权限目录已全部登记在 Hub 上"
),
}
# ---------------------------------------------------------------------------
# 连通性自检(挂在 hub_sync.probe 后面)
# ---------------------------------------------------------------------------
def probe_steps(hub_token: str = "") -> list[dict[str, Any]]:
"""权限这一层逐项体检:角色/权限/数据范围问不问得到,目录对得上对不上。
判"不合格"只发生在 enforce 模式 —— 那时候问不到权限就是真出事。对照模式下这些
步骤一律只报问题不判死:Hub 侧还没登记权限、集成账号不是 Hub 管理员,都不该让
整次自检红一片。
"""
cfg = hubconfig.get()
strict = cfg.hub_perm_mode == MODE_ENFORCE
if not cfg.hub_perm_enabled:
return [
{
"name": "统一身份权限",
"ok": True,
"detail": "未启用(权限与数据范围按本系统自己的角色矩阵),跳过",
}
]
app_id = application_id()
hub_client = hub_api.client()
steps: list[dict[str, Any]] = []
try:
if hub_token:
result = _via_user(hub_client, hub_token, app_id)
asked = f"用当前用户令牌问 {cfg.hub_perm_path_permissions}"
else:
# 自检这一步问的是"Hub 这一层通不通",不是某个人的权限,所以问角色目录
asked = f"没有用户令牌,改用服务端凭证问 {cfg.hub_perm_path_admin_roles}"
service = hub_api.service_token()
roles = _role_rows(hub_client.admin_roles(service))
table = _role_code_map(hub_client, service, app_id)
result = HubGrant(
permissions=tuple(sorted({code for codes in table.values() for code in codes})),
roles=_role_names(roles),
source="admin",
)
steps.append(
{
"name": f"统一身份角色与权限 {cfg.hub_perm_path_permissions}",
"ok": True,
"detail": (
f"应用 {app_id};{asked};角色 {len(result.roles)} 个,"
f"权限 {len(result.known)} 项,数据范围 {result.scope_label}"
f",permission_version {result.version}"
),
}
)
except hub_api.HubError as exc:
steps.append(
{
"name": f"统一身份角色与权限 {cfg.hub_perm_path_permissions}",
"ok": not strict,
"detail": f"{exc.message}" + ("(生效模式,判定会受影响)" if strict else "(对照模式,不影响判定)"),
}
)
catalog = catalog_view()
if catalog.get("error"):
steps.append(
{
"name": f"权限目录对账 {cfg.hub_perm_path_admin_permissions}",
"ok": not strict,
"detail": str(catalog["error"]) + ("(生效模式)" if strict else "(对照模式,不影响判定)"),
}
)
else:
missing = catalog.get("missing") or []
extra = catalog.get("extra") or []
steps.append(
{
"name": f"权限目录对账 {cfg.hub_perm_path_admin_permissions}",
"ok": True,
"detail": (
f"Hub 上 {catalog['hub_total']} 项,本系统目录 {catalog['local_total']} 项"
+ (f";Hub 缺 {len(missing)} 项(可在「权限对接」里一键登记)" if missing else "")
+ (f";Hub 多 {len(extra)} 项本系统不认" if extra else "")
),
}
)
try:
scoped = hub_client.directory_scoped(hub_api.service_token(), member_limit=1)
steps.append(
{
"name": f"按数据权限导出人员 {cfg.hub_perm_path_directory_scoped}",
"ok": True,
"detail": (
f"可见 {scoped.get('returned_users', 0)} 人(上限内),"
f"permission_version {scoped.get('permission_version', 0)}"
),
}
)
except hub_api.HubError as exc:
# 集成账号没分配组织/角色时文档说就是回 403001,这不是本系统的毛病
steps.append(
{
"name": f"按数据权限导出人员 {cfg.hub_perm_path_directory_scoped}",
"ok": True,
"detail": f"没问到({exc.message});账号未分配组织或数据权限不可用时 Hub 就该这么回",
}
)
return steps
def status_payload() -> dict[str, Any]:
"""``GET /hub/permissions/status`` 的配置段:这一层现在是怎么配的。"""
cfg = hubconfig.get()
return {
"enabled": bool(cfg.hub_perm_enabled),
"active": cfg.perm_on,
"mode": cfg.hub_perm_mode,
"mode_label": MODE_LABELS.get(cfg.hub_perm_mode, cfg.hub_perm_mode),
"application_id": application_id(),
"cache_seconds": cfg.hub_perm_cache_seconds,
"scope_mode": cfg.hub_perm_scope_mode,
"admin_query": bool(cfg.hub_perm_admin_query),
"keep_local": bool(cfg.hub_perm_keep_local),
"enforce": cfg.perm_on and cfg.hub_perm_mode == MODE_ENFORCE,
"api_paths": cfg.perm_api_paths,
"cache_size": len(_grants),
}