Skip to content

The agent that grows with you

fix(docker): stage2 routing sync removes its own lines when the platform unsets the variable

kshitijk4poor6cd2502629cf
diff --git a/docker/stage2-hook.sh b/docker/stage2-hook.sh
index 16707c5741e..61d5d12b57a 100755
--- a/docker/stage2-hook.sh
+++ b/docker/stage2-hook.sh
@@ -515,72 +515,75 @@ elif ! grep -q '^API_SERVER_KEY=..*' "$HERMES_HOME/.env" 2>/dev/null; then
fi
# --- Sync deploy-injected Nous routing overrides into every profile .env ---
-# Hosted deploys point an instance at a non-production Portal / inference
-# host with HERMES_PORTAL_BASE_URL (or its NOUS_PORTAL_BASE_URL alias) and
-# NOUS_INFERENCE_BASE_URL in the container environment, and run the gateway
-# with GATEWAY_MULTIPLEX_PROFILES.
-# Under multiplex, hermes_cli.auth_nous resolves both through the profile
-# secret scope (agent.secret_scope.get_secret, #108319 / #111809), which is
-# built from <profile>/.env and never falls back to os.environ. A value that
-# lives only in the process env is therefore invisible on every routed turn:
-# the Portal allowlist then heals the URL to production, the staging refresh
-# token is POSTed to portal.nousresearch.com, the Portal answers
-# invalid_grant, and the login is quarantined ("No access token found for
-# Nous Portal login") within seconds of every boot. The two commits that
-# scoped these reads assign the deploy this duty: "Deployments that set
-# HERMES_PORTAL_BASE_URL only in the process env must carry it in each served
-# profile's .env". The container value wins over a stale line (the platform
-# is the authority on where this instance routes); operators who never set
-# the variable are untouched. Idempotent: an already-correct line is left
-# alone so the volume is not rewritten every boot. Known gap: a profile
-# created while the container runs gets a placeholder .env and is not
-# re-synced until the next boot; the durable home for these stamps is the
-# managed scope (/etc/hermes/.env), once its profile-scope composition is
-# restored (reverted by #111600).
-sync_routing_override() {
- _name="$1"
- _value="$2"
- _file="$3"
- if refuse_symlinked_path "sync $_name" "$_file"; then
+# Under multiplex, hermes_cli.auth_nous reads HERMES_PORTAL_BASE_URL (or its
+# NOUS_PORTAL_BASE_URL alias) and NOUS_INFERENCE_BASE_URL through the profile
+# secret scope (agent.secret_scope.get_secret, #108319 / #111809), built from
+# <profile>/.env with no os.environ fallback — a value that lives only in the
+# container env is invisible on every routed turn, the Portal URL heals to
+# production and a non-production login is quarantined. The deploy therefore
+# carries the value into $HERMES_HOME/.env and every profiles/*/.env: the
+# container wins over a stale line, an already-correct line is left alone, and
+# lines written here carry a marker so a boot WITHOUT the variable removes them
+# again (a hand-set line is never touched). Known gap: a profile created while the container
+# runs is synced on the next boot. Interim until the managed scope
+# (/etc/hermes/.env) composition reverted by #111600 is restored.
+_ROUTING_MARK='# stage2-managed'
+# rewrite_env_var FILE NAME DROP_PATTERN [LINE]: drop the lines matching DROP_PATTERN (a BRE),
+# append LINE when given. Rewritten through the existing inode (owner and mode kept — sed -i would
+# re-create the file). `grep -v` exits 1 when nothing remains (fine) and 2 when the file could not
+# be read (then a rewrite would wipe every other secret — refuse). A read-only volume degrades to a
+# warning, never a boot abort.
+rewrite_env_var() {
+ _rc=0
+ _rest=$(grep -v -- "$3" "$1" 2>/dev/null) || _rc=$?
+ if [ "$_rc" -gt 1 ]; then
+ echo "[stage2] Warning: could not read $1 — leaving $2 untouched"
+ return 1
+ fi
+ if [ $# -ge 4 ]; then
+ _rest="${_rest:+$_rest
+}$4"
+ fi
+ if printf '%s' "${_rest:+$_rest
+}" 2>/dev/null > "$1"; then
return 0
fi
- if grep -qxF -- "$_name=$_value" "$_file" 2>/dev/null; then
+ echo "[stage2] Warning: could not write $2 to $1 (read-only volume?) — routed turns will fall back to the production Portal"
+ return 1
+}
+sync_routing_overrides() {
+ _file="$1"
+ if refuse_symlinked_path "sync" "$_file"; then
return 0
fi
- if [ ! -f "$_file" ]; then
- # Owner-only from the first instant, hermes-owned (same shape as the
- # API_SERVER_KEY bootstrap above).
- if ! (umask 077 && as_hermes touch "$_file") 2>/dev/null; then
- echo "[stage2] Warning: could not create $_file — $_name will not reach this profile's secret scope"
+ for _name in HERMES_PORTAL_BASE_URL NOUS_PORTAL_BASE_URL NOUS_INFERENCE_BASE_URL; do
+ eval "_value=\${$_name:-}"
+ _managed="^$_name=.* $_ROUTING_MARK\$"
+ if [ -z "$_value" ]; then
+ if grep -q -- "$_managed" "$_file" 2>/dev/null && rewrite_env_var "$_file" "$_name" "$_managed"; then
+ echo "[stage2] Removed $_name from $_file (no longer set in the container environment)"
+ fi
+ continue
+ fi
+ _line="$_name=$_value $_ROUTING_MARK"
+ if grep -qxF -- "$_line" "$_file" 2>/dev/null; then
+ continue
+ fi
+ if [ ! -f "$_file" ] && ! (umask 077 && as_hermes touch "$_file") 2>/dev/null; then
+ echo "[stage2] Warning: could not create $_file — the Nous routing overrides will not reach this profile's secret scope"
return 0
fi
- fi
- # Rewrite in place (redirect keeps inode, owner and mode) so a stale value
- # is replaced, not shadowed by a second assignment. `grep -v` exits 1 when
- # nothing remains (new or single-line file) — that is not an error here.
- # Guarded: a read-only volume degrades to a warning, never a boot abort
- # under `set -e`.
- if _rewritten=$( { grep -v -- "^$_name=" "$_file" 2>/dev/null || true; } ; printf '%s=%s\n' "$_name" "$_value") \
- && printf '%s\n' "$_rewritten" > "$_file" 2>/dev/null; then
- echo "[stage2] Synced $_name from the container environment into $_file"
- else
- echo "[stage2] Warning: could not write $_name to $_file (read-only volume?) — routed turns will fall back to the production Portal"
- fi
- unset _rewritten
-}
-
-# NOUS_PORTAL_BASE_URL is the alias _nous_portal_env_override() accepts beside
-# HERMES_PORTAL_BASE_URL; a deploy may set either.
-for _routing_name in HERMES_PORTAL_BASE_URL NOUS_PORTAL_BASE_URL NOUS_INFERENCE_BASE_URL; do
- eval "_routing_value=\${$_routing_name:-}"
- [ -n "$_routing_value" ] || continue
- sync_routing_override "$_routing_name" "$_routing_value" "$HERMES_HOME/.env"
- for _profile_dir in "$HERMES_HOME"/profiles/*/; do
- [ -d "$_profile_dir" ] || continue
- sync_routing_override "$_routing_name" "$_routing_value" "${_profile_dir}.env"
+ if rewrite_env_var "$_file" "$_name" "^$_name=" "$_line"; then
+ echo "[stage2] Synced $_name from the container environment into $_file"
+ fi
done
+}
+sync_routing_overrides "$HERMES_HOME/.env"
+for _profile_dir in "$HERMES_HOME"/profiles/*/; do
+ [ -d "$_profile_dir" ] || continue
+ sync_routing_overrides "${_profile_dir}.env"
done
-unset _routing_name _routing_value _profile_dir
+unset _profile_dir _file _name _value _managed _line _rest _rc
# .env holds API keys and secrets — restrict to owner-only access. Applied
# unconditionally (not only on first-seed) so a host-mounted .env that was
diff --git a/tests/tools/test_stage2_hook_nous_routing_env.py b/tests/tools/test_stage2_hook_nous_routing_env.py
index e6541c3256c..cb55b6d2965 100644
--- a/tests/tools/test_stage2_hook_nous_routing_env.py
+++ b/tests/tools/test_stage2_hook_nous_routing_env.py
@@ -1,11 +1,10 @@
"""Regression tests for the stage2 Nous routing-override sync.
-Hosted deploys carry ``HERMES_PORTAL_BASE_URL`` / ``NOUS_INFERENCE_BASE_URL`` only in the
-container environment. Under ``GATEWAY_MULTIPLEX_PROFILES`` both are resolved through the
-profile secret scope (#108319 / #111809), which is built from ``<profile>/.env`` and never
-falls back to ``os.environ`` — so the staging Portal URL was dropped, the refresh token went
-to the production Portal, and the login was quarantined on every boot. stage2 must carry the
-container value into every served profile's ``.env``.
+Hosted deploys carry ``HERMES_PORTAL_BASE_URL`` / ``NOUS_INFERENCE_BASE_URL`` only in the container
+environment. Under ``GATEWAY_MULTIPLEX_PROFILES`` both resolve through the profile secret scope
+(#108319 / #111809), built from ``<profile>/.env`` with no ``os.environ`` fallback, so stage2 must
+carry the container value into every served profile's ``.env`` — and take it out again when the
+platform stops setting it.
"""
from __future__ import annotations
@@ -16,11 +15,14 @@ from pathlib import Path
import pytest
+from agent.secret_scope import load_env_file
+
REPO_ROOT = Path(__file__).resolve().parents[2]
STAGE2_HOOK = REPO_ROOT / "docker" / "stage2-hook.sh"
PORTAL = "https://portal.staging-nousresearch.com"
INFERENCE = "https://stg-inference-api.nousresearch.com/v1"
+NAMES = ("HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL", "NOUS_INFERENCE_BASE_URL")
@pytest.fixture(scope="module")
@@ -45,9 +47,8 @@ def _path_guard_functions(text: str) -> str:
def _run_sync(stage2_text: str, home: Path, env: dict[str, str | None]) -> subprocess.CompletedProcess[str]:
if shutil.which("sh") is None:
pytest.skip("sh not available")
- env_setup = "".join(
- f"unset {k}\n" if v is None else f"{k}='{v}'\n" for k, v in env.items()
- )
+ env = {name: env.get(name) for name in NAMES}
+ env_setup = "".join(f"unset {k}\n" if v is None else f"{k}='{v}'\n" for k, v in env.items())
script = (
"set -eu\n" # production runs the hook under set -eu
f"{env_setup}"
@@ -59,82 +60,81 @@ def _run_sync(stage2_text: str, home: Path, env: dict[str, str | None]) -> subpr
return subprocess.run(["sh", "-c", script], capture_output=True, text=True, timeout=30)
-def _lines(path: Path, name: str) -> list[str]:
+def _assignments(path: Path, name: str) -> list[str]:
return [ln for ln in path.read_text().splitlines() if ln.startswith(f"{name}=")]
-def test_container_value_reaches_home_and_every_profile_env(stage2_text: str, tmp_path: Path) -> None:
- """Both overrides land in $HERMES_HOME/.env and each profiles/*/.env (created when missing)."""
+def test_container_values_reach_home_and_every_profile_env(stage2_text: str, tmp_path: Path) -> None:
+ """All three overrides land in $HERMES_HOME/.env and each profiles/*/.env (created 0600 when
+ missing), unrelated secrets survive, and the runtime tokenizer reads the marked line back."""
home = tmp_path / "home"
(home / "profiles" / "work").mkdir(parents=True)
(home / "profiles" / "ops").mkdir()
(home / ".env").write_text("API_SERVER_KEY=abc\n")
(home / "profiles" / "ops" / ".env").write_text("SLACK_BOT_TOKEN=xoxb-x\n")
- result = _run_sync(
- stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL, "NOUS_PORTAL_BASE_URL": None, "NOUS_INFERENCE_BASE_URL": INFERENCE}
- )
+ result = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL, "NOUS_PORTAL_BASE_URL": PORTAL,
+ "NOUS_INFERENCE_BASE_URL": INFERENCE})
assert result.returncode == 0, result.stderr
for env_file in (home / ".env", home / "profiles" / "work" / ".env", home / "profiles" / "ops" / ".env"):
- assert _lines(env_file, "HERMES_PORTAL_BASE_URL") == [f"HERMES_PORTAL_BASE_URL={PORTAL}"], env_file
- assert _lines(env_file, "NOUS_INFERENCE_BASE_URL") == [f"NOUS_INFERENCE_BASE_URL={INFERENCE}"], env_file
- # Existing unrelated secrets survive the rewrite.
- assert "API_SERVER_KEY=abc" in (home / ".env").read_text()
- assert "SLACK_BOT_TOKEN=xoxb-x" in (home / "profiles" / "ops" / ".env").read_text()
- created = home / "profiles" / "work" / ".env"
- assert (created.stat().st_mode & 0o777) == 0o600
-
-
-def test_stale_value_replaced_and_correct_value_left_alone(stage2_text: str, tmp_path: Path) -> None:
- """The container value wins over a stale line (one assignment, not two); a matching line is not rewritten."""
+ parsed = load_env_file(env_file)
+ assert parsed["HERMES_PORTAL_BASE_URL"] == parsed["NOUS_PORTAL_BASE_URL"] == PORTAL, env_file
+ assert parsed["NOUS_INFERENCE_BASE_URL"] == INFERENCE, env_file
+ assert len(_assignments(env_file, "HERMES_PORTAL_BASE_URL")) == 1, env_file
+ assert load_env_file(home / ".env")["API_SERVER_KEY"] == "abc"
+ assert load_env_file(home / "profiles" / "ops" / ".env")["SLACK_BOT_TOKEN"] == "xoxb-x"
+ assert ((home / "profiles" / "work" / ".env").stat().st_mode & 0o777) == 0o600
+
+
+def test_container_wins_over_stale_line_then_idempotent_then_removed_when_unset(stage2_text: str, tmp_path: Path) -> None:
+ """Boot 1: a stale line is replaced (one assignment). Boot 2 (same value): the volume is not rewritten.
+ Boot 3 (variable gone): the stage2-written line is removed while hand-set lines stay. A read-only file
+ degrades to a warning; a symlinked .env is never written through."""
home = tmp_path / "home"
home.mkdir()
env_file = home / ".env"
- env_file.write_text("HERMES_PORTAL_BASE_URL=https://portal.nousresearch.com\nOTHER=1\n")
+ env_file.write_text("HERMES_PORTAL_BASE_URL=https://portal.nousresearch.com\nNOUS_INFERENCE_BASE_URL=https://by-hand/v1\nOTHER=1\n")
- first = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL, "NOUS_PORTAL_BASE_URL": None, "NOUS_INFERENCE_BASE_URL": None})
+ first = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL})
assert first.returncode == 0, first.stderr
- assert _lines(env_file, "HERMES_PORTAL_BASE_URL") == [f"HERMES_PORTAL_BASE_URL={PORTAL}"]
- assert "OTHER=1" in env_file.read_text()
+ assert load_env_file(env_file)["HERMES_PORTAL_BASE_URL"] == PORTAL
+ assert len(_assignments(env_file, "HERMES_PORTAL_BASE_URL")) == 1
assert "Synced HERMES_PORTAL_BASE_URL" in first.stdout
before = env_file.stat().st_mtime_ns
os.utime(env_file, ns=(before - 5_000_000_000, before - 5_000_000_000))
stamped = env_file.stat().st_mtime_ns
- second = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL, "NOUS_PORTAL_BASE_URL": None, "NOUS_INFERENCE_BASE_URL": None})
+ second = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL})
assert second.returncode == 0, second.stderr
assert env_file.stat().st_mtime_ns == stamped, "an already-correct line must not rewrite the volume"
assert "Synced" not in second.stdout
-
-def test_unset_override_touches_nothing_and_symlinked_env_is_refused(stage2_text: str, tmp_path: Path) -> None:
- """No container value → no .env is created or edited; a symlinked .env is never written through."""
- home = tmp_path / "home"
- (home / "profiles" / "work").mkdir(parents=True)
- result = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": None, "NOUS_PORTAL_BASE_URL": None, "NOUS_INFERENCE_BASE_URL": None})
- assert result.returncode == 0, result.stderr
- assert not (home / ".env").exists()
- assert not (home / "profiles" / "work" / ".env").exists()
+ with env_file.open("a") as fh:
+ fh.write("HERMES_PORTAL_BASE_URL=https://by-hand\n") # operator line beside the managed one
+ third = _run_sync(stage2_text, home, {})
+ assert third.returncode == 0, third.stderr
+ parsed = load_env_file(env_file)
+ assert _assignments(env_file, "HERMES_PORTAL_BASE_URL") == ["HERMES_PORTAL_BASE_URL=https://by-hand"], \
+ "only the stage2-written line goes when the platform unsets it"
+ assert parsed["NOUS_INFERENCE_BASE_URL"] == "https://by-hand/v1", "a hand-set line is never touched"
+ assert parsed["OTHER"] == "1"
+ assert "Removed HERMES_PORTAL_BASE_URL" in third.stdout
+
+ if os.geteuid() != 0:
+ env_file.chmod(0o444)
+ frozen = env_file.read_text()
+ readonly = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL})
+ env_file.chmod(0o600)
+ assert readonly.returncode == 0, "a read-only volume degrades to a warning under set -e"
+ assert "could not write HERMES_PORTAL_BASE_URL" in readonly.stdout
+ assert env_file.read_text() == frozen
outside = tmp_path / "outside.env"
outside.write_text("KEEP=1\n")
- (home / ".env").symlink_to(outside)
- result = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL, "NOUS_PORTAL_BASE_URL": None, "NOUS_INFERENCE_BASE_URL": None})
- assert result.returncode == 0, result.stderr
+ env_file.unlink()
+ env_file.symlink_to(outside)
+ fourth = _run_sync(stage2_text, home, {"HERMES_PORTAL_BASE_URL": PORTAL})
+ assert fourth.returncode == 0, fourth.stderr
assert outside.read_text() == "KEEP=1\n"
- assert "refusing sync HERMES_PORTAL_BASE_URL" in result.stdout
-
-
-def test_nous_portal_alias_is_synced_too(stage2_text: str, tmp_path: Path) -> None:
- """``NOUS_PORTAL_BASE_URL`` is accepted by ``_nous_portal_env_override`` and must reach the scope as well."""
- home = tmp_path / "home"
- home.mkdir()
- result = _run_sync(
- stage2_text,
- home,
- {"HERMES_PORTAL_BASE_URL": None, "NOUS_PORTAL_BASE_URL": PORTAL, "NOUS_INFERENCE_BASE_URL": None},
- )
- assert result.returncode == 0, result.stderr
- assert _lines(home / ".env", "NOUS_PORTAL_BASE_URL") == [f"NOUS_PORTAL_BASE_URL={PORTAL}"]
- assert _lines(home / ".env", "HERMES_PORTAL_BASE_URL") == []
+ assert "refusing sync through symlinked path" in fourth.stdout