ForcePilot/backend/package/yuxi/channels/adapters/feishu/secret_resolver.py
Kris 69b7139863 refactor(feishu): 清理冗余代码并补全飞书工具集实现
1.  移除多个文件中的空行、冗余导入
2.  修复文件末尾缺少换行符的问题
3.  新增并补全飞书多类工具API实现:
    - 多维表格:更新、删除记录,列出视图
    - 文档:更新、追加、删除块
    - 云文档:上传、下载文件
    - 群组:创建、添加成员、更新信息、创建公告
    - 目录:重构用户部门缓存逻辑
4.  优化消息发送、回复、转发等API的错误处理和逻辑
5.  新增消息列表查询、已读状态查询等功能
2026-05-13 16:07:59 +08:00

94 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]] = {}