The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): plugin-mirrored registry rows are visible only to homes with the profile
Tekniume67e19ac1b18
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 32567788e73..b18ab1959f8 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -238,9 +238,9 @@ _REGISTRY_ROWS: tuple[Any, ...] = (# region (agent/vertex_adapter.py build_vertex_base_url), not a fixed host.("vertex", "Google Vertex AI", "", (), "", "vertex"),("azure-foundry", "Azure Foundry", "", ("AZURE_FOUNDRY_API_KEY",), "AZURE_FOUNDRY_BASE_URL"))-PROVIDER_REGISTRY: dict[str, ProviderConfig] = {- p.id: p for p in (r if isinstance(r, ProviderConfig) else _api_key_provider(*r) for r in _REGISTRY_ROWS)-}+from hermes_cli.auth_plugin_providers import HomeScopedRegistry # mirrored rows are read per home+PROVIDER_REGISTRY: dict[str, ProviderConfig] = HomeScopedRegistry(+ (p.id, p) for p in (r if isinstance(r, ProviderConfig) else _api_key_provider(*r) for r in _REGISTRY_ROWS))# The rows above, before any plugin touches the dict (a user plugin may override these; #48450).BUILTIN_PROVIDER_IDS = frozenset(PROVIDER_REGISTRY)diff --git a/hermes_cli/auth_plugin_providers.py b/hermes_cli/auth_plugin_providers.pyindex 8119d4465a0..6593fb22ca4 100644--- a/hermes_cli/auth_plugin_providers.py+++ b/hermes_cli/auth_plugin_providers.py@@ -35,6 +35,62 @@ PLUGIN_AUTH_ACTIONS = ("add", "status", "logout", "refresh")PLUGIN_MIRRORED_PROVIDERS: set[str] = set()+def _absent_mirrored(ids) -> set[str]:+ """The plugin-mirrored ids among *ids* that the bound home has no profile for."""+ mirrored = [pid for pid in ids if pid in PLUGIN_MIRRORED_PROVIDERS]+ if not mirrored:+ return set()+ from providers import names_without_profile+ return names_without_profile(mirrored)+++class HomeScopedRegistry(dict):+ """``PROVIDER_REGISTRY``: process-wide storage, read per profile home.++ Plugin profiles are per ``$HERMES_HOME`` but their mirrored rows (and the alias keys pointing at+ them) live in one process-wide dict, and one process serves many profiles (multiplex gateway,+ Desktop ``serve``). Every read hides a mirrored row whose provider has no profile in the bound+ home, so a profile without the plugin never resolves, auto-detects or reads credentials for a+ provider another profile installed. Built-in rows are never hidden; writes are plain dict writes.+ """++ def _hidden(self) -> set[str]:+ return _absent_mirrored({row.id for row in dict.values(self)}) if PLUGIN_MIRRORED_PROVIDERS else set()++ def _shown(self, row: Any) -> bool:+ return row.id not in PLUGIN_MIRRORED_PROVIDERS or not _absent_mirrored((row.id,))++ def __getitem__(self, key: str) -> Any:+ row = dict.__getitem__(self, key)+ if not self._shown(row):+ raise KeyError(key)+ return row++ def get(self, key: str, default: Any = None) -> Any:+ row = dict.get(self, key)+ return row if row is not None and self._shown(row) else default++ def __contains__(self, key: object) -> bool:+ row = dict.get(self, key)+ return row is not None and self._shown(row)++ def items(self) -> list[tuple[str, Any]]:+ hidden = self._hidden()+ return [(key, row) for key, row in dict.items(self) if row.id not in hidden]++ def keys(self) -> list[str]:+ return [key for key, _ in self.items()]++ def values(self) -> list[Any]:+ return [row for _, row in self.items()]++ def __iter__(self):+ return iter(self.keys())++ def __len__(self) -> int:+ return len(self.items())++def _api_key_env_fields(pp: Any) -> tuple[tuple, str]:"""Split a profile's ``env_vars`` into (api-key vars, base-URL var); the URL var may be ""."""is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL")@@ -73,11 +129,13 @@ def registry_auth_type(pp: Any) -> str:def _insert_row(registry: dict, pconfig: Any, after: str) -> None:- """Add *pconfig* right after the *after* row (in place: callers hold the dict), else append."""- if after not in registry:+ """Add *pconfig* right after the *after* row (in place: callers hold the dict), else append.++ Reads the raw storage: rows hidden from the bound home must survive the rebuild."""+ if not dict.__contains__(registry, after):registry[pconfig.id] = pconfigreturn- rows = list(registry.items())+ rows = list(dict.items(registry))at = [key for key, _ in rows].index(after) + 1registry.clear()registry.update(rows[:at] + [(pconfig.id, pconfig)] + rows[at:])diff --git a/providers/__init__.py b/providers/__init__.pyindex 32ccc5be508..177a9e5019a 100644--- a/providers/__init__.py+++ b/providers/__init__.py@@ -349,6 +349,21 @@ def unlisted_provider_names() -> set[str]:return hidden+def names_without_profile(names) -> set[str]:+ """The *names* that have no profile in the bound home: neither process-wide nor its plugins.++ Lets process-wide mirrors of profiles (``hermes_cli.auth.PROVIDER_REGISTRY``) hide the rows+ another home's plugins put there. Cheap enough for per-lookup use: no discovery, no miss re-scan;+ only the periodic plugin-dir stamp check, skipped mid-scan so a plugin reading the mirror while+ it imports cannot re-enter its own scan.+ """+ rest = [name for name in names if name not in _REGISTRY]+ if not rest:+ return set()+ layer = _bound_home_layer()[0] if _discovering else _home_layer()+ return {name for name in rest if name not in layer.registry}++def _home_layer(*, force_stamp_check: bool = False) -> _HomeLayer:"""The layer for the home bound right now, importing plugin dirs it has not seen yet."""layer, home, key = _bound_home_layer()diff --git a/tests/providers/test_registry_home_scope.py b/tests/providers/test_registry_home_scope.pynew file mode 100644index 00000000000..33737134815--- /dev/null+++ b/tests/providers/test_registry_home_scope.py@@ -0,0 +1,154 @@+"""Plugin-mirrored ``PROVIDER_REGISTRY`` rows are per profile home.++One process serves many profiles (multiplex gateway, Desktop ``serve``). A ``$HERMES_HOME`` plugin+mirrors its profile into the process-wide auth registry, so after profile A served a turn, profile B+(no such plugin) auto-detected that provider from a stray env token and handed the raw token to the+plugin's endpoint through the generic env ladder. A home with no profile for a slug must see the slug+as absent everywhere: registry rows, resolve_provider, env auto-detect, credential lookups, runtime.+"""++from __future__ import annotations++import sys+import textwrap+from pathlib import Path++import pytest++from hermes_constants import reset_hermes_home_override, set_hermes_home_override++SLUG = "ambient-fake"+TOKEN = "fake-ambient-token-0123456789abcdef"++_PLUGIN = textwrap.dedent(+ f"""+ from providers import register_provider+ from providers.base import ProviderProfile++ register_provider(ProviderProfile(+ name="{SLUG}", aliases=("{SLUG}-alias",), display_name="Ambient Fake", auth_type="api_key",+ env_vars=("FAKE_AMBIENT_GH_TOKEN",), base_url="https://ambient-fake.invalid/v1",+ api_mode="chat_completions", registry_after="lmstudio", ambient_credentials=True))+ """+)+++def homes(tmp_path, monkeypatch):+ import providers+ from hermes_cli import auth_plugin_providers as app+ from hermes_cli.auth import PROVIDER_REGISTRY++ plugin_home, bare_home = tmp_path / "with_plugin", tmp_path / "bare"+ plugin = plugin_home / "plugins" / "model-providers" / SLUG+ plugin.mkdir(parents=True)+ (plugin / "__init__.py").write_text(_PLUGIN, encoding="utf-8")+ bare_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(bare_home))+ monkeypatch.setenv("FAKE_AMBIENT_GH_TOKEN", TOKEN)+ monkeypatch.setenv("GEMINI_API_KEY", "AIza" + "x" * 35)+ monkeypatch.setattr(providers, "_REGISTRY", dict(providers._REGISTRY))+ monkeypatch.setattr(providers, "_ALIASES", dict(providers._ALIASES))+ monkeypatch.setattr(providers, "_PROVIDER_LIST_CACHE", None)+ monkeypatch.setattr(providers, "_HOME_LAYERS", {})+ monkeypatch.setattr(app, "PLUGIN_MIRRORED_PROVIDERS", set(app.PLUGIN_MIRRORED_PROVIDERS))+ rows = list(dict.items(PROVIDER_REGISTRY))+ yield plugin_home, bare_home+ PROVIDER_REGISTRY.clear()+ PROVIDER_REGISTRY.update(rows)+ for mod in [m for m in sys.modules if m.startswith("_hermes_user_provider")]:+ del sys.modules[mod]+++def _bound(home: Path, fn):+ token = set_hermes_home_override(home)+ try:+ return fn()+ except Exception as exc: # the outcome under test may be a refusal+ return exc+ finally:+ reset_hermes_home_override(token)+++def _view(home: Path) -> dict:+ from hermes_cli.auth import PROVIDER_REGISTRY, resolve_api_key_provider_credentials, resolve_provider+ from hermes_cli.auth_plugin_providers import canonical_registry_rows+ from hermes_cli.runtime_provider import resolve_runtime_provider++ def runtime(requested):+ out = resolve_runtime_provider(requested=requested)+ return out["provider"], out.get("base_url"), out.get("api_key") == TOKEN++ import providers++ return { # a turn starts with a profile lookup; that is what loads the home's plugins+ "profile": _bound(home, lambda: getattr(providers.get_provider_profile(SLUG), "name", None)),+ "rows": _bound(home, lambda: SLUG in {pid for pid, _ in canonical_registry_rows()}),+ "lookup": _bound(home, lambda: (SLUG in PROVIDER_REGISTRY, PROVIDER_REGISTRY.get(f"{SLUG}-alias") is not None)),+ "explicit": _bound(home, lambda: resolve_provider(SLUG)),+ "auto": _bound(home, lambda: resolve_provider("auto")),+ "creds": _bound(home, lambda: resolve_api_key_provider_credentials(SLUG).get("api_key") == TOKEN),+ "runtime_explicit": _bound(home, lambda: runtime(SLUG)),+ "runtime_auto": _bound(home, lambda: runtime(None)),+ }+++def _assert_owner(view: dict) -> None:+ assert view["profile"] == SLUG+ assert view["rows"] is True+ assert view["lookup"] == (True, True)+ assert view["explicit"] == SLUG+ assert view["creds"] is True+ assert view["runtime_explicit"] == (SLUG, "https://ambient-fake.invalid/v1", True)+ # ambient credentials never auto-select, even where the plugin lives+ assert view["auto"] == "gemini"+ assert view["runtime_auto"][0] == "gemini"+++def _assert_absent(view: dict) -> None:+ from hermes_cli.auth import AuthError++ assert view["profile"] is None+ assert view["rows"] is False+ assert view["lookup"] == (False, False)+ assert isinstance(view["explicit"], AuthError)+ assert isinstance(view["creds"], AuthError)+ assert isinstance(view["runtime_explicit"], Exception)+ assert view["auto"] == "gemini"+ assert view["runtime_auto"][0] == "gemini" and view["runtime_auto"][2] is False+++def test_mirrored_row_is_absent_in_a_home_without_the_plugin_a_b_a(homes):+ plugin_home, bare_home = homes++ _assert_owner(_view(plugin_home))+ _assert_absent(_view(bare_home))+ _assert_owner(_view(plugin_home))+ _assert_absent(_view(bare_home))+++def test_setup_detection_ignores_another_homes_mirrored_row(homes, monkeypatch):+ from hermes_cli.setup_migration import _model_section_has_credentials++ import providers++ plugin_home, bare_home = homes+ monkeypatch.delenv("GEMINI_API_KEY")+ _bound(plugin_home, lambda: providers.get_provider_profile(SLUG))+ assert _bound(plugin_home, lambda: _model_section_has_credentials({"model": {"provider": SLUG}})) is True+ assert _bound(bare_home, lambda: _model_section_has_credentials({"model": {"provider": SLUG}})) is False+++def test_hidden_rows_survive_registry_reordering(homes):+ """A later mirror inserted mid-registry while another home is bound must not drop hidden rows."""+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.auth_plugin_providers import _insert_row++ import providers++ plugin_home, bare_home = homes+ _bound(plugin_home, lambda: providers.get_provider_profile(SLUG))+ assert _bound(plugin_home, lambda: SLUG in PROVIDER_REGISTRY) is True+ row = dict.__getitem__(PROVIDER_REGISTRY, "gemini")+ _bound(bare_home, lambda: _insert_row(PROVIDER_REGISTRY, row, "lmstudio"))+ assert _bound(plugin_home, lambda: SLUG in PROVIDER_REGISTRY) is True