Skip to content

The agent that grows with you

fix(secret-sources): revoke a removed source's value from os.environ

Austin Pickett9c5da5a1c765
diff --git a/agent/secret_sources/registry.py b/agent/secret_sources/registry.py
index 06274c8c6ff..2a3e140d512 100644
--- a/agent/secret_sources/registry.py
+++ b/agent/secret_sources/registry.py
@@ -287,6 +287,14 @@ def _ordered_enabled_sources(secrets_cfg: dict, *, scope: Optional[str] = None)
return enabled
+def enabled_source_names(secrets_cfg: dict, home_path: Path) -> frozenset:
+ """Names of the sources :func:`apply_all` would fetch for *home_path* right now (registered
+ and enabled). A source missing here was removed or disabled, so a value it injected earlier
+ is no longer backed by anything and must be revoked, not kept as process residue."""
+ secrets_cfg = secrets_cfg if isinstance(secrets_cfg, dict) else {}
+ return frozenset(s.name for s in _ordered_enabled_sources(secrets_cfg, scope=hermes_home_key(home_path)))
+
+
def _active_profile_name(home_path: Optional[Path]) -> str:
"""Active profile name (``~/.hermes/profiles/<name>``); "" for the default profile."""
if home_path is not None:
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index d521e8725d0..92b4bcf113b 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -50,6 +50,14 @@ _MANAGED_DOTENV_KEYS: set[str] = set()
_SECRET_SOURCE_VALUES_BY_HOME: dict[str, dict[str, str]] = {}
# Per home: the subset of the snapshot a dotenv reload may re-assert — see ``AppliedVar.authoritative`` (#74265).
_SECRET_SOURCE_RESTORE_BY_HOME: dict[str, dict[str, str]] = {}
+# Per home: what the process-global path WROTE into ``os.environ`` for an external source — name →
+# (source name, value written, value the name held before the first write or None). The per-home
+# snapshot above is republished on every pass, but ``os.environ`` is not: without this record a value a
+# since-removed or disabled source injected stayed in the process env, and single-profile
+# ``get_secret()`` kept serving it through its ``os.environ`` fallback until restart. Deliberately NOT
+# cleared by a per-home ``reset_secret_source_cache``: it describes ``os.environ``, which a reset does not
+# touch, and the next pass needs it to revoke.
+_SECRET_SOURCE_WRITES_BY_HOME: dict[str, dict[str, tuple[str, str, str | None]]] = {}
# HERMES_HOME paths already pulled external secrets for: load_hermes_dotenv() runs at import time from
# several hot modules, so without this the Bitwarden status line prints 3-5x per startup and the config
# re-parse + ASCII sweep re-run each time (Bitwarden's own cache only saves the network call).
@@ -238,6 +246,7 @@ def reset_secret_source_cache(hermes_home: str | os.PathLike | None = None) -> N
_SOURCE_SUPPLIED_NAMES.clear()
_SECRET_SOURCE_VALUES_BY_HOME.clear()
_SECRET_SOURCE_RESTORE_BY_HOME.clear()
+ _SECRET_SOURCE_WRITES_BY_HOME.clear()
return
home_key = str(Path(hermes_home).resolve())
_APPLIED_HOMES.discard(home_key)
@@ -583,6 +592,45 @@ def _apply_managed_env(*, load_pass: int | None = None) -> None:
_load_dotenv_with_fallback(managed_env, override=True, load_pass=load_pass, managed=True)
+def _revoke_secret_source_writes(home_path: Path, *, keep) -> None:
+ """Take back what a source wrote into ``os.environ`` for *home_path* once nothing backs it.
+
+ ``keep(name, source)`` says which recorded writes are still owned. Every other write is revoked,
+ but only while ``os.environ`` still holds exactly the value the source wrote: a value another owner
+ replaced since (the profile's ``.env``, the administrator-managed ``.env``, a shell export, a later
+ source) is theirs and stays. A revoked name gets back the value it held before the source's first
+ write, or is removed when it had none."""
+ home_key = str(Path(home_path).resolve())
+ writes = _SECRET_SOURCE_WRITES_BY_HOME.get(home_key)
+ if not writes:
+ return
+ try:
+ from agent.secret_scope import load_env_file
+
+ owned_by_dotenv = set(load_env_file(Path(home_path) / ".env")) | _MANAGED_DOTENV_KEYS
+ except Exception: # noqa: BLE001 — unreadable .env: treat nothing as dotenv-owned
+ owned_by_dotenv = set(_MANAGED_DOTENV_KEYS)
+ kept: dict[str, tuple[str, str, str | None]] = {}
+ for name, (source, value, prior) in writes.items():
+ if keep(name, source):
+ kept[name] = (source, value, prior)
+ continue
+ if name not in owned_by_dotenv and os.environ.get(name) == value:
+ if prior is None:
+ os.environ.pop(name, None)
+ else:
+ os.environ[name] = prior
+ still_attributed = any(
+ other.get(name, ("",))[0] == source
+ for key, other in _SECRET_SOURCE_WRITES_BY_HOME.items() if key != home_key)
+ if _SECRET_SOURCES.get(name) == source and not still_attributed:
+ _SECRET_SOURCES.pop(name, None)
+ if kept:
+ _SECRET_SOURCE_WRITES_BY_HOME[home_key] = kept
+ else:
+ _SECRET_SOURCE_WRITES_BY_HOME.pop(home_key, None)
+
+
def _apply_external_secret_sources(home_path: Path) -> None:
"""Pull secrets from every enabled external source into env — AFTER dotenv (sources need .env bootstrap
tokens), BEFORE Hermes reads credentials; failures never block startup. Precedence/conflicts/provenance
@@ -600,7 +648,10 @@ def _apply_external_secret_sources(home_path: Path) -> None:
except Exception: # noqa: BLE001 — config errors must not block startup
# See #40597.
return
+ # No source configured / enabled any more: whatever one wrote earlier is no longer backed (#126982
+ # review). A config READ failure above keeps them — fail-open, same as the fetch-failure path below.
if not cfg:
+ _revoke_secret_source_writes(home_path, keep=lambda _name, _source: False)
return
# Defer the registry import until a source is enabled — bitwarden eagerly loads cryptography._rust.pyd,
@@ -608,13 +659,24 @@ def _apply_external_secret_sources(home_path: Path) -> None:
# flag), not names, so plugin/test sources pass and a plain dict entry never forces the crypto load.
any_enabled = any(isinstance(v, dict) and v.get("enabled") is True for v in cfg.values())
if not any_enabled:
+ _revoke_secret_source_writes(home_path, keep=lambda _name, _source: False)
return
try:
- from agent.secret_sources.registry import apply_all
+ from agent.secret_sources.registry import apply_all, enabled_source_names
except ImportError:
return
+ # Revoke a removed/disabled source's writes BEFORE the pass: left in place, its stale value would make
+ # a still-enabled source that supplies the same name skip it as pre-existing (``skipped_existing``).
+ try:
+ active = enabled_source_names(cfg, home_path)
+ except Exception: # noqa: BLE001 — cannot tell which sources remain: keep everything (fail-open)
+ active = None
+ if active is not None:
+ _revoke_secret_source_writes(home_path, keep=lambda _name, source: source in active)
+ environ_before = dict(os.environ)
+
try:
report = apply_all(cfg, home_path)
except Exception: # noqa: BLE001 — belt-and-braces; apply_all shouldn't raise
@@ -645,6 +707,7 @@ def _apply_external_secret_sources(home_path: Path) -> None:
for name in supplied:
if name in os.environ:
values[name] = os.environ[name]
+ _record_secret_source_writes(home_key, report, supplied, environ_before)
if values:
_SECRET_SOURCE_VALUES_BY_HOME[home_key] = values
_SECRET_SOURCE_RESTORE_BY_HOME[home_key] = {
@@ -665,6 +728,31 @@ def _apply_external_secret_sources(home_path: Path) -> None:
print(f" Secret sources: {conflict}", file=sys.stderr)
+def _record_secret_source_writes(home_key: str, report, supplied: set[str], environ_before: dict) -> None:
+ """Refresh ``_SECRET_SOURCE_WRITES_BY_HOME`` after one process-global pass, revoking a write its
+ still-enabled source has stopped supplying (rotated out, mapping removed). A source whose fetch
+ FAILED this pass keeps its earlier writes: a transient vault outage is not a revocation."""
+ failed = {src.name for src in report.sources if not src.result.ok}
+ previous = _SECRET_SOURCE_WRITES_BY_HOME.get(home_key, {})
+ _revoke_secret_source_writes(
+ Path(home_key),
+ keep=lambda name, source: name in report.provenance or name in supplied or source in failed)
+ writes = {name: rec for name, rec in _SECRET_SOURCE_WRITES_BY_HOME.get(home_key, {}).items()
+ if name not in report.provenance and os.environ.get(name) == rec[1]}
+ for name, applied in report.provenance.items():
+ if name not in os.environ:
+ continue
+ before = environ_before.get(name)
+ earlier = previous.get(name)
+ # Re-applied over our own earlier write: the pre-source value is the one recorded then.
+ prior = earlier[2] if earlier is not None and earlier[1] == before else before
+ writes[name] = (applied.source, os.environ[name], prior)
+ if writes:
+ _SECRET_SOURCE_WRITES_BY_HOME[home_key] = writes
+ else:
+ _SECRET_SOURCE_WRITES_BY_HOME.pop(home_key, None)
+
+
def _remediation_hint(source_name: str, error_kind, secrets_cfg: dict, *, scope: str | None = None) -> str:
"""The failed source's one-line fix-it hint; a plugin remediation() could raise and startup must not."""
try:
diff --git a/tests/hermes_cli/test_secret_source_bootstrap.py b/tests/hermes_cli/test_secret_source_bootstrap.py
index 0fb2abf5d7c..7575c8eabc6 100644
--- a/tests/hermes_cli/test_secret_source_bootstrap.py
+++ b/tests/hermes_cli/test_secret_source_bootstrap.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import os
from pathlib import Path
+import pytest
+
from agent.secret_sources.base import (
SECRET_SOURCE_API_VERSION,
FetchResult,
@@ -243,3 +245,88 @@ def test_real_plugin_source_discovery_applies_dotenv(monkeypatch, tmp_path):
os.environ.pop("HERMES_TEST_PLUGIN_BOOTSTRAP", None)
reg._reset_registry_for_tests()
env_loader.reset_secret_source_cache()
+
+
+_FIXTURE_PLUGIN = (
+ "from pathlib import Path\n"
+ "from agent.secret_sources.base import (\n"
+ " SECRET_SOURCE_API_VERSION, FetchResult, SecretSource,\n"
+ ")\n\n"
+ "class FixtureVault(SecretSource):\n"
+ " name = 'fixturevault'\n"
+ " label = 'Fixture vault'\n"
+ " api_version = SECRET_SOURCE_API_VERSION\n"
+ " shape = 'bulk'\n\n"
+ " def fetch(self, cfg: dict, home_path: Path) -> FetchResult:\n"
+ " return FetchResult(secrets={'REVIEW_PLUGIN_SECRET': 'from-plugin'})\n\n"
+ "def register(ctx):\n"
+ " ctx.register_secret_source(FixtureVault())\n"
+)
+
+
+def _write_plugin_home(home: Path, *, plugin_enabled: bool) -> None:
+ plugin_dir = home / "plugins" / "fixture-secret-source"
+ plugin_dir.mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "plugin.yaml").write_text("name: fixture-secret-source\nversion: 0.1.0\n", encoding="utf-8")
+ (plugin_dir / "__init__.py").write_text(_FIXTURE_PLUGIN, encoding="utf-8")
+ enabled = "[fixture-secret-source]" if plugin_enabled else "[]"
+ (home / "config.yaml").write_text(
+ f"plugins:\n enabled: {enabled}\nsecrets:\n fixturevault:\n enabled: true\n", encoding="utf-8")
+
+
[email protected]("replaced_by_other_owner", [False, True], ids=["revoked", "other-owner-kept"])
+def test_removing_the_last_plugin_source_revokes_its_process_env_value(
+ monkeypatch, tmp_path, replaced_by_other_owner):
+ """Disabling/removing a plugin secret source takes its value back out of ``os.environ`` (#126982
+ review): the per-home snapshot was already rebuilt, but the process env kept the injected value and
+ single-profile ``get_secret()`` served it through its ``os.environ`` fallback until restart. A value
+ another owner wrote over the plugin's since is theirs and stays. A sibling home (A -> B -> A) never
+ has its own view disturbed by the revocation."""
+ import agent.secret_sources.registry as reg
+ from agent.secret_scope import get_secret
+ from hermes_cli import env_loader
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ reg._reset_registry_for_tests()
+ env_loader.reset_secret_source_cache()
+ home_a = tmp_path / "a" / ".hermes"
+ home_b = tmp_path / "b" / ".hermes"
+ _write_plugin_home(home_a, plugin_enabled=True)
+ home_b.mkdir(parents=True)
+ (home_b / ".env").write_text("SIBLING_ONLY=sibling\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home_a))
+ monkeypatch.delenv("REVIEW_PLUGIN_SECRET", raising=False)
+
+ try:
+ manager = PluginManager()
+ manager.discover_and_load()
+ assert os.environ["REVIEW_PLUGIN_SECRET"] == "from-plugin"
+ assert get_secret("REVIEW_PLUGIN_SECRET") == "from-plugin"
+
+ # B: a sibling profile's activity in between does not touch A's record or value.
+ token = set_hermes_home_override(str(home_b))
+ try:
+ env_loader.hydrate_profile_secret_sources(home_b)
+ finally:
+ reset_hermes_home_override(token)
+ assert os.environ["REVIEW_PLUGIN_SECRET"] == "from-plugin"
+
+ if replaced_by_other_owner:
+ os.environ["REVIEW_PLUGIN_SECRET"] = "from-operator"
+
+ # A: the plugin is disabled; the next discovery unloads its registration and reconciles.
+ _write_plugin_home(home_a, plugin_enabled=False)
+ manager.discover_and_load(force=True)
+ assert reg.list_plugin_sources() == []
+
+ if replaced_by_other_owner:
+ assert os.environ["REVIEW_PLUGIN_SECRET"] == "from-operator"
+ assert get_secret("REVIEW_PLUGIN_SECRET") == "from-operator"
+ else:
+ assert "REVIEW_PLUGIN_SECRET" not in os.environ
+ assert get_secret("REVIEW_PLUGIN_SECRET") is None
+ assert env_loader.get_secret_source("REVIEW_PLUGIN_SECRET") is None
+ finally:
+ os.environ.pop("REVIEW_PLUGIN_SECRET", None)
+ reg._reset_registry_for_tests()
+ env_loader.reset_secret_source_cache()