Skip to content

The agent that grows with you

fix(config-remote): review round 9c: dashboard model saves keep the credential mask and refuse late locks

Ben Barclay60c215db4c0b
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.py
index 3af5c5d0b98..e2904e6b45b 100644
--- a/hermes_cli/config_backend.py
+++ b/hermes_cli/config_backend.py
@@ -18,6 +18,8 @@ whatever user layer the backend returns.
"""
from __future__ import annotations
+import contextlib
+import contextvars
import os
import sys
import threading
@@ -441,6 +443,30 @@ def keeping_read_base(read):
mod._READ_BASE.set(held)
+# Dotted prefixes a document save in this context must write whole: a lock on a changed key under
+# one refuses the save (ConfigLockedError) instead of being silently omitted from it.
+_REFUSE_LOCKED_OMISSIONS: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar(
+ "config_refuse_locked_omissions", default=())
+
+
+def refusing_locked_omissions(*prefixes: str):
+ """Within the block, a document save that changes a key under one of *prefixes* (dotted, e.g.
+ ``"model"``) and finds it locked raises :class:`ConfigLockedError` and sends nothing, instead
+ of dropping the locked key and landing the rest (Remote Config bulk-save rule). Checked against
+ the locks the save itself sees, so a lock published after an earlier preflight still refuses;
+ a CAS retry re-checks every key it sends. No-op for the file backend (no locks)."""
+ token = _REFUSE_LOCKED_OMISSIONS.set(_REFUSE_LOCKED_OMISSIONS.get() + tuple(prefixes))
+ try:
+ yield
+ finally:
+ _REFUSE_LOCKED_OMISSIONS.reset(token)
+
+
+def refused_locked_omission_prefixes() -> tuple[str, ...]:
+ return _REFUSE_LOCKED_OMISSIONS.get()
+
+
def write_changes(config_path: PathLike, changes: Changes) -> None:
"""One :class:`Changes` write. Unlike :func:`write_config_keys`, a ``None`` in ``set`` stores
an explicit null (Remote Config: "no value", masking an inherited scalar); the file backend
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py
index 221778d306b..b31b862a21e 100644
--- a/hermes_cli/web_routers/config_env.py
+++ b/hermes_cli/web_routers/config_env.py
@@ -15,9 +15,10 @@ from hermes_cli.web_routers._common import (
REDACTED_CREDENTIAL_WRITE_DETAIL, http_failure, is_redacted_credential_preview,
redacted_credential_preview, scoped_to_thread,
)
+from hermes_cli.config_backend import refusing_locked_omissions
from hermes_cli.web_deps import LateState, late
from hermes_cli.web_server_config import (
- _apply_main_model_assignment, _denormalize_config_from_web, _normalize_config_for_web, _schema_with_dynamic_provider_options,
+ _apply_main_model_assignment, _denormalize_config_from_web, drop_model_key, _normalize_config_for_web, _schema_with_dynamic_provider_options,
_validated_main_model_selection,
)
from hermes_cli.web_server_profiles import (
@@ -720,7 +721,7 @@ def _write_custom_endpoint(cfg: dict[str, Any], body: CustomEndpointUpdate) -> t
cfg["model"] = _apply_main_model_assignment(cfg.get("model", {}), result)
if entry.get("key_env") and isinstance(cfg["model"], dict):
cfg["model"]["key_env"] = entry["key_env"]
- cfg["model"].pop("api_key", None)
+ drop_model_key(cfg["model"], "api_key")
return endpoint_id, entry
@@ -751,7 +752,8 @@ def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] =
created = _resolve_custom_endpoint_entry(
providers if isinstance(providers, dict) else {}, body.id or body.name)[1] is None
endpoint_id, _entry = _write_custom_endpoint(cfg, body)
- save_config(cfg)
+ with refusing_locked_omissions("model") if body.make_default else contextlib.nullcontext():
+ save_config(cfg)
response = _custom_endpoint_response(cfg)
from hermes_constants import get_hermes_home
home = get_hermes_home()
@@ -804,7 +806,7 @@ def activate_custom_endpoint(endpoint_id: str, profile: Optional[str] = None):
cfg.get("model", {}), _validated_main_model_selection(cfg, provider_key, model, base_url))
if entry.get("key_env"):
model_cfg["key_env"] = entry["key_env"]
- model_cfg.pop("api_key", None)
+ drop_model_key(model_cfg, "api_key")
elif entry.get("api_key"):
# `cfg` is env-expanded, so a raw `${VAR}` api_key would land as
# plaintext; copy the raw template when that's what's on disk.
@@ -817,7 +819,8 @@ def activate_custom_endpoint(endpoint_id: str, profile: Optional[str] = None):
else:
model_cfg["api_key"] = entry["api_key"]
cfg["model"] = model_cfg
- save_config(cfg)
+ with refusing_locked_omissions("model"):
+ save_config(cfg)
return {"ok": True, "provider": provider_key, "model": model}
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index 8c60f23c4c5..740cc754373 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -139,13 +139,15 @@ def _write_profile_model(profile_dir: Path, provider: str, model: str, validate_
``base_url`` is the endpoint a bare ``custom``/``local`` pick binds to (a fresh profile's config
names none); other providers ignore it."""
from hermes_cli.config import load_config, save_config
+ from hermes_cli.config_backend import refusing_locked_omissions
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, base_url)
with _config_profile_scope(_scope_profile_name(profile_dir)), _CONFIG_MUTATION_LOCK: # RMW span
cfg = load_config()
cfg["model"] = _apply_main_model_assignment(cfg.get("model", {}), result)
- save_config(cfg)
+ with refusing_locked_omissions("model"):
+ save_config(cfg)
def _disable_unselected_skills(profile_dir: Path, keep: list[str]) -> int:
diff --git a/hermes_cli/web_server_config.py b/hermes_cli/web_server_config.py
index 139cea4b24b..bcc48d7f8fe 100644
--- a/hermes_cli/web_server_config.py
+++ b/hermes_cli/web_server_config.py
@@ -14,6 +14,7 @@ from hermes_cli.config import (
find_provider_entry,
read_raw_config,
)
+from hermes_cli.config_backend import refusing_locked_omissions
from hermes_cli.web_server_memory import _normalize_memory_provider_name
from tools.transcription_common import STT_MODEL_CATALOG
from tools.wake_word import _PROVIDER_PREFERENCE
@@ -526,11 +527,26 @@ def _apply_main_model_assignment(model_cfg: Any, result: "ModelSwitchResult", ap
model_cfg = apply_model_selection(model_cfg, result, mask_cleared=not supports_file_tooling())
if api_key.strip():
model_cfg["api_key"] = api_key.strip()
- model_cfg.pop("api", None)
+ drop_model_key(model_cfg, "api")
remote_model_selection_guard(before, model_cfg)
return model_cfg
+def drop_model_key(model_cfg: dict, key: str) -> None:
+ """Remove *key* from a ``model`` block an assignment is building. Under Remote Config the block
+ is the EFFECTIVE one, so a key it holds may be inherited from an upper level that a profile
+ removal cannot reach (contract §5.4); store null ("no value") instead, the same mask
+ :func:`hermes_cli.model_switch.apply_model_selection` applies. A key the block lacks stays
+ absent. File backend: a plain removal."""
+ from hermes_cli.config_backend import supports_file_tooling
+ if key not in model_cfg:
+ return
+ if supports_file_tooling():
+ model_cfg.pop(key, None)
+ else:
+ model_cfg[key] = None
+
+
def _normalize_config_for_web(config: dict[str, Any]) -> dict[str, Any]:
"""Flatten a dict-form ``model`` to its string form (the schema is built from
DEFAULT_CONFIG where ``model`` is a string) and surface ``model_context_length``
@@ -644,8 +660,9 @@ def _resolve_assignment_credentials(model_cfg: dict, provider: str, provider_ent
key_env = str(raw_entry.get("key_env") or "").strip()
if key_env:
model_cfg["key_env"] = key_env
- # #88990: carry the credential POINTER, never a resolved secret.
- model_cfg.pop("api_key", None)
+ # #88990: carry the credential POINTER, never a resolved secret. Masked, not dropped, under
+ # Remote Config: an inherited inline key outranks key_env at runtime.
+ drop_model_key(model_cfg, "api_key")
elif isinstance(provider_entry, dict) and provider_entry.get("api_key"):
raw_key = str(raw_entry.get("api_key") or "").strip()
model_cfg["api_key"] = raw_key if raw_key.startswith("${") and raw_key.endswith("}") else provider_entry["api_key"]
@@ -777,7 +794,10 @@ def _apply_main_assignment_sync(cfg: dict, provider: str, model: str, base_url:
new_provider = provider.strip().lower()
gateway_tools = _apply_nous_gateway_defaults(cfg) if new_provider == "nous" else []
- save_config(cfg)
+ # One route: a model.* key locked by the time the save runs (even after the preflight guard
+ # above, or on its CAS retry) refuses the whole save instead of being omitted from it.
+ with refusing_locked_omissions("model"):
+ save_config(cfg)
if new_provider in {"custom", "local"} and base_url and not endpoint_already_known:
_register_custom_endpoint(base_url, api_key, model)
# The serve process's boot record may still say "nothing configured"; the chat gates on it.
diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.py
index fd7e8ffc029..d4524f62d80 100644
--- a/plugins/config_backends/remote/backend.py
+++ b/plugins/config_backends/remote/backend.py
@@ -21,13 +21,14 @@ from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from hermes_cli.config_backend import (
- Changes, ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, ConfigWriteError, UserLayer)
+ Changes, ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, ConfigWriteError, UserLayer,
+ refused_locked_omission_prefixes)
from . import client
from .credentials import PLANE_CREDENTIAL_ENV_NAMES, PlaneCredentialError
from .diff import _get_path, apply_intent, diff, encode_changes, intent_diff, json_equal, strip_locked, write_check
from .paths import Path as KeyPath
-from .paths import PathError, decode, encode, from_dotted
+from .paths import PathError, covers, decode, encode, from_dotted
from .values import secret_literal_path, to_wire
logger = logging.getLogger(__name__)
@@ -565,6 +566,13 @@ class RemoteBackend:
if changes.document is not None:
base, new, dropped = strip_locked(base, new, st.locks)
+ for prefix in refused_locked_omission_prefixes():
+ whole = from_dotted(prefix)
+ for path in dropped:
+ if covers(whole, path) or covers(path, whole):
+ level = next((lv for lk, lv in st.locks if lk == path), "upper")
+ raise ConfigLockedError(encode(path), level,
+ f"{encode(path)} is locked by the {level} level of Remote Config")
if dropped:
print(f"Note: {len(dropped)} setting(s) locked by Remote Config were not saved: "
f"{', '.join(sorted(encode(p) for p in dropped))}", file=sys.stderr)
diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.py
index e6b18371a02..829c8298e68 100644
--- a/tests/plugins/config_backends/test_remote_backend.py
+++ b/tests/plugins/config_backends/test_remote_backend.py
@@ -1766,3 +1766,50 @@ def test_dashboard_model_switch_refuses_whole_assignment_on_a_locked_route_key(p
_dashboard_switch(monkeypatch, url)
assert exc.value.status_code in (403, 409), exc.value
assert plane.patches() == []
+
+
+def test_dashboard_model_switch_keeps_mask_when_target_provider_carries_key_env(plane, monkeypatch):
+ """The target provider's key_env pointer replaces the inline key. Under Remote Config the
+ inherited ``model.api_key`` must stay masked (null) after that credential step, or the old
+ endpoint's key (which outranks key_env at runtime) reaches the new endpoint."""
+ from hermes_cli.config import read_user_config_raw
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ url = "https://new.example/v1"
+ monkeypatch.setenv("OLD_KEY", "old-synthetic-key")
+ monkeypatch.setenv("NEW_KEY", "new-synthetic-key")
+ plane.upper = {"model": dict(_OLD_ROUTE), "providers": {"custom": {"base_url": url, "key_env": "NEW_KEY"}}}
+ assert _dashboard_switch(monkeypatch, url)["ok"] is True
+ body = plane.patches()[-1]["body"]
+ assert body["set"].get("model.api_key", "absent") is None and "model.api_key" not in body.get("unset", []), body
+ model = read_user_config_raw()["model"]
+ assert model["base_url"] == url and model.get("api_key") is None and model["key_env"] == "NEW_KEY", model
+ route = resolve_runtime_provider(requested="custom")
+ assert route.get("base_url") == url and route.get("api_key") == "new-synthetic-key", route
+
+
[email protected]("conflict_first", [False, True], ids=["poll", "cas-retry"])
+def test_dashboard_model_switch_refuses_when_a_lock_lands_after_the_guard(plane, monkeypatch, conflict_first):
+ """A lock published after the preflight guard (seen by a poll right before the save, or by the
+ re-read after a 409) refuses the whole assignment: no half route is saved and acknowledged."""
+ from fastapi import HTTPException
+ from hermes_cli import config as cfgmod
+ url = "https://new.example/v1"
+ plane.upper = {"model": dict(_OLD_ROUTE), "providers": {"known-new": {"base_url": url}}}
+ backend = get_config_backend()
+ orig = cfgmod.save_config
+
+ def lock_then_save(cfg, **kw):
+ plane.upper_locks = [{"path": "model.api_key", "level": "tenant"}]
+ if conflict_first:
+ plane.profile("default")["version"] += 1 # the save's PATCH meets a 409 and re-reads
+ else:
+ assert backend.poll_one(backend._state(plane.home))
+ return orig(cfg, **kw)
+
+ monkeypatch.setattr(cfgmod, "save_config", lock_then_save)
+ with pytest.raises(HTTPException) as exc:
+ _dashboard_switch(monkeypatch, url)
+ assert exc.value.status_code == 403, exc.value
+ if not conflict_first:
+ assert plane.patches() == []
+ assert plane.profile("default")["values"].get("model") in (None, {}), plane.profile("default")