# -*- coding: utf-8 -*- """执行机敏感凭证下发与缓存:中心机在线拉取(RSA 解密) + 加密缓存(离线复用)。 流程: sync(): 有登录云令牌且中心机可达 → 1. POST /api/admin/creds/register 上报本机 RSA 公钥(幂等 upsert,本人云令牌可登记) 2. GET /api/admin/creds (Bearer) 拉取 {key: base64(RSA 密文)}——服务端仅管理员可拉, 员工账号 403 会走缓存(本地无密文则为空,不影响业务) 3. 本机私钥逐个解密 → 返回明文 dict 4. 拉到的密文 JSON 原样写缓存 %LOCALAPPDATA%\\37duAutomation\\creds\\cache.json (落盘的是密文,叠加中心机加密层) load(): 中心机可达走 sync();不可达/无云令牌则读缓存密文用私钥解密(离线可用)。 敏感键白名单与服务端 config_push._ALLOWED_KEYS 保持一致(仅钉钉开放平台凭证; HR/OA 平台登录账号由本地加密存储 platform_accounts,不经中心机)。 钉钉扫码 URL 已由控制面代理构造(/api/dingtalk/login-url),本模块下发的值当前无消费点, 链路保留供未来每账号敏感值下发能力使用。 """ from __future__ import annotations import json import logging import os from pathlib import Path from webhost.backend.core import config from webhost.backend.core.creds_store import decrypt, public_key_pem _LOGGER = logging.getLogger(__name__) # 与服务端 apis/config_push.py _ALLOWED_KEYS 保持一致(双重保障:下发限定范围) _ALLOWED_KEYS = ( "DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID", ) _CACHE_DIR = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home()) / "37duAutomation" / "creds") _CACHE_FILE = _CACHE_DIR / "cache.json" def _cloud_token(account: str) -> str: """当前账号的云端会话 token(登录时中心机签发,进程内存态;重启后需重新登录才有)。""" from webhost.backend.core.session import _ACCT_CLOUD_TOKEN return (_ACCT_CLOUD_TOKEN or {}).get(account) or "" def _headers(account: str) -> dict: h = {"Authorization": f"Bearer {_cloud_token(account)}"} if config.CONTROLPLANE_TOKEN: h["X-API-Token"] = config.CONTROLPLANE_TOKEN return h def _save_cache(encrypted: dict) -> None: """密文 JSON 原样落盘(落盘的是密文,叠加中心机加密层;离线用私钥解密)。""" try: _CACHE_DIR.mkdir(parents=True, exist_ok=True) _CACHE_FILE.write_text(json.dumps(encrypted, ensure_ascii=False), encoding="utf-8") except OSError as _exc: # noqa: BLE001 _LOGGER.warning("敏感凭证缓存写入失败: %s", _exc) def _load_cache() -> dict: """读缓存密文并用本机私钥解密为明文 dict;缺失/解密失败返回空 dict(不阻断)。""" if not _CACHE_FILE.is_file(): return {} try: raw = json.loads(_CACHE_FILE.read_text(encoding="utf-8")) except (OSError, ValueError): return {} out = {} for _k, _b64 in (raw or {}).items(): if _k not in _ALLOWED_KEYS: continue try: out[_k] = decrypt(_b64) except Exception: # noqa: BLE001 单值解密失败跳过(如密钥更换后旧缓存) _LOGGER.warning("敏感凭证缓存解密失败: %s", _k) return out def sync(account: str) -> dict | None: """中心机在线拉取并解密敏感凭证,返回明文 dict;不可用返回 None(走缓存兜底)。""" if not config.CONTROLPLANE_URL or not account or not _cloud_token(account): return None import requests try: # 1. 上报本机 RSA 公钥(幂等 upsert;中心机用该公钥加密下发) r = requests.post(f"{config.CONTROLPLANE_URL}/api/admin/creds/register", json={"account": account, "pubkey_pem": public_key_pem()}, headers=_headers(account), timeout=10) r.raise_for_status() # 2. 拉取加密后的敏感凭证 r = requests.get(f"{config.CONTROLPLANE_URL}/api/admin/creds", headers=_headers(account), timeout=10) r.raise_for_status() encrypted = r.json().get("creds") or {} except Exception as _exc: # noqa: BLE001 中心机不可达/鉴权失败 → 走缓存 _LOGGER.warning("中心机敏感凭证拉取失败(用本地缓存): %s", _exc) return None if not encrypted: return {} # 3. 本机私钥逐个解密 out = {} for _k, _b64 in encrypted.items(): if _k not in _ALLOWED_KEYS: continue try: out[_k] = decrypt(_b64) except Exception as _exc: # noqa: BLE001 单值解密失败跳过 _LOGGER.warning("敏感凭证解密失败: %s", _k) # 4. 密文原样落盘缓存(离线复用) _save_cache(encrypted) return out def load(account: str = "") -> dict: """获取当前账号敏感凭证明文:中心机可达走 sync();否则读缓存密文解密(离线可用)。 返回 dict[key]=明文,仅含成功解密项;空 dict 表示无可用的下发值(不阻断启动)。 """ account = account or config.CONTROLPLANE_ACCOUNT if not account: from webhost.backend.core.session import _sess_active_account account = _sess_active_account() synced = sync(account) if synced is not None: return synced cached = _load_cache() if cached: _LOGGER.info("使用本地敏感凭证缓存(中心机不可达或无云令牌)") return cached