The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(secrets_cli): defer bitwarden backend import to first attribute access
Halldrix3f9150e5c4ca
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 5fa4489f441..e13cedcef68 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -11816,19 +11816,14 @@ def main():# Lazy-import secrets_cli: the module imports agent.secret_sources.bitwarden# which loads cryptography._rust.pyd. On Windows this maps the native# extension into the updater process, causing the self-lock preflight to- # defer (#86781). We pre-create the subparsers here (parse-time, no- # crypto cost) and let secrets_cli import only when a command actually- # runs — at which point the parse has long since completed.- def _register_bitwarden(_p): # noqa: ANN001- from hermes_cli import secrets_cli as _secrets_cli- return _secrets_cli.register_cli(_p)-- def _register_onepassword(_p): # noqa: ANN001- from hermes_cli import onepassword_secrets_cli as _op_secrets_cli- return _op_secrets_cli.register_cli(_p)-- _register_bitwarden(secrets_bw)- _register_onepassword(secrets_op)+ # defer (#86781). secrets_cli defers its backend import to first use+ # (module-level __getattr__ + handler-level _load_bw()), so register_cli+ # at parse time only wires argparse structure with no crypto cost.+ from hermes_cli import secrets_cli as _secrets_cli+ from hermes_cli import onepassword_secrets_cli as _op_secrets_cli++ _secrets_cli.register_cli(secrets_bw)+ _op_secrets_cli.register_cli(secrets_op)def _dispatch_secrets(args): # noqa: ANN001sub = getattr(args, "secrets_command", None)diff --git a/hermes_cli/secrets_cli.py b/hermes_cli/secrets_cli.pyindex 2ae7f4f55dc..60128da00ed 100644--- a/hermes_cli/secrets_cli.py+++ b/hermes_cli/secrets_cli.py@@ -23,7 +23,20 @@ from rich.console import Consolefrom rich.panel import Panelfrom rich.table import Table-from agent.secret_sources import bitwarden as bw+# NOTE: the Bitwarden backend (``agent.secret_sources.bitwarden``) pulls in+# ``cryptography`` at module-import time. On Windows the resulting+# ``cryptography._rust.pyd`` is mapped into the running process — and when+# that process is ``hermes update``, the self-lock preflight detects the+# loaded native module and defers (#86781). Keep the backend import lazy:+# this module is registered parse-time from ``hermes_cli.main`` and must not+# touch ``bw`` until a handler actually runs.+#+# ``_BWS_VERSION`` is duplicated here (as a plain string) so ``register_cli``+# can render the ``install --help`` text without importing the backend.+# ``agent.secret_sources.bitwarden._BWS_VERSION`` is the source of truth;+# bump both together when pinning a new bws release.+_BWS_VERSION = "2.0.0"+from hermes_cli.config import (get_env_path,load_config,@@ -33,6 +46,28 @@ from hermes_cli.config import (from hermes_cli.secret_prompt import masked_secret_prompt+def _load_bw():+ """Import ``agent.secret_sources.bitwarden`` on first use (crypto payload)."""+ from agent.secret_sources import bitwarden as _bw++ return _bw+++def __getattr__(name: str):+ """PEP 562 module-level lazy resolver.++ Existing callers (and upstream tests) monkeypatch attributes on+ ``hermes_cli.secrets_cli.bw`` directly. Resolving that attribute at+ module-import time would re-import ``cryptography`` eagerly — the very+ self-lock we are preventing (#86781). Defer the backend import until+ the first actual attribute access, so ``import hermes_cli.secrets_cli``+ stays crypto-free while ``secrets_cli.bw.find_bws`` still resolves.+ """+ if name == "bw":+ return _load_bw()+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++# ---------------------------------------------------------------------------# Argparse wiring — called from hermes_cli.main# ---------------------------------------------------------------------------@@ -103,7 +138,7 @@ def register_cli(parent_parser: argparse.ArgumentParser) -> None:install = sub.add_parser("install",- help=f"Download and verify the pinned bws binary (v{bw._BWS_VERSION})",+ help=f"Download and verify the pinned bws binary (v{_BWS_VERSION})",)install.add_argument("--force",@@ -119,6 +154,7 @@ def register_cli(parent_parser: argparse.ArgumentParser) -> None:def cmd_setup(args: argparse.Namespace) -> int:+ bw = _load_bw()console = Console()console.print(Panel.fit(@@ -308,6 +344,7 @@ def cmd_setup(args: argparse.Namespace) -> int:def cmd_status(args: argparse.Namespace) -> int:+ bw = _load_bw()console = Console()cfg = load_config()bw_cfg = (cfg.get("secrets") or {}).get("bitwarden") or {}@@ -373,6 +410,7 @@ def cmd_token(args: argparse.Namespace) -> int:token, probes Bitwarden with it (unless ``--no-verify``), and only thenpersists it to .env — so a bad paste never bricks the working token."""+ bw = _load_bw()console = Console()cfg = load_config()bw_cfg = (cfg.get("secrets") or {}).get("bitwarden") or {}@@ -448,6 +486,7 @@ def cmd_token(args: argparse.Namespace) -> int:def cmd_sync(args: argparse.Namespace) -> int:+ bw = _load_bw()console = Console()cfg = load_config()bw_cfg = (cfg.get("secrets") or {}).get("bitwarden") or {}@@ -538,6 +577,7 @@ def cmd_disable(args: argparse.Namespace) -> int:def cmd_install(args: argparse.Namespace) -> int:+ bw = _load_bw()console = Console()try:path = bw.install_bws(force=bool(args.force))diff --git a/tests/test_lazy_secrets_dispatch.py b/tests/test_lazy_secrets_dispatch.pyindex fad991b22d0..ec75e0562a3 100644--- a/tests/test_lazy_secrets_dispatch.py+++ b/tests/test_lazy_secrets_dispatch.py@@ -120,4 +120,89 @@ class TestUpdatePathE2E:# must not contain the self-lock defer messageassert "deferred" not in result.stderr.lower()assert "self-lock" not in result.stderr.lower()- assert "_rust.pyd" not in result.stderr.lower()\ No newline at end of file+ assert "_rust.pyd" not in result.stderr.lower()++ @pytest.mark.live_system_guard_bypass+ def test_main_update_check_crypto_absent_in_sys_modules(self) -> None:+ """Decisive invariant: invoking main() with argv=['hermes','update','--check']+ leaves cryptography.hazmat.bindings._rust absent from sys.modules.++ This is the exact invariant review flagged as unproven (#86782 review+ 2026-08-15): an import-only test cannot observe lazy failures, because+ parser construction happens inside main(). Run main() itself in a+ subprocess, let it execute the update path, then assert sys.modules.++ The check must run before _dispatch_update calls its (potentially+ lazy) network layer, so we instrument sys.modules immediately after+ parse_args() and before dispatch returns, using a monkeypatched+ _cmd_update_check that captures state then short-circuits.+ """+ script = """+import sys+from unittest.mock import patch++crypto_seen_at_dispatch = []++def capture_update_check(*args, **kwargs):+ # Run just before the real handler would; record crypto state.+ crypto_seen_at_dispatch.append(+ 'cryptography.hazmat.bindings._rust' in sys.modules+ )+ # Short-circuit: don't actually call the network in tests.+ return 0++sys.argv = ['hermes', 'update', '--check']++import hermes_cli.main as m++# Patch the update handler so main() exercises its parser + dispatch+# without doing network I/O. cmd_update (in main.py) calls+# _self()._cmd_update_check(branch=..., branch_explicit=...) where _self()+# resolves the hermes_cli.main module's lazily re-exported attribute —+# so the patch must land on hermes_cli.main._cmd_update_check.+with patch('hermes_cli.main._cmd_update_check', capture_update_check):+ try:+ m.main()+ except SystemExit as e:+ # argparse may sys.exit for --help / bad args; ignore for this probe+ if e.code not in (0, None):+ print(f'FAIL: main() exited with code {e.code}')+ sys.exit(1)++# 1. main() must have dispatched into our capture hook+if not crypto_seen_at_dispatch:+ print('FAIL: update --check did not dispatch to _cmd_update_check')+ sys.exit(1)++# 2. At dispatch time, crypto must NOT be loaded+if crypto_seen_at_dispatch[0]:+ print('FAIL: cryptography._rust loaded by main() before update dispatch')+ sys.exit(1)++# 3. After main() returned, crypto must STILL not be loaded+if 'cryptography.hazmat.bindings._rust' in sys.modules:+ print('FAIL: cryptography._rust present in sys.modules after main()')+ sys.exit(1)++print('PASS: main() update --check path never loaded cryptography._rust')+sys.exit(0)+"""+ repo_root = Path(__file__).parent.parent+ probe = repo_root / "_test_main_update_crypto_probe.py"+ probe.write_text(script)+ try:+ result = subprocess.run(+ [sys.executable, probe.name],+ capture_output=True,+ text=True,+ cwd=str(repo_root),+ timeout=60,+ )+ assert result.returncode == 0, (+ f"Decisive main()-level probe failed:\n"+ f"stdout: {result.stdout}\n"+ f"stderr: {result.stderr}"+ )+ assert "PASS" in result.stdout+ finally:+ probe.unlink(missing_ok=True)\ No newline at end of file