2026-07-05 15:39:33 +08:00
|
|
|
"""Secret redaction and environment reference helpers."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from typing import Any, Mapping
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|