ForcePilot/backend/package/yuxi/channels/adapters/feishu/secret_resolver.py
Kris 1f78c44b03 refactor: 整理并清理项目中的冗余代码与格式问题
这是一个批量整理提交,包含以下主要改动:
1.  删除多处冗余的空行和未使用的导入
2.  修复文件末尾缺少换行符的问题
3.  调整部分模块的导入顺序与代码排版
4.  修复部分配置默认值与策略逻辑
5.  新增多个功能模块与辅助工具
6.  完善异常处理与日志记录
7.  修复速率限制、消息缓存、权限校验等逻辑bug
8.  废弃部分旧有API与配置项并添加警告提示
2026-05-12 14:51:53 +08:00

93 lines
2.5 KiB
Python

from __future__ import annotations
import os
import subprocess
import time
from typing import Any
from yuxi.utils.logging_config import logger
_KEY_ROTATION_WINDOW_S = 3600
def resolve_secret(config: dict[str, Any], key: str, env_key: str = "") -> str:
env_val = os.environ.get(env_key or key.upper(), "")
if env_val:
return env_val
value = config.get(key, "")
if isinstance(value, dict):
source = value.get("source", "")
path = value.get("path", "")
command = value.get("command", "")
env = value.get("env", "")
if source == "file" and path:
return _read_file_secret(path)
if source == "exec" and command:
return _exec_secret(command)
if source == "env" and env:
return os.environ.get(env, "")
if source == "raw":
return value.get("value", "")
return str(value) if value else ""
def resolve_secret_with_rotation(
config: dict[str, Any],
key: str,
env_key: str = "",
rotation_window_s: float = _KEY_ROTATION_WINDOW_S,
) -> str:
cached = _secrets_cache.get(key)
if cached is not None:
secret, cached_at = cached
if time.monotonic() - cached_at < rotation_window_s:
return secret
secret = resolve_secret(config, key, env_key)
if secret:
_secrets_cache[key] = (secret, time.monotonic())
return secret
def invalidate_secret_cache(key: str = "") -> None:
if key:
_secrets_cache.pop(key, None)
else:
_secrets_cache.clear()
def _read_file_secret(path: str) -> str:
try:
with open(path, encoding="utf-8") as f:
return f.read().strip()
except OSError as e:
logger.warning(f"[SecretResolver] Failed to read file '{path}': {e}")
return ""
def _exec_secret(command: str) -> str:
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=10,
)
if result.returncode == 0:
return result.stdout.strip()
logger.warning(f"[SecretResolver] Command failed (exit={result.returncode}): {command}")
return ""
except subprocess.TimeoutExpired:
logger.warning(f"[SecretResolver] Command timed out: {command}")
return ""
except Exception as e:
logger.warning(f"[SecretResolver] Command execution failed: {e}")
return ""
_secrets_cache: dict[str, tuple[str, float]] = {}