The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(vault): login backends only from bundled or verified/official catalog plugins
Teknium895eb4ed9c4d
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 21513d123bf..4c9232552f7 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -59,7 +59,7 @@ from hermes_cli.plugins_dispatch import ()from hermes_cli.plugins_capability_ctx import PluginCapabilityCtxMixinfrom hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistration-from hermes_cli.plugins_registrars import _NAME_NORMALIZERS, _SCOPED_PROVIDER_REGISTRARS+from hermes_cli.plugins_registrars import _SCOPED_PROVIDER_REGISTRARS, make_scoped_provider_registrarfrom hermes_cli.plugins_state import (PluginState, _locked_plugin_state, _nested_plugin_mapping, _nested_plugin_value,_plugin_relative_segments, _plugin_settings_entry, save_plugin_setting,@@ -1016,34 +1016,8 @@ class PluginContext(PluginCapabilityCtxMixin):# -- scoped provider registrars ------------------------------------------------------------------# One generated ``register_<category>_provider`` method per row of plugins_registrars.py's table.----def _make_scoped_provider_registrar(method_name, kind, registry_mod, base_ref, label, doc, options):- """Build one ``register_<category>_provider`` method from a ``_SCOPED_PROVIDER_REGISTRARS`` row."""- base_mod, base_attr = base_ref.split(":")- normalize_fn = _NAME_NORMALIZERS[options.get("normalize", "strip")]- register_name = options.get("register")-- def register(self, provider) -> Optional[PluginRegistration]:- registry = importlib.import_module(registry_mod)- return self._register_scoped_provider(- provider, kind=kind, base_class=getattr(importlib.import_module(base_mod), base_attr),- registry=registry, label=label, article=options.get("article", "a"), normalize=normalize_fn,- register=getattr(registry, register_name) if register_name else None,- reject_message=options.get("reject_message"),- )-- def register_source(self, source) -> Optional[PluginRegistration]: # secret sources: ``source``- return register(self, source)-- method = register_source if options.get("param") == "source" else register- method.__name__, method.__qualname__, method.__doc__ = method_name, f"PluginContext.{method_name}", doc- return _serialized_replacement(method)--for _row in _SCOPED_PROVIDER_REGISTRARS:- setattr(PluginContext, _row[0], _make_scoped_provider_registrar(*_row))+ setattr(PluginContext, _row[0], make_scoped_provider_registrar(*_row))del _rowdiff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.pyindex efe12e1e5f0..758a11db4ef 100644--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@ -203,6 +203,38 @@ def catalog_install_record(plugin_dir) -> Optional[dict]:return read_catalog_sidecar(plugin_dir)+LOGIN_BACKEND_TIERS = frozenset({"official", "verified"})+LOGIN_BACKEND_RULE = ("password-manager login backends are accepted only from plugins bundled with Hermes or "+ "installed from the Hermes plugin catalog at tier verified or official (published by the "+ "password-manager vendor itself or by Nous)")+_NON_CATALOG_SOURCES = {"project": "a project .hermes/plugins directory", "entrypoint": "a pip entry point"}+++def login_backend_provenance_error(manifest) -> str:+ """Why *manifest*'s plugin may not register a login backend, or "" when it may.++ Read from the installer-owned ``.install-metadata.json`` record of the CURRENT home's plugins dir, never+ from the tree (a repo can commit a ``.hermes-catalog.json``). No config key relaxes it. This decides+ which plugins Hermes offers the seam to; code already running in-process is not sandboxed by it."""+ if manifest.source == "bundled":+ return ""+ if manifest.source in _NON_CATALOG_SOURCES:+ return f"{LOGIN_BACKEND_RULE}; this plugin was loaded from {_NON_CATALOG_SOURCES[manifest.source]}"+ record = _install_record(Path(manifest.path)) if manifest.source == "user" and manifest.path else None+ block = (record or {}).get("catalog")+ if not isinstance(block, dict) or not block.get("name"):+ return (f"{LOGIN_BACKEND_RULE}; this plugin was not installed from the Hermes plugin catalog "+ "(a local directory or Git URL install)")+ if record.get("allow_removed"):+ return f"{LOGIN_BACKEND_RULE}; this plugin was installed with --allow-removed"+ tier = str(block.get("tier") or "community")+ if tier not in LOGIN_BACKEND_TIERS:+ return f"{LOGIN_BACKEND_RULE}; catalog entry '{block['name']}' is tier {tier}"+ if not block.get("pin"):+ return f"{LOGIN_BACKEND_RULE}; this install is not at the catalog's reviewed pin (installed with --ref)"+ return ""++def catalog_annotation(dir_path) -> Optional[str]:"""``catalog:<tier>@<sha8>`` for a catalog install (``list`` Source column), else ``None``."""sidecar = catalog_install_record(dir_path)diff --git a/hermes_cli/plugins_registrars.py b/hermes_cli/plugins_registrars.pyindex bb30a0b6871..0bb1bb5d990 100644--- a/hermes_cli/plugins_registrars.py+++ b/hermes_cli/plugins_registrars.py@@ -4,21 +4,31 @@ Every ``register_<category>_provider`` shares one body (:meth:`PluginContext._retype-check, register in the scope-keyed process-global registry, lease the slot so unload restoresthe displaced entry. ``hermes_cli.plugins`` generates one ctx method per row. Rows: (method, kind,registry module, base-class module:attr, label, docstring, options). ``normalize``: ``strip``-(default), ``lower`` (strip+lowercase) or ``None`` (raw name). Object-taking rows also need a+(default), ``lower`` (strip+lowercase) or ``None`` (raw name). ``admit``: ``module:function`` taking+the plugin's manifest and returning why it may not register this kind ("" = it may), judged under the+manager's home before the registry is touched. Object-taking rows also need a``plugin_isolation.HOST_OBJECT_BASES`` entry so the provider works under ``plugins.isolation: host``."""from __future__ import annotations+import importlib+import loggingfrom typing import Any, Callable, Optional+from hermes_cli.plugins_loader import _plugin_home_scope, _serialized_replacement++logger = logging.getLogger(__name__)+_SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str, Any]], ...] = (("register_login_backend", "login_backend", "agent.vault_backend_registry","agent.vault_backends.base:LoginBackend", "login backend","Register a trusted in-process browser-vault LoginBackend; explicit vault.<name>.enabled ""is required. Registration is profile-scoped and removed on plugin unload. "- "Backend instances must read active-profile configuration lazily.",- {"normalize": None, "reject_message": "Plugin '%s' login backend rejected: %s"}),+ "Backend instances must read active-profile configuration lazily. Accepted only from bundled "+ "plugins and catalog installs at tier verified or official.",+ {"normalize": None, "reject_message": "Plugin '%s' login backend rejected: %s",+ "admit": "hermes_cli.plugins_cmd_catalog:login_backend_provenance_error"}),("register_image_gen_provider", "image_gen_provider", "agent.image_gen_registry","agent.image_gen_provider:ImageGenProvider", "image_gen provider","Register an :class:`agent.image_gen_provider.ImageGenProvider`; "@@ -74,3 +84,37 @@ _SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str,_NAME_NORMALIZERS: dict[Optional[str], Optional[Callable[[str], str]]] = {"strip": lambda n: n.strip(), "lower": lambda n: n.strip().lower(), None: None,}+++def _resolve(ref: str) -> Any:+ module, attr = ref.split(":")+ return getattr(importlib.import_module(module), attr)+++def make_scoped_provider_registrar(method_name, kind, registry_mod, base_ref, label, doc, options):+ """Build one ``register_<category>_provider`` method from a ``_SCOPED_PROVIDER_REGISTRARS`` row."""+ normalize_fn = _NAME_NORMALIZERS[options.get("normalize", "strip")]+ register_name = options.get("register")+ admit = options.get("admit")++ def register(self, provider):+ if admit:+ with _plugin_home_scope(self._manager.home_path):+ refusal = _resolve(admit)(self.manifest)+ if refusal:+ logger.warning(options["reject_message"], self.manifest.name, refusal)+ return None+ registry = importlib.import_module(registry_mod)+ return self._register_scoped_provider(+ provider, kind=kind, base_class=_resolve(base_ref),+ registry=registry, label=label, article=options.get("article", "a"), normalize=normalize_fn,+ register=getattr(registry, register_name) if register_name else None,+ reject_message=options.get("reject_message"),+ )++ def register_source(self, source): # secret sources: ``source``+ return register(self, source)++ method = register_source if options.get("param") == "source" else register+ method.__name__, method.__qualname__, method.__doc__ = method_name, f"PluginContext.{method_name}", doc+ return _serialized_replacement(method)diff --git a/tests/agent/test_vault_backend_registry.py b/tests/agent/test_vault_backend_registry.pyindex 4d0c55d2177..d52a10767ee 100644--- a/tests/agent/test_vault_backend_registry.py+++ b/tests/agent/test_vault_backend_registry.py@@ -1,4 +1,5 @@"""Plugin vault registration uses existing scoped leases; no browser/secrets."""+import jsonfrom unittest.mock import patchfrom textwrap import dedentimport pytest@@ -16,6 +17,17 @@ class Example(LoginBackend):raise AssertionError("registry tests must never resolve passwords")+def _record_verified_install(home, dirname):+ """The installer-owned record a catalog install at tier ``verified`` leaves (login backends need one)."""+ path = home / "plugins" / ".install-metadata.json"+ records = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+ sha = "a" * 40+ records[dirname] = {"source": f"https://github.com/example/{dirname}", "revision": sha, "pinned": True,+ "catalog": {"name": dirname, "repo": f"https://github.com/example/{dirname}",+ "tier": "verified", "pin": sha, "sha": sha}}+ path.write_text(json.dumps(records), encoding="utf-8")++def test_registration_requires_explicit_profile_enablement():with patch.dict(registry._providers, clear=True), \patch("agent.vault_backends.base.is_enabled", return_value=False), \@@ -41,7 +53,7 @@ def test_reload_cannot_change_prefix_and_leave_ambiguous_restore(tmp_path):from hermes_cli.plugins import PluginContext, PluginManagerfrom hermes_cli.plugins_manifest import PluginManifestscope = str(tmp_path / "home")- context = PluginContext(PluginManifest(name="login-example"), PluginManager(scope_key=scope))+ context = PluginContext(PluginManifest(name="login-example", source="bundled"), PluginManager(scope_key=scope))original = Example()first = context.register_login_backend(original)class ChangedPrefix(Example):@@ -59,7 +71,7 @@ def test_lease_reload_and_unload_do_not_cross_profiles(tmp_path):from hermes_cli.plugins import PluginContext, PluginManagerfrom hermes_cli.plugins_manifest import PluginManifestfirst, second = str(tmp_path / "first"), str(tmp_path / "second")- manifest = PluginManifest(name="test-vault")+ manifest = PluginManifest(name="test-vault", source="bundled")first_ctx = PluginContext(manifest, PluginManager(scope_key=first))second_ctx = PluginContext(manifest, PluginManager(scope_key=second))original, replacement, sibling = Example(), Example(), Example()@@ -94,6 +106,7 @@ def test_real_plugin_discovery_reload_and_disable(tmp_path, monkeypatch):def register(ctx):ctx.register_login_backend(Backend())'''), encoding="utf-8")+ _record_verified_install(home, "login_example")config = home / "config.yaml"config.write_text("plugins:\n enabled: [login_example]\nvault:\n example:\n enabled: true\n", encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(home))diff --git a/tests/hermes_cli/test_login_backend_provenance.py b/tests/hermes_cli/test_login_backend_provenance.pynew file mode 100644index 00000000000..ca8630c0425--- /dev/null+++ b/tests/hermes_cli/test_login_backend_provenance.py@@ -0,0 +1,203 @@+"""Who may register a password-manager login backend (``ctx.register_login_backend``).++Only plugins bundled with Hermes, or installed from the plugin catalog at tier ``verified`` or ``official``+and at the catalog's reviewed pin, are accepted. Provenance comes from the installer-owned+``.install-metadata.json`` record, never from the plugin tree. Real git, file:// repos, the real installer,+and the real plugin manager loading into a temp ``HERMES_HOME``.+"""++from __future__ import annotations++import json+import logging+import os+import shutil+import subprocess as sp+from pathlib import Path++import pytest++from hermes_cli import plugin_catalog as pc_cat+from hermes_cli import plugins_cmd as pc+from hermes_cli import plugins_cmd_catalog as cat+from tests.pm._fixtures import client, isolated_python # pytest fixtures: PM-isolated HOME/HERMES_HOME++pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git not available")++_GIT_ENV = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}++_PLUGIN = '''+from agent.vault_backends.base import LoginBackend+++class Backend(LoginBackend):+ name, prefix, display_name = "acme", "acme:", "Acme"++ def list_items(self):+ return []++ def get_meta(self, handle):+ return None++ def resolve_password(self, handle):+ raise AssertionError("provenance tests never resolve passwords")+++def register(ctx):+ ctx.register_login_backend(Backend())+'''++RULE = "verified or official"+++def _commit(repo: Path, msg: str) -> str:+ sp.run(["git", "add", "-A"], cwd=repo, check=True, env=_GIT_ENV)+ sp.run(["git", "commit", "-q", "-m", msg], cwd=repo, check=True, env=_GIT_ENV)+ return sp.run(["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True).stdout.strip()+++def world(request, tmp_path, monkeypatch):+ """A file:// login-backend plugin repo (two commits), a catalog entry pinned to the first, a temp home."""+ request.getfixturevalue("client")+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ repo = tmp_path / "repo"+ repo.mkdir()+ (repo / "plugin.yaml").write_text("name: acme-vault\nversion: 1.0.0\ndescription: d\n")+ (repo / "__init__.py").write_text(_PLUGIN)+ sp.run(["git", "init", "-q"], cwd=repo, check=True, env=_GIT_ENV)+ sha1 = _commit(repo, "v1")+ (repo / "__init__.py").write_text(_PLUGIN + "# v2\n")+ sha2 = _commit(repo, "v2")++ home = tmp_path / "home"+ plugins_dir = home / "plugins"+ plugins_dir.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ token = set_hermes_home_override(home)+ monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: False)+ monkeypatch.setattr(pc, "_console", lambda: type("C", (), {"print": lambda *a, **k: None})())++ def publish_without_environment(*_args, plugins=None, **_kwargs):+ from hermes_cli.runtime_state import finish_publication+ from pm import paths+ from pm.plugin_inputs import StagedUpdate+ from pm.publication import PluginSelection, StagedPlugin++ change = StagedPlugin(dict(plugins.data)) if isinstance(plugins, StagedUpdate) else PluginSelection(+ dict(plugins.data))+ change.publish(paths.repo_root())+ finish_publication(paths.repo_root())++ monkeypatch.setattr("pm.client.sync_venv", publish_without_environment)+ monkeypatch.setattr(pc_cat, "fetch_live_catalog", lambda **_: None) # in-tree only, no network+ monkeypatch.setattr(pc_cat, "load_removed_list", lambda catalog_dir=None: [])+ tier = {"value": "verified"}++ def entry() -> pc_cat.PluginCatalogEntry:+ return pc_cat.PluginCatalogEntry(name="acme-vault", repo=repo.as_uri(), sha=sha1, description="d",+ maintainer="Acme", tier=tier["value"])++ monkeypatch.setattr(pc_cat, "load_catalog", lambda catalog_dir=None: [entry()])+ managers = []++ def load():+ from agent import vault_backend_registry as registry+ from hermes_cli.plugins import PluginManager++ (home / "config.yaml").write_text("plugins:\n enabled: [acme-vault]\nvault:\n acme: {enabled: true}\n")+ manager = PluginManager(scope_key=str(home))+ manager.discover_and_load()+ managers.append(manager)+ return registry.get_provider("acme", scope=str(home))++ try:+ yield {"repo": repo, "sha1": sha1, "sha2": sha2, "home": home, "plugins_dir": plugins_dir,+ "tier": tier, "entry": entry, "load": load}+ finally:+ for manager in managers:+ manager.unload()+ reset_hermes_home_override(token)++[email protected]("tier", ["verified", "official"])+def test_catalog_install_at_verified_or_official_tier_registers(world, tier):+ world["tier"]["value"] = tier+ cat.install_catalog_entry(world["entry"](), force=False)+ backend = world["load"]()+ assert backend is not None and backend.name == "acme"+++def test_community_catalog_install_is_refused(world, caplog):+ world["tier"]["value"] = "community"+ cat.install_catalog_entry(world["entry"](), force=False)+ with caplog.at_level(logging.WARNING):+ assert world["load"]() is None+ assert RULE in caplog.text and "tier community" in caplog.text+++def test_local_directory_plugin_is_refused(world, caplog):+ plugin = world["plugins_dir"] / "acme-vault"+ plugin.mkdir()+ (plugin / "plugin.yaml").write_text("name: acme-vault\n")+ (plugin / "__init__.py").write_text(_PLUGIN)+ with caplog.at_level(logging.WARNING):+ assert world["load"]() is None+ assert RULE in caplog.text and "not installed from the Hermes plugin catalog" in caplog.text+++def test_url_install_with_forged_in_tree_catalog_file_is_refused(world, caplog):+ """A repo can commit a ``.hermes-catalog.json`` claiming a verified entry; Python never reads it."""+ (world["repo"] / ".hermes-catalog.json").write_text(json.dumps(+ {"catalog_name": "acme-vault", "repo": world["repo"].as_uri(), "sha": world["sha1"], "tier": "verified"}))+ forged = _commit(world["repo"], "forge provenance")+ pc._install_plugin_core(world["repo"].as_uri(), force=False, ref=forged)+ assert json.loads((world["plugins_dir"] / "acme-vault" / ".hermes-catalog.json").read_text())["tier"] == "verified"+ with caplog.at_level(logging.WARNING):+ assert world["load"]() is None+ assert RULE in caplog.text+++def test_verified_entry_installed_off_the_reviewed_pin_is_refused(world, caplog):+ cat.install_catalog_entry(world["entry"](), force=False, ref=world["sha2"])+ with caplog.at_level(logging.WARNING):+ assert world["load"]() is None+ assert RULE in caplog.text and "reviewed pin" in caplog.text+++def test_verified_entry_installed_with_allow_removed_is_refused(world, caplog):+ cat.install_catalog_entry(world["entry"](), force=False, allow_removed=True)+ with caplog.at_level(logging.WARNING):+ assert world["load"]() is None+ assert RULE in caplog.text and "--allow-removed" in caplog.text++[email protected]("source, accepted", [("bundled", True), ("project", False), ("entrypoint", False)])+def test_bundled_plugins_register_and_project_or_pip_plugins_do_not(tmp_path, source, accepted):+ from agent import vault_backend_registry as registry+ from agent.vault_backends.base import LoginBackend+ from hermes_cli.plugins import PluginContext, PluginManager+ from hermes_cli.plugins_manifest import PluginManifest++ class Backend(LoginBackend):+ name, prefix, display_name = "acme", "acme:", "Acme"++ def list_items(self):+ return []++ def get_meta(self, handle):+ return None++ def resolve_password(self, handle):+ raise AssertionError("never resolved")++ scope = str(tmp_path / "home")+ manifest = PluginManifest(name="acme-vault", source=source, path=str(tmp_path / "acme-vault"))+ handle = PluginContext(manifest, PluginManager(scope_key=scope)).register_login_backend(Backend())+ try:+ assert (registry.get_provider("acme", scope=scope) is not None) is accepted+ finally:+ if handle is not None:+ handle.dispose()diff --git a/tests/tools/test_browser_vault_plugin_isolation.py b/tests/tools/test_browser_vault_plugin_isolation.pyindex dbfab462fad..1fbdee22a88 100644--- a/tests/tools/test_browser_vault_plugin_isolation.py+++ b/tests/tools/test_browser_vault_plugin_isolation.py@@ -118,6 +118,18 @@ def _write_plugin(home, dirname, body, register):plugin.mkdir(parents=True)(plugin / "plugin.yaml").write_text(f"name: {dirname}\n", encoding="utf-8")(plugin / "__init__.py").write_text(body + "\n\ndef register(ctx):\n" + register, encoding="utf-8")+ _record_verified_install(home, dirname)+++def _record_verified_install(home, dirname):+ """The installer-owned record a catalog install at tier ``verified`` leaves (login backends need one)."""+ path = home / "plugins" / ".install-metadata.json"+ records = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+ sha = "a" * 40+ records[dirname] = {"source": f"https://github.com/example/{dirname}", "revision": sha, "pinned": True,+ "catalog": {"name": dirname, "repo": f"https://github.com/example/{dirname}",+ "tier": "verified", "pin": sha, "sha": sha}}+ path.write_text(json.dumps(records), encoding="utf-8")def _write_config(home, plugins, vault):