The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: make the allow_all_users env bridge own what it writes and re-derive it on restart
teknium108bb2273e466
diff --git a/agent/secret_scope.py b/agent/secret_scope.pyindex 8446cdec5a5..58c80a143ce 100644--- a/agent/secret_scope.py+++ b/agent/secret_scope.py@@ -250,4 +250,19 @@ def build_profile_secret_scope(hermes_home: Path) -> Dict[str, str]:except Exception:external_secrets = {}secrets.update((k, v) for k, v in external_secrets.items() if not _is_global_env(k))+ # The DEFAULT profile's config.yaml allow_all_users grant lives only in os.environ (bridged by+ # gateway.config_loader); scoped gate readers under multiplex never fall to os.environ, so seed it+ # into that profile's own mapping. A secondary never inherits it (#80099 class).+ from gateway.config_loader import bridged_allow_all_users+ bridged = bridged_allow_all_users()+ if bridged is not None and _is_process_home(hermes_home):+ secrets.setdefault("GATEWAY_ALLOW_ALL_USERS", bridged)return secrets+++def _is_process_home(hermes_home: Path) -> bool:+ from hermes_constants import get_process_hermes_home+ try:+ return Path(hermes_home).resolve() == get_process_hermes_home().resolve()+ except OSError:+ return Falsediff --git a/gateway/config_loader.py b/gateway/config_loader.pyindex f26c5d5ba37..46fe00fc66c 100644--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@ -11,7 +11,7 @@ import jsonimport loggingimport osfrom pathlib import Path-from typing import Any+from typing import Any, Optionalfrom gateway.config import UNAUTHORIZED_DM_BEHAVIORS, Platform, PlatformConfig, _coerce_dict, _dict_slot, _normalize_choice@@ -48,6 +48,23 @@ def load_legacy_gateway_json(home: Path) -> Any:# "dict": top-level value is not a mapping → nested value; accepted only if a mapping.# "nested": nested form only (no top-level spelling is bridged).+# True while GATEWAY_ALLOW_ALL_USERS in os.environ is the bridge's own write (from config.yaml), not an+# operator's env var: only then may a reload overwrite/clear it, and restart env builders drop it so a+# child gateway re-derives the grant from its config.yaml instead of inheriting a stale open posture.+_BRIDGED_ALLOW_ALL_USERS = False+++def bridged_allow_all_users() -> Optional[str]:+ """``os.environ['GATEWAY_ALLOW_ALL_USERS']`` when it is the bridge's own write, else None."""+ return os.environ.get("GATEWAY_ALLOW_ALL_USERS") if _BRIDGED_ALLOW_ALL_USERS else None+++def drop_bridged_env(env: dict) -> dict:+ """Remove the bridge-owned ``GATEWAY_ALLOW_ALL_USERS`` from a child-process env (operator-set stays)."""+ if bridged_allow_all_users() is not None:+ env.pop("GATEWAY_ALLOW_ALL_USERS", None)+ return env+def _quick_commands_ok(value: Any) -> bool:if isinstance(value, dict):return True@@ -312,6 +329,7 @@ def bridge_core_env_settings(yaml_cfg: dict, platforms_data: dict) -> None:there would make the secondary's policy the DEFAULT profile's (#80099 class). A secondary profilesets ``GATEWAY_ALLOW_ALL_USERS`` in its own ``.env`` like every other scoped authorization gate."""+ global _BRIDGED_ALLOW_ALL_USERSfrom gateway.platforms._shared import profile_scopedskip_env_bridge = profile_scoped()@@ -319,15 +337,21 @@ def bridge_core_env_settings(yaml_cfg: dict, platforms_data: dict) -> None:allow_all = yaml_cfg.get("allow_all_users")if allow_all is None and isinstance(gateway_section, dict):allow_all = gateway_section.get("allow_all_users")- if allow_all is not None and not skip_env_bridge and not os.getenv("GATEWAY_ALLOW_ALL_USERS"):- os.environ["GATEWAY_ALLOW_ALL_USERS"] = str(allow_all).lower()- if os.environ["GATEWAY_ALLOW_ALL_USERS"] in {"true", "1", "yes"}:+ # Only a value this bridge wrote may be overwritten/cleared by a later load (config flipped to+ # false + reload); an operator's explicit env var still wins. Only a truthy grant is exported:+ # presence-based readers treat any non-empty value as "auth configured".+ if not skip_env_bridge and (_BRIDGED_ALLOW_ALL_USERS or not os.getenv("GATEWAY_ALLOW_ALL_USERS")):+ _BRIDGED_ALLOW_ALL_USERS = str(allow_all).lower() in {"true", "1", "yes"}+ if _BRIDGED_ALLOW_ALL_USERS:+ os.environ["GATEWAY_ALLOW_ALL_USERS"] = "true"# The key was inert before it was bridged, so a forgotten line silently flips the# posture to open — name the grant source at startup.logger.warning("config.yaml allow_all_users: true grants every sender on every platform access ""(bridged to GATEWAY_ALLOW_ALL_USERS; an explicit env var wins).")+ else:+ os.environ.pop("GATEWAY_ALLOW_ALL_USERS", None)tl_require_mention = yaml_cfg.get("require_mention")if tl_require_mention is not None and "require_mention" not in (yaml_cfg.get("telegram") or {}):tg_plat = platforms_data.setdefault(Platform.TELEGRAM.value, {})diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex d148d40ccef..ee20fffa2e5 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1284,8 +1284,9 @@ class GatewayShutdownMixin:@staticmethoddef _restart_watcher_env() -> dict:"""Watcher env minus ``_HERMES_GATEWAY`` (else the CLI's self-restart guard refuses; gateway stays down)."""+ from gateway.config_loader import drop_bridged_envfrom tools.environments.local import build_subprocess_env- watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)+ watcher_env = drop_bridged_env(build_subprocess_env(scrub_secrets=False, inherit_profile_home=True))watcher_env.pop("_HERMES_GATEWAY", None)return watcher_envdiff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex e928b6d03d5..cc9c94ab5a3 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -386,6 +386,10 @@ def _profile_action_environment(apply_subprocess_home_env(action_env)action_env["HERMES_NONINTERACTIVE"] = "1"+ # A config.yaml allow_all_users grant bridged into os.environ must not outlive the config that+ # produced it: drop it so the restarted child re-derives the posture from its own config.yaml.+ from gateway.config_loader import drop_bridged_env+ drop_bridged_env(action_env)# The dashboard runs inside the gateway process, so os.environ carries _HERMES_GATEWAY=1;# inheriting it trips the child's in-process restart-loop guard (exit 1). Drop it, like# the gateway's own restart watcher does (gateway/run.py, #52470).diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.pyindex f78a482a6f6..e0d8af4fcb4 100644--- a/tests/gateway/test_config.py+++ b/tests/gateway/test_config.py@@ -864,7 +864,7 @@ class TestLoadGatewayConfig:assert runner._is_user_authorized(stranger) is True@pytest.mark.parametrize("yaml_text, env, expected", [- ("gateway:\n allow_all_users: false\n", None, "false"),+ ("gateway:\n allow_all_users: false\n", None, None), # only a truthy grant is exported("gateway:\n allow_all_users: true\n", "false", "false"), # explicit env wins over YAML("gateway: {}\n", None, None),])@@ -888,6 +888,54 @@ class TestLoadGatewayConfig:stranger = SessionSource(platform=Platform.TELEGRAM, user_id="999", chat_id="999", chat_type="dm")assert runner._is_user_authorized(stranger) is False+ def test_bridged_allow_all_users_does_not_survive_a_config_flip_or_restart(self, tmp_path, monkeypatch):+ """The bridge owns what it wrote: flipping config.yaml to false and reloading closes the gate,+ and the restart/dashboard child envs never carry the bridged value (a sticky env var would make+ the restarted gateway ignore the flipped config and stay open)."""+ from gateway.run_shutdown import GatewayShutdownMixin+ from hermes_cli.web_server_gateway import _profile_action_environment++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ (hermes_home / "config.yaml").write_text("gateway:\n allow_all_users: true\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.delenv("GATEWAY_ALLOW_ALL_USERS", raising=False)+ load_gateway_config()+ assert os.environ.get("GATEWAY_ALLOW_ALL_USERS") == "true"+ assert "GATEWAY_ALLOW_ALL_USERS" not in GatewayShutdownMixin._restart_watcher_env()+ assert "GATEWAY_ALLOW_ALL_USERS" not in _profile_action_environment(["gateway", "restart"])++ (hermes_home / "config.yaml").write_text("gateway:\n allow_all_users: false\n", encoding="utf-8")+ load_gateway_config()+ assert os.environ.get("GATEWAY_ALLOW_ALL_USERS") is None++ def test_allow_all_users_yaml_reaches_the_default_profile_under_multiplex(self, tmp_path, monkeypatch):+ """Default-profile events are authorized inside its secret scope, where gate readers never fall to+ os.environ: the bridged grant must be part of that profile's scope (and only that profile's)."""+ from agent.secret_scope import build_profile_secret_scope, set_multiplex_active+ from gateway.authz_mixin import GatewayAuthorizationMixin+ from gateway.run import _profile_runtime_scope+ from gateway.session import SessionSource++ hermes_home = tmp_path / ".hermes"+ secondary = hermes_home / "profiles" / "other"+ secondary.mkdir(parents=True)+ (hermes_home / "config.yaml").write_text(+ "gateway:\n allow_all_users: true\n multiplex_profiles: true\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.delenv("GATEWAY_ALLOW_ALL_USERS", raising=False)+ runner = object.__new__(GatewayAuthorizationMixin)+ runner.config = load_gateway_config()+ runner.adapters = {}+ set_multiplex_active(True)+ try:+ stranger = SessionSource(platform=Platform.TELEGRAM, user_id="999", chat_id="999", chat_type="dm")+ with _profile_runtime_scope(hermes_home):+ assert runner._is_user_authorized(stranger) is True+ assert "GATEWAY_ALLOW_ALL_USERS" not in build_profile_secret_scope(secondary)+ finally:+ set_multiplex_active(False)+def test_top_level_platforms_override_nested_gateway_platforms(self, tmp_path, monkeypatch):hermes_home = tmp_path / ".hermes"diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex 70788100799..f710dd8a2ae 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -410,7 +410,7 @@ DISCORD_ALLOW_ALL_USERS=trueGATEWAY_ALLOW_ALL_USERS=true```-The global allow-all can also live in `config.yaml` as `gateway.allow_all_users: true` (or top-level `allow_all_users: true`); it is bridged to `GATEWAY_ALLOW_ALL_USERS` at gateway startup, an explicit env var wins, and the gateway logs a warning naming `config.yaml` as the grant source. In a multi-profile gateway a secondary profile sets `GATEWAY_ALLOW_ALL_USERS` in its own `.env` (its `config.yaml` is never bridged into the process environment).+The global allow-all can also live in `config.yaml` as `gateway.allow_all_users: true` (or top-level `allow_all_users: true`); a true value is bridged to `GATEWAY_ALLOW_ALL_USERS` at gateway startup (re-derived on every config load and restart, so flipping it back to `false` closes the gate), an explicit env var wins, and the gateway logs a warning naming `config.yaml` as the grant source. In a multi-profile gateway a secondary profile sets `GATEWAY_ALLOW_ALL_USERS` in its own `.env` (its `config.yaml` is never bridged into the process environment).:::warningIf **no allowlists are configured** and `GATEWAY_ALLOW_ALL_USERS` is not set, **all users are denied**. The gateway logs a warning at startup: