astrbot_plugin_imagestudio/core/secret_service.py

113 行
3.6 KiB
Python

"""Secret redaction and environment reference helpers."""
from __future__ import annotations
import os
from dataclasses import dataclass
2026-07-06 01:56:43 +08:00
from typing import Any, Mapping, Protocol
MASK = "***MASKED***"
SECRET_KEY_PARTS = ("api_key", "apikey", "token", "secret", "password", "dsn", "credential")
@dataclass(frozen=True)
class SecretRef:
name: str
is_set: bool
def to_dict(self) -> dict[str, Any]:
return {"name": self.name, "is_set": self.is_set, "value": MASK if self.is_set else None}
2026-07-06 01:56:43 +08:00
class SecretStore(Protocol):
def get(self, name: str) -> str | None:
...
@dataclass(frozen=True)
class SecretResolution:
source: str
is_set: bool
value: str | None = None
def to_public_dict(self) -> dict[str, Any]:
return {"source": self.source, "is_set": self.is_set, "value": MASK if self.is_set else None}
def is_secret_key(path: str) -> bool:
lowered = path.lower()
if lowered.endswith("_set"):
return False
return any(part in lowered for part in SECRET_KEY_PARTS)
def redact(value: Any, path: str = "") -> Any:
if isinstance(value, Mapping):
redacted: dict[str, Any] = {}
for key, child in value.items():
child_path = f"{path}.{key}" if path else str(key)
redacted[str(key)] = MASK if is_secret_key(child_path) and child else redact(child, child_path)
return redacted
if isinstance(value, list):
return [redact(item, path) for item in value]
return value
def env_ref(name: str) -> SecretRef:
normalized = str(name or "").strip()
if not normalized:
raise ValueError("secret env name is required")
return SecretRef(name=normalized, is_set=bool(os.environ.get(normalized)))
def resolve_env_value(reference: str) -> str | None:
normalized = str(reference or "").strip()
if normalized.startswith("env:"):
normalized = normalized[4:]
if not normalized:
return None
return os.environ.get(normalized)
2026-07-06 01:56:43 +08:00
def resolve_secret_value(
*,
env_var: str | None = None,
secret_ref: str | None = None,
plaintext: str | None = None,
secret_store: SecretStore | None = None,
) -> SecretResolution:
normalized_env = str(env_var or "").strip()
if normalized_env:
value = resolve_env_value(normalized_env)
return SecretResolution(source=f"env:{normalized_env.removeprefix('env:')}", is_set=bool(value), value=value)
normalized_ref = str(secret_ref or "").strip()
if normalized_ref:
value = secret_store.get(normalized_ref) if secret_store else None
return SecretResolution(source=f"secret:{normalized_ref}", is_set=bool(value), value=value)
normalized_plaintext = str(plaintext or "").strip()
if normalized_plaintext:
return SecretResolution(source="plaintext", is_set=True, value=normalized_plaintext)
return SecretResolution(source="missing", is_set=False, value=None)
def redact_provider_secret_state(provider: Mapping[str, Any]) -> dict[str, Any]:
redacted = dict(provider)
resolution = resolve_secret_value(
env_var=_text(provider.get("api_key_env_var")),
secret_ref=_text(provider.get("api_key_secret_ref")),
plaintext=_text(provider.get("api_key_plaintext")),
)
redacted.pop("api_key_plaintext", None)
redacted["api_key_secret_ref"] = MASK if provider.get("api_key_secret_ref") else None
redacted["api_key_set"] = resolution.is_set
redacted["api_key_source"] = resolution.source if resolution.source != "plaintext" else "plaintext"
return redacted
def _text(value: Any) -> str:
return str(value or "").strip()