Skip to content

The agent that grows with you

fix(config-remote): review round 2 — staged secret-source publication, generation-checked migration, plane value refusals

Ben Barclay99e5ea17968d
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index 760a8999534..339cfba5f84 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -701,7 +701,7 @@ def _revoke_secret_source_writes(home_path: Path, *, keep) -> None:
_SECRET_SOURCE_WRITES_BY_HOME.pop(home_key, None)
-def _refuse_protected_env_from_sources(report, backend=None, environ_before=None) -> None:
+def _refuse_protected_env_from_sources(report, backend=None, environ_before=None, env=None) -> None:
"""D32: the config backend's own credential (which plane, which agent, which token) must never
come from a secret source — a source that could change it could point config at another plane.
Exits (the backend is unusable), even when the pre-existing value won.
@@ -709,7 +709,14 @@ def _refuse_protected_env_from_sources(report, backend=None, environ_before=None
*backend* is the backend selected BEFORE the sources ran: judging by the backend selected after
them would let a source that writes ``HERMES_CONFIG_BACKEND=file`` switch remote mode off and
disarm this very check. The selector itself is never a source's to change, under any backend:
- a source's write to it is reverted (to its *environ_before* value) before anything else."""
+ a source's write to it is reverted in *env* (the mapping the sources wrote into; default
+ ``os.environ``) to its *environ_before* value before anything else.
+
+ Startup runs the sources against a private staging copy of the environment and calls this
+ BEFORE publishing it (:func:`_publish_staged_env`), so a refused value is never visible to a
+ concurrent request — the poller reads the plane URL and credential live from ``os.environ``."""
+ if env is None:
+ env = os.environ
from hermes_cli.config_backend import BACKEND_ENV, ConfigBackendUnavailable, get_config_backend
if backend is None:
@@ -724,9 +731,9 @@ def _refuse_protected_env_from_sources(report, backend=None, environ_before=None
if environ_before is not None: # undo the source's writes to protected names before deciding
for name in clash:
if name in environ_before:
- os.environ[name] = environ_before[name]
+ env[name] = environ_before[name]
else:
- os.environ.pop(name, None)
+ env.pop(name, None)
if not backend.protected_env_names():
# The file backend has no plane credential: only the selector clashed. Reverted, and dropped
# from the report so no provenance/snapshot re-applies it later; keep going.
@@ -745,6 +752,15 @@ def _refuse_protected_env_from_sources(report, backend=None, environ_before=None
"from a secret source; remove the mapping. Hermes does not start with it.")
+def _publish_staged_env(staged: dict, environ_before: dict) -> None:
+ """Copy into ``os.environ`` exactly the names the sources set in *staged* (value differs from
+ *environ_before*). Sources only ever set names, so nothing is removed; a name nobody's source
+ touched is left alone even if another thread changed it meanwhile."""
+ for name, value in staged.items():
+ if environ_before.get(name) != value:
+ os.environ[name] = value
+
+
def _apply_external_secret_sources(home_path: Path) -> None:
"""Pull secrets from every enabled external source into env — AFTER dotenv (sources need .env bootstrap
tokens), BEFORE Hermes reads credentials; failures never block startup. Precedence/conflicts/provenance
@@ -795,14 +811,19 @@ def _apply_external_secret_sources(home_path: Path) -> None:
backend_before = get_config_backend()
+ # The sources write into a private staging copy, published only after the D32 check: written
+ # straight into os.environ, a forbidden plane URL or credential would be live for any request
+ # (the config poller, another thread's write) until the check reverted it.
+ staged = dict(environ_before)
try:
- report = apply_all(cfg, home_path)
+ report = apply_all(cfg, home_path, environ=staged)
except Exception:
return
if not report.sources: # no source enabled: keep retrying cheaply so flipping one on takes effect
return
- _refuse_protected_env_from_sources(report, backend_before, environ_before)
+ _refuse_protected_env_from_sources(report, backend_before, environ_before, env=staged)
+ _publish_staged_env(staged, environ_before)
# A real fetch attempt happened (success OR error): mark the home so the 3-5 import-time calls per
# startup don't re-fetch / re-print (error retries are opt-in via reset_secret_source_cache()).
diff --git a/hermes_cli/web_routers/_common.py b/hermes_cli/web_routers/_common.py
index 46b2e19bc4b..2e977db2d54 100644
--- a/hermes_cli/web_routers/_common.py
+++ b/hermes_cli/web_routers/_common.py
@@ -88,14 +88,17 @@ def destructive_profile(profile: Optional[str], route: str) -> Optional[str]:
def config_refusal_http(exc: ConfigWriteError) -> Optional[HTTPException]:
"""The HTTP error for an EXPECTED config-backend refusal, or None for an unexpected failure.
- A lock (403), a value the backend cannot store (400) and a lost CAS race (409) are the
+ A lock (403), a value the backend cannot store (400, or 413 when too large; ours or the
+ plane's ``config_value_invalid``/``config_path_*``/``config_secret_literal``) and a lost CAS
+ race (409) are the
caller's to fix, and their messages are ours or the config plane's own refusal text (a path
and the level that locks it; never a value or a credential), so they pass through (design
§4.3: v1 shows the server's 403 message). Anything else stays opaque."""
if isinstance(exc, ConfigLockedError):
return HTTPException(status_code=403, detail=str(exc))
if isinstance(exc, ConfigValueError):
- return HTTPException(status_code=400, detail=str(exc))
+ status = 413 if exc.code in ("config_level_too_large", "config_body_too_large") else 400
+ return HTTPException(status_code=status, detail=str(exc))
if exc.code == "config_version_conflict":
return HTTPException(status_code=409, detail=str(exc))
return None
diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.py
index f8b6a4ba705..63b1817d9ae 100644
--- a/plugins/config_backends/remote/backend.py
+++ b/plugins/config_backends/remote/backend.py
@@ -87,6 +87,14 @@ class _ProfileState:
_UNKNOWN = object()
+# Plane refusals caused by the submitted value (contract §2.5, §11.1): surfaced to the caller as
+# ConfigValueError with the plane's code. config_request_invalid is deliberately absent: a request
+# the plane cannot parse is this client's bug, not the user's value, so it stays opaque.
+_VALUE_REFUSALS = frozenset({
+ (400, "config_secret_literal"), (400, "config_value_invalid"), (400, "config_path_invalid"),
+ (400, "config_path_reserved"), (413, "config_level_too_large"), (413, "config_body_too_large"),
+})
+
def _profile_writer(body: Dict[str, Any]) -> Any:
"""The profile level's stored ``writerConfigVersion`` (int or None), or ``_UNKNOWN``."""
@@ -247,20 +255,25 @@ class RemoteBackend:
if st.postprocessed or st.in_postprocess:
return
st.in_postprocess = True
- seen = st.installed
+ # The doc's schema version and its generation are captured together: a poll may install
+ # a newer doc at any point after this, and migrating that doc from THIS version would
+ # run steps its data never needed (and, D12, drop settings it holds on purpose).
+ seen = st.installed
+ current = int(st.doc.get("_config_version") or 0)
+ keys = set(st.doc)
try:
try:
from hermes_cli.config import _known_top_level_keys
from hermes_cli.config_migrations import SUPPORT_FLOOR_VERSION, run_migrations
except ImportError:
return # still importing; the next read retries
- for key in sorted(set(st.doc) - _known_top_level_keys() - {"_config_version"}):
+ for key in sorted(keys - _known_top_level_keys() - {"_config_version"}):
if key not in self._unknown_warned:
self._unknown_warned.add(key)
logger.warning("Remote Config: unknown config key %r is ignored by this Hermes version", key)
- current, latest = int(st.doc.get("_config_version") or 0), _latest_config_version()
+ latest = _latest_config_version()
if SUPPORT_FLOOR_VERSION <= current < latest:
- self._migrate_in_memory(st, current, run_migrations)
+ self._migrate_in_memory(st, seen, current, run_migrations)
elif current < SUPPORT_FLOOR_VERSION:
logger.warning("Remote Config: profile %r was written by config version %d, below the "
"migration floor %d; not migrated", st.profile, current, SUPPORT_FLOOR_VERSION)
@@ -268,12 +281,19 @@ class RemoteBackend:
finally:
st.in_postprocess = False
- def _migrate_in_memory(self, st: _ProfileState, current: int, run_migrations) -> None:
- """Migrate the installed doc in memory (D12). The migrated doc also becomes the base later
- writes diff against: a reader was handed the migrated doc, so a write that leaves the
- migration's changes in place must not send them (D12: never write the migration back)."""
+ def _migrate_in_memory(self, st: _ProfileState, started: int, current: int, run_migrations) -> None:
+ """Migrate doc generation *started* (whose schema version is *current*) in memory (D12).
+ The migrated doc also becomes the base later writes diff against: a reader was handed the
+ migrated doc, so a write that leaves the migration's changes in place must not send them
+ (D12: never write the migration back).
+
+ Generation-checked at start, at each step (:meth:`apply_in_memory`) and at commit: once a
+ poll or write has installed another doc, nothing of this migration lands on it."""
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
- started = st.migrating = st.installed
+ with st.lock:
+ if st.installed != started:
+ return # replaced before we began; the new doc gets its own pass
+ st.migrating = started
token = set_hermes_home_override(st.home)
try:
run_migrations(current, {"env_added": [], "config_added": [], "warnings": []}, True)
@@ -411,8 +431,17 @@ class RemoteBackend:
if resp.status == 403 and resp.error == "config_key_locked":
return ConfigLockedError(str(resp.body.get("path") or ""), str(resp.body.get("lockedBy") or "upper"),
f"Remote Config refused the write: {resp.message}")
- if resp.status == 400 and resp.error == "config_secret_literal":
- return ConfigValueError(f"Remote Config refused the write: {resp.message}", code=resp.error)
+ if (resp.status, resp.error) in _VALUE_REFUSALS:
+ # The submitted value is the problem (contract §2.5 table): the caller's to fix, so it
+ # keeps its code and the plane's refusal text, which names a path and a reason, never a
+ # value (config_secret_literal never echoes it).
+ detail = resp.message or resp.error
+ path, reason = resp.body.get("path"), resp.body.get("reason")
+ extras = [f"{k} {v}" for k, v in (("path", path), ("reason", reason))
+ if isinstance(v, str) and v and v not in detail]
+ if extras:
+ detail = f"{detail} ({', '.join(extras)})"
+ return ConfigValueError(f"Remote Config refused the write: {detail}", code=resp.error)
return ConfigWriteError(f"Remote Config refused the write ({resp.status} {resp.error}): {resp.message}",
code=resp.error)
diff --git a/tests/agent/test_env_loader_secret_sources.py b/tests/agent/test_env_loader_secret_sources.py
index 3bf605e5e8e..d84a18de57e 100644
--- a/tests/agent/test_env_loader_secret_sources.py
+++ b/tests/agent/test_env_loader_secret_sources.py
@@ -544,9 +544,13 @@ def test_external_secret_values_are_isolated_between_homes(tmp_path, monkeypatch
str(home_b.resolve()): "value-b",
}
- def _fake_apply_all(_cfg, home_path):
+ # Registered for teardown restore, then removed: the loader publishes the source's write itself.
+ monkeypatch.setenv("SHARED_API_KEY", "unset")
+ monkeypatch.delenv("SHARED_API_KEY")
+
+ def _fake_apply_all(_cfg, home_path, environ=None):
value = values[str(Path(home_path).resolve())]
- monkeypatch.setenv("SHARED_API_KEY", value)
+ environ["SHARED_API_KEY"] = value # startup applies sources into a staging copy
return ApplyReport(
# Real apply_all always appends a SourceReport per enabled
# source; the env_loader guard (#40597) early-returns on an
diff --git a/tests/plugins/config_backends/stub_plane.py b/tests/plugins/config_backends/stub_plane.py
index 34fd2b0e082..3ccbb2dc920 100644
--- a/tests/plugins/config_backends/stub_plane.py
+++ b/tests/plugins/config_backends/stub_plane.py
@@ -43,6 +43,17 @@ def deep_merge(base: Dict[str, Any], over: Dict[str, Any]) -> Dict[str, Any]:
return out
+MAX_VALUE_DEPTH = 32 # contract §11.1: nesting depth of values (objects + lists)
+
+
+def _depth(value: Any) -> int:
+ if isinstance(value, dict):
+ return 1 + max((_depth(v) for v in value.values()), default=0)
+ if isinstance(value, list):
+ return 1 + max((_depth(v) for v in value), default=0)
+ return 0
+
+
class StubPlane:
def __init__(self) -> None:
self.upper: Dict[str, Any] = {}
@@ -160,6 +171,11 @@ class StubPlane:
path = encode(refused[0])
return self._send(403, {"error": "config_key_locked", "path": path, "lockedBy": refused[1],
"message": f"{path} is locked by {refused[1]}"})
+ for p, v in sets.items():
+ if _depth(v) > MAX_VALUE_DEPTH: # contract §11.1
+ path = encode(p)
+ return self._send(400, {"error": "config_value_invalid", "path": path, "reason": "too_deep",
+ "message": f"{path}: value nesting exceeds {MAX_VALUE_DEPTH}"})
for p, v in sets.items():
if secret_literal_path(p, v) is not None:
return self._send(400, {"error": "config_secret_literal", "message": "secret literal"})
diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.py
index 45d210d5699..97d7a4d5f8d 100644
--- a/tests/plugins/config_backends/test_remote_backend.py
+++ b/tests/plugins/config_backends/test_remote_backend.py
@@ -616,9 +616,10 @@ def test_bulk_save_after_migration_sends_only_the_edit(plane):
save_config(doc)
- for p in plane.patches():
- assert "unset" not in p["body"]
- assert "compression" not in json.dumps(p["body"])
+ (p,) = plane.patches()
+ assert p["body"]["set"] == {"display": {"personality": "pirate"}}
+ assert "unset" not in p["body"]
+ assert "compression" not in json.dumps(p["body"])
def test_unrelated_write_keeps_an_old_profile_stamp_so_later_reads_still_migrate(plane):
@@ -710,6 +711,145 @@ def test_dashboard_unexpected_config_failure_stays_opaque(plane):
assert (status, detail) == (500, "Internal server error")
+# --- review round 2 regressions -----------------------------------------------------------
+
+def test_refused_source_plane_url_is_never_visible_to_a_concurrent_request(plane, monkeypatch):
+ """D32 credential boundary: a real command source supplies HERMES_CONFIG_REMOTE_URL pointing
+ at another plane. A poll scheduled right after the sources ran (before the refusal) must still
+ go to the configured plane: the forbidden URL is never published, so the bearer and instance id
+ never reach the other server."""
+ import os
+ import threading
+
+ from agent.secret_sources import registry
+ from hermes_cli import env_loader
+ monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())
+ with StubPlane() as other:
+ plane.upper = {"secrets": {"command": {
+ "enabled": True, "override_existing": True,
+ "command": f"printf 'HERMES_CONFIG_REMOTE_URL={other.url}\\n'"}}}
+ backend = get_config_backend()
+ st = backend._state(plane.home)
+ real_apply_all = registry.apply_all
+ seen = {}
+
+ def apply_then_poll(*args, **kwargs):
+ report = real_apply_all(*args, **kwargs)
+ seen["url_after_sources"] = os.environ.get("HERMES_CONFIG_REMOTE_URL")
+ poll = threading.Thread(target=backend.poll_one, args=(st,))
+ poll.start()
+ poll.join(10)
+ assert not poll.is_alive()
+ return report
+
+ monkeypatch.setattr(registry, "apply_all", apply_then_poll)
+ gets_before = len(_gets(plane))
+ with pytest.raises(ConfigBackendUnavailable, match="HERMES_CONFIG_REMOTE_URL"):
+ env_loader.load_hermes_dotenv(hermes_home=plane.home)
+
+ assert "url_after_sources" in seen, "precondition: the source ran"
+ assert other.requests == [] # nothing — least of all the bearer — reached the other plane
+ assert seen["url_after_sources"] == plane.url
+ assert len(_gets(plane)) > gets_before # the gap poll went to the configured plane
+ assert os.environ["HERMES_CONFIG_REMOTE_URL"] == plane.url
+
+
+def test_file_mode_publishes_permitted_source_values(monkeypatch, tmp_path):
+ """Staging must not lose ordinary secrets: permitted names are published after the check."""
+ import os
+
+ from hermes_cli import env_loader
+ monkeypatch.delenv("HERMES_CONFIG_BACKEND", raising=False)
+ monkeypatch.setenv("CC_STAGED_SECRET", "x")
+ monkeypatch.delenv("CC_STAGED_SECRET")
+ monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text(
+ "secrets:\n command:\n enabled: true\n command: \"printf 'CC_STAGED_SECRET=from-source\\\\n'\"\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ env_loader._apply_external_secret_sources(home)
+
+ assert os.environ.get("CC_STAGED_SECRET") == "from-source"
+
+
+def test_migration_of_a_replaced_doc_does_not_touch_the_replacement(plane, monkeypatch):
+ """A read starts migrating the stored-46 doc; before the migration begins, a poll installs the
+ current-version doc that keeps compression.threshold_tokens on purpose. The stale 46->47 step
+ must not run against it (the replacement stays intact, nothing is written back)."""
+ import threading
+
+ from hermes_cli.config import read_raw_config
+ latest = backend_mod._latest_config_version()
+ assert latest > 46
+ plane.profile("default").update(values={"compression": {"threshold_tokens": 256000}}, writer=46)
+ backend = get_config_backend()
+ st = backend._state(plane.home)
+ entered, resume = threading.Event(), threading.Event()
+ real_migrate = backend._migrate_in_memory
+
+ def paused(*args, **kwargs):
+ entered.set()
+ assert resume.wait(10)
+ return real_migrate(*args, **kwargs)
+
+ monkeypatch.setattr(backend, "_migrate_in_memory", paused)
+ failures = []
+
+ def read():
+ try:
+ read_raw_config()
+ except BaseException as exc: # noqa: BLE001 — surfaced below
+ failures.append(exc)
+
+ reader = threading.Thread(target=read)
+ reader.start()
+ assert entered.wait(10)
+ plane.profile("default").update(writer=latest, version=1)
+ assert backend.poll_one(st)
+ assert st.doc["compression"] == {"threshold_tokens": 256000}
+ resume.set()
+ reader.join(10)
+ assert not reader.is_alive() and not failures, failures
+
+ doc = read_raw_config()
+ assert doc["_config_version"] == latest
+ assert doc["compression"] == {"threshold_tokens": 256000}
+ assert plane.patches() == []
+
+
+def test_dashboard_save_refused_by_plane_value_check_is_a_400(plane):
+ """The plane's own value refusal (config_value_invalid too_deep, contract §11.1) reaches the
+ dashboard as a 400 with its reason, not an opaque 500."""
+ from hermes_cli.config import read_raw_config
+ read_raw_config()
+ value = "leaf"
+ for _ in range(33):
+ value = [value]
+
+ status, detail = _dashboard_put({"display": {"custom": value}})
+
+ assert len(plane.patches()) == 1 # client sent it; the server refused
+ assert status == 400
+ assert "too_deep" in detail and "display" in detail # the plane's reason and path pass through
+
+
[email protected]("status,error,expected", [
+ (400, "config_value_invalid", 400), (400, "config_path_invalid", 400), (400, "config_path_reserved", 400),
+ (400, "config_secret_literal", 400), (413, "config_level_too_large", 413), (413, "config_body_too_large", 413),
+ (400, "config_request_invalid", None), (500, "internal", None)])
+def test_plane_refusals_map_to_http(status, error, expected):
+ from hermes_cli.web_routers._common import config_refusal_http
+ from plugins.config_backends.remote import client
+ exc = backend_mod.RemoteBackend._write_error(
+ client.Response(status=status, body={"error": error, "message": "refused", "path": "a.b"},
+ etag=None, retry_after=None))
+ http = config_refusal_http(exc)
+ assert (http.status_code if http else None) == expected
+ assert exc.code == error
+
+
def test_stub_plane_deep_merge_follows_contract_6_2():
"""The test double resolves like the plane: null over a mapping is ignored (contract §6.2)."""
from .stub_plane import deep_merge