The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): bind the profile secret scope around PUT /api/profiles/{name}/model
liuhao1024dad20814e44b
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex 1adc8ce25a8..145f07795fd 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -44,7 +44,7 @@ from hermes_cli.web_models import (ProfileCreate, ProfileActiveUpdate, ProfileExport, ProfileImport, ProfileRename,ProfileSoulUpdate, ProfileDescriptionUpdate, ProfileModelUpdate, ProfileDescribeAuto,SessionPrScanBody)-from hermes_cli.web_server_profiles import _hermes_home_scope+from hermes_cli.web_server_profiles import _config_profile_scope, _hermes_home_scope# Same logger the handlers used before extraction (identical logger object)._log = logging.getLogger("hermes_cli.web_server")@@ -101,6 +101,13 @@ def _profile_setup_command(name: str) -> str:return "hermes setup" if name == "default" else f"{name} setup"+def _scope_profile_name(path: Path) -> Optional[str]:+ """Map a profile directory onto the query name ``_config_profile_scope`` expects: None for+ the process home (current-profile semantics: launch secret scope, no home override), the+ directory name for ``profiles/<name>``."""+ return None if path.resolve() == get_process_hermes_home().resolve() else path.name++def _write_profile_model(profile_dir: Path, provider: str, model: str, validate_in: Optional[Path] = None) -> None:"""Write the main model assignment into ``profile_dir``'s config.yaml (HERMES_HOME-scoped)through the same validated /model shape as ``POST /api/model/set``.@@ -108,12 +115,17 @@ def _write_profile_model(profile_dir: Path, provider: str, model: str, validate_``validate_in`` is the home whose ``providers:``/``.env``/catalog vouch for the pick (default:``profile_dir`` itself). Profile-create passes the dashboard's own home: the picker that offeredthe model read THAT catalog, and a just-created profile has no credentials yet, so validating- in the empty profile rejected every non-env provider (anthropic, ollama, custom)."""+ in the empty profile rejected every non-env provider (anthropic, ollama, custom).++ Both spans enter ``_config_profile_scope`` (home + secret scope), matching ``/api/model/set``:+ once the dashboard has served a secondary profile, ``switch_model``'s ``key_env`` probe goes+ through ``get_secret``, which fails closed without a scope and reports the provider as+ unconnected (UnscopedSecretError class, #114676)."""from hermes_cli.config import load_config, save_config- with _hermes_home_scope(validate_in or profile_dir):+ with _config_profile_scope(_scope_profile_name(validate_in or profile_dir)):provider, model = _normalize_main_model_assignment(provider, model)result = _validated_main_model_selection(load_config(), provider, model)- with _hermes_home_scope(profile_dir), _CONFIG_MUTATION_LOCK: # RMW span+ with _config_profile_scope(_scope_profile_name(profile_dir)), _CONFIG_MUTATION_LOCK: # RMW spancfg = load_config()cfg["model"] = _apply_main_model_assignment(cfg.get("model", {}), result)save_config(cfg)diff --git a/tests/hermes_cli/test_web_profiles_model_scope.py b/tests/hermes_cli/test_web_profiles_model_scope.pynew file mode 100644index 00000000000..174019d2ff1--- /dev/null+++ b/tests/hermes_cli/test_web_profiles_model_scope.py@@ -0,0 +1,143 @@+"""``PUT /api/profiles/{name}/model`` must validate under the target profile's secret scope.++``_write_profile_model`` used to enter only the HERMES_HOME override. Once the dashboard+has served a secondary profile (fail-closed multiplexing on), ``switch_model``'s+``key_env`` probe reads through ``get_secret``, which fails closed without an installed+scope — the pick was rejected with "<provider> is not connected" even though the named+profile's ``.env`` held the key (#114676). ``POST /api/model/set`` already binds+``_config_profile_scope``; the profiles router now composes the same scope (home ++secrets) around both the validate and save spans.+"""++import pytest++pytest.importorskip("fastapi")+from fastapi.testclient import TestClient # noqa: E402++from agent import secret_scope # noqa: E402++ACME_YAML = (+ "providers:\n"+ " acme:\n"+ " base_url: https://api.acme.test/v1\n"+ " key_env: ACME_RELAY_KEY\n"+)+++def homes(tmp_path, monkeypatch):+ """A throwaway HERMES_HOME whose named profile carries its own ``.env`` credential.++ The process env holds a DIFFERENT value for the same variable: a scoped read must+ resolve the profile's key, never the dashboard home's (fail-closed isolation).+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("ACME_RELAY_KEY", "dashboard-home-key")+ from hermes_cli import profiles as profiles_mod+ from hermes_cli.config import invalidate_env_cache++ demo = profiles_mod.get_profile_dir("demo")+ demo.mkdir(parents=True, exist_ok=True)+ (demo / "config.yaml").write_text(ACME_YAML, encoding="utf-8")+ (demo / ".env").write_text("ACME_RELAY_KEY=profile-key\n", encoding="utf-8")+ (tmp_path / "config.yaml").write_text(ACME_YAML, encoding="utf-8")+ invalidate_env_cache()+ return tmp_path, demo+++def probe(monkeypatch):+ """Capture the credential ``switch_model`` resolved, without network round-trips."""+ captured = {}++ def _fake_runtime(+ requested,+ explicit_api_key=None,+ explicit_base_url=None,+ target_model=None,+ **kw,+ ):+ captured.setdefault("api_key", explicit_api_key)+ return {+ "api_key": explicit_api_key or "",+ "base_url": explicit_base_url,+ "api_mode": "",+ }++ def _fake_validate(+ model, provider, api_key=None, base_url=None, api_mode=None, headers=None, **kw+ ):+ return {"accepted": True, "persist": True, "recognized": True, "message": ""}++ import hermes_cli.model_switch as ms+ import hermes_cli.models_validate as mv++ monkeypatch.setattr(+ "hermes_cli.runtime_provider.resolve_runtime_provider", _fake_runtime+ )+ monkeypatch.setattr(ms, "resolve_alias", lambda *a, **k: None)+ monkeypatch.setattr(mv, "validate_requested_model", _fake_validate)+ return captured+++def client(homes):+ from hermes_cli import web_server++ with TestClient(web_server.app, raise_server_exceptions=False) as c:+ c.headers["Authorization"] = f"Bearer {web_server._SESSION_TOKEN}"+ yield c+++def test_model_pick_resolves_key_env_from_profile_scope(client, homes, probe):+ """Multiplexed dashboard: the named profile's ``.env`` authenticates the pick."""+ secret_scope.set_multiplex_active(True)+ try:+ resp = client.put(+ "/api/profiles/demo/model", json={"provider": "acme", "model": "acme/mini"}+ )+ finally:+ secret_scope.set_multiplex_active(False)++ assert resp.status_code == 200, resp.text+ # The profile's key, not the dashboard home's value from the process env.+ assert probe["api_key"] == "profile-key"+++def test_model_pick_persists_into_profile_config(client, homes, probe):+ """The save span still lands in the named profile's config.yaml."""+ _, demo = homes+ secret_scope.set_multiplex_active(True)+ try:+ resp = client.put(+ "/api/profiles/demo/model", json={"provider": "acme", "model": "acme/mini"}+ )+ finally:+ secret_scope.set_multiplex_active(False)++ assert resp.status_code == 200, resp.text+ from hermes_cli.config import load_config+ from hermes_cli.web_server_profiles import _hermes_home_scope++ with _hermes_home_scope(demo):+ model_cfg = load_config().get("model") or {}+ assert model_cfg.get("default") == "acme/mini"+ assert model_cfg.get("provider") == "acme"+++def test_model_pick_for_process_home_uses_launch_scope(client, homes, probe):+ """The dashboard's own profile maps to None (current-profile semantics) and still+ validates through the launch scope once multiplexing is active."""+ secret_scope.set_multiplex_active(True)+ try:+ resp = client.put(+ "/api/profiles/default/model",+ json={"provider": "acme", "model": "acme/mini"},+ )+ finally:+ secret_scope.set_multiplex_active(False)++ assert resp.status_code == 200, resp.text+ # Launch scope: live process env while single-profile... frozen at activation once+ # multiplexed — the dashboard home's value, resolved through get_secret, not a raise.+ assert probe["api_key"] == "dashboard-home-key"