# -*- coding: utf-8 -*- """webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。 """ from __future__ import annotations import json import logging import os from pathlib import Path from fastapi import HTTPException, Request from webhost.backend.core import licensing from webhost.backend.core import config from webhost.backend.core.session import _sess_account _LOGGER = logging.getLogger(__name__) _ALLOW_CACHE = (Path(os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or Path.home()) / "37duAutomation" / "plugin_allow.json") def _save_allowed_cache(ids: set) -> None: """权限清单落盘缓存(登录拉取时写入,离线/中心机不可达时直接复用)。""" try: _ALLOW_CACHE.parent.mkdir(parents=True, exist_ok=True) _ALLOW_CACHE.write_text(json.dumps(sorted(ids), ensure_ascii=False), encoding="utf-8") except OSError as _exc: # noqa: BLE001 _LOGGER.warning("插件权限清单缓存写入失败: %s", _exc) def _load_allowed_cache() -> set | None: """读权限清单缓存;无缓存/损坏返回 None。""" if not _ALLOW_CACHE.is_file(): return None try: raw = json.loads(_ALLOW_CACHE.read_text(encoding="utf-8")) except (OSError, ValueError): return None return {str(x) for x in (raw or [])} def _resolve_allowed() -> set: """插件权限白名单(fail-closed,绝不回退全量):控制面拉取 + 本地缓存。 语义: - 未登录(无恢复会话账号)→ 无权限,返回空集(零权限,不加载任何插件); - 登录过 → 拉取账号插件清单并落盘缓存;后续离线直接复用缓存清单; - 有账号但离线且无缓存 → 空集(无权限依据,fail-closed 防越权)。 """ if not config.CONTROLPLANE_URL: return set() from webhost.backend.core.session import _sess_active_account account = config.CONTROLPLANE_ACCOUNT or _sess_active_account() if not account: _LOGGER.info("未登录(无会话账号),插件零权限加载") return set() import requests headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {} try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins", params={"account": account}, headers=headers, timeout=5) r.raise_for_status() allowed = {p["id"] for p in r.json().get("plugins", [])} _LOGGER.info("控制面权限清单(%s):%s", account, sorted(allowed) or "(空)") _save_allowed_cache(allowed) return allowed except Exception as _exc: # noqa: BLE001 不可达/失败:缓存兜底,无缓存零权限 cached = _load_allowed_cache() if cached is not None: _LOGGER.info("权限清单拉取失败,用本地缓存(%s):%s", account, _exc) return cached _LOGGER.warning("权限清单拉取失败且无缓存,插件零权限加载:%s", _exc) return set() def _cp_headers(request: Request) -> dict: """构造到中心机的调用头:优先带「当前登录账号的云令牌」(登录时中心机签发,中心机 _cloud_account 据此定位用户),不再依赖 CONTROLPLANE_TOKEN;X-Admin-User 仅作兜底。""" from webhost.backend.core.session import _ACCT_CLOUD_TOKEN h = {} account = _sess_account(request) if account: _cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account) if _cloud_tok: h["Authorization"] = f"Bearer {_cloud_tok}" h["X-Admin-User"] = account if config.CONTROLPLANE_TOKEN: h["X-API-Token"] = config.CONTROLPLANE_TOKEN return h def _cp_call(method: str, path: str, **kw) -> dict: if not config.CONTROLPLANE_URL: raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)") import requests r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw) try: body = r.json() except ValueError: body = {"detail": r.text[:300]} if r.status_code >= 400: raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}")) return body def _sync_licensing(account: str) -> None: """联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。 逐资源容错:公钥/授权票据/管控清单各自 try,单个接口失败不阻断其余(成功部分照常落盘 + touch_sync),保证一次刷新尽量完整;全部失败也静默,调用方按本地缓存兜底。 """ if not config.CONTROLPLANE_URL or not account: return import requests headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {} got_any = False try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5) r.raise_for_status() licensing.cache_public_key(r.json().get("pub", "")) got_any = True except Exception as _exc: # noqa: BLE001 公钥拉取失败不阻断授权/管控刷新 _LOGGER.warning("中心机公钥拉取失败:%s", _exc) try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license", params={"account": account}, headers=headers, timeout=5) r.raise_for_status() licensing.save_license(r.json()) got_any = True except Exception as _exc: # noqa: BLE001 授权票据拉取失败不阻断公钥/管控刷新 _LOGGER.warning("离线授权票据拉取失败:%s", _exc) try: r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5) r.raise_for_status() licensing.save_control(r.json()) got_any = True except Exception as _exc: # noqa: BLE001 管控清单拉取失败不阻断公钥/授权刷新 _LOGGER.warning("管控清单拉取失败:%s", _exc) if got_any: licensing.flush_offline_reports()