Skip to content

The agent that grows with you

refactor(agent/secret_sources): shared fingerprint + remediation_hints table, _validate_source, drop unused _cache re-exports, compact docstrings

Teknium5117249d39b8
diff --git a/agent/secret_scope.py b/agent/secret_scope.py
index 7497d6abb78..81e3935c3d5 100644
--- a/agent/secret_scope.py
+++ b/agent/secret_scope.py
@@ -1,22 +1,13 @@
"""Profile-scoped credential resolution for multi-profile gateway multiplexing.
-The multiplexing gateway serves many profiles from one process. Each profile
-has its own ``.env`` with its own keys, so they **cannot** be unioned into the
-process-global ``os.environ`` (profile A's keys would leak into profile B's
-turns and into every subprocess spawned with ``env=dict(os.environ)``).
-
-This module is a fail-closed, context-local secret scope:
-
-- ``set_secret_scope(mapping)`` installs the active profile's secrets for the
- current task (a contextvar, so it propagates into the agent's worker thread
- via ``copy_context()`` exactly like the HERMES_HOME override).
-- ``get_secret(name)`` reads from that scope. When multiplexing is **active**
- and no scope is set it RAISES rather than falling back to ``os.environ`` —
- an un-migrated call site fails loud at that line instead of leaking another
- profile's value. When multiplexing is **off** (default) it reads
- ``os.environ`` so every non-multiplex caller behaves exactly as before.
-
-Design rationale: ``docs/design/multiplexing-gateway.md`` (Workstream A).
+The multiplexing gateway serves many profiles from one process; each profile's
+``.env`` keys **cannot** be unioned into ``os.environ`` (profile A's keys would
+leak into profile B's turns and subprocesses). This module is a fail-closed,
+context-local secret scope: ``set_secret_scope(mapping)`` installs the active
+profile's secrets for the current task (a contextvar, so it propagates into the
+agent's worker thread via ``copy_context()``); ``get_secret(name)`` reads from
+it and, when multiplexing is active with no scope set, RAISES rather than
+falling back to ``os.environ``. Design: ``docs/design/multiplexing-gateway.md``.
"""
from __future__ import annotations
@@ -42,9 +33,7 @@ def is_multiplex_active() -> bool:
return _MULTIPLEX_ACTIVE
-_SECRET_SCOPE: ContextVar[Optional[Mapping[str, str]]] = ContextVar(
- "_SECRET_SCOPE", default=None
-)
+_SECRET_SCOPE: ContextVar[Optional[Mapping[str, str]]] = ContextVar("_SECRET_SCOPE", default=None)
class UnscopedSecretError(RuntimeError):
@@ -56,7 +45,7 @@ class UnscopedSecretError(RuntimeError):
def set_secret_scope(secrets: Optional[Mapping[str, str]]) -> Token:
- """Install the active profile's secret mapping; ``None`` clears. Returns a reset token."""
+ """Install the active profile's secret mapping; ``None`` clears. Returns a reset token."""
return _SECRET_SCOPE.set(secrets)
@@ -71,8 +60,8 @@ def current_secret_scope() -> Optional[Mapping[str, str]]:
# Genuinely-global env vars: process/deployment settings, NOT profile secrets.
# They keep reading os.environ even in multiplex mode (routing them through the
-# fail-closed path would wrongly crash). Keep this tight — when in doubt a
-# value is a profile secret. Membership is exact name OR prefix.
+# fail-closed path would wrongly crash). Keep this tight — when in doubt a
+# value is a profile secret. Membership is exact name OR prefix.
_GLOBAL_ENV_EXACT = frozenset({
# Hermes runtime / deployment
"HERMES_HOME", "HERMES_PROFILE", "HERMES_GATEWAY_LOCK_DIR",
@@ -86,13 +75,13 @@ _GLOBAL_ENV_EXACT = frozenset({
"HERMES_KANBAN_DB", "HERMES_KANBAN_WORKSPACES_ROOT", "HERMES_KANBAN_BOARD",
# API-server LISTENER settings — deployment config (compose/systemd env),
# which the scoped runner reload must keep seeing or containers silently
- # lose the api_server platform. API_SERVER_KEY is a credential: NOT here.
+ # lose the api_server platform. API_SERVER_KEY is a credential: NOT here.
"API_SERVER_ENABLED", "API_SERVER_HOST", "API_SERVER_PORT",
"API_SERVER_CORS_ORIGINS",
- # Relay-connector ROUTING stamps injected by managed deploys. Every reader
+ # Relay-connector ROUTING stamps injected by managed deploys. Every reader
# (gateway.config, relay_url()/registration/self-provision) must resolve
# the SAME value or the adapter registers while the platform is absent
- # from config. GATEWAY_RELAY_SECRET/_ID/_DELIVERY_KEY and IDP_* are auth
+ # from config. GATEWAY_RELAY_SECRET/_ID/_DELIVERY_KEY and IDP_* are auth
# material and deliberately stay profile-scoped.
"GATEWAY_RELAY_URL", "GATEWAY_RELAY_ENDPOINT",
"GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS",
@@ -121,9 +110,9 @@ def get_secret(name: str, default: Optional[str] = None) -> Optional[str]:
"""Resolve a credential by env-var name, honoring the active profile scope.
1. Global vars (``_is_global_env``) always read ``os.environ``.
- 2. Scope installed: read from it. Under multiplexing the scope is
+ 2. Scope installed: read from it. Under multiplexing the scope is
authoritative (a miss returns ``default``, never ``os.environ``, which
- may hold another profile's value). With multiplexing OFF a miss falls
+ may hold another profile's value). With multiplexing OFF a miss falls
through to ``os.environ``: single-profile deployments legitimately
inject credentials via the process env (systemd, ``op run``, shell
exports) and the scope — installed around e.g. every cron job — must
@@ -139,9 +128,7 @@ def get_secret(name: str, default: Optional[str] = None) -> Optional[str]:
val = scope.get(name)
if val is not None:
return val
- if _MULTIPLEX_ACTIVE:
- return default
- return _environ_or(name, default)
+ return default if _MULTIPLEX_ACTIVE else _environ_or(name, default)
if _MULTIPLEX_ACTIVE:
raise UnscopedSecretError(
@@ -152,7 +139,6 @@ def get_secret(name: str, default: Optional[str] = None) -> Optional[str]:
f"profile's value. See docs/design/multiplexing-gateway.md "
f"(Workstream A)."
)
-
return _environ_or(name, default)
@@ -178,10 +164,7 @@ def _strip_inline_comment(value: str) -> str:
i += 2 # skip the escaped character
continue
if ch == quote:
- remainder = value[i + 1:].lstrip()
- if remainder.startswith("#"):
- return value[: i + 1]
- return value
+ return value[: i + 1] if value[i + 1:].lstrip().startswith("#") else value
i += 1
return value # unterminated quote: leave as-is
return re.split(r"\s+#", value, maxsplit=1)[0].strip()
@@ -193,7 +176,7 @@ def load_env_file(env_path: Path) -> Dict[str, str]:
Handles the subset Hermes writes (``export`` prefix, full-line and inline
``#`` comments, quotes with the writer's escapes reversed via the canonical
``_parse_env_value`` — stripping only outer quotes would corrupt credentials
- containing ``"`` or ``\\``). ``utf-8-sig`` so a Windows BOM doesn't prefix
+ containing ``"`` or ``\\``). ``utf-8-sig`` so a Windows BOM doesn't prefix
the first key as ``\\ufeffNAME``.
"""
secrets: Dict[str, str] = {}
@@ -210,32 +193,23 @@ def load_env_file(env_path: Path) -> Dict[str, str]:
continue
if line.startswith("export "):
line = line[len("export "):].lstrip()
- if "=" not in line:
- continue
- key, _, value = line.partition("=")
+ key, sep, value = line.partition("=")
key = key.strip()
- if not key:
- continue
- secrets[key] = _parse_env_value(_strip_inline_comment(value))
-
+ if sep and key:
+ secrets[key] = _parse_env_value(_strip_inline_comment(value))
return secrets
def build_profile_secret_scope(hermes_home: Path) -> Dict[str, str]:
"""Build a profile's secret mapping from ``<home>/.env`` plus its external
- secret sources. Global vars are NOT copied in — ``get_secret`` reads those
+ secret sources. Global vars are NOT copied in — ``get_secret`` reads those
from ``os.environ`` — so the scope holds only profile secrets."""
home = Path(hermes_home)
secrets = load_env_file(home / ".env")
-
try:
from hermes_cli.env_loader import get_secret_source_values
external_secrets = get_secret_source_values(home)
except Exception:
external_secrets = {}
-
- for key, value in external_secrets.items():
- if not _is_global_env(key):
- secrets[key] = value
-
+ secrets.update((k, v) for k, v in external_secrets.items() if not _is_global_env(k))
return secrets
diff --git a/agent/secret_sources/__init__.py b/agent/secret_sources/__init__.py
index cfbca8154e9..06bef0c8968 100644
--- a/agent/secret_sources/__init__.py
+++ b/agent/secret_sources/__init__.py
@@ -1,16 +1,11 @@
"""External secret source integrations.
-A secret source supplies environment-variable-shaped credentials at process
-startup, _after_ ~/.hermes/.env has loaded. The contract is
-:class:`agent.secret_sources.base.SecretSource`; the orchestrator (ordering,
-mapped-beats-bulk precedence, first-claim-wins, ``override_existing``,
-provenance) is :func:`agent.secret_sources.registry.apply_all`. The
-atomic-write / 0600 / TTL disk cache is shared in ``_cache``.
-
-Bundled: ``bitwarden`` (bws CLI), ``onepassword`` (op CLI), ``command`` (user
-helper). The set is deliberately closed — new third-party managers ship as
-standalone plugin repos that subclass ``SecretSource`` and register through
-``PluginContext.register_secret_source()``.
+A secret source supplies env-var-shaped credentials at process startup, after
+~/.hermes/.env has loaded. Contract: :class:`base.SecretSource`; orchestrator
+(ordering, mapped-beats-bulk, first-claim-wins, provenance): :func:`registry.apply_all`.
+Bundled: ``bitwarden``, ``onepassword``, ``command``. The set is deliberately
+closed — third-party managers ship as plugins that subclass ``SecretSource`` and
+register through ``PluginContext.register_secret_source()``.
"""
from agent.secret_sources.base import ( # noqa: F401
diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.py
index c789cb7ed17..b95d8c0fbb7 100644
--- a/agent/secret_sources/_cache.py
+++ b/agent/secret_sources/_cache.py
@@ -1,18 +1,15 @@
"""Shared cache substrate for external secret-source backends.
-Every backend needs the same security-sensitive primitives: a two-layer fetch
-cache (in-process + on-disk) whose disk half writes atomically with ``0600``
-permissions and honours a TTL. Keeping them here means the atomic-write /
-``0600`` / TTL logic is audited in exactly one place; each backend supplies
-only its cache-key shape and a serializer for it.
-
-Nothing here raises into the caller's hot path: the disk layer is strictly
-best-effort (a miss just triggers a refetch) because a cache problem must
-never block Hermes startup.
+Two-layer fetch cache (in-process + on-disk); the disk half writes atomically
+with ``0600`` permissions and honours a TTL, so that logic is audited in exactly
+one place. Each backend supplies only its cache-key shape and a serializer.
+The disk layer is strictly best-effort: a miss just triggers a refetch, because
+a cache problem must never block Hermes startup.
"""
from __future__ import annotations
+import hashlib
import json
import os
import tempfile
@@ -21,20 +18,22 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Dict, Generic, Optional, TypeVar
-from agent.secret_sources.base import FetchResult, is_valid_env_name # noqa: F401 — re-export
-
__all__ = [
- "FetchResult",
"CachedFetch",
"DiskCache",
"SecretCache",
"atomic_write_json",
"entry_from_payload",
- "is_valid_env_name",
+ "fingerprint",
"resolve_cache_home",
]
+def fingerprint(material: str) -> str:
+ """SHA-256 prefix used as a cache key — never logged, never displayed."""
+ return hashlib.sha256(material.encode("utf-8")).hexdigest()[:16]
+
+
@dataclass
class CachedFetch:
"""A set of fetched secret values plus when they were fetched."""
@@ -43,9 +42,7 @@ class CachedFetch:
fetched_at: float
def is_fresh(self, ttl_seconds: float) -> bool:
- if ttl_seconds <= 0:
- return False
- return (time.time() - self.fetched_at) < ttl_seconds
+ return ttl_seconds > 0 and (time.time() - self.fetched_at) < ttl_seconds
def resolve_cache_home(home_path: Optional[Path] = None) -> Path:
@@ -75,7 +72,7 @@ def atomic_write_json(path: Path, payload: dict, *, tmp_prefix: str) -> None:
"""Write ``payload`` to ``path`` via mkstemp → chmod 0600 → os.replace.
The containing dir is forced to ``0700`` (``mkdir``'s mode is umask-subject,
- so the chmod is the reliable form). Raises ``OSError`` on failure; callers
+ so the chmod is the reliable form). Raises ``OSError`` on failure; callers
decide whether that is best-effort.
"""
cache_dir = path.parent
@@ -110,7 +107,7 @@ class DiskCache(Generic[K]):
{"key": "<serialized cache key>", "secrets": {...}, "fetched_at": 1.0}
The file holds only secret *values*, never raw auth material — backends
- fingerprint tokens/sessions before they reach ``key_serializer``. Both
+ fingerprint tokens/sessions before they reach ``key_serializer``. Both
``read`` and ``write`` short-circuit when ``ttl_seconds <= 0``, so a TTL of
zero disables both layers symmetrically: an opted-out user never gets
secret values written to disk at all.
@@ -125,12 +122,7 @@ class DiskCache(Generic[K]):
def path(self, home_path: Optional[Path] = None) -> Path:
return resolve_cache_home(home_path) / "cache" / self._basename
- def read(
- self,
- key: K,
- ttl_seconds: float,
- home_path: Optional[Path] = None,
- ) -> Optional[CachedFetch]:
+ def read(self, key: K, ttl_seconds: float, home_path: Optional[Path] = None) -> Optional[CachedFetch]:
"""Fresh cached entry for ``key``, or None (I/O error, mismatch, stale)."""
if ttl_seconds <= 0:
return None
@@ -144,21 +136,11 @@ class DiskCache(Generic[K]):
entry = entry_from_payload(payload)
return entry if entry is not None and entry.is_fresh(ttl_seconds) else None
- def write(
- self,
- key: K,
- entry: CachedFetch,
- ttl_seconds: float,
- home_path: Optional[Path] = None,
- ) -> None:
+ def write(self, key: K, entry: CachedFetch, ttl_seconds: float, home_path: Optional[Path] = None) -> None:
"""Persist ``entry`` atomically at mode 0600; no-op when ``ttl_seconds <= 0`` or on I/O error."""
if ttl_seconds <= 0:
return
- payload = {
- "key": self._key_serializer(key),
- "secrets": entry.secrets,
- "fetched_at": entry.fetched_at,
- }
+ payload = {"key": self._key_serializer(key), "secrets": entry.secrets, "fetched_at": entry.fetched_at}
try:
atomic_write_json(self.path(home_path), payload, tmp_prefix=self._tmp_prefix)
except OSError:
@@ -202,13 +184,7 @@ class SecretCache(Generic[K]):
self.memory[key] = disk_cached
return disk_cached
- def store(
- self,
- key: K,
- entry: CachedFetch,
- ttl_seconds: float,
- home_path: Optional[Path] = None,
- ) -> None:
+ def store(self, key: K, entry: CachedFetch, ttl_seconds: float, home_path: Optional[Path] = None) -> None:
self.memory[key] = entry
self.disk.write(key, entry, ttl_seconds, home_path)
diff --git a/agent/secret_sources/base.py b/agent/secret_sources/base.py
index 56f6ba348cf..628c865ff97 100644
--- a/agent/secret_sources/base.py
+++ b/agent/secret_sources/base.py
@@ -1,27 +1,16 @@
"""Secret-source contract: the ABC every secret backend implements.
-A *secret source* resolves credentials from an external secret manager
-(Bitwarden, 1Password, a user script, ...) into env-var-shaped values at
-process startup, AFTER ``~/.hermes/.env`` has loaded and BEFORE the rest of
-Hermes reads ``os.environ``.
-
-Scope of the contract (deliberate, please do not widen):
-
-* **Read-only.** Sources resolve refs → values; no write-back, no arbitrary
- secret objects, no mid-session secret API.
-* **Startup-time, synchronous.** ``fetch()`` runs once per process (per
- HERMES_HOME) under a wall-clock timeout enforced by the registry. Sources
- must not spawn background refreshers.
-* **Never raises, never prompts.** Errors go in ``FetchResult.error`` with a
- machine-readable :class:`ErrorKind`; interactive auth belongs in the CLI
- ``setup`` flow (non-TTY gateway/cron startup must never block on stdin).
-* **Sources fetch; the orchestrator applies.** Precedence, conflict warnings,
- provenance and the ``os.environ`` writes live in ``registry.apply_all`` so
- no backend can get them wrong.
+A *secret source* resolves credentials from an external secret manager into
+env-var-shaped values at process startup, AFTER ``~/.hermes/.env`` has loaded
+and BEFORE the rest of Hermes reads ``os.environ``. The contract is deliberately
+narrow: read-only; startup-time and synchronous (one ``fetch()`` per process per
+HERMES_HOME, under a registry-enforced wall-clock timeout, no background
+refreshers); never raises, never prompts (errors go in ``FetchResult.error``
+with an :class:`ErrorKind`; interactive auth belongs in the CLI ``setup`` flow);
+sources fetch, the orchestrator (``registry.apply_all``) applies.
``SECRET_SOURCE_API_VERSION`` gates plugin compatibility: additive optional
-hooks with defaults do NOT bump it; required-signature changes do, and the
-registry skips (with a warning) sources built against another version.
+hooks with defaults do NOT bump it; required-signature changes do.
"""
from __future__ import annotations
@@ -65,7 +54,7 @@ def source_child_env() -> Dict[str, str]:
"""Environment for a helper child that legitimately needs the caller's env.
Single-profile startup keeps the legacy contract (full process env, minus
- the terminal blocklist). A profile-local fetch (multiplex) gets ONLY the
+ the terminal blocklist). A profile-local fetch (multiplex) gets ONLY the
per-fetch view so a child can never inherit sibling profiles' secrets.
"""
source_env = get_source_environment()
@@ -122,7 +111,7 @@ class FetchResult:
"""Outcome of one source's fetch.
``secrets`` is what the source *would* contribute; whether each var is
- applied is the orchestrator's decision. ``applied``/``skipped`` exist for
+ applied is the orchestrator's decision. ``applied``/``skipped`` exist for
the legacy fetch-and-apply entry points and stay empty in ``fetch()``.
"""
@@ -144,23 +133,35 @@ class FetchResult:
return self
+_GENERIC_REMEDIATION = {
+ ErrorKind.NOT_CONFIGURED: "Run `hermes secrets {name} setup` to finish configuration.",
+ ErrorKind.BINARY_MISSING: "Run `hermes secrets {name} setup` to install the helper CLI.",
+ ErrorKind.AUTH_FAILED: "Credentials rejected — run `hermes secrets {name} setup` to re-authenticate.",
+ ErrorKind.AUTH_EXPIRED: "Credentials expired — run `hermes secrets {name} setup` to re-authenticate.",
+ ErrorKind.NETWORK: "Network problem reaching the secrets backend — check connectivity and retry.",
+ ErrorKind.TIMEOUT: "Backend was slow — raise secrets.{name}.timeout_seconds if this recurs.",
+}
+
+
class SecretSource(ABC):
- """One external secret backend. Subclasses set attributes + ``fetch``.
+ """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
+ (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
+ 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
+ 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.
"""
api_version: int = SECRET_SOURCE_API_VERSION
@@ -171,10 +172,11 @@ class SecretSource(ABC):
token_env_key: Optional[str] = None
default_token_env: str = ""
override_existing_default: bool = False
+ remediation_hints: Dict[ErrorKind, str] = {}
@abstractmethod
def fetch(self, cfg: dict, home_path: Path) -> FetchResult:
- """Resolve this source's secrets. MUST NOT raise or prompt.
+ """Resolve this source's secrets. MUST NOT raise or prompt.
``cfg`` is the raw ``secrets.<name>`` section — may be malformed.
"""
@@ -215,24 +217,15 @@ class SecretSource(ABC):
"""One-line actionable next step for a failed fetch (pure, no I/O).
Shown right after the fetch error by the startup status printer and
- ``hermes secrets ... status``. Empty string suppresses the hint.
+ ``hermes secrets ... status``. Empty string suppresses the hint.
"""
- return _GENERIC_REMEDIATION.get(kind, "").format(name=self.name) if kind is not None else ""
-
-
-_GENERIC_REMEDIATION = {
- ErrorKind.NOT_CONFIGURED: "Run `hermes secrets {name} setup` to finish configuration.",
- ErrorKind.BINARY_MISSING: "Run `hermes secrets {name} setup` to install the helper CLI.",
- ErrorKind.AUTH_FAILED: "Credentials rejected — run `hermes secrets {name} setup` to re-authenticate.",
- ErrorKind.AUTH_EXPIRED: "Credentials expired — run `hermes secrets {name} setup` to re-authenticate.",
- ErrorKind.NETWORK: "Network problem reaching the secrets backend — check connectivity and retry.",
- ErrorKind.TIMEOUT: "Backend was slow — raise secrets.{name}.timeout_seconds if this recurs.",
-}
+ if kind is None:
+ return ""
+ template = self.remediation_hints.get(kind) or _GENERIC_REMEDIATION.get(kind, "")
+ return template.format(name=self.name, token_env=self.token_env(cfg))
-# ---------------------------------------------------------------------------
-# Shared helpers — use these instead of hand-rolling per backend
-# ---------------------------------------------------------------------------
+# --- Shared helpers — use these instead of hand-rolling per backend ---------
_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -292,9 +285,9 @@ def run_secret_cli(
The child gets PATH/HOME/locale basics plus only ``allow_env`` (auth/session
vars) and ``extra_env`` — never the full post-dotenv ``os.environ``, which
- holds every credential Hermes knows. ``NO_COLOR=1`` plus ANSI-scrubbed
+ holds every credential Hermes knows. ``NO_COLOR=1`` plus ANSI-scrubbed
stderr keep helper diagnostics out of Hermes output; stdin is /dev/null so
- a prompting helper fails fast. Pass user refs AFTER a ``--`` terminator.
+ a prompting helper fails fast. Pass user refs AFTER a ``--`` terminator.
"""
base_keep = ("PATH", "HOME", "USERPROFILE", "SYSTEMROOT", "TMPDIR", "TEMP",
"LANG", "LC_ALL", "XDG_CONFIG_HOME", "XDG_DATA_HOME")
diff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.py
index b305d973b92..8770f46f44f 100644
--- a/agent/secret_sources/bitwarden.py
+++ b/agent/secret_sources/bitwarden.py
@@ -1,19 +1,12 @@
"""Bitwarden Secrets Manager (`bws` CLI) integration.
-Hermes pulls API keys from Bitwarden Secrets Manager at startup so they don't
-have to live in plaintext in ``~/.hermes/.env``.
-
-* ``bws`` is auto-installed into ``<hermes_home>/bin/bws`` on first use: one
- pinned version (``_BWS_VERSION``) downloaded from the official GitHub
- release and SHA-256-verified against the published checksum file.
-* The one bootstrap secret is the access token in ``.env`` (``BWS_ACCESS_TOKEN``
- or ``secrets.bitwarden.access_token_env``); every other key can live in BSM.
-* One ``bws secret list <project_id> --output json`` call per fetch, cached
- in-process and on disk for ``cache_ttl_seconds``.
-* Failures NEVER block startup: a one-line warning, then continue with .env.
-
-Subprocess-driven on purpose: one cross-platform binary is easier to
-lazy-install than the ``bitwarden-sdk-secrets`` Rust-extension wheel.
+Pulls API keys from BSM at startup so they need not live in ``~/.hermes/.env``.
+``bws`` is auto-installed into ``<hermes_home>/bin/bws`` (one pinned version,
+SHA-256-verified against the published checksum). The one bootstrap secret is
+the access token in ``.env``; every other key can live in BSM. One
+``bws secret list <project_id>`` call per fetch, cached in-process and on disk
+for ``cache_ttl_seconds``. Failures NEVER block startup. Subprocess-driven on
+purpose: one cross-platform binary beats the ``bitwarden-sdk-secrets`` Rust wheel.
"""
from __future__ import annotations
@@ -40,6 +33,7 @@ from agent.secret_sources._cache import (
SecretCache,
atomic_write_json,
entry_from_payload,
+ fingerprint as _token_fingerprint,
resolve_cache_home,
)
from agent.secret_sources.base import (
@@ -59,9 +53,7 @@ logger = logging.getLogger(__name__)
# Pinned upstream version — never auto-resolve "latest": release shape (asset
# names, CLI flags) may change between majors and updates must be deliberate.
_BWS_VERSION = "2.0.0"
-_BWS_RELEASE_BASE = (
- f"https://github.com/bitwarden/sdk-sm/releases/download/bws-v{_BWS_VERSION}"
-)
+_BWS_RELEASE_BASE = f"https://github.com/bitwarden/sdk-sm/releases/download/bws-v{_BWS_VERSION}"
_BWS_CHECKSUM_NAME = f"bws-sha256-checksums-{_BWS_VERSION}.txt"
_BWS_DOWNLOAD_TIMEOUT = 60
_BWS_RUN_TIMEOUT = 30
@@ -77,8 +69,7 @@ _ENCRYPTED_CACHE_INFO = b"hermes-bws-encrypted-cache-v1"
def _cache_key_str(cache_key: _CacheKey) -> str:
- token_fp, project_id, server_url = cache_key
- return f"{token_fp}|{project_id}|{server_url}"
+ return "|".join(cache_key)
_STORE: SecretCache[_CacheKey] = SecretCache(_DISK_CACHE_BASENAME, key_serializer=_cache_key_str)
@@ -92,13 +83,27 @@ def _encrypted_disk_cache_path(home_path: Optional[Path] = None) -> Path:
return resolve_cache_home(home_path) / "cache" / _ENCRYPTED_CACHE_BASENAME
-# ---------------------------------------------------------------------------
-# Binary discovery + lazy install
-# ---------------------------------------------------------------------------
+# First matching rule wins. The BSM identity endpoint rejects a revoked /
+# expired machine-account token with an OAuth-style
+# `[400 Bad Request] {"error":"invalid_client"}`, hence those AUTH tokens.
+_BWS_ERROR_RULES = (
+ (ErrorKind.TIMEOUT, ("timed out",)),
+ (ErrorKind.BINARY_MISSING, ("binary not available", "failed to invoke")),
+ (ErrorKind.AUTH_FAILED, ("unauthorized", "invalid token", "access token", "401", "403",
+ "invalid_client", "invalid_grant", "400 bad request")),
+ (ErrorKind.NETWORK, ("network", "connection", "resolve", "download", "dns")),
+)
+
+
+def _classify_bws_error(message: str) -> ErrorKind:
+ return classify_cli_error(message, _BWS_ERROR_RULES)
+
+
+# --- Binary discovery + lazy install ----------------------------------------
def _hermes_bin_dir() -> Path:
- """Where Hermes stores its managed binaries. Profile-aware."""
+ """Where Hermes stores its managed binaries. Profile-aware."""
from hermes_constants import get_hermes_home
return get_hermes_home() / "bin"
@@ -109,17 +114,14 @@ def find_bws(*, install_if_missing: bool = False) -> Optional[Path]:
managed = _hermes_bin_dir() / _platform_binary_name()
if managed.exists() and os.access(managed, os.X_OK):
return managed
-
system = shutil.which("bws")
if system:
return Path(system)
-
if install_if_missing:
try:
return install_bws()
except Exception as exc: # noqa: BLE001 — never block startup
logger.warning("bws auto-install failed: %s", exc)
- return None
return None
@@ -139,7 +141,7 @@ def _platform_asset_name() -> str:
return f"bws-{arch}-pc-windows-msvc-{_BWS_VERSION}.zip"
if system == "Linux":
# glibc default; musl only if ldd says so (glibc prints to stderr, musl
- # to stdout). A wrong guess surfaces as a loader error we catch.
+ # to stdout). A wrong guess surfaces as a loader error we catch.
libc = "gnu"
try:
res = subprocess.run(
@@ -155,9 +157,7 @@ def _platform_asset_name() -> str:
pass
return f"bws-{arch}-unknown-linux-{libc}-{_BWS_VERSION}.zip"
- raise RuntimeError(
- f"Unsupported platform for bws auto-install: {system} {machine}"
- )
+ raise RuntimeError(f"Unsupported platform for bws auto-install: {system} {machine}")
def install_bws(*, force: bool = False) -> Path:
@@ -169,30 +169,23 @@ def install_bws(*, force: bool = False) -> Path:
bin_dir = _hermes_bin_dir()
bin_dir.mkdir(parents=True, exist_ok=True)
target = bin_dir / _platform_binary_name()
-
if target.exists() and not force:
return target
asset_name = _platform_asset_name()
- asset_url = f"{_BWS_RELEASE_BASE}/{asset_name}"
- checksum_url = f"{_BWS_RELEASE_BASE}/{_BWS_CHECKSUM_NAME}"
-
with tempfile.TemporaryDirectory(prefix="hermes-bws-") as tmpdir:
tmp = Path(tmpdir)
zip_path = tmp / asset_name
checksum_path = tmp / _BWS_CHECKSUM_NAME
- logger.info("Downloading %s", asset_url)
- _http_download(asset_url, zip_path)
- _http_download(checksum_url, checksum_path)
+ logger.info("Downloading %s", f"{_BWS_RELEASE_BASE}/{asset_name}")
+ _http_download(f"{_BWS_RELEASE_BASE}/{asset_name}", zip_path)
+ _http_download(f"{_BWS_RELEASE_BASE}/{_BWS_CHECKSUM_NAME}", checksum_path)
expected = _expected_sha256(checksum_path, asset_name)
actual = _sha256_file(zip_path)
if expected.lower() != actual.lower():
- raise RuntimeError(
- f"Checksum mismatch for {asset_name}: "
- f"expected {expected}, got {actual}"
- )
+ raise RuntimeError(f"Checksum mismatch for {asset_name}: expected {expected}, got {actual}")
with zipfile.ZipFile(zip_path) as zf:
member = _pick_zip_member(zf, _platform_binary_name())
@@ -212,23 +205,19 @@ def install_bws(*, force: bool = False) -> Path:
def _http_download(url: str, dest: Path) -> None:
req = urllib.request.Request(url, headers={"User-Agent": "hermes-agent"})
try:
- with urllib.request.urlopen(req, timeout=_BWS_DOWNLOAD_TIMEOUT) as resp: # noqa: S310
- with open(dest, "wb") as f:
- shutil.copyfileobj(resp, f)
+ with urllib.request.urlopen(req, timeout=_BWS_DOWNLOAD_TIMEOUT) as resp, open(dest, "wb") as f: # noqa: S310
+ shutil.copyfileobj(resp, f)
except urllib.error.URLError as exc:
raise RuntimeError(f"Failed to download {url}: {exc}") from exc
def _expected_sha256(checksum_file: Path, asset_name: str) -> str:
"""Parse standard ``sha256sum`` output (``<hex> <filename>`` per line)."""
- text = checksum_file.read_text(encoding="utf-8", errors="replace")
- for line in text.splitlines():
+ for line in checksum_file.read_text(encoding="utf-8", errors="replace").splitlines():
parts = line.strip().split()
if len(parts) >= 2 and parts[-1] == asset_name:
return parts[0]
- raise RuntimeError(
- f"No checksum entry for {asset_name} in {checksum_file.name}"
- )
+ raise RuntimeError(f"No checksum entry for {asset_name} in {checksum_file.name}")
def _sha256_file(path: Path) -> str:
@@ -247,13 +236,10 @@ def _pick_zip_member(zf: zipfile.ZipFile, binary_name: str) -> str:
f"Could not find {binary_name} inside downloaded archive "
f"(members: {zf.namelist()[:5]}...)"
)
- candidates.sort(key=len)
- return candidates[0]
+ return min(candidates, key=len)
-def _safe_extract_member(
- zf: zipfile.ZipFile, member: str, dest_dir: Path
-) -> Path:
+def _safe_extract_member(zf: zipfile.ZipFile, member: str, dest_dir: Path) -> Path:
"""Extract one member, refusing zip-slip (``../`` or absolute member names).
``ZipFile.extract`` joins the member onto ``dest_dir`` without verifying the
@@ -274,14 +260,7 @@ def _safe_extract_member(
return Path(target)
-# ---------------------------------------------------------------------------
-# Encrypted last-good cache (opt-in)
-# ---------------------------------------------------------------------------
-
-
-def _token_fingerprint(token: str) -> str:
- """SHA-256 prefix used as a cache key — never logged, never displayed."""
- return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
+# --- Encrypted last-good cache (opt-in) -------------------------------------
def _b64e(raw: bytes) -> str:
@@ -302,12 +281,8 @@ def _derive_encrypted_cache_key(access_token: str, salt: bytes) -> bytes:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
- return HKDF(
- algorithm=hashes.SHA256(),
- length=32,
- salt=salt,
- info=_ENCRYPTED_CACHE_INFO,
- ).derive(access_token.encode("utf-8"))
+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt,
+ info=_ENCRYPTED_CACHE_INFO).derive(access_token.encode("utf-8"))
def _write_encrypted_disk_cache(
@@ -319,7 +294,7 @@ def _write_encrypted_disk_cache(
) -> 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
+ The raw token is never stored; it only derives the key. A successful write
completes migration, so the legacy plaintext cache is removed.
"""
try:
@@ -330,12 +305,9 @@ def _write_encrypted_disk_cache(
serialized_key = _cache_key_str(cache_key)
key = _derive_encrypted_cache_key(access_token, salt)
plaintext = json.dumps(
- {"secrets": entry.secrets, "fetched_at": entry.fetched_at},
- separators=(",", ":"),
+ {"secrets": entry.secrets, "fetched_at": entry.fetched_at}, separators=(",", ":"),
).encode("utf-8")
- ciphertext = AESGCM(key).encrypt(
- nonce, plaintext, serialized_key.encode("utf-8")
- )
+ ciphertext = AESGCM(key).encrypt(nonce, plaintext, serialized_key.encode("utf-8"))
payload = {
"version": _ENCRYPTED_CACHE_VERSION,
"key": serialized_key,
@@ -343,8 +315,7 @@ def _write_encrypted_disk_cache(
"nonce": _b64e(nonce),
"ciphertext": _b64e(ciphertext),
}
- atomic_write_json(_encrypted_disk_cache_path(home_path), payload,
- tmp_prefix=".bws_cache_enc_")
+ 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
@@ -369,26 +340,20 @@ def _read_encrypted_disk_cache(
or payload.get("version") != _ENCRYPTED_CACHE_VERSION
or payload.get("key") != serialized_key):
return None
- salt = _b64d(str(payload.get("salt", "")))
- nonce = _b64d(str(payload.get("nonce", "")))
- ciphertext = _b64d(str(payload.get("ciphertext", "")))
+ salt, nonce, ciphertext = (_b64d(str(payload.get(k, ""))) 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")))
+ entry = entry_from_payload(json.loads(
+ AESGCM(key).decrypt(nonce, ciphertext, serialized_key.encode("utf-8")).decode("utf-8")
+ ))
if entry is None:
return None
entry_age = time.time() - entry.fetched_at
- if entry_age < 0 or entry_age > max_age_seconds:
- return None
- return entry
+ return None if entry_age < 0 or entry_age > max_age_seconds else entry
except Exception: # noqa: BLE001 — cache miss on parse/decrypt/I/O errors
return None
-# ---------------------------------------------------------------------------
-# Secret fetch
-# ---------------------------------------------------------------------------
+# --- Secret fetch -----------------------------------------------------------
def fetch_bitwarden_secrets(
@@ -405,10 +370,10 @@ def fetch_bitwarden_secrets(
) -> Tuple[Dict[str, str], List[str]]:
"""Pull the secrets for ``project_id`` from BSM → ``(secrets, warnings)``.
- ``server_url`` selects a region / self-hosted instance (``BWS_SERVER_URL``;
- 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
+ ``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.
@@ -453,14 +418,13 @@ def fetch_bitwarden_secrets(
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
+ # 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
+ # (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.
- kind = _classify_bws_error(str(exc))
- if use_cache and kind in (ErrorKind.NETWORK, ErrorKind.TIMEOUT):
+ if use_cache and _classify_bws_error(str(exc)) in (ErrorKind.NETWORK, ErrorKind.TIMEOUT):
stale = label = None
if encrypted_cache_enabled:
stale = _read_encrypted(encrypted_cache_max_stale_seconds)
@@ -481,10 +445,9 @@ def fetch_bitwarden_secrets(
_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.
+ # 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,
+ 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)
@@ -523,8 +486,7 @@ def _run_bws_list(
env = source_child_env()
env["BWS_ACCESS_TOKEN"] = access_token
env.setdefault("NO_COLOR", "1")
- # Empty server_url keeps whatever BWS_SERVER_URL the shell already had.
- if server_url:
+ if server_url: # empty keeps whatever BWS_SERVER_URL the shell already had
env["BWS_SERVER_URL"] = server_url
proc = run_cli(cmd, env=env, timeout=_BWS_RUN_TIMEOUT, label="bws",
@@ -532,52 +494,38 @@ def _run_bws_list(
if proc.returncode != 0:
err = _summarize_bws_stderr(proc.stderr or proc.stdout or "")
- raise RuntimeError(
- f"bws exited {proc.returncode}: {err[:200]}"
- )
+ raise RuntimeError(f"bws exited {proc.returncode}: {err[:200]}")
raw = proc.stdout.strip()
if not raw:
return {}, ["bws returned no output (empty project?)"]
-
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
raise RuntimeError(f"bws returned non-JSON output: {exc}") from exc
-
if not isinstance(payload, list):
- raise RuntimeError(
- f"bws returned unexpected shape: {type(payload).__name__}"
- )
+ raise RuntimeError(f"bws returned unexpected shape: {type(payload).__name__}")
secrets: Dict[str, str] = {}
warnings: List[str] = []
for item in payload:
if not isinstance(item, dict):
continue
- key = item.get("key")
- value = item.get("value")
+ key, value = item.get("key"), item.get("value")
if not isinstance(key, str) or not isinstance(value, str):
continue
if not _is_valid_env_name(key):
- warnings.append(
- f"Skipping secret {key!r}: not a valid env-var name"
- )
+ warnings.append(f"Skipping secret {key!r}: not a valid env-var name")
continue
secrets[key] = value
return secrets, warnings
-# ---------------------------------------------------------------------------
-# SecretSource adapter — the registry-facing wrapper around this module.
-# ---------------------------------------------------------------------------
-
-
class BitwardenSource(SecretSource):
"""Bitwarden Secrets Manager as a registered **bulk** source.
``fetch()`` only fetches — precedence, overrides and the ``os.environ``
- writes are the orchestrator's. Bulk: it injects every secret in the BSM
+ writes are the orchestrator's. Bulk: it injects every secret in the BSM
project, so explicit per-var bindings from mapped sources outrank it.
"""
@@ -590,6 +538,13 @@ class BitwardenSource(SecretSource):
# override_existing defaults True: the point of BSM is centralized rotation
# — a stale .env line must not have the final say.
override_existing_default = True
+ _AUTH_HINT = (
+ "Run `hermes secrets bitwarden token` to paste a fresh access "
+ "token (create one in the Bitwarden web app: Secrets Manager → "
+ "Machine accounts → Access tokens). Wrong region? Re-run "
+ "`hermes secrets bitwarden setup` and pick EU/self-hosted."
+ )
+ remediation_hints = {ErrorKind.AUTH_FAILED: _AUTH_HINT, ErrorKind.AUTH_EXPIRED: _AUTH_HINT}
def config_schema(self) -> dict:
return {
@@ -628,8 +583,7 @@ class BitwardenSource(SecretSource):
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`.",
+ "secrets.bitwarden.project_id is empty. Run `hermes secrets bitwarden setup`.",
ErrorKind.NOT_CONFIGURED,
)
@@ -654,8 +608,7 @@ class BitwardenSource(SecretSource):
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),
+ 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)))
@@ -672,32 +625,6 @@ class BitwardenSource(SecretSource):
result.warnings.extend(warnings)
return result
- def remediation(self, kind, cfg: dict) -> str:
- if kind in (ErrorKind.AUTH_FAILED, ErrorKind.AUTH_EXPIRED):
- return (
- "Run `hermes secrets bitwarden token` to paste a fresh access "
- "token (create one in the Bitwarden web app: Secrets Manager → "
- "Machine accounts → Access tokens). Wrong region? Re-run "
- "`hermes secrets bitwarden setup` and pick EU/self-hosted."
- )
- return super().remediation(kind, cfg)
-
-
-# First matching rule wins. The BSM identity endpoint rejects a revoked /
-# expired machine-account token with an OAuth-style
-# `[400 Bad Request] {"error":"invalid_client"}`, hence those AUTH tokens.
-_BWS_ERROR_RULES = (
- (ErrorKind.TIMEOUT, ("timed out",)),
- (ErrorKind.BINARY_MISSING, ("binary not available", "failed to invoke")),
- (ErrorKind.AUTH_FAILED, ("unauthorized", "invalid token", "access token", "401", "403",
- "invalid_client", "invalid_grant", "400 bad request")),
- (ErrorKind.NETWORK, ("network", "connection", "resolve", "download", "dns")),
-)
-
-
-def _classify_bws_error(message: str) -> ErrorKind:
- return classify_cli_error(message, _BWS_ERROR_RULES)
-
def clear_caches(home_path: Optional[Path] = None) -> None:
"""Drop in-process AND disk caches (plaintext and encrypted).
diff --git a/agent/secret_sources/command.py b/agent/secret_sources/command.py
index c8d3ee7ce72..1b0994b8071 100644
--- a/agent/secret_sources/command.py
+++ b/agent/secret_sources/command.py
@@ -1,25 +1,17 @@
"""``command`` secret source — resolve secrets via a user-configured helper.
-Ports the security semantics of the desktop app's TypeScript
-``CommandSecretsProvider`` (``src/main/secrets/commandProvider.ts``). The
-helper command (``keepassxc-cli``, ``secret-tool``, a script that cats a tmpfs
-env file, ...) comes from ``secrets.command`` in ``config.yaml`` — NEVER from
+Ports the desktop app's TypeScript ``CommandSecretsProvider`` semantics. The
+helper (``keepassxc-cli``, ``secret-tool``, a script that cats a tmpfs env
+file, ...) comes from ``secrets.command`` in ``config.yaml`` — NEVER from
``.env``, which holds only secret values.
-Security model:
-
-* The command string is the USER'S OWN configuration (same trust level as the
- ``.env`` they control), so it runs via ``/bin/sh -c <command>``.
-* The requested key reaches the child ONLY via ``HERMES_SECRET_KEY`` — never
- interpolated into the shell string, so a hostile key name is inert data.
-* Hard timeout (default 3s) + output cap (1 MiB); every failure (non-zero exit,
- timeout, spawn failure, oversized output) degrades to "no value", never raises.
-* Failure logs carry ONLY structured fields (exit code / signal / errno) — never
- the command string, the helper's stderr (captured and DISCARDED, it can carry
- secret material) or any value.
-* Startup runs the helper exactly ONCE with an empty ``HERMES_SECRET_KEY`` —
- never per key — so a helper blocked on a vault prompt isn't spawned N times.
-* POSIX-only (needs ``/bin/sh``); on Windows it degrades to an empty result.
+Security model: the command string is the USER'S OWN configuration, so it runs
+via ``/bin/sh -c``; the requested key reaches the child ONLY via
+``HERMES_SECRET_KEY`` (never interpolated, so a hostile key name is inert); hard
+timeout (default 3s) + 1 MiB output cap, every failure degrades to "no value";
+failure logs carry ONLY structured fields (exit code / signal / errno), never
+the command, the helper's stderr (captured and DISCARDED) or any value; startup
+runs the helper exactly ONCE with an empty key; POSIX-only (needs ``/bin/sh``).
"""
from __future__ import annotations
@@ -70,24 +62,16 @@ def unquote_dotenv_value(raw: str) -> str:
correctly yield an empty string.
"""
t = raw.strip()
- if len(t) >= 2 and (
- (t.startswith('"') and t.endswith('"'))
- or (t.startswith("'") and t.endswith("'"))
- ):
+ if len(t) >= 2 and t[0] == t[-1] and t[0] in "\"'":
return t[1:-1]
return t
-def _run_helper(
- command: str,
- secret_key: str,
- timeout_seconds: float,
- max_output_bytes: int,
-) -> Optional[str]:
+def _run_helper(command: str, secret_key: str, timeout_seconds: float, max_output_bytes: int) -> Optional[str]:
"""Run the helper via ``/bin/sh -c`` and return its stdout, or None.
- The key travels as DATA in ``HERMES_SECRET_KEY``. stdout/stderr are piped
- (never inherited); stderr is discarded. Any failure logs structured fields
+ The key travels as DATA in ``HERMES_SECRET_KEY``. stdout/stderr are piped
+ (never inherited); stderr is discarded. Any failure logs structured fields
only and returns None — never raises.
"""
if _is_windows():
@@ -116,7 +100,7 @@ def _run_helper(
stdout_bytes, _stderr_discarded = proc.communicate(timeout=timeout_seconds)
except subprocess.TimeoutExpired:
# Kill the whole group: a helper may have forked children that would
- # otherwise keep the pipe open. POSIX-only by the early return above.
+ # otherwise keep the pipe open. POSIX-only by the early return above.
try:
os.killpg(os.getpgid(proc.pid), _signal.SIGKILL) # windows-footgun: ok
except (ProcessLookupError, PermissionError, OSError):
@@ -164,8 +148,8 @@ class CommandSource(SecretSource):
"""User-configured helper command as a registered **bulk** source.
Composes with the other sources through ``apply_all()``; there is
- deliberately NO single-provider selector. The helper enumerates a
- KEY=VALUE blob in one run. Config::
+ deliberately NO single-provider selector. The helper enumerates a
+ KEY=VALUE blob in one run. Config::
secrets:
command:
@@ -176,6 +160,13 @@ class CommandSource(SecretSource):
name = "command"
label = "Command helper"
shape = "bulk"
+ remediation_hints = {
+ ErrorKind.NOT_CONFIGURED: "Set secrets.command.command in config.yaml to a fast, "
+ "non-interactive helper that prints KEY=VALUE lines.",
+ ErrorKind.INTERNAL: "Run the helper manually in a shell to see its real error — "
+ "Hermes discards helper stderr so diagnostics can't leak "
+ "secret material.",
+ }
def config_schema(self) -> dict:
return {
@@ -206,45 +197,24 @@ class CommandSource(SecretSource):
"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",
+ "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",
+ "helper command failed (see structured fields above); no secrets applied",
ErrorKind.INTERNAL,
)
secrets = _parse_dotenv_map(stdout)
if not secrets:
- result.warnings.append(
- "helper output was not a KEY=VALUE map; nothing to apply"
- )
+ result.warnings.append("helper output was not a KEY=VALUE map; nothing to apply")
return result
-
result.secrets = secrets
return result
-
- def remediation(self, kind, cfg: dict) -> str:
- if kind == ErrorKind.NOT_CONFIGURED:
- return (
- "Set secrets.command.command in config.yaml to a fast, "
- "non-interactive helper that prints KEY=VALUE lines."
- )
- if kind == ErrorKind.INTERNAL:
- return (
- "Run the helper manually in a shell to see its real error — "
- "Hermes discards helper stderr so diagnostics can't leak "
- "secret material."
- )
- return super().remediation(kind, cfg)
diff --git a/agent/secret_sources/onepassword.py b/agent/secret_sources/onepassword.py
index 864c6aa9aa6..e2f8142a867 100644
--- a/agent/secret_sources/onepassword.py
+++ b/agent/secret_sources/onepassword.py
@@ -1,21 +1,16 @@
"""1Password (`op` CLI) secret source.
-Users map env-var names to official ``op://vault/item/field`` references in
-``secrets.onepassword.env``; after ``.env`` loads each reference is resolved
-with one ``op read -- <reference>`` call. Authentication is whatever the
-user's ``op`` CLI already uses (``OP_SERVICE_ACCOUNT_TOKEN`` for headless
-boxes, ``OP_SESSION_*`` for interactive sessions) — Hermes never authenticates
-on the user's behalf. Failures NEVER block startup.
-
-Successful, complete pulls are cached in-process and under
-``<hermes_home>/cache/op_cache.json`` (values only; auth material is
-fingerprinted, never stored) so back-to-back ``hermes`` invocations don't
-re-shell ``op`` for every reference.
+Users map env-var names to ``op://vault/item/field`` references in
+``secrets.onepassword.env``; each is resolved with one ``op read -- <ref>``
+call using whatever auth the user's ``op`` already has (``OP_SERVICE_ACCOUNT_TOKEN``
+headless, ``OP_SESSION_*`` interactive) — Hermes never authenticates on the
+user's behalf, and failures never block startup. Complete pulls are cached
+in-process and under ``<hermes_home>/cache/op_cache.json`` (values only; auth
+material is fingerprinted, never stored).
"""
from __future__ import annotations
-import hashlib
import logging
import os
import shutil
@@ -24,7 +19,7 @@ import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple
-from agent.secret_sources._cache import CachedFetch, SecretCache
+from agent.secret_sources._cache import CachedFetch, SecretCache, fingerprint as _fingerprint
from agent.secret_sources.base import (
ErrorKind,
FetchResult,
@@ -45,7 +40,7 @@ _OP_RUN_TIMEOUT = 30
_DEFAULT_TOKEN_ENV = "OP_SERVICE_ACCOUNT_TOKEN"
# Minimal allowlisted child env (never the full post-dotenv os.environ, which
-# holds every provider credential). OP_SESSION_* and the token are added
+# holds every provider credential). OP_SESSION_* and the token are added
# dynamically in _op_child_env().
_OP_ENV_ALLOWLIST = (
"PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot",
@@ -56,13 +51,8 @@ _OP_ENV_ALLOWLIST = (
"OP_LOAD_DESKTOP_APP_SETTINGS",
)
-
-# ---------------------------------------------------------------------------
-# Cache
-# ---------------------------------------------------------------------------
-
# L1 key folds in str(home_path) so a HERMES_HOME switch inside one long-lived
-# process (the gateway) can't return another profile's secrets. The disk key
+# process (the gateway) can't return another profile's secrets. The disk key
# omits home because the file already lives under <home>/cache/.
_CacheKey = Tuple[str, str, str, str] # (auth_fp, account, home, refs_fp)
_DISK_CACHE_BASENAME = "op_cache.json"
@@ -76,39 +66,42 @@ def _disk_key_str(cache_key: _CacheKey) -> str:
_STORE: SecretCache[_CacheKey] = SecretCache(_DISK_CACHE_BASENAME, key_serializer=_disk_key_str)
_CACHE = _STORE.memory # tests flush L1 directly
+_MISSING_BINARY_HINT = (
+ "Install the 1Password CLI (https://developer.1password.com/docs/cli/get-started/) "
+ "or set secrets.onepassword.binary_path."
+)
-# ---------------------------------------------------------------------------
-# Reference validation + fingerprinting
-# ---------------------------------------------------------------------------
+# First matching rule wins.
+_OP_ERROR_RULES = (
+ (ErrorKind.TIMEOUT, ("timed out",)),
+ (ErrorKind.BINARY_MISSING, ("not found on path", "not an executable", "failed to invoke")),
+ (ErrorKind.AUTH_FAILED, ("unauthorized", "not signed in", "session expired",
+ "authentication", "401", "403")),
+ (ErrorKind.EMPTY_VALUE, ("empty value",)),
+ (ErrorKind.NETWORK, ("network", "connection", "resolve host", "dns")),
+)
-def _validate_references(
- references: Optional[Dict[str, str]],
-) -> Tuple[Dict[str, str], List[str]]:
+def _classify_op_error(message: str) -> ErrorKind:
+ return classify_cli_error(message, _OP_ERROR_RULES)
+
+
+def _validate_references(references: Optional[Dict[str, str]]) -> Tuple[Dict[str, str], List[str]]:
"""``(valid_refs, warnings)``: keep valid env names bound to stripped ``op://`` strings."""
valid: Dict[str, str] = {}
warnings: List[str] = []
for name, ref in (references or {}).items():
if not is_valid_env_name(name):
warnings.append(f"Skipping {name!r}: not a valid env-var name")
- continue
- if not isinstance(ref, str):
+ elif not isinstance(ref, str):
warnings.append(f"Skipping {name!r}: reference is not a string")
- continue
- cleaned = ref.strip()
- if not cleaned.startswith("op://"):
- warnings.append(
- f"Skipping {name!r}: {ref!r} is not an op:// secret reference"
- )
- continue
- valid[name] = cleaned
+ elif not ref.strip().startswith("op://"):
+ warnings.append(f"Skipping {name!r}: {ref!r} is not an op:// secret reference")
+ else:
+ valid[name] = ref.strip()
return valid, warnings
-def _fingerprint(material: str) -> str:
- return hashlib.sha256(material.encode("utf-8")).hexdigest()[:16]
-
-
def _auth_fingerprint(token_env: str) -> str:
"""SHA-256 prefix over everything `op` would authenticate with.
@@ -123,9 +116,7 @@ def _auth_fingerprint(token_env: str) -> str:
f"connect_host={source_env.get('OP_CONNECT_HOST', '')}",
f"connect_token={source_env.get('OP_CONNECT_TOKEN', '')}",
]
- for key in sorted(source_env):
- if key.startswith("OP_SESSION_"):
- parts.append(f"{key}={source_env[key]}")
+ parts += [f"{key}={source_env[key]}" for key in sorted(source_env) if key.startswith("OP_SESSION_")]
return _fingerprint("\n".join(parts))
@@ -133,11 +124,6 @@ def _refs_fingerprint(references: Dict[str, str]) -> str:
return _fingerprint("\n".join(f"{name}={references[name]}" for name in sorted(references)))
-# ---------------------------------------------------------------------------
-# Binary discovery + `op read`
-# ---------------------------------------------------------------------------
-
-
def find_op(binary_path: str = "") -> Optional[Path]:
"""Resolve a usable ``op`` binary, or None.
@@ -146,9 +132,7 @@ def find_op(binary_path: str = "") -> Optional[Path]:
"""
if binary_path:
pinned = Path(binary_path)
- if pinned.exists() and os.access(pinned, os.X_OK):
- return pinned
- return None
+ return pinned if pinned.exists() and os.access(pinned, os.X_OK) else None
found = shutil.which("op")
return Path(found) if found else None
@@ -170,13 +154,7 @@ def _op_child_env(token_value: str) -> Dict[str, str]:
return env
-def _run_op_read(
- op: Path,
- reference: str,
- *,
- account: str = "",
- token_value: str = "",
-) -> str:
+def _run_op_read(op: Path, reference: str, *, account: str = "", token_value: str = "") -> str:
"""Resolve one ``op://`` reference; raises ``RuntimeError`` on any failure.
An exit-0 empty/whitespace-only value is a failure too — applying it would
@@ -197,9 +175,7 @@ def _run_op_read(
err = _scrub(proc.stderr or "")[:200]
if err:
raise RuntimeError(f"op read failed for {reference!r}: {err}")
- raise RuntimeError(
- f"op read exited {proc.returncode} for {reference!r}"
- )
+ raise RuntimeError(f"op read exited {proc.returncode} for {reference!r}")
# Strip only op's trailing newline so intentional edge spaces survive.
value = (proc.stdout or "").rstrip("\r\n")
@@ -208,11 +184,6 @@ def _run_op_read(
return value
-# ---------------------------------------------------------------------------
-# Fetch
-# ---------------------------------------------------------------------------
-
-
def fetch_onepassword_secrets(
*,
references: Dict[str, str],
@@ -226,9 +197,9 @@ def fetch_onepassword_secrets(
) -> Tuple[Dict[str, str], List[str]]:
"""Resolve ``references`` (name → ``op://…``) to ``(secrets, warnings)``.
- Raises ``RuntimeError`` only when no ``op`` binary is available. Per-ref
+ Raises ``RuntimeError`` only when no ``op`` binary is available. Per-ref
failures become warnings and the ref is dropped, so one bad entry never
- sinks the rest. Only a complete, error-free pull is cached, so a transient
+ sinks the rest. Only a complete, error-free pull is cached, so a transient
auth failure isn't frozen in for the whole TTL window.
"""
valid, warnings = _validate_references(references)
@@ -260,26 +231,21 @@ def fetch_onepassword_secrets(
read_errors = 0
for name in sorted(valid):
try:
- secrets[name] = _run_op_read(
- op, valid[name], account=account, token_value=token_value
- )
+ secrets[name] = _run_op_read(op, valid[name], account=account, token_value=token_value)
except RuntimeError as exc:
warnings.append(str(exc))
read_errors += 1
if use_cache and not read_errors and secrets:
- entry = CachedFetch(secrets=dict(secrets), fetched_at=time.time())
- _STORE.store(cache_key, entry, cache_ttl_seconds, home_path)
+ _STORE.store(cache_key, CachedFetch(secrets=dict(secrets), fetched_at=time.time()),
+ cache_ttl_seconds, home_path)
return secrets, warnings
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 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 "
@@ -288,11 +254,6 @@ def _missing_binary_error(binary_path: str) -> str:
)
-# ---------------------------------------------------------------------------
-# Public entry point — used by `hermes secrets onepassword sync --apply`
-# ---------------------------------------------------------------------------
-
-
def apply_onepassword_secrets(
*,
enabled: bool,
@@ -304,15 +265,15 @@ def apply_onepassword_secrets(
cache_ttl_seconds: float = 300,
home_path: Optional[Path] = None,
) -> FetchResult:
- """Resolve configured ``op://`` references and set them on ``os.environ``.
+ """Resolve configured ``op://`` references and set them on ``os.environ``
+ (``hermes secrets onepassword sync --apply``).
- Never raises. References already satisfied by the environment (when
+ Never raises. References already satisfied by the environment (when
``override_existing`` is false) and the token var itself are skipped
*before* fetching, so ``op`` is never invoked for a value that would be
discarded.
"""
result = FetchResult()
-
if not enabled:
return result
@@ -331,7 +292,6 @@ def apply_onepassword_secrets(
result.skipped.append(name)
else:
refs_to_fetch[name] = ref
-
if not refs_to_fetch:
return result
@@ -356,29 +316,21 @@ def apply_onepassword_secrets(
result.secrets = secrets
result.warnings.extend(fetch_warnings)
-
for name, value in secrets.items():
- # Defensive re-check: keys should already be ⊆ refs_to_fetch.
- if _guarded(name):
+ if _guarded(name): # defensive re-check: keys should already be ⊆ refs_to_fetch
if name not in result.skipped:
result.skipped.append(name)
continue
os.environ[name] = value
result.applied.append(name)
-
return result
-# ---------------------------------------------------------------------------
-# SecretSource adapter — the registry-facing wrapper around this module.
-# ---------------------------------------------------------------------------
-
-
class OnePasswordSource(SecretSource):
"""1Password as a registered **mapped** source.
``fetch()`` only fetches — precedence, overrides and the ``os.environ``
- writes are the orchestrator's. Mapped: the user explicitly binds each env
+ writes are the orchestrator's. Mapped: the user explicitly binds each env
var to an ``op://`` ref, so its claims outrank bulk sources on contested vars.
"""
@@ -391,6 +343,15 @@ 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,
+ }
def config_schema(self) -> dict:
return {
@@ -412,9 +373,7 @@ class OnePasswordSource(SecretSource):
result = FetchResult()
env_map = cfg.get("env")
- valid, warnings = _validate_references(
- env_map if isinstance(env_map, dict) else None
- )
+ valid, warnings = _validate_references(env_map if isinstance(env_map, dict) else None)
result.warnings.extend(warnings)
if not valid:
if not warnings:
@@ -447,35 +406,6 @@ class OnePasswordSource(SecretSource):
result.warnings.extend(fetch_warnings)
return result
- def remediation(self, kind, cfg: dict) -> str:
- if kind in (ErrorKind.AUTH_FAILED, ErrorKind.AUTH_EXPIRED):
- return (
- "Run `hermes secrets onepassword token` to paste a fresh "
- f"service-account token ({self.token_env(cfg)}), or `op signin` for an "
- "interactive session."
- )
- if kind == ErrorKind.BINARY_MISSING:
- return (
- "Install the 1Password CLI "
- "(https://developer.1password.com/docs/cli/get-started/) or "
- "set secrets.onepassword.binary_path."
- )
- return super().remediation(kind, cfg)
-
-
-_OP_ERROR_RULES = (
- (ErrorKind.TIMEOUT, ("timed out",)),
- (ErrorKind.BINARY_MISSING, ("not found on path", "not an executable", "failed to invoke")),
- (ErrorKind.AUTH_FAILED, ("unauthorized", "not signed in", "session expired",
- "authentication", "401", "403")),
- (ErrorKind.EMPTY_VALUE, ("empty value",)),
- (ErrorKind.NETWORK, ("network", "connection", "resolve host", "dns")),
-)
-
-
-def _classify_op_error(message: str) -> ErrorKind:
- return classify_cli_error(message, _OP_ERROR_RULES)
-
def clear_caches(home_path: Optional[Path] = None) -> None:
"""Drop in-process AND disk caches (after a token rotation, so the next
diff --git a/agent/secret_sources/registry.py b/agent/secret_sources/registry.py
index 06f4fcb064a..034f0117572 100644
--- a/agent/secret_sources/registry.py
+++ b/agent/secret_sources/registry.py
@@ -1,16 +1,13 @@
"""Secret-source registry + apply orchestrator.
-Owns everything that must be uniform across backends so no source can get it
-wrong: registration (name/scheme uniqueness, API-version gating), the
-wall-clock timeout around ``fetch()``, precedence (mapped beats bulk; within a
-shape ``secrets.sources`` order, else registration order; first claim wins),
-``override_existing`` semantics (may beat .env/shell, never another source,
-never a protected var), cross-source conflict warnings, and provenance.
-
-Startup entry point: :func:`apply_all` via
-``hermes_cli.env_loader._apply_external_secret_sources()``. Plugins register
-through ``PluginContext.register_secret_source()`` → :func:`register_source`;
-bundled sources register lazily in :func:`_ensure_builtin_sources`.
+Owns everything that must be uniform across backends: registration
+(name/scheme uniqueness, API-version gating), the wall-clock timeout around
+``fetch()``, precedence (mapped beats bulk; within a shape ``secrets.sources``
+order, else registration order; first claim wins), ``override_existing``
+semantics (may beat .env/shell, never another source, never a protected var),
+cross-source conflict warnings, and provenance. Startup entry point:
+:func:`apply_all` via ``hermes_cli.env_loader``; plugins register through
+``PluginContext.register_secret_source()`` → :func:`register_source`.
"""
from __future__ import annotations
@@ -36,8 +33,8 @@ from hermes_constants import hermes_home_key
logger = logging.getLogger(__name__)
-# Ordered registry: name → source. Dict insertion order doubles as the default
-# apply order. Origin is recorded so consumers never infer ownership from names.
+# Ordered registry: name → source. Dict insertion order doubles as the default
+# apply order. Origin is recorded so consumers never infer ownership from names.
_SOURCES: Dict[str, SecretSource] = {}
_SOURCE_ORIGINS: Dict[str, str] = {}
_SCOPED_SOURCES: Dict[str, Dict[str, SecretSource]] = {}
@@ -89,9 +86,22 @@ class ApplyReport:
return bool(self.provenance)
-# ---------------------------------------------------------------------------
-# Registration
-# ---------------------------------------------------------------------------
+# --- Registration -----------------------------------------------------------
+
+
+def _validate_source(source: SecretSource) -> Optional[str]:
+ """Reason a source is unregistrable (already formatted for the log), or None."""
+ if not isinstance(source, SecretSource):
+ return f"Ignoring secret source {source!r}: does not inherit from SecretSource"
+ name = source.name or ""
+ if not name or not name.replace("_", "").isalnum() or name != name.lower():
+ return f"Ignoring secret source with invalid name {name!r}"
+ if source.api_version != SECRET_SOURCE_API_VERSION:
+ return (f"Ignoring secret source '{name}': built against secret-source API "
+ f"v{source.api_version}, this Hermes speaks v{SECRET_SOURCE_API_VERSION}")
+ if source.shape not in ("mapped", "bulk"):
+ return f"Ignoring secret source '{name}': shape must be 'mapped' or 'bulk', got {source.shape!r}"
+ return None
def register_source(
@@ -101,54 +111,31 @@ def register_source(
builtin: bool = False,
scope: Optional[str] = None,
) -> bool:
- """Register a secret source. Returns True on success.
+ """Register a secret source. Returns True on success.
Rejections are logged, never raised — a bad plugin must not take down
- startup. ``replace`` lets tests / user plugins override a same-named
+ startup. ``replace`` lets tests / user plugins override a same-named
source (last-writer-wins); scheme collisions across *different* names are
always rejected.
"""
- if not isinstance(source, SecretSource):
- logger.warning(
- "Ignoring secret source %r: does not inherit from SecretSource",
- source,
- )
- return False
- name = source.name or ""
- if not name or not name.replace("_", "").isalnum() or name != name.lower():
- logger.warning("Ignoring secret source with invalid name %r", name)
- return False
- if source.api_version != SECRET_SOURCE_API_VERSION:
- logger.warning(
- "Ignoring secret source '%s': built against secret-source API v%s, "
- "this Hermes speaks v%s",
- name, source.api_version, SECRET_SOURCE_API_VERSION,
- )
- return False
- if source.shape not in ("mapped", "bulk"):
- logger.warning(
- "Ignoring secret source '%s': shape must be 'mapped' or 'bulk', got %r",
- name, source.shape,
- )
+ problem = _validate_source(source)
+ if problem:
+ logger.warning(problem)
return False
+ name = source.name
with _REGISTRY_LOCK:
effective = dict(_SOURCES)
if scope is not None:
effective.update(_SCOPED_SOURCES.get(scope, {}))
if name in effective and not replace:
- logger.warning(
- "Secret source '%s' already registered; ignoring duplicate", name
- )
+ 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,
+ "Ignoring secret source '%s': scheme '%s://' is already owned by source '%s'",
+ name, source.scheme, other_name,
)
return False
target = _SOURCES if scope is None else _SCOPED_SOURCES.setdefault(scope, {})
@@ -171,9 +158,7 @@ def get_source(name: str, *, scope: Optional[str] = None) -> Optional[SecretSour
return _merged(scope).get(name)
-def snapshot_registration(
- name: str, *, scope: Optional[str] = None
-) -> Optional[SecretSource]:
+def snapshot_registration(name: str, *, scope: Optional[str] = None) -> Optional[SecretSource]:
"""Return the registration owned by exactly one registry layer."""
_ensure_builtin_sources()
with _REGISTRY_LOCK:
@@ -214,11 +199,7 @@ def list_plugin_sources() -> List[SecretSource]:
plus every scoped registration (bundled sources register with scope=None)."""
_ensure_builtin_sources()
with _REGISTRY_LOCK:
- merged: Dict[str, SecretSource] = {
- name: source
- for name, source in _SOURCES.items()
- if _SOURCE_ORIGINS.get(name) == "plugin"
- }
+ merged = {n: s for n, s in _SOURCES.items() if _SOURCE_ORIGINS.get(n) == "plugin"}
merged.update(_SCOPED_SOURCES.get(hermes_home_key(), {}))
return list(merged.values())
@@ -239,10 +220,7 @@ def _ensure_builtin_sources() -> None:
module = __import__(module_name, fromlist=[class_name])
register_source(getattr(module, class_name)(), builtin=True)
except Exception: # noqa: BLE001 — never block startup
- logger.warning(
- "Failed to register bundled %s secret source", label,
- exc_info=True,
- )
+ logger.warning("Failed to register bundled %s secret source", label, exc_info=True)
def _reset_registry_for_tests() -> None:
@@ -254,9 +232,7 @@ def _reset_registry_for_tests() -> None:
_BUILTINS_LOADED = False
-# ---------------------------------------------------------------------------
-# Orchestrated apply
-# ---------------------------------------------------------------------------
+# --- Orchestrated apply -----------------------------------------------------
def _fetch_with_timeout(
@@ -266,7 +242,7 @@ def _fetch_with_timeout(
"""Run source.fetch() under a wall-clock budget; never raises.
A daemon worker thread enforces the budget: a source that blows it is
- reported as TIMEOUT and its eventual result discarded. The thread may
+ reported as TIMEOUT and its eventual result discarded. The thread may
linger until process exit — acceptable for a startup-only path, and far
better than an unbounded hang on every ``hermes`` invocation.
"""
@@ -294,16 +270,13 @@ def _fetch_with_timeout(
ErrorKind.TIMEOUT,
)
except Exception as exc: # noqa: BLE001 — contract violation, contain it
- return FetchResult().fail(
- f"fetch raised {type(exc).__name__}: {exc}", ErrorKind.INTERNAL
- )
+ 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,
+ f"fetch returned {type(result).__name__} instead of FetchResult", ErrorKind.INTERNAL,
)
return result
@@ -313,9 +286,7 @@ def _section(secrets_cfg: dict, name: str) -> dict:
return cfg if isinstance(cfg, dict) else {}
-def _ordered_enabled_sources(
- secrets_cfg: dict, *, scope: Optional[str] = None
-) -> List[SecretSource]:
+def _ordered_enabled_sources(secrets_cfg: dict, *, scope: Optional[str] = None) -> List[SecretSource]:
"""Which sources run, in which order: ``secrets.sources`` first, then the
rest in registration order; enabled = the source's own ``is_enabled``.
Mapped-vs-bulk precedence is applied on top by :func:`apply_all`."""
@@ -341,8 +312,7 @@ def _ordered_enabled_sources(
if source.is_enabled(_section(secrets_cfg, name)):
enabled.append(source)
except Exception: # noqa: BLE001
- logger.warning("Secret source '%s' is_enabled() raised; skipping",
- name, exc_info=True)
+ logger.warning("Secret source '%s' is_enabled() raised; skipping", name, exc_info=True)
return enabled
@@ -372,9 +342,7 @@ def _profile_alias_target(var: str, profile: str) -> Optional[str]:
if not var.endswith(suffix):
return None
alias = var[: -len(suffix)]
- if not alias or not is_valid_env_name(alias):
- return None
- if not any(alias.endswith(s) for s in _ALIAS_SUFFIXES):
+ if not alias or not is_valid_env_name(alias) or not alias.endswith(_ALIAS_SUFFIXES):
return None
return alias
@@ -407,8 +375,7 @@ class _Applier:
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} "
- f"(active profile {profile!r})"
+ f"applied profile-scoped {var} as {alias} (active profile {profile!r})"
)
def _try_apply(self, sr: SourceReport, source: SecretSource, override: bool,
@@ -460,7 +427,7 @@ def apply_all(secrets_cfg: dict, home_path: Path,
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
+ adapters reading fixed env names see the profile's value. The alias obeys
the same guards and is disabled with ``secrets.profile_alias: false``.
"""
env = environ if environ is not None else os.environ
@@ -481,7 +448,6 @@ def apply_all(secrets_cfg: dict, home_path: Path,
ordered = ([s for s in enabled if s.shape == "mapped"]
+ [s for s in enabled if s.shape == "bulk"])
- # Fetch phase.
fetches: List[tuple[SecretSource, dict, FetchResult]] = []
protected: Dict[str, str] = {} # var → source that protects it
for source in ordered:
@@ -500,5 +466,4 @@ def apply_all(secrets_cfg: dict, home_path: Path,
applier = _Applier(env, report, protected, preserve)
for source, cfg, result in fetches:
applier.apply_source(source, cfg, result, profile, supplied_directly)
-
return report