unis-oa/backend/app/hubconfig.py

794 lines
36 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)配置:存在数据库里,界面上保存后立刻生效。
配置项(含每一项的中文说明、取值范围、环境变量名)都登记在 :mod:`app.dbconfig`,
分两组:``config:hub``(登录校验)与 ``config:hub_sync``(组织人员同步)。
取值顺序 ``环境变量 > 数据库 > 配置文件 > 默认值``,对接口径见
``docs/hub-integration.md``。
这里在配置之上只做两件事:
1. **洗值**:地址去掉结尾斜杠、登录模式认不出时回落到 ``hybrid``、时间写错回落到
01:00、数值夹在合法区间里。配置写错不该让整个后端起不来。
2. **应急总闸**:配置项 ``hub_disabled``(或环境变量 ``OA_HUB_DISABLED``)打开时
无视其它所有 Hub 配置,登录与同步一律回本地。Hub 地址写错导致谁都登不进来时,
在服务器上把环境变量一开就能进门;库里的这一项也可以在界面上勾,保存即生效。
密钥(目录密钥、长期 token、集成账号口令)只进不出:状态接口一律不回传,日志里也不写值。
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from . import dbconfig
logger = logging.getLogger("unisoa.hub.config")
#: 应急总闸的环境变量名,状态接口用它解释"为什么配置看着是开的但没走 Hub"
ENV_SWITCH = "OA_HUB_DISABLED"
LOGIN_MODES = ("hub", "hybrid", "sso", "local")
LOGIN_MODE_LABELS = {
"hub": "只认统一身份",
"hybrid": "统一身份优先,服务不可用时回退本地口令",
"sso": "只允许统一门户免登",
"local": "只用品口令,不查统一身份",
}
#: 会拿账号密码去问 Hub 的模式;``sso`` 模式下本系统不再收账号密码,只认门户票据
PASSWORD_LOGIN_MODES = ("hub", "hybrid")
#: 全量同步的排期档位:每天 / 每周挑几天 / 每月挑几天 / 从上一趟算起隔多少分钟
SYNC_MODES = ("daily", "weekly", "monthly", "interval")
SYNC_MODE_LABELS = {
"daily": "每天",
"weekly": "每周选几天",
"monthly": "每月选几天",
"interval": "按间隔",
}
#: 星期几的中文名(配置项里存 1-7,1=周一),界面与排期文案都用它
WEEKDAY_LABELS = {1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日"}
#: 每周这一档一个都没配时的兜底:工作日,与老部署"每天凌晨跑"的意图最接近
WEEKDAY_FALLBACK = (1, 2, 3, 4, 5)
#: 每月这一档一个都没配时的兜底
MONTHDAY_FALLBACK = (1,)
#: 统一身份权限的两种用法:只对照着看,还是真按它判定
PERM_MODES = ("shadow", "enforce")
#: 本地角色与 Hub 各给了一个数据范围时怎么取
PERM_SCOPE_MODES = ("merge", "hub")
#: Hub 接口的出厂路径(文档口径);配置文件里 [hub.api] 可以逐项改
API_PATHS = (
"hub_path_captcha",
"hub_path_login",
"hub_path_verify_token",
"hub_path_me",
"hub_path_directory",
"hub_path_directory_changes",
"hub_path_ticket_verify",
"hub_path_apps",
"hub_path_launch",
)
API_PATH_DEFAULTS = {
"hub_path_captcha": "/auth/captcha",
"hub_path_login": "/auth/login",
"hub_path_verify_token": "/api/v1/auth/token/verify",
"hub_path_me": "/api/v1/auth/me",
"hub_path_directory": "/api/v1/auth/directory",
"hub_path_directory_changes": "/api/v1/auth/directory/changes",
"hub_path_ticket_verify": "/api/v1/auth/tickets/verify",
"hub_path_apps": "/api/v1/auth/apps",
# {code} 在调用时换成本系统的应用编码(hub_app_code)
"hub_path_launch": "/api/v1/auth/apps/{code}/launch",
}
#: 《Hub 权限接口交互文档》那一层的接口路径(第 5~8、11 节)
PERM_API_PATH_DEFAULTS = {
"hub_perm_path_roles": "/api/v1/auth/me/roles",
"hub_perm_path_permissions": "/api/v1/auth/me/permissions",
"hub_perm_path_data_scope": "/api/v1/auth/me/data-scope",
"hub_perm_path_directory_scoped": "/api/v1/auth/directory/scoped",
"hub_perm_path_admin_roles": "/api/v1/auth/admin/roles",
"hub_perm_path_admin_permissions": "/api/v1/auth/admin/permissions",
"hub_perm_path_admin_role_permissions": "/api/v1/auth/admin/roles/{role_id}/permissions",
"hub_perm_path_admin_user_roles": "/api/v1/auth/admin/users/{user_id}/roles",
"hub_perm_path_admin_user_data_scope": "/api/v1/auth/admin/users/{user_id}/data-scope",
}
API_PATH_DEFAULTS.update(PERM_API_PATH_DEFAULTS)
#: 占位符在调用时才填值的两项
PERM_PATH_PLACEHOLDERS = ("hub_perm_path_admin_role_permissions", "hub_perm_path_admin_user_roles",
"hub_perm_path_admin_user_data_scope")
#: 免登跳转路径里的应用编码占位符
LAUNCH_CODE_PLACEHOLDER = "{code}"
#: ``/hub/config`` 管的配置项(Hub 登录 + 同步两组)
MANAGED = tuple(
name
for name in (
"hub_enabled",
"hub_base_url",
*API_PATHS,
*PERM_API_PATH_DEFAULTS,
"hub_login_mode",
"hub_timeout_seconds",
"hub_breaker_seconds",
"hub_max_inflight",
"hub_verify_token",
"hub_auto_provision",
"hub_local_accounts",
"hub_directory_key",
"hub_service_token",
"hub_service_account",
"hub_service_password",
"hub_captcha_auto_solve",
"hub_directory_needs_token",
"hub_password_managed_by_hub",
"hub_sso_enabled",
"hub_app_code",
"hub_integration_key",
"hub_portal_url",
"hub_sso_state_required",
"hub_disabled",
"hub_sync_enabled",
"hub_sync_when",
"hub_sync_time",
"hub_sync_weekdays",
"hub_sync_monthdays",
"hub_sync_interval_minutes",
"hub_sync_orgs",
"hub_sync_bind_local_by_code",
"hub_sync_include_disabled_units",
"hub_sync_offboard",
"hub_sync_skip_unchanged",
"hub_sync_member_limit",
"hub_sync_email_domain",
"hub_sync_protect_admins",
"hub_sync_locked_accounts",
"hub_sync_changes_enabled",
"hub_sync_changes_interval_seconds",
"hub_sync_changes_limit",
"hub_sync_changes_full_on_gap",
"hub_sync_retry_minutes",
"hub_sync_retries",
"hub_perm_enabled",
"hub_perm_mode",
"hub_perm_application_id",
"hub_perm_cache_seconds",
"hub_perm_scope_mode",
"hub_perm_admin_query",
"hub_perm_keep_local",
)
)
GROUP_OF = {
name: (
"hub_perm"
if name.startswith("hub_perm_")
else ("hub_sync" if name.startswith("hub_sync_") else "hub")
)
for name in MANAGED
}
def _clamp(value: int, low: int, high: int, fallback: int) -> int:
try:
number = int(value)
except (TypeError, ValueError):
return fallback
return min(high, max(low, number))
@dataclass(frozen=True)
class HubConfig:
"""当前生效的 Hub 配置,字段名与历史 ``settings.hub_*`` 保持一致。"""
hub_enabled: bool
hub_base_url: str
# 五个接口的路径:Hub 换前缀 / 挂网关时只改配置,不用改代码
hub_path_captcha: str
hub_path_login: str
hub_path_verify_token: str
hub_path_me: str
hub_path_directory: str
# 增量变更流水(GET /api/v1/auth/directory/changes)
hub_path_directory_changes: str
# 免登三件套:票据校验地址 + 应用编码 + 应用密钥(X-Integration-Key)
hub_path_ticket_verify: str
hub_path_apps: str
hub_path_launch: str
hub_sso_enabled: bool
hub_app_code: str
hub_integration_key: str
#: 没登录时把用户送回的统一门户首页;留空回落到 hub_base_url
hub_portal_url: str
hub_sso_state_required: bool
hub_login_mode: str
hub_timeout_seconds: int
#: Hub 失联后的冷却秒数(0 = 关掉熔断这一层),见 ``service/hub.py`` 的 ``_Breaker``
hub_breaker_seconds: int
#: 同时卡在等 Hub 上的请求数上限(0 = 不限制),见 ``service/hub.py`` 的 ``_Inflight``
hub_max_inflight: int
hub_verify_token: bool
hub_auto_provision: bool
hub_local_accounts: str
# 拉全量组织人员的长期密钥:随请求头 X-Directory-Key 走,不换 token
hub_directory_key: str
hub_service_token: str
hub_service_account: str
hub_service_password: str
hub_captcha_auto_solve: bool
hub_directory_needs_token: bool
hub_password_managed_by_hub: bool
hub_sync_enabled: bool
hub_sync_time: str
hub_sync_orgs: bool
# 本地自建部门能不能按组织编码被 Hub 部门认领(认领后交给 Hub 管名称与层级)
hub_sync_bind_local_by_code: bool
hub_sync_include_disabled_units: bool
hub_sync_offboard: bool
hub_sync_skip_unchanged: bool
hub_sync_member_limit: int
hub_sync_email_domain: str
hub_sync_protect_admins: bool
hub_sync_locked_accounts: str
# 增量同步(变更流水轮询)
hub_sync_changes_enabled: bool
hub_sync_changes_interval_seconds: int
hub_sync_changes_limit: int
hub_sync_changes_full_on_gap: bool
hub_sync_retry_minutes: int
hub_sync_retries: int
# ------------------------------------------- 统一身份权限(角色 / 权限码 / 数据范围)
hub_perm_enabled: bool = False
#: shadow = 只对照;enforce = 以 Hub 为准
hub_perm_mode: str = "shadow"
#: 问 Hub 要哪个应用的权限,留空回落到 hub_app_code
hub_perm_application_id: str = ""
hub_perm_cache_seconds: int = 60
#: merge = 本地与 Hub 取较大;hub = 完全照 Hub
hub_perm_scope_mode: str = "merge"
hub_perm_admin_query: bool = True
hub_perm_keep_local: bool = True
hub_perm_path_roles: str = PERM_API_PATH_DEFAULTS["hub_perm_path_roles"]
hub_perm_path_permissions: str = PERM_API_PATH_DEFAULTS["hub_perm_path_permissions"]
hub_perm_path_data_scope: str = PERM_API_PATH_DEFAULTS["hub_perm_path_data_scope"]
hub_perm_path_directory_scoped: str = PERM_API_PATH_DEFAULTS["hub_perm_path_directory_scoped"]
hub_perm_path_admin_roles: str = PERM_API_PATH_DEFAULTS["hub_perm_path_admin_roles"]
hub_perm_path_admin_permissions: str = PERM_API_PATH_DEFAULTS["hub_perm_path_admin_permissions"]
hub_perm_path_admin_role_permissions: str = PERM_API_PATH_DEFAULTS["hub_perm_path_admin_role_permissions"]
hub_perm_path_admin_user_roles: str = PERM_API_PATH_DEFAULTS["hub_perm_path_admin_user_roles"]
hub_perm_path_admin_user_data_scope: str = PERM_API_PATH_DEFAULTS["hub_perm_path_admin_user_data_scope"]
# ------------------------------------------- 全量同步的排期(见 SYNC_MODES)
hub_sync_when: str = "daily"
#: 「每周选几天」这一档挑的星期,1=周一 … 7=周日,升序
hub_sync_weekdays: tuple[int, ...] = WEEKDAY_FALLBACK
#: 「每月选几天」这一档挑的几号,1-31,升序
hub_sync_monthdays: tuple[int, ...] = MONTHDAY_FALLBACK
#: 「按间隔」这一档的间隔(分钟),从上一趟跑完开始计时
hub_sync_interval_minutes: int = 1440
# 应急总闸:true 时下面这些一律当"没开"处理
forced_off: bool = False
#: 总闸这一项当前被环境变量 OA_HUB_DISABLED 钉住了:界面上是灰的,改不动
forced_off_locked: bool = False
# 配置存在哪儿:界面上写清楚"改这里就会生效"
config_file: str = ""
config_source: str = ""
#: 每一项现在是谁给的(环境变量 / 数据库 / 配置文件 / 默认值)
sources: dict[str, str] = None # type: ignore[assignment]
def __post_init__(self) -> None:
if self.sources is None:
object.__setattr__(self, "sources", {})
@property
def login_on(self) -> bool:
"""账号密码登录是否要拿去问 Hub(``sso`` 模式下不收账号密码,所以是 False)。"""
if self.forced_off:
return False
return (
self.hub_enabled
and self.hub_login_mode in PASSWORD_LOGIN_MODES
and bool(self.hub_base_url)
)
@property
def sso_ready(self) -> bool:
"""免登配置是否齐活(地址 + 应用编码 + 应用密钥)。"""
return bool(
self.hub_base_url and self.hub_app_code.strip() and self.hub_integration_key.strip()
)
@property
def sso_on(self) -> bool:
"""是否接受「Hub 门户 ticket -> 本地会话」这条免登通道。"""
if self.forced_off:
return False
return self.hub_enabled and self.hub_sso_enabled and self.sso_ready
@property
def sso_only(self) -> bool:
"""登录是否只允许免登:本系统不再收账号密码,也不再有注册/找回密码入口。"""
if self.forced_off:
return False
return self.hub_enabled and self.hub_login_mode == "sso"
@property
def portal_url(self) -> str:
"""统一门户首页:没登录时把用户送回哪里,没单独配就用 Hub 站点地址。"""
return (self.hub_portal_url or self.hub_base_url).strip().rstrip("/")
@property
def sync_allowed(self) -> bool:
return self.hub_enabled and bool(self.hub_base_url) and not self.forced_off
@property
def perm_on(self) -> bool:
"""角色 / 权限 / 数据范围这一层现在问不问 Hub。"""
if self.forced_off:
return False
return bool(self.hub_enabled and self.hub_perm_enabled and self.hub_base_url)
@property
def perm_app_id(self) -> str:
"""权限目录归属的应用编码:没单独配就用免登那个应用编码,再留空兜一个 oa。"""
return (self.hub_perm_application_id or self.hub_app_code or "oa").strip().lower()
@property
def password_managed(self) -> bool:
"""登录口令归不归 Hub 管:显式打开,或只用 Hub 登录 / 只允许免登,都算归它管。"""
if self.forced_off:
return bool(self.hub_password_managed_by_hub)
return self.hub_password_managed_by_hub or self.hub_login_mode in {"hub", "sso"}
@property
def sync_at(self) -> tuple[int, int]:
try:
hour_text, _, minute_text = self.hub_sync_time.strip().partition(":")
hour, minute = int(hour_text), int(minute_text or 0)
except (TypeError, ValueError):
return (1, 0)
if not (0 <= hour <= 23 and 0 <= minute <= 59):
return (1, 0)
return (hour, minute)
@property
def sync_weekday_set(self) -> frozenset[int]:
"""每周这一档挑的星期集合(空集当"没配",回落到工作日,免得排期静默失效)。"""
days = frozenset(day for day in self.hub_sync_weekdays if 1 <= int(day) <= 7)
return days or frozenset(WEEKDAY_FALLBACK)
@property
def sync_monthday_set(self) -> frozenset[int]:
"""每月这一档挑的几号集合(空集回落到 1 号,理由同上)。"""
days = frozenset(day for day in self.hub_sync_monthdays if 1 <= int(day) <= 31)
return days or frozenset(MONTHDAY_FALLBACK)
@property
def api_paths(self) -> dict[str, str]:
"""各个接口的当前路径,状态接口与自检步骤名都用它。"""
return {
"captcha": self.hub_path_captcha,
"login": self.hub_path_login,
"verify_token": self.hub_path_verify_token,
"me": self.hub_path_me,
"directory": self.hub_path_directory,
"directory_changes": self.hub_path_directory_changes,
"ticket_verify": self.hub_path_ticket_verify,
"apps": self.hub_path_apps,
"launch": self.hub_path_launch,
}
def launch_path(self, code: str = "") -> str:
"""免登跳转接口的完整路径:``{code}`` 占位符换成本系统(或指定)的应用编码。"""
code = (code or self.hub_app_code).strip().lower()
from urllib.parse import quote
encoded = quote(code, safe="")
if LAUNCH_CODE_PLACEHOLDER in self.hub_path_launch:
return self.hub_path_launch.replace(LAUNCH_CODE_PLACEHOLDER, encoded)
return f"{self.hub_path_launch}/{encoded}"
@property
def perm_api_paths(self) -> dict[str, str]:
"""权限这一层当前在打哪些接口(界面与自检步骤名都用它,路径不写死在代码里)。"""
return {
"roles": self.hub_perm_path_roles,
"permissions": self.hub_perm_path_permissions,
"data_scope": self.hub_perm_path_data_scope,
"directory_scoped": self.hub_perm_path_directory_scoped,
"admin_roles": self.hub_perm_path_admin_roles,
"admin_permissions": self.hub_perm_path_admin_permissions,
"admin_role_permissions": self.hub_perm_path_admin_role_permissions,
"admin_user_roles": self.hub_perm_path_admin_user_roles,
"admin_user_data_scope": self.hub_perm_path_admin_user_data_scope,
}
@property
def locked_hub_accounts(self) -> frozenset[str]:
"""``hub_sync_locked_accounts`` -> 账号集合(大小写不敏感):OA 里只读的平台管理员账号。"""
return frozenset(
part.strip().lower() for part in self.hub_sync_locked_accounts.split(",") if part.strip()
)
@property
def local_only_accounts(self) -> frozenset[str]:
"""这些账号永远只用本地口令登录,不去问 Hub。
内置超管(``[seed] admin_account``,本部署叫 ``localadmin``)**永远在这份名单里**:
它是唯一的本地管理员,也是 Hub 挂了、目录密钥写错、库里配置被清空时唯一能保证
进得了门的账号,所以不跟着「应急账号」那一栏一起被抹掉。名单本身存在数据库里
(``config:hub.hub_local_accounts``),配置文件不再是它的存放处。
"""
from .config import settings
names = {part.strip().lower() for part in self.hub_local_accounts.split(",") if part.strip()}
built_in = str(getattr(settings, "admin_account", "") or "").strip().lower()
if built_in:
names.add(built_in)
return frozenset(names)
@property
def credential_mode(self) -> str:
"""拉全量目录用哪种凭证:目录密钥 / 长期 token / 集成账号 / 匿名。
Hub 的目录接口已改成用 ``X-Directory-Key`` 认服务端调用,所以配了目录密钥
就以它为准;没配才退回老的 Bearer token 口径(长期 token、集成账号),
两者都没有才是匿名拉(只在对方不校验时才拉得到)。
"""
if self.hub_directory_key.strip():
return "directory_key"
if self.hub_service_token.strip():
return "token"
if self.hub_service_account.strip() and self.hub_service_password:
return "account"
return "anonymous"
_warned: set[str] = set()
def _warn_once(key: str, message: str, *args) -> None:
"""同一份坏配置只报一次,别让每次登录都被同一行日志刷屏。"""
if key in _warned:
return
_warned.add(key)
logger.warning(message, *args)
def _api_path(value, name: str) -> str:
"""接口路径兜底:万一库里的值不对,也用出厂路径,别把登录与同步整个带崩。"""
text = str(value or "").strip()
if not text.startswith("/") or len(text.rstrip("/")) < 2:
return API_PATH_DEFAULTS[name]
return text.rstrip("/")
def build() -> HubConfig:
"""把当前生效的 Hub 配置洗成一份能直接用的值对象。"""
values = dbconfig.values()
login_mode = str(values.get("hub_login_mode") or "").strip().lower()
if login_mode not in LOGIN_MODES:
_warn_once(f"mode:{login_mode}", "Hub 登录模式 %r 不认识,按 hybrid 处理", login_mode)
login_mode = "hybrid"
sync_time = str(values.get("hub_sync_time") or "").strip()
return HubConfig(
hub_enabled=bool(values.get("hub_enabled")),
hub_base_url=str(values.get("hub_base_url") or "").strip().rstrip("/"),
hub_path_captcha=_api_path(values.get("hub_path_captcha"), "hub_path_captcha"),
hub_path_login=_api_path(values.get("hub_path_login"), "hub_path_login"),
hub_path_verify_token=_api_path(values.get("hub_path_verify_token"), "hub_path_verify_token"),
hub_path_me=_api_path(values.get("hub_path_me"), "hub_path_me"),
hub_path_directory=_api_path(values.get("hub_path_directory"), "hub_path_directory"),
hub_path_directory_changes=_api_path(
values.get("hub_path_directory_changes"), "hub_path_directory_changes"
),
hub_path_ticket_verify=_api_path(values.get("hub_path_ticket_verify"), "hub_path_ticket_verify"),
hub_path_apps=_api_path(values.get("hub_path_apps"), "hub_path_apps"),
hub_path_launch=_launch_path_value(values.get("hub_path_launch")),
hub_sso_enabled=bool(values.get("hub_sso_enabled", True)),
hub_app_code=str(values.get("hub_app_code") or "").strip().lower(),
hub_integration_key=str(values.get("hub_integration_key") or "").strip(),
hub_portal_url=str(values.get("hub_portal_url") or "").strip().rstrip("/"),
hub_sso_state_required=bool(values.get("hub_sso_state_required")),
hub_login_mode=login_mode,
hub_timeout_seconds=_clamp(values.get("hub_timeout_seconds"), 1, 120, 10),
hub_breaker_seconds=_clamp(values.get("hub_breaker_seconds"), 0, 60, 5),
hub_max_inflight=_clamp(values.get("hub_max_inflight"), 0, 64, 8),
hub_verify_token=bool(values.get("hub_verify_token", True)),
hub_auto_provision=bool(values.get("hub_auto_provision", True)),
hub_local_accounts=str(values.get("hub_local_accounts") or "").strip(),
hub_directory_key=str(values.get("hub_directory_key") or "").strip(),
hub_service_token=str(values.get("hub_service_token") or "").strip(),
hub_service_account=str(values.get("hub_service_account") or "").strip(),
hub_service_password=str(values.get("hub_service_password") or ""),
hub_captcha_auto_solve=bool(values.get("hub_captcha_auto_solve", True)),
hub_directory_needs_token=bool(values.get("hub_directory_needs_token")),
hub_password_managed_by_hub=bool(values.get("hub_password_managed_by_hub")),
hub_sync_enabled=bool(values.get("hub_sync_enabled", True)),
hub_sync_when=_sync_mode(values.get("hub_sync_when")),
hub_sync_time=sync_time if _time_ok(sync_time) else "01:00",
hub_sync_orgs=bool(values.get("hub_sync_orgs", True)),
hub_sync_bind_local_by_code=bool(values.get("hub_sync_bind_local_by_code", True)),
hub_sync_include_disabled_units=bool(values.get("hub_sync_include_disabled_units", True)),
hub_sync_offboard=bool(values.get("hub_sync_offboard", True)),
hub_sync_skip_unchanged=bool(values.get("hub_sync_skip_unchanged", True)),
hub_sync_member_limit=_clamp(values.get("hub_sync_member_limit"), 1, 5000, 5000),
hub_sync_email_domain=str(values.get("hub_sync_email_domain") or "").strip().lstrip("@").strip(),
hub_sync_protect_admins=bool(values.get("hub_sync_protect_admins", True)),
hub_sync_locked_accounts=str(values.get("hub_sync_locked_accounts") or "").strip(),
hub_sync_changes_enabled=bool(values.get("hub_sync_changes_enabled", True)),
hub_sync_changes_interval_seconds=_clamp(values.get("hub_sync_changes_interval_seconds"), 15, 3600, 45),
hub_sync_changes_limit=_clamp(values.get("hub_sync_changes_limit"), 1, 500, 200),
hub_sync_changes_full_on_gap=bool(values.get("hub_sync_changes_full_on_gap", True)),
hub_sync_retry_minutes=_clamp(values.get("hub_sync_retry_minutes"), 1, 240, 10),
hub_sync_retries=_clamp(values.get("hub_sync_retries"), 0, 23, 3),
hub_sync_weekdays=_day_tuple(values.get("hub_sync_weekdays"), 1, 7, WEEKDAY_FALLBACK),
hub_sync_monthdays=_day_tuple(values.get("hub_sync_monthdays"), 1, 31, MONTHDAY_FALLBACK),
hub_sync_interval_minutes=_clamp(values.get("hub_sync_interval_minutes"), 30, 43200, 1440),
# ---- 统一身份权限
hub_perm_enabled=bool(values.get("hub_perm_enabled")),
hub_perm_mode=_perm_mode(values.get("hub_perm_mode")),
hub_perm_application_id=str(values.get("hub_perm_application_id") or "").strip().lower(),
hub_perm_cache_seconds=_clamp(values.get("hub_perm_cache_seconds"), 0, 86400, 60),
hub_perm_scope_mode=_perm_scope_mode(values.get("hub_perm_scope_mode")),
hub_perm_admin_query=bool(values.get("hub_perm_admin_query", True)),
hub_perm_keep_local=bool(values.get("hub_perm_keep_local", True)),
hub_perm_path_roles=_api_path(values.get("hub_perm_path_roles"), "hub_perm_path_roles"),
hub_perm_path_permissions=_api_path(values.get("hub_perm_path_permissions"), "hub_perm_path_permissions"),
hub_perm_path_data_scope=_api_path(values.get("hub_perm_path_data_scope"), "hub_perm_path_data_scope"),
hub_perm_path_directory_scoped=_api_path(
values.get("hub_perm_path_directory_scoped"), "hub_perm_path_directory_scoped"
),
hub_perm_path_admin_roles=_api_path(values.get("hub_perm_path_admin_roles"), "hub_perm_path_admin_roles"),
hub_perm_path_admin_permissions=_api_path(
values.get("hub_perm_path_admin_permissions"), "hub_perm_path_admin_permissions"
),
hub_perm_path_admin_role_permissions=_api_path(
values.get("hub_perm_path_admin_role_permissions"), "hub_perm_path_admin_role_permissions"
),
hub_perm_path_admin_user_roles=_api_path(
values.get("hub_perm_path_admin_user_roles"), "hub_perm_path_admin_user_roles"
),
hub_perm_path_admin_user_data_scope=_api_path(
values.get("hub_perm_path_admin_user_data_scope"), "hub_perm_path_admin_user_data_scope"
),
forced_off=bool(values.get("hub_disabled")),
forced_off_locked=bool(dbconfig.env_locks().get("hub_disabled")),
config_file=f"database://{dbconfig.SETTING_TABLE}/{dbconfig.DB_KEY_PREFIX}hub",
config_source="database",
sources={name: dbconfig.source(name) for name in MANAGED},
)
def _launch_path_value(value) -> str:
"""免登跳转路径兜底:这一项可以带 ``{code}`` 占位符,其余口径与其它接口路径一样。
校验时把占位符临时换成一个普通片段再过一遍 :func:`_api_path`,写坏了就退回出厂路径,
免得免登整条通道因为一处路径写错而静默失效。
"""
placeholder_stand_in = "code"
text = str(value or "").strip().replace(LAUNCH_CODE_PLACEHOLDER, placeholder_stand_in)
cleaned = _api_path(text, "hub_path_launch")
if cleaned == API_PATH_DEFAULTS["hub_path_launch"] and placeholder_stand_in not in text:
return cleaned
return cleaned.replace(placeholder_stand_in, LAUNCH_CODE_PLACEHOLDER)
def _time_ok(value: str) -> bool:
import re
return bool(re.match(r"^([01]?\d|2[0-3]):([0-5]\d)$", value or ""))
def _sync_mode(value) -> str:
"""排期档位:写法不认识就按"每天"处理,与登录模式那一档的兜底口径一致。"""
text = str(value or "").strip().lower()
if text not in SYNC_MODES:
_warn_once(f"sync_mode:{text}", "组织人员同步频率 %r 不认识,按 daily(每天)处理", text)
return "daily"
return text
def _day_tuple(value, low: int, high: int, fallback: tuple[int, ...]) -> tuple[int, ...]:
"""把"哪几天"洗成升序去重的整数元组;一个都没认出来就回落到出厂那一档。
配置文件与环境变量里写的是字符串(``"1,3,5"``),界面上多选框给的是数组,两种都收。
运行期读到的值不该让调度整条链路抛异常,所以这里只兜底、不报错。
"""
import re
if isinstance(value, str):
parts = [part for part in re.split(r"[,\s]+", value.strip()) if part]
elif isinstance(value, (list, tuple, set, frozenset)):
parts = [str(part).strip() for part in value]
else:
parts = []
days: set[int] = set()
for part in parts:
try:
day = int(part)
except (TypeError, ValueError):
continue
if low <= day <= high:
days.add(day)
return tuple(sorted(days or fallback))
def _perm_mode(value) -> str:
"""权限生效口径:认不出来的写法一律按"只对照"处理,别因为一处写错就悄悄改了判定。"""
text = str(value or "").strip().lower()
if text not in PERM_MODES:
_warn_once(f"perm_mode:{text}", "统一身份权限口径 %r 不认识,按 shadow(只对照)处理", text)
return "shadow"
return text
def _perm_scope_mode(value) -> str:
text = str(value or "").strip().lower()
if text not in PERM_SCOPE_MODES:
_warn_once(f"perm_scope:{text}", "统一身份数据范围口径 %r 不认识,按 merge(取较大)处理", text)
return "merge"
return text
_built: HubConfig | None = None
_built_revision = -1
def get(db=None) -> HubConfig:
"""当前生效配置。配置存在库里,界面上保存后这里下一次就是新值。
``db`` 参数保留只为兼容老调用点:取值不需要库(走 dbconfig 的快照)。
这里先 :func:`dbconfig.refresh` 再比版本号,不是多余的一步:版本号只在刷新快照时
才会 +1,只 :func:`dbconfig.revision` 的话,本进程可能一直拿着旧配置,直到别的
代码路径顺手刷了一次才跟上——界面上刚保存完、后端还在按老排期跑,就是它。
``refresh()`` 自带 TTL(``OA_CONFIG_CACHE_SECONDS``:订阅上失效广播时 60 秒,
否则 2 秒),到点才真读库。
"""
global _built, _built_revision
dbconfig.refresh()
revision = dbconfig.revision()
if _built is None or _built_revision != revision:
_built = build()
_built_revision = revision
return _built
def reload() -> HubConfig:
"""强制重读一遍(保存配置、或测试里改完环境变量会用到)。
顺手把 Hub 的 HTTP 客户端与缓存的同步 token 丢掉:地址、超时、接口路径都可能
跟着变了,留着旧的会让"改了配置保存了但还在打老接口"这种问题查半天。
"""
global _built, _built_revision
dbconfig.invalidate()
_built = build()
_built_revision = dbconfig.revision()
_warned.clear()
from .service import hub as hub_service
hub_service.reset_client()
# 应用编码、口径、路径都可能跟着变了,缓存的权限一律作废
from .service import hub_perm
hub_perm.clear_cache()
return _built
def invalidate() -> None:
"""兼容旧调用点:缓存按配置版本号自动失效,这里什么都不用做。"""
return None
def env_disabled() -> bool:
"""应急总闸是否被环境变量打开(``OA_HUB_DISABLED=true``)。"""
import os
return str(os.environ.get(ENV_SWITCH, "")).strip().lower() in {"1", "true", "yes", "on"}
def kill_switch(db=None) -> dict:
"""应急总闸的当前口径,界面上那个开关与状态接口都读这里。
单独抽一个口子是为了把三件容易说混的事分清:
* ``disabled`` —— 总闸现在开没开(开 = 登录与同步一律走本地);
* ``locked`` —— 这一项是不是被环境变量 ``OA_HUB_DISABLED`` 钉住了,钉住了界面上
就只能看不能改;
* ``unlocked_value`` —— 把环境变量摘掉之后会生效的那一稿:先问库里,库里没存过
就回落到配置文件。被钉住时它和 ``disabled`` 可以不一致,界面上得说清"摘掉变量
之后按哪一稿走",不然管理员只会对着一个改不动的开关发懵。
"""
cfg = get(db)
lock = str(dbconfig.env_locks().get("hub_disabled") or "")
return {
"name": "hub_disabled",
"env": ENV_SWITCH,
"disabled": cfg.forced_off,
"locked": cfg.forced_off_locked,
"env_value": lock,
"unlocked_value": unlocked_value(),
"source": dbconfig.source("hub_disabled"),
"editable": not cfg.forced_off_locked,
"reason": forced_off_reason(cfg),
}
def unlocked_value() -> bool:
"""没有环境变量插手时这一项会是多少:库里的值优先,库里没存过就问配置文件。"""
row = dbconfig.stored("hub")
if "hub_disabled" in row:
return bool(row.get("hub_disabled"))
item = dbconfig.BY_NAME.get("hub_disabled")
return bool(dbconfig.file_value(item)) if item is not None else False
def forced_off_reason(cfg: "HubConfig | None" = None) -> str:
"""总闸打开时给界面看的那句话:说清是谁打开的、要怎么才能关回去。"""
cfg = cfg if cfg is not None else get()
if not cfg.forced_off:
return ""
if cfg.forced_off_locked:
return (
f"统一身份已被总闸关闭:环境变量 {ENV_SWITCH} 钉住了配置项 hub_disabled,"
"界面上改不动。登录与同步一律走本地;去掉这个环境变量再重启后端才恢复。"
)
return (
"统一身份已被总闸关闭(配置项 hub_disabled,配置文件里是 [hub] disabled),"
"登录与同步一律走本地。在「系统设置」页把应急总闸关掉就恢复,不用重启后端。"
)
def view() -> dict:
"""``GET /hub/config``:把 Hub 相关配置项连中文说明一起给界面。"""
hub = dbconfig.group_view("hub")
sync = dbconfig.group_view("hub_sync")
perm = dbconfig.group_view("hub_perm")
items = {item["name"]: item for item in hub["items"] + sync["items"] + perm["items"]}
values = {name: items[name]["value"] for name in MANAGED}
return {
"values": values,
"items": [items[name] for name in MANAGED],
"labels": {name: items[name]["label"] for name in MANAGED},
"hints": {name: items[name]["help"] for name in MANAGED},
"sources": {name: items[name]["source"] for name in MANAGED},
"env_locks": {name: items[name].get("env_locked") for name in MANAGED if items[name].get("env_locked")},
"secret_set": {name: items[name]["secret_set"] for name in MANAGED if items[name]["secret"]},
"login_modes": [{"value": mode, "label": label} for mode, label in LOGIN_MODE_LABELS.items()],
# 同步排期:档位与星期/几号的中文口径,界面上的多选框照着摆
"sync_modes": [{"value": mode, "label": SYNC_MODE_LABELS[mode]} for mode in SYNC_MODES],
"weekdays": [{"value": day, "label": WEEKDAY_LABELS[day]} for day in sorted(WEEKDAY_LABELS)],
"config_file": f"database://{dbconfig.SETTING_TABLE}/{dbconfig.DB_KEY_PREFIX}hub",
"restart_required": False,
# 界面上那个「应急总闸」开关只看这一段:省得前端自己去 items 里翻
"kill_switch": kill_switch(),
}
def apply(db, patch: dict) -> dict[str, object]:
"""保存 Hub 配置(``PUT /hub/config``):存库 + 立刻生效,不重启服务。"""
unknown = [name for name in patch if name not in MANAGED]
if unknown:
raise dbconfig.ConfigValidationError("不认识的 Hub 配置项:" + "、".join(sorted(unknown)))
buckets: dict[str, dict] = {}
for name, raw_value in patch.items():
buckets.setdefault(GROUP_OF[name], {})[name] = raw_value
changed: dict[str, object] = {}
for group, values in buckets.items():
changed.update(dbconfig.apply(db, group, values))
reload()
return changed
def mask_secret(value: str) -> str:
"""日志与状态接口里代表"这里有个密钥"的占位符。"""
return "********" if value else ""
def login_mode_label(mode: str) -> str:
return LOGIN_MODE_LABELS.get(mode, mode)