Skip to content

The agent that grows with you

refactor(agent/secret_sources): compact signatures/schemas/error strings, next()-based scheme owner lookup, drop _b64d

Teknium2ac0a6a73d09
diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.py
index b95d8c0fbb7..aaddb87bd39 100644
--- a/agent/secret_sources/_cache.py
+++ b/agent/secret_sources/_cache.py
@@ -165,13 +165,8 @@ class SecretCache(Generic[K]):
self.memory: Dict[K, CachedFetch] = {}
self.disk: DiskCache[K] = DiskCache(basename, key_serializer=key_serializer)
- def lookup(
- self,
- key: K,
- ttl_seconds: float,
- home_path: Optional[Path] = None,
- read_disk: Optional[Callable[[], Optional[CachedFetch]]] = None,
- ) -> Optional[CachedFetch]:
+ def lookup(self, key: K, ttl_seconds: float, home_path: Optional[Path] = None,
+ read_disk: Optional[Callable[[], Optional[CachedFetch]]] = None) -> Optional[CachedFetch]:
"""Fresh entry from L1, else from L2 (promoted into L1), else None.
``read_disk`` swaps in an alternative L2 reader (e.g. an encrypted file).
diff --git a/agent/secret_sources/base.py b/agent/secret_sources/base.py
index 628c865ff97..65c3111de56 100644
--- a/agent/secret_sources/base.py
+++ b/agent/secret_sources/base.py
@@ -146,22 +146,15 @@ _GENERIC_REMEDIATION = {
class SecretSource(ABC):
"""One external secret backend. Subclasses set attributes + ``fetch``.
- Attributes:
- name: Config-section key under ``secrets:`` (``[a-z0-9_]+``); also the
- provenance label for every var this source supplies.
- label: Human-readable name for startup messages / ``secrets status``.
- shape: ``"mapped"`` (user binds env-var names to refs) or ``"bulk"``
- (backend injects whole projects). Mapped beats bulk: an explicit
- binding is stronger intent than a project dump.
- scheme: URI scheme this source owns for refs (``"op"``). Unique across
- sources so refs can later appear outside the ``secrets:`` block.
- token_env_key / default_token_env: config key naming the bootstrap-auth
- env var, and its default. Drives :meth:`protected_env_vars` so a
- vault holding its own access token can't clobber the credential
- used to reach it.
- override_existing_default: value of ``override_existing`` when unset.
- remediation_hints: per-kind overrides of the generic remediation text;
- ``{name}`` / ``{token_env}`` placeholders are filled in.
+ ``name``: config-section key under ``secrets:`` (``[a-z0-9_]+``) and the
+ provenance label. ``shape``: ``"mapped"`` (user binds env-var names to refs)
+ or ``"bulk"`` (backend injects whole projects); mapped beats bulk because an
+ explicit binding is stronger intent. ``scheme``: URI scheme this source owns
+ for refs, unique across sources. ``token_env_key`` / ``default_token_env``:
+ config key naming the bootstrap-auth env var and its default; drives
+ :meth:`protected_env_vars` so a vault holding its own access token can't
+ clobber the credential used to reach it. ``remediation_hints``: per-kind
+ overrides of the generic remediation text (``{name}`` / ``{token_env}``).
"""
api_version: int = SECRET_SOURCE_API_VERSION
@@ -245,15 +238,8 @@ def scrub_ansi(text: str) -> str:
return _ANSI_RE.sub("", text or "")
-def run_cli(
- argv: Sequence[str],
- *,
- env: Dict[str, str],
- timeout: float,
- label: str,
- timeout_message: str,
- stdin: Any = subprocess.DEVNULL,
-) -> subprocess.CompletedProcess:
+def run_cli(argv: Sequence[str], *, env: Dict[str, str], timeout: float, label: str,
+ timeout_message: str, stdin: Any = subprocess.DEVNULL) -> subprocess.CompletedProcess:
"""``subprocess.run`` an argv list (never a shell), capturing utf-8 text.
Timeout and spawn failure become ``RuntimeError`` with messages safe to
@@ -261,12 +247,8 @@ def run_cli(
"""
try:
return subprocess.run( # noqa: S603 — argv list, no shell
- list(argv),
- env=env,
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=timeout,
- stdin=stdin,
+ list(argv), env=env, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, stdin=stdin,
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(timeout_message) from exc
@@ -274,13 +256,8 @@ def run_cli(
raise RuntimeError(f"failed to invoke {label}: {exc}") from exc
-def run_secret_cli(
- argv: Sequence[str],
- *,
- allow_env: Sequence[str] = (),
- extra_env: Optional[Dict[str, str]] = None,
- timeout: float = DEFAULT_CLI_TIMEOUT_SECONDS,
-) -> subprocess.CompletedProcess:
+def run_secret_cli(argv: Sequence[str], *, allow_env: Sequence[str] = (), extra_env: Optional[Dict[str, str]] = None,
+ timeout: float = DEFAULT_CLI_TIMEOUT_SECONDS) -> subprocess.CompletedProcess:
"""Run a secret-manager helper CLI with a minimal, allowlisted env.
The child gets PATH/HOME/locale basics plus only ``allow_env`` (auth/session
diff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.py
index 8770f46f44f..c0f1130d564 100644
--- a/agent/secret_sources/bitwarden.py
+++ b/agent/secret_sources/bitwarden.py
@@ -29,23 +29,12 @@ from pathlib import Path
from typing import Dict, List, Optional, Tuple
from agent.secret_sources._cache import (
- CachedFetch as _CachedFetch,
- SecretCache,
- atomic_write_json,
- entry_from_payload,
- fingerprint as _token_fingerprint,
- resolve_cache_home,
+ CachedFetch as _CachedFetch, SecretCache, atomic_write_json, entry_from_payload,
+ fingerprint as _token_fingerprint, resolve_cache_home,
)
from agent.secret_sources.base import (
- ErrorKind,
- FetchResult,
- SecretSource,
- classify_cli_error,
- coerce_float,
- is_valid_env_name as _is_valid_env_name,
- get_source_environment,
- run_cli,
- source_child_env,
+ ErrorKind, FetchResult, SecretSource, classify_cli_error, coerce_float,
+ is_valid_env_name as _is_valid_env_name, get_source_environment, run_cli, source_child_env,
)
logger = logging.getLogger(__name__)
@@ -144,13 +133,8 @@ def _platform_asset_name() -> str:
# to stdout). A wrong guess surfaces as a loader error we catch.
libc = "gnu"
try:
- res = subprocess.run(
- ["ldd", "--version"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=2,
- stdin=subprocess.DEVNULL,
- )
+ res = subprocess.run(["ldd", "--version"], capture_output=True, text=True, encoding='utf-8',
+ errors='replace', timeout=2, stdin=subprocess.DEVNULL)
if "musl" in (res.stdout + res.stderr).lower():
libc = "musl"
except (OSError, subprocess.TimeoutExpired):
@@ -232,10 +216,8 @@ def _pick_zip_member(zf: zipfile.ZipFile, binary_name: str) -> str:
"""Find the binary in the zip; tolerate a top-level dir, prefer the shortest path."""
candidates = [n for n in zf.namelist() if n.split("/")[-1] == binary_name]
if not candidates:
- raise RuntimeError(
- f"Could not find {binary_name} inside downloaded archive "
- f"(members: {zf.namelist()[:5]}...)"
- )
+ raise RuntimeError(f"Could not find {binary_name} inside downloaded archive "
+ f"(members: {zf.namelist()[:5]}...)")
return min(candidates, key=len)
@@ -252,10 +234,8 @@ def _safe_extract_member(zf: zipfile.ZipFile, member: str, dest_dir: Path) -> Pa
except ValueError:
contained = False
if not contained or target == dest_root:
- raise RuntimeError(
- f"Refusing to extract unsafe archive member {member!r}: "
- f"it escapes the extraction directory"
- )
+ raise RuntimeError(f"Refusing to extract unsafe archive member {member!r}: "
+ f"it escapes the extraction directory")
zf.extract(member, dest_root)
return Path(target)
@@ -267,10 +247,6 @@ def _b64e(raw: bytes) -> str:
return base64.b64encode(raw).decode("ascii")
-def _b64d(text: str) -> bytes:
- return base64.b64decode(text.encode("ascii"), validate=True)
-
-
def _derive_encrypted_cache_key(access_token: str, salt: bytes) -> bytes:
"""HKDF the local cache key from the bootstrap BWS token.
@@ -285,13 +261,8 @@ def _derive_encrypted_cache_key(access_token: str, salt: bytes) -> bytes:
info=_ENCRYPTED_CACHE_INFO).derive(access_token.encode("utf-8"))
-def _write_encrypted_disk_cache(
- *,
- cache_key: _CacheKey,
- access_token: str,
- entry: _CachedFetch,
- home_path: Optional[Path] = None,
-) -> None:
+def _write_encrypted_disk_cache(*, cache_key: _CacheKey, access_token: str, entry: _CachedFetch,
+ home_path: Optional[Path] = None) -> None:
"""Persist an AES-GCM encrypted last-good entry atomically (best-effort).
The raw token is never stored; it only derives the key. A successful write
@@ -308,26 +279,16 @@ def _write_encrypted_disk_cache(
{"secrets": entry.secrets, "fetched_at": entry.fetched_at}, separators=(",", ":"),
).encode("utf-8")
ciphertext = AESGCM(key).encrypt(nonce, plaintext, serialized_key.encode("utf-8"))
- payload = {
- "version": _ENCRYPTED_CACHE_VERSION,
- "key": serialized_key,
- "salt": _b64e(salt),
- "nonce": _b64e(nonce),
- "ciphertext": _b64e(ciphertext),
- }
+ payload = {"version": _ENCRYPTED_CACHE_VERSION, "key": serialized_key,
+ "salt": _b64e(salt), "nonce": _b64e(nonce), "ciphertext": _b64e(ciphertext)}
atomic_write_json(_encrypted_disk_cache_path(home_path), payload, tmp_prefix=".bws_cache_enc_")
_STORE.disk.clear(home_path)
except Exception: # noqa: BLE001 — best-effort cache only
return
-def _read_encrypted_disk_cache(
- *,
- cache_key: _CacheKey,
- access_token: str,
- max_age_seconds: float,
- home_path: Optional[Path] = None,
-) -> Optional[_CachedFetch]:
+def _read_encrypted_disk_cache(*, cache_key: _CacheKey, access_token: str, max_age_seconds: float,
+ home_path: Optional[Path] = None) -> Optional[_CachedFetch]:
"""Decrypted encrypted-cache entry if it matches ``cache_key`` and is in-window."""
if max_age_seconds <= 0:
return None
@@ -340,7 +301,8 @@ def _read_encrypted_disk_cache(
or payload.get("version") != _ENCRYPTED_CACHE_VERSION
or payload.get("key") != serialized_key):
return None
- salt, nonce, ciphertext = (_b64d(str(payload.get(k, ""))) for k in ("salt", "nonce", "ciphertext"))
+ salt, nonce, ciphertext = (base64.b64decode(str(payload.get(k, "")).encode("ascii"), validate=True)
+ for k in ("salt", "nonce", "ciphertext"))
key = _derive_encrypted_cache_key(access_token, salt)
entry = entry_from_payload(json.loads(
AESGCM(key).decrypt(nonce, ciphertext, serialized_key.encode("utf-8")).decode("utf-8")
@@ -357,30 +319,20 @@ def _read_encrypted_disk_cache(
def fetch_bitwarden_secrets(
- *,
- access_token: str,
- project_id: str,
- binary: Optional[Path] = None,
- cache_ttl_seconds: float = 300,
- use_cache: bool = True,
- server_url: str = "",
- home_path: Optional[Path] = None,
- encrypted_cache_enabled: bool = False,
+ *, access_token: str, project_id: str, binary: Optional[Path] = None,
+ cache_ttl_seconds: float = 300, use_cache: bool = True, server_url: str = "",
+ home_path: Optional[Path] = None, encrypted_cache_enabled: bool = False,
encrypted_cache_max_stale_seconds: float = 0,
) -> Tuple[Dict[str, str], List[str]]:
"""Pull the secrets for ``project_id`` from BSM → ``(secrets, warnings)``.
- ``server_url`` selects a region / self-hosted instance (empty = bws default,
- US Cloud). ``cache_ttl_seconds`` governs the fresh cache. With
- ``encrypted_cache_enabled`` fresh entries are written AES-GCM encrypted
- instead of plaintext, and a last-good entry may be served after
- NETWORK/TIMEOUT failures for up to ``encrypted_cache_max_stale_seconds`` —
- independent of the fresh TTL, so ``cache_ttl_seconds: 0`` can coexist with
- a break-glass offline cache.
-
- Raises ``RuntimeError`` for fatal conditions (missing binary, auth failure,
- unparseable output); the env_loader path catches, the setup wizard lets it
- propagate.
+ ``server_url``: region / self-hosted instance (empty = US Cloud). With
+ ``encrypted_cache_enabled`` fresh entries are written AES-GCM encrypted and a
+ last-good entry may be served after NETWORK/TIMEOUT failures for up to
+ ``encrypted_cache_max_stale_seconds`` — independent of the fresh TTL, so
+ ``cache_ttl_seconds: 0`` can coexist with a break-glass offline cache.
+ Raises ``RuntimeError`` on fatal conditions (missing binary, auth failure,
+ unparseable output); env_loader catches, the setup wizard lets it propagate.
"""
if not access_token:
raise RuntimeError("Bitwarden access token is empty")
@@ -390,10 +342,8 @@ def fetch_bitwarden_secrets(
cache_key = (_token_fingerprint(access_token), project_id, server_url or "")
def _read_encrypted(max_age: float) -> Optional[_CachedFetch]:
- return _read_encrypted_disk_cache(
- cache_key=cache_key, access_token=access_token,
- max_age_seconds=max_age, home_path=home_path,
- )
+ return _read_encrypted_disk_cache(cache_key=cache_key, access_token=access_token,
+ max_age_seconds=max_age, home_path=home_path)
if use_cache and cache_ttl_seconds > 0:
# L2 (~5ms) vs ~380ms for `bws secret list`.
@@ -406,24 +356,19 @@ def fetch_bitwarden_secrets(
bws = binary or find_bws(install_if_missing=True)
if bws is None:
- raise RuntimeError(
- "bws binary not available — auto-install failed and `bws` is "
- "not on PATH. Install manually from "
- "https://github.com/bitwarden/sdk-sm/releases or re-run "
- "`hermes secrets bitwarden setup`."
- )
+ raise RuntimeError("bws binary not available — auto-install failed and `bws` is "
+ "not on PATH. Install manually from "
+ "https://github.com/bitwarden/sdk-sm/releases or re-run "
+ "`hermes secrets bitwarden setup`.")
try:
secrets, warnings = _run_bws_list(bws, access_token, project_id, server_url)
except RuntimeError as exc:
- # Stale fallback ONLY for transport failures — never AUTH_FAILED or a
- # malformed-output INTERNAL error, where serving old secrets would mask
- # a real config/credential problem. Without it a fleet sharing one BSM
- # project all stops on a single network blip.
- # When the encrypted cache is enabled it is the ONLY fallback consulted
- # (the at-rest payload must never be plaintext). Otherwise the plain
- # DiskCache is read with ttl=inf (a stale hit is the point) but only if
- # the caller's real TTL > 0 — ttl<=0 means caching is opted out.
+ # Stale fallback ONLY for transport failures — never AUTH_FAILED / INTERNAL,
+ # where old secrets would mask a real problem (without it a fleet sharing
+ # one project all stops on a network blip). With the encrypted cache on it
+ # is the ONLY fallback (at-rest payload must never be plaintext); else the
+ # plain DiskCache is read with ttl=inf, but only when the real TTL > 0.
if use_cache and _classify_bws_error(str(exc)) in (ErrorKind.NETWORK, ErrorKind.TIMEOUT):
stale = label = None
if encrypted_cache_enabled:
@@ -443,12 +388,9 @@ def fetch_bitwarden_secrets(
if use_cache:
if cache_ttl_seconds > 0:
_STORE.memory[cache_key] = entry
- if encrypted_cache_enabled:
- # Encryption is the storage policy; max_stale only gates outage
- # reads. Never fall back to plaintext because stale fallback is off.
- _write_encrypted_disk_cache(
- cache_key=cache_key, access_token=access_token, entry=entry, home_path=home_path,
- )
+ if encrypted_cache_enabled: # storage policy; max_stale only gates outage reads
+ _write_encrypted_disk_cache(cache_key=cache_key, access_token=access_token,
+ entry=entry, home_path=home_path)
else:
_STORE.disk.write(cache_key, entry, cache_ttl_seconds, home_path)
return secrets, warnings
@@ -477,9 +419,7 @@ def _summarize_bws_stderr(raw: str) -> str:
return "; ".join(causes) if causes else text
-def _run_bws_list(
- bws: Path, access_token: str, project_id: str, server_url: str = ""
-) -> Tuple[Dict[str, str], List[str]]:
+def _run_bws_list(bws: Path, access_token: str, project_id: str, server_url: str = "") -> Tuple[Dict[str, str], List[str]]:
cmd = [str(bws), "secret", "list", project_id, "--output", "json"]
# The bws child intentionally receives the access token; a profile-local
# fetch must not inherit sibling credentials (source_child_env).
@@ -509,15 +449,13 @@ def _run_bws_list(
secrets: Dict[str, str] = {}
warnings: List[str] = []
for item in payload:
- if not isinstance(item, dict):
- continue
- key, value = item.get("key"), item.get("value")
+ key, value = (item.get("key"), item.get("value")) if isinstance(item, dict) else (None, None)
if not isinstance(key, str) or not isinstance(value, str):
continue
- if not _is_valid_env_name(key):
+ if _is_valid_env_name(key):
+ secrets[key] = value
+ else:
warnings.append(f"Skipping secret {key!r}: not a valid env-var name")
- continue
- secrets[key] = value
return secrets, warnings
@@ -549,19 +487,13 @@ class BitwardenSource(SecretSource):
def config_schema(self) -> dict:
return {
"enabled": {"description": "Master switch", "default": False},
- "access_token_env": {
- "description": "Env var holding the machine-account access token",
- "default": "BWS_ACCESS_TOKEN",
- },
+ "access_token_env": {"description": "Env var holding the machine-account access token",
+ "default": "BWS_ACCESS_TOKEN"},
"project_id": {"description": "BSM project UUID", "default": ""},
- "cache_ttl_seconds": {
- "description": "Fresh disk+memory cache TTL; 0 disables fresh-cache reuse",
- "default": 300,
- },
- "encrypted_cache": {
- "description": "Encrypted last-good cache for network/timeout fallback",
- "default": {"enabled": False, "max_stale_seconds": 0},
- },
+ "cache_ttl_seconds": {"description": "Fresh disk+memory cache TTL; 0 disables fresh-cache reuse",
+ "default": 300},
+ "encrypted_cache": {"description": "Encrypted last-good cache for network/timeout fallback",
+ "default": {"enabled": False, "max_stale_seconds": 0}},
"override_existing": {"description": "BSM values overwrite .env/shell values", "default": True},
"auto_install": {"description": "Auto-download the pinned bws binary", "default": True},
"server_url": {"description": "Region / self-hosted endpoint (empty = US Cloud)", "default": ""},
@@ -574,51 +506,35 @@ class BitwardenSource(SecretSource):
access_token_env = self.token_env(cfg)
access_token = get_source_environment().get(access_token_env, "").strip()
if not access_token:
- return result.fail(
- f"secrets.bitwarden.enabled is true but {access_token_env} is "
- "not set. Run `hermes secrets bitwarden setup`.",
- ErrorKind.NOT_CONFIGURED,
- )
-
+ return result.fail(f"secrets.bitwarden.enabled is true but {access_token_env} is "
+ "not set. Run `hermes secrets bitwarden setup`.", ErrorKind.NOT_CONFIGURED)
project_id = str(cfg.get("project_id") or "")
if not project_id:
- return result.fail(
- "secrets.bitwarden.project_id is empty. Run `hermes secrets bitwarden setup`.",
- ErrorKind.NOT_CONFIGURED,
- )
-
+ return result.fail("secrets.bitwarden.project_id is empty. Run `hermes secrets bitwarden setup`.",
+ ErrorKind.NOT_CONFIGURED)
binary = find_bws(install_if_missing=bool(cfg.get("auto_install", True)))
result.binary_path = binary
if binary is None:
- return result.fail(
- "bws binary not available and auto-install is disabled. "
- "Run `hermes secrets bitwarden setup` to install.",
- ErrorKind.BINARY_MISSING,
- )
+ return result.fail("bws binary not available and auto-install is disabled. "
+ "Run `hermes secrets bitwarden setup` to install.", ErrorKind.BINARY_MISSING)
encrypted_cfg = cfg.get("encrypted_cache")
encrypted_cfg = encrypted_cfg if isinstance(encrypted_cfg, dict) else {}
try:
secrets, warnings = fetch_bitwarden_secrets(
- access_token=access_token,
- project_id=project_id,
- binary=binary,
+ access_token=access_token, project_id=project_id, binary=binary,
cache_ttl_seconds=coerce_float(cfg.get("cache_ttl_seconds", 300), 300.0),
- server_url=str(cfg.get("server_url", "") or "").strip(),
- home_path=home_path,
+ server_url=str(cfg.get("server_url", "") or "").strip(), home_path=home_path,
encrypted_cache_enabled=bool(encrypted_cfg.get("enabled", False)),
encrypted_cache_max_stale_seconds=coerce_float(encrypted_cfg.get("max_stale_seconds", 0), 0.0),
)
except RuntimeError as exc:
result.fail(str(exc), _classify_bws_error(str(exc)))
- if result.error_kind == ErrorKind.AUTH_FAILED:
- # Say what the raw OAuth reject means for the user first.
- result.error = (
- "Bitwarden rejected the machine-account access token "
- f"({access_token_env}) — it was likely revoked, expired, "
- f"or belongs to another region. ({result.error})"
- )
+ if result.error_kind == ErrorKind.AUTH_FAILED: # say what the raw OAuth reject means first
+ result.error = ("Bitwarden rejected the machine-account access token "
+ f"({access_token_env}) — it was likely revoked, expired, "
+ f"or belongs to another region. ({result.error})")
return result
result.secrets = secrets
diff --git a/agent/secret_sources/command.py b/agent/secret_sources/command.py
index 1b0994b8071..43af5830712 100644
--- a/agent/secret_sources/command.py
+++ b/agent/secret_sources/command.py
@@ -25,18 +25,9 @@ import sys
from pathlib import Path
from typing import Dict, Optional
-from agent.secret_sources.base import (
- ErrorKind,
- FetchResult,
- SecretSource,
- coerce_float,
- source_child_env,
-)
-
-__all__ = [
- "FetchResult",
- "unquote_dotenv_value",
-]
+from agent.secret_sources.base import ErrorKind, FetchResult, SecretSource, coerce_float, source_child_env
+
+__all__ = ["FetchResult", "unquote_dotenv_value"]
# TIGHT on purpose: a helper MUST be fast and NON-INTERACTIVE (an already
# unlocked DB, `secret-tool lookup`, `cat` of a tmpfs file) — not a PIN prompt.
@@ -85,11 +76,8 @@ def _run_helper(command: str, secret_key: str, timeout_seconds: float, max_outpu
try:
proc = subprocess.Popen( # noqa: S602 — command is the user's own config
- ["/bin/sh", "-c", command],
- env=env,
- stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE, # captured and DISCARDED — never inherited
+ ["/bin/sh", "-c", command], env=env, stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, # stderr captured and DISCARDED — never inherited
start_new_session=True, # so the hard timeout can kill the whole group
)
except OSError as exc:
@@ -113,14 +101,13 @@ def _run_helper(command: str, secret_key: str, timeout_seconds: float, max_outpu
return None
if proc.returncode != 0:
+ code, signame = str(proc.returncode), "none"
if proc.returncode < 0:
try:
- sig = _signal.Signals(-proc.returncode).name
+ signame = _signal.Signals(-proc.returncode).name
except ValueError:
- sig = str(-proc.returncode)
- code, signame = "?", sig
- else:
- code, signame = str(proc.returncode), "none"
+ signame = str(-proc.returncode)
+ code = "?"
_log(f"helper failed; resolving no value: code={code} signal={signame}")
return None
@@ -171,19 +158,11 @@ class CommandSource(SecretSource):
def config_schema(self) -> dict:
return {
"enabled": {"description": "Master switch", "default": False},
- "command": {
- "description": "Helper run via /bin/sh -c; must print a "
- "KEY=VALUE blob on stdout",
- "default": "",
- },
- "helper_timeout_seconds": {
- "description": "Hard timeout for one helper run",
- "default": _COMMAND_TIMEOUT_SECONDS,
- },
- "override_existing": {
- "description": "Helper values overwrite .env/shell values",
- "default": False,
- },
+ "command": {"description": "Helper run via /bin/sh -c; must print a KEY=VALUE blob on stdout",
+ "default": ""},
+ "helper_timeout_seconds": {"description": "Hard timeout for one helper run",
+ "default": _COMMAND_TIMEOUT_SECONDS},
+ "override_existing": {"description": "Helper values overwrite .env/shell values", "default": False},
}
def fetch(self, cfg: dict, home_path: Path) -> FetchResult:
@@ -192,25 +171,18 @@ class CommandSource(SecretSource):
command = str(cfg.get("command") or "").strip()
if not command:
- return result.fail(
- "secrets.command.enabled is true but secrets.command.command "
- "is empty. Set the helper command in config.yaml.",
- ErrorKind.NOT_CONFIGURED,
- )
+ return result.fail("secrets.command.enabled is true but secrets.command.command "
+ "is empty. Set the helper command in config.yaml.", ErrorKind.NOT_CONFIGURED)
if _is_windows():
- return result.fail(
- "the 'command' secret source is POSIX-only (needs /bin/sh); skipping on Windows",
- ErrorKind.NOT_CONFIGURED,
- )
+ return result.fail("the 'command' secret source is POSIX-only (needs /bin/sh); skipping on Windows",
+ ErrorKind.NOT_CONFIGURED)
timeout = coerce_float(cfg.get("helper_timeout_seconds", _COMMAND_TIMEOUT_SECONDS),
_COMMAND_TIMEOUT_SECONDS)
stdout = _run_helper(command, "", timeout, _MAX_OUTPUT_BYTES)
if stdout is None: # _run_helper already logged structured fields
- return result.fail(
- "helper command failed (see structured fields above); no secrets applied",
- ErrorKind.INTERNAL,
- )
+ return result.fail("helper command failed (see structured fields above); no secrets applied",
+ ErrorKind.INTERNAL)
secrets = _parse_dotenv_map(stdout)
if not secrets:
diff --git a/agent/secret_sources/onepassword.py b/agent/secret_sources/onepassword.py
index e2f8142a867..c9165294d17 100644
--- a/agent/secret_sources/onepassword.py
+++ b/agent/secret_sources/onepassword.py
@@ -21,14 +21,8 @@ from typing import Dict, List, Optional, Tuple
from agent.secret_sources._cache import CachedFetch, SecretCache, fingerprint as _fingerprint
from agent.secret_sources.base import (
- ErrorKind,
- FetchResult,
- SecretSource,
- classify_cli_error,
- coerce_float,
- get_source_environment,
- is_valid_env_name,
- run_cli,
+ ErrorKind, FetchResult, SecretSource, classify_cli_error, coerce_float,
+ get_source_environment, is_valid_env_name, run_cli,
)
logger = logging.getLogger(__name__)
@@ -110,12 +104,9 @@ def _auth_fingerprint(token_env: str) -> str:
cache key and a value cached under the old identity is never served.
"""
source_env = get_source_environment()
- parts: List[str] = [
- f"token={source_env.get(token_env, '')}",
- f"account={source_env.get('OP_ACCOUNT', '')}",
- f"connect_host={source_env.get('OP_CONNECT_HOST', '')}",
- f"connect_token={source_env.get('OP_CONNECT_TOKEN', '')}",
- ]
+ parts: List[str] = [f"{label}={source_env.get(var, '')}" for label, var in (
+ ("token", token_env), ("account", "OP_ACCOUNT"),
+ ("connect_host", "OP_CONNECT_HOST"), ("connect_token", "OP_CONNECT_TOKEN"))]
parts += [f"{key}={source_env[key]}" for key in sorted(source_env) if key.startswith("OP_SESSION_")]
return _fingerprint("\n".join(parts))
@@ -165,11 +156,8 @@ def _run_op_read(op: Path, reference: str, *, account: str = "", token_value: st
cmd += ["--account", account]
cmd += ["--", reference] # `--` so a reference can never parse as an op flag
- proc = run_cli(
- cmd, env=_op_child_env(token_value), timeout=_OP_RUN_TIMEOUT, label="op",
- timeout_message=f"op read timed out after {_OP_RUN_TIMEOUT}s for {reference!r}",
- stdin=None,
- )
+ proc = run_cli(cmd, env=_op_child_env(token_value), timeout=_OP_RUN_TIMEOUT, label="op",
+ timeout_message=f"op read timed out after {_OP_RUN_TIMEOUT}s for {reference!r}", stdin=None)
if proc.returncode != 0:
err = _scrub(proc.stderr or "")[:200]
@@ -185,15 +173,9 @@ def _run_op_read(op: Path, reference: str, *, account: str = "", token_value: st
def fetch_onepassword_secrets(
- *,
- references: Dict[str, str],
- account: str = "",
- token_env: str = _DEFAULT_TOKEN_ENV,
- binary: Optional[Path] = None,
- binary_path: str = "",
- use_cache: bool = True,
- cache_ttl_seconds: float = 300,
- home_path: Optional[Path] = None,
+ *, references: Dict[str, str], account: str = "", token_env: str = _DEFAULT_TOKEN_ENV,
+ binary: Optional[Path] = None, binary_path: str = "", use_cache: bool = True,
+ cache_ttl_seconds: float = 300, home_path: Optional[Path] = None,
) -> Tuple[Dict[str, str], List[str]]:
"""Resolve ``references`` (name → ``op://…``) to ``(secrets, warnings)``.
@@ -207,12 +189,8 @@ def fetch_onepassword_secrets(
return {}, warnings
token_value = get_source_environment().get(token_env, "").strip()
- cache_key: _CacheKey = (
- _auth_fingerprint(token_env),
- account or "",
- str(home_path) if home_path is not None else "",
- _refs_fingerprint(valid),
- )
+ cache_key: _CacheKey = (_auth_fingerprint(token_env), account or "",
+ str(home_path) if home_path is not None else "", _refs_fingerprint(valid))
if use_cache:
cached = _STORE.lookup(cache_key, cache_ttl_seconds, home_path)
@@ -221,11 +199,9 @@ def fetch_onepassword_secrets(
op = binary or find_op(binary_path)
if op is None:
- raise RuntimeError(
- "op CLI not found. Install the 1Password CLI "
- "(https://developer.1password.com/docs/cli/get-started/) or set "
- "secrets.onepassword.binary_path to its absolute location."
- )
+ raise RuntimeError("op CLI not found. Install the 1Password CLI "
+ "(https://developer.1password.com/docs/cli/get-started/) or set "
+ "secrets.onepassword.binary_path to its absolute location.")
secrets: Dict[str, str] = {}
read_errors = 0
@@ -246,24 +222,14 @@ def fetch_onepassword_secrets(
def _missing_binary_error(binary_path: str) -> str:
if binary_path:
return f"secrets.onepassword.binary_path ({binary_path!r}) is not an executable op binary."
- return (
- "secrets.onepassword.enabled is true but the op CLI was not "
- "found on PATH. Install it "
- "(https://developer.1password.com/docs/cli/get-started/) or set "
- "secrets.onepassword.binary_path."
- )
+ return ("secrets.onepassword.enabled is true but the op CLI was not found on PATH. Install it "
+ "(https://developer.1password.com/docs/cli/get-started/) or set secrets.onepassword.binary_path.")
def apply_onepassword_secrets(
- *,
- enabled: bool,
- env: Optional[Dict[str, str]] = None,
- account: str = "",
- service_account_token_env: str = _DEFAULT_TOKEN_ENV,
- binary_path: str = "",
- override_existing: bool = True,
- cache_ttl_seconds: float = 300,
- home_path: Optional[Path] = None,
+ *, enabled: bool, env: Optional[Dict[str, str]] = None, account: str = "",
+ service_account_token_env: str = _DEFAULT_TOKEN_ENV, binary_path: str = "",
+ override_existing: bool = True, cache_ttl_seconds: float = 300, home_path: Optional[Path] = None,
) -> FetchResult:
"""Resolve configured ``op://`` references and set them on ``os.environ``
(``hermes secrets onepassword sync --apply``).
@@ -282,16 +248,10 @@ def apply_onepassword_secrets(
def _guarded(name: str) -> bool:
"""True when ``name`` must not be applied (token var or env already set)."""
- return name == service_account_token_env or (
- not override_existing and bool(os.environ.get(name))
- )
-
- refs_to_fetch: Dict[str, str] = {}
- for name, ref in valid.items():
- if _guarded(name):
- result.skipped.append(name)
- else:
- refs_to_fetch[name] = ref
+ return name == service_account_token_env or (not override_existing and bool(os.environ.get(name)))
+
+ result.skipped.extend(n for n in valid if _guarded(n))
+ refs_to_fetch = {n: ref for n, ref in valid.items() if not _guarded(n)}
if not refs_to_fetch:
return result
@@ -303,13 +263,8 @@ def apply_onepassword_secrets(
try:
secrets, fetch_warnings = fetch_onepassword_secrets(
- references=refs_to_fetch,
- account=account,
- token_env=service_account_token_env,
- binary=binary,
- cache_ttl_seconds=cache_ttl_seconds,
- home_path=home_path,
- )
+ references=refs_to_fetch, account=account, token_env=service_account_token_env,
+ binary=binary, cache_ttl_seconds=cache_ttl_seconds, home_path=home_path)
except RuntimeError as exc:
result.error = str(exc)
return result
@@ -343,26 +298,19 @@ class OnePasswordSource(SecretSource):
# override_existing defaults True: an explicit VAR→op:// binding is the
# strongest user intent; a stale .env line must not silently defeat it.
override_existing_default = True
- remediation_hints = {
- ErrorKind.AUTH_FAILED: "Run `hermes secrets onepassword token` to paste a fresh "
- "service-account token ({token_env}), or `op signin` for an "
- "interactive session.",
- ErrorKind.AUTH_EXPIRED: "Run `hermes secrets onepassword token` to paste a fresh "
- "service-account token ({token_env}), or `op signin` for an "
- "interactive session.",
- ErrorKind.BINARY_MISSING: _MISSING_BINARY_HINT,
- }
+ _AUTH_HINT = ("Run `hermes secrets onepassword token` to paste a fresh service-account token "
+ "({token_env}), or `op signin` for an interactive session.")
+ remediation_hints = {ErrorKind.AUTH_FAILED: _AUTH_HINT, ErrorKind.AUTH_EXPIRED: _AUTH_HINT,
+ ErrorKind.BINARY_MISSING: _MISSING_BINARY_HINT}
def config_schema(self) -> dict:
return {
"enabled": {"description": "Master switch", "default": False},
"env": {"description": "Map of ENV_VAR -> op://vault/item/field reference", "default": {}},
"account": {"description": "op --account shorthand (empty = default account)", "default": ""},
- "service_account_token_env": {
- "description": "Env var holding the service-account token "
- "(unset = desktop/interactive session)",
- "default": _DEFAULT_TOKEN_ENV,
- },
+ "service_account_token_env": {"description": "Env var holding the service-account token "
+ "(unset = desktop/interactive session)",
+ "default": _DEFAULT_TOKEN_ENV},
"binary_path": {"description": "Pin the op binary (empty = resolve via PATH)", "default": ""},
"cache_ttl_seconds": {"description": "Disk+memory cache TTL; 0 disables", "default": 300},
"override_existing": {"description": "Resolved values overwrite .env/shell values", "default": True},
@@ -377,11 +325,8 @@ class OnePasswordSource(SecretSource):
result.warnings.extend(warnings)
if not valid:
if not warnings:
- result.fail(
- "secrets.onepassword.enabled is true but the env: map is "
- "empty. Add ENV_VAR: op://vault/item/field entries.",
- ErrorKind.NOT_CONFIGURED,
- )
+ result.fail("secrets.onepassword.enabled is true but the env: map is "
+ "empty. Add ENV_VAR: op://vault/item/field entries.", ErrorKind.NOT_CONFIGURED)
return result
binary_path = str(cfg.get("binary_path") or "")
@@ -392,13 +337,9 @@ class OnePasswordSource(SecretSource):
try:
secrets, fetch_warnings = fetch_onepassword_secrets(
- references=valid,
- account=str(cfg.get("account") or ""),
- token_env=self.token_env(cfg),
- binary=binary,
- cache_ttl_seconds=coerce_float(cfg.get("cache_ttl_seconds", 300), 300.0),
- home_path=home_path,
- )
+ references=valid, account=str(cfg.get("account") or ""), token_env=self.token_env(cfg),
+ binary=binary, cache_ttl_seconds=coerce_float(cfg.get("cache_ttl_seconds", 300), 300.0),
+ home_path=home_path)
except RuntimeError as exc:
return result.fail(str(exc), _classify_op_error(str(exc)))
diff --git a/agent/secret_sources/registry.py b/agent/secret_sources/registry.py
index 034f0117572..55da1d962dd 100644
--- a/agent/secret_sources/registry.py
+++ b/agent/secret_sources/registry.py
@@ -21,13 +21,8 @@ from pathlib import Path
from typing import Dict, List, MutableMapping, Optional
from agent.secret_sources.base import (
- SECRET_SOURCE_API_VERSION,
- ErrorKind,
- FetchResult,
- SecretSource,
- is_valid_env_name,
- reset_source_environment,
- set_source_environment,
+ SECRET_SOURCE_API_VERSION, ErrorKind, FetchResult, SecretSource, is_valid_env_name,
+ reset_source_environment, set_source_environment,
)
from hermes_constants import hermes_home_key
@@ -104,13 +99,8 @@ def _validate_source(source: SecretSource) -> Optional[str]:
return None
-def register_source(
- source: SecretSource,
- *,
- replace: bool = False,
- builtin: bool = False,
- scope: Optional[str] = None,
-) -> bool:
+def register_source(source: SecretSource, *, replace: bool = False, builtin: bool = False,
+ scope: Optional[str] = None) -> bool:
"""Register a secret source. Returns True on success.
Rejections are logged, never raised — a bad plugin must not take down
@@ -130,14 +120,12 @@ def register_source(
if name in effective and not replace:
logger.warning("Secret source '%s' already registered; ignoring duplicate", name)
return False
- if source.scheme:
- for other_name, other in effective.items():
- if other_name != name and other.scheme == source.scheme:
- logger.warning(
- "Ignoring secret source '%s': scheme '%s://' is already owned by source '%s'",
- name, source.scheme, other_name,
- )
- return False
+ owner = next((n for n, o in effective.items()
+ if n != name and source.scheme and o.scheme == source.scheme), None)
+ if owner:
+ logger.warning("Ignoring secret source '%s': scheme '%s://' is already owned by source '%s'",
+ name, source.scheme, owner)
+ return False
target = _SOURCES if scope is None else _SCOPED_SOURCES.setdefault(scope, {})
target[name] = source
if scope is None:
@@ -166,13 +154,8 @@ def snapshot_registration(name: str, *, scope: Optional[str] = None) -> Optional
return target.get(name)
-def restore_registration(
- name: str,
- current: SecretSource,
- previous: Optional[SecretSource],
- *,
- scope: Optional[str] = None,
-) -> bool:
+def restore_registration(name: str, current: SecretSource, previous: Optional[SecretSource], *,
+ scope: Optional[str] = None) -> bool:
"""Restore a host-owned source registration if it is still current."""
_ensure_builtin_sources()
with _REGISTRY_LOCK:
@@ -235,10 +218,8 @@ def _reset_registry_for_tests() -> None:
# --- Orchestrated apply -----------------------------------------------------
-def _fetch_with_timeout(
- source: SecretSource, cfg: dict, home_path: Path,
- environ: MutableMapping[str, str],
-) -> FetchResult:
+def _fetch_with_timeout(source: SecretSource, cfg: dict, home_path: Path,
+ environ: MutableMapping[str, str]) -> FetchResult:
"""Run source.fetch() under a wall-clock budget; never raises.
A daemon worker thread enforces the budget: a source that blows it is
@@ -247,9 +228,7 @@ def _fetch_with_timeout(
better than an unbounded hang on every ``hermes`` invocation.
"""
timeout = source.fetch_timeout_seconds(cfg)
- executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=1, thread_name_prefix=f"secret-src-{source.name}"
- )
+ executor = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"secret-src-{source.name}")
try:
def _fetch() -> FetchResult:
token = set_source_environment(environ)
@@ -263,21 +242,18 @@ def _fetch_with_timeout(
result = future.result(timeout=timeout)
except concurrent.futures.TimeoutError:
future.cancel()
- return FetchResult().fail(
- f"fetch exceeded {timeout:.0f}s budget — startup continued "
- "without this source (raise secrets."
- f"{source.name}.timeout_seconds if the backend is just slow)",
- ErrorKind.TIMEOUT,
- )
+ return FetchResult().fail(f"fetch exceeded {timeout:.0f}s budget — startup continued "
+ "without this source (raise secrets."
+ f"{source.name}.timeout_seconds if the backend is just slow)",
+ ErrorKind.TIMEOUT)
except Exception as exc: # noqa: BLE001 — contract violation, contain it
return FetchResult().fail(f"fetch raised {type(exc).__name__}: {exc}", ErrorKind.INTERNAL)
finally:
executor.shutdown(wait=False)
if not isinstance(result, FetchResult):
- return FetchResult().fail(
- f"fetch returned {type(result).__name__} instead of FetchResult", ErrorKind.INTERNAL,
- )
+ return FetchResult().fail(f"fetch returned {type(result).__name__} instead of FetchResult",
+ ErrorKind.INTERNAL)
return result
@@ -299,10 +275,8 @@ def _ordered_enabled_sources(secrets_cfg: dict, *, scope: Optional[str] = None)
order.update((n, None) for n in names if n in sources)
unknown = [n for n in names if n not in sources]
if unknown:
- logger.warning(
- "secrets.sources names unknown source(s): %s (known: %s)",
- ", ".join(unknown), ", ".join(sources) or "none",
- )
+ logger.warning("secrets.sources names unknown source(s): %s (known: %s)",
+ ", ".join(unknown), ", ".join(sources) or "none")
order.update((n, None) for n in sources)
enabled: List[SecretSource] = []
@@ -374,9 +348,7 @@ class _Applier:
alias = _profile_alias_target(var, profile)
if (alias and alias not in supplied_directly and alias not in self.claimed
and self._try_apply(sr, source, override, alias, value)):
- result.warnings.append(
- f"applied profile-scoped {var} as {alias} (active profile {profile!r})"
- )
+ result.warnings.append(f"applied profile-scoped {var} as {alias} (active profile {profile!r})")
def _try_apply(self, sr: SourceReport, source: SecretSource, override: bool,
var: str, value: str) -> bool:
@@ -389,11 +361,9 @@ class _Applier:
return False
if var in self.claimed:
sr.skipped_claimed.append(var)
- self.report.conflicts.append(
- f"{var}: kept value from {self.claimed[var]}; "
- f"{source.name} also supplies it (first source wins — "
- "remove one binding or reorder secrets.sources)"
- )
+ self.report.conflicts.append(f"{var}: kept value from {self.claimed[var]}; "
+ f"{source.name} also supplies it (first source wins — "
+ "remove one binding or reorder secrets.sources)")
return False
existed = bool(self.env.get(var))
if existed and (var in self.preserve or not override):
@@ -408,27 +378,20 @@ class _Applier:
def apply_all(secrets_cfg: dict, home_path: Path,
environ: Optional[MutableMapping[str, str]] = None) -> ApplyReport:
- """Fetch from every enabled source and apply the merged result to env.
-
- ``environ`` defaults to ``os.environ``; injectable for tests.
-
- Precedence per env var (most-specific intent wins):
-
- 1. ``secrets.preserve_existing`` names — a pre-existing env value always
- wins, even against ``override_existing: true``.
- 2. Pre-existing env (.env / shell) — unless the winning source has
- ``override_existing: true``.
- 3. Mapped sources, in configured order.
- 4. Bulk sources, in configured order.
-
- First claim wins: a later source carrying the same var gets a
- ``skipped_claimed`` entry and a conflict warning — never a silent clobber,
+ """Fetch from every enabled source and apply the merged result to ``environ``
+ (default ``os.environ``).
+
+ Precedence per env var, most-specific intent first: (1) ``secrets.preserve_existing``
+ names always keep a pre-existing value, even against ``override_existing: true``;
+ (2) pre-existing .env/shell value, unless the winning source has
+ ``override_existing: true``; (3) mapped sources in configured order; (4) bulk
+ sources in configured order. First claim wins: a later source carrying the same
+ var gets ``skipped_claimed`` plus a conflict warning — never a silent clobber,
and ``override_existing`` never applies across sources.
Profile aliasing: under a named profile an applied ``FOO_<PROFILE>``
- (credential-shaped suffixes only) also hydrates canonical ``FOO`` so
- adapters reading fixed env names see the profile's value. The alias obeys
- the same guards and is disabled with ``secrets.profile_alias: false``.
+ (credential-shaped suffixes only) also hydrates canonical ``FOO``, under the
+ same guards; disabled with ``secrets.profile_alias: false``.
"""
env = environ if environ is not None else os.environ
report = ApplyReport()
@@ -439,14 +402,12 @@ def apply_all(secrets_cfg: dict, home_path: Path,
return report
preserve_raw = secrets_cfg.get("preserve_existing")
- preserve = frozenset(
- n.strip() for n in preserve_raw if isinstance(n, str) and n.strip()
- ) if isinstance(preserve_raw, list) else frozenset()
+ preserve = frozenset(n.strip() for n in preserve_raw if isinstance(n, str) and n.strip()
+ ) if isinstance(preserve_raw, list) else frozenset()
profile = _active_profile_name(home_path) if secrets_cfg.get("profile_alias", True) else ""
# Mapped outranks bulk regardless of list order.
- ordered = ([s for s in enabled if s.shape == "mapped"]
- + [s for s in enabled if s.shape == "bulk"])
+ ordered = [s for s in enabled if s.shape == "mapped"] + [s for s in enabled if s.shape == "bulk"]
fetches: List[tuple[SecretSource, dict, FetchResult]] = []
protected: Dict[str, str] = {} # var → source that protects it