From 67292ec5b81d38230928494c053c60dbf3d6c987 Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 12:16:06 +1000 Subject: [PATCH 1/9] fix(gateway): GATEWAY_RELAY_URL env stamp disables direct messaging platforms A GATEWAY_RELAY_URL set in the process environment marks a connector-fronted deployment where the connector owns every platform connection. A directly-connected messaging adapter in the same process is a second, unmanaged ingress path: it causes duplicate deliveries and split sessions, and its live socket disarms scale-to-zero. At the end of _apply_env_overrides, after all enablement passes, the env stamp now disables every other enabled messaging platform: - Explicitly-enabled platforms (config.yaml enabled: true) are disabled with a WARNING that names the platform. - Credential-auto-enabled platforms are disabled with an INFO line. - Non-messaging surfaces (local, api_server, webhook) are untouched -- the same exclusion set as the scale-to-zero arm gate. - gateway.relay_url in config.yaml alone (no env stamp) keeps the old additive behavior: relay runs beside direct adapters. --- gateway/config.py | 34 ++++++++++++++++++++ tests/gateway/test_config.py | 60 ++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/gateway/config.py b/gateway/config.py index a00fa0f9a1..590bb5ebe8 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -2761,5 +2761,39 @@ def _apply_env_overrides(config: GatewayConfig) -> None: relay_config = _enable_from_env(Platform.RELAY) relay_config.extra["relay_url"] = relay_url_val.rstrip("/") + # Relay-exclusive: a GATEWAY_RELAY_URL env stamp marks a connector-fronted + # deployment where the connector owns every platform connection. Any + # directly-connected messaging adapter in the same process would be a + # second, unmanaged ingress path (duplicate deliveries, split sessions, + # and a live socket that disarms scale-to-zero), so the env stamp disables + # all other messaging platforms — including ones explicitly enabled in + # config.yaml. Non-messaging surfaces (local, api_server, webhook — the + # same exclusion set as the scale-to-zero arm gate) are untouched. + # Deployments that configure relay only via gateway.relay_url in + # config.yaml keep the old additive behavior (relay beside direct + # adapters). + if relay_url_env: + non_messaging = {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK} + for platform, platform_config in config.platforms.items(): + if platform is Platform.RELAY or platform in non_messaging: + continue + if not platform_config.enabled: + continue + if platform_config.extra.get("_enabled_explicit"): + logger.warning( + "Relay connector is configured via GATEWAY_RELAY_URL; " + "disabling directly-connected platform '%s' even though " + "it is explicitly enabled in config.yaml. All messaging " + "goes through the connector on this deployment.", + platform.value, + ) + else: + logger.info( + "Relay connector is configured via GATEWAY_RELAY_URL; " + "disabling directly-connected platform '%s'.", + platform.value, + ) + platform_config.enabled = False + for platform_config in config.platforms.values(): platform_config.extra.pop("_enabled_explicit", None) diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index 29c71a387b..8e110714df 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -686,6 +686,66 @@ class TestLoadGatewayConfig: assert Platform.RELAY in config.get_connected_platforms() + def test_relay_env_url_disables_other_messaging_platforms(self, tmp_path, monkeypatch): + """A GATEWAY_RELAY_URL env stamp means the connector owns all platform + connections: directly-connected messaging platforms must be disabled, + even when explicitly enabled in config.yaml, while non-messaging + surfaces (api_server et al.) survive.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n" + " api_server:\n" + " enabled: true\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + # Credential-based auto-enable path must be suppressed too. + monkeypatch.setenv("DISCORD_BOT_TOKEN", "fake-token-for-test") + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + discord_cfg = config.platforms.get(Platform.DISCORD) + assert discord_cfg is None or discord_cfg.enabled is False + # Non-messaging surfaces are untouched. + assert config.platforms[Platform.API_SERVER].enabled is True + + + def test_relay_yaml_url_keeps_other_platforms_enabled(self, tmp_path, monkeypatch): + """gateway.relay_url in config.yaml (no env stamp) keeps the old + additive behavior: relay runs beside directly-connected platforms.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " relay:\n" + " enabled: true\n" + " extra:\n" + " relay_url: https://connector.example/relay\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.delenv("GATEWAY_RELAY_URL", raising=False) + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is True + + def test_thread_require_mention_yaml_does_not_overwrite_env(self, tmp_path, monkeypatch): """Explicit env var should win over config.yaml (env > yaml precedence).""" hermes_home = tmp_path / ".hermes" From 2d3f5c1554b29df73b12110f8ecf657fe90762a2 Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 12:26:41 +1000 Subject: [PATCH 2/9] feat(gateway): GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS opt-out for relay-exclusive mode Deployments that intentionally mix connector-fronted and direct ingress can set GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true to keep directly- connected messaging adapters enabled beside the relay. Unset, the GATEWAY_RELAY_URL env stamp keeps its exclusive behavior. Like the trigger, the opt-out is a deploy-stamp env var, not config.yaml. --- gateway/config.py | 10 +++++++++- tests/gateway/test_config.py | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/gateway/config.py b/gateway/config.py index 590bb5ebe8..172eaf4ff2 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -2772,7 +2772,15 @@ def _apply_env_overrides(config: GatewayConfig) -> None: # Deployments that configure relay only via gateway.relay_url in # config.yaml keep the old additive behavior (relay beside direct # adapters). - if relay_url_env: + # + # Opt-out: GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true keeps direct + # adapters running beside the relay for deployments that intentionally + # mix both ingress paths. Like the trigger, it is a deploy-stamp env var, + # not a config.yaml setting. + allow_direct = os.getenv( + "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "" + ).strip().lower() in ("1", "true", "yes", "on") + if relay_url_env and not allow_direct: non_messaging = {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK} for platform, platform_config in config.platforms.items(): if platform is Platform.RELAY or platform in non_messaging: diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index 8e110714df..5fd626051b 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -746,6 +746,31 @@ class TestLoadGatewayConfig: assert config.platforms[Platform.TELEGRAM].enabled is True + def test_relay_env_url_opt_out_keeps_direct_platforms(self, tmp_path, monkeypatch): + """GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true opts a deployment out of + the relay-exclusive sweep: direct adapters stay enabled beside the + relay even with the GATEWAY_RELAY_URL env stamp present.""" + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + monkeypatch.setenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "true") + + config = load_gateway_config() + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is True + + def test_thread_require_mention_yaml_does_not_overwrite_env(self, tmp_path, monkeypatch): """Explicit env var should win over config.yaml (env > yaml precedence).""" hermes_home = tmp_path / ".hermes" From 477a0222f92a631538e8ca2a3a4b386656f8ee0f Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 12:42:06 +1000 Subject: [PATCH 3/9] fix(gateway): read relay-exclusive env vars through profile secret scope sol-reviewer IMPORTANT: the relay trigger and opt-out read os.getenv() directly, bypassing the profile secret scope that _apply_env_overrides uses everywhere else. Under a multiplexed gateway a profile-scoped GATEWAY_RELAY_URL was invisible, and a process-global one leaked into every profile, disabling direct platforms in profiles that are not relay-fronted. Both reads now go through the scope-aware getenv. Also folds the NIT: opt-out truthiness now uses the shared is_truthy_value helper instead of a local truthy tuple. --- gateway/config.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/gateway/config.py b/gateway/config.py index 172eaf4ff2..556f5a467f 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -2751,7 +2751,7 @@ def _apply_env_overrides(config: GatewayConfig) -> None: # config.platforms for start_gateway()'s connect loop to bring it up. The # connected-checker (Platform.RELAY in _PLATFORM_CONNECTED_CHECKERS) keys on # extra["relay_url"], so mirror the URL into extra here. - relay_url_env = os.getenv("GATEWAY_RELAY_URL", "").strip() + relay_url_env = getenv("GATEWAY_RELAY_URL", "").strip() relay_url_yaml = "" existing_relay = config.platforms.get(Platform.RELAY) if existing_relay is not None: @@ -2776,10 +2776,12 @@ def _apply_env_overrides(config: GatewayConfig) -> None: # Opt-out: GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true keeps direct # adapters running beside the relay for deployments that intentionally # mix both ingress paths. Like the trigger, it is a deploy-stamp env var, - # not a config.yaml setting. - allow_direct = os.getenv( - "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "" - ).strip().lower() in ("1", "true", "yes", "on") + # not a config.yaml setting. Both reads go through the profile-scope-aware + # getenv so multiplexed profiles see their own values, not the process + # globals. + allow_direct = is_truthy_value( + getenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "") + ) if relay_url_env and not allow_direct: non_messaging = {Platform.LOCAL, Platform.API_SERVER, Platform.WEBHOOK} for platform, platform_config in config.platforms.items(): From 2ef095ce460c0522ed1bcf559d407935ba1bddc7 Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 12:42:13 +1000 Subject: [PATCH 4/9] fix(gateway): source-neutral log wording for relay-exclusive sweep sol-reviewer MINOR: the _enabled_explicit marker is set by config.yaml, gateway.json, and dashboard PUTs alike, so the WARNING no longer claims config.yaml specifically. Also names the opt-out env var in the message so an operator seeing the WARNING knows the escape hatch. --- gateway/config.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gateway/config.py b/gateway/config.py index 556f5a467f..fece329595 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -2793,8 +2793,10 @@ def _apply_env_overrides(config: GatewayConfig) -> None: logger.warning( "Relay connector is configured via GATEWAY_RELAY_URL; " "disabling directly-connected platform '%s' even though " - "it is explicitly enabled in config.yaml. All messaging " - "goes through the connector on this deployment.", + "it is explicitly enabled in this profile's configuration. " + "All messaging goes through the connector on this " + "deployment. Set GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true " + "to keep direct platforms alongside the relay.", platform.value, ) else: From 55a272d0dc9d7c282bd0f73c4e4acacb41f7364a Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 12:42:13 +1000 Subject: [PATCH 5/9] test(gateway): cover profile-scoped relay stamps, log levels, marker cleanup sol-reviewer findings: multiplex secret-scope regression test (global stamp must not leak into a scoped profile; scoped stamp must trigger the sweep), WARNING-vs-INFO log-level assertions, and a check that _enabled_explicit never survives config load. --- tests/gateway/test_config.py | 95 ++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index 5fd626051b..a6daa8d687 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -771,6 +771,101 @@ class TestLoadGatewayConfig: assert config.platforms[Platform.TELEGRAM].enabled is True + def test_relay_exclusive_reads_profile_scoped_env(self, tmp_path, monkeypatch): + """Under a multiplexed profile secret scope, the relay-exclusive + trigger and opt-out must read the PROFILE's values, not process + globals. A process-wide GATEWAY_RELAY_URL must not disable direct + platforms in a profile whose own .env carries no relay stamp.""" + from agent import secret_scope as ss + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + # Process-global stamp that must be INVISIBLE inside the scope. + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://global.example/relay") + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text("", encoding="utf-8") # no relay stamp + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + # No profile-scoped relay stamp -> no exclusive sweep in this profile. + assert config.platforms[Platform.TELEGRAM].enabled is True + + # And the inverse: a profile-scoped stamp triggers the sweep even + # though the process env carries none. + monkeypatch.delenv("GATEWAY_RELAY_URL", raising=False) + (profile_dir / ".env").write_text( + "GATEWAY_RELAY_URL=https://profile.example/relay\n", encoding="utf-8" + ) + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + + + def test_relay_exclusive_sweep_log_levels_and_marker_cleanup(self, tmp_path, monkeypatch, caplog): + """Explicitly-enabled platforms are disabled at WARNING, auto-enabled + ones at INFO, and the _enabled_explicit marker never survives config + load.""" + import logging as _logging + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + config_path = hermes_home / "config.yaml" + config_path.write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://connector.example/relay") + monkeypatch.setenv("DISCORD_BOT_TOKEN", "fake-token-for-test") + + with caplog.at_level(_logging.INFO, logger="gateway.config"): + config = load_gateway_config() + + warnings = [ + r for r in caplog.records + if r.levelno == _logging.WARNING and "telegram" in r.getMessage() + ] + assert warnings, "explicit platform must be disabled at WARNING" + discord_infos = [ + r for r in caplog.records + if r.levelno == _logging.INFO and "discord" in r.getMessage() + ] + if config.platforms.get(Platform.DISCORD) is not None: + assert discord_infos, "auto-enabled platform must be disabled at INFO" + + for pc in config.platforms.values(): + assert "_enabled_explicit" not in (pc.extra or {}) + + def test_thread_require_mention_yaml_does_not_overwrite_env(self, tmp_path, monkeypatch): """Explicit env var should win over config.yaml (env > yaml precedence).""" hermes_home = tmp_path / ".hermes" From f8c3635d4046de196c9e8e45e6c299baf4d0c13d Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 13:21:46 +1000 Subject: [PATCH 6/9] fix(gateway): classify relay routing stamps as process-global deployment config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sol-reviewer round-2 IMPORTANT: relay env vars had no scope classification, so the two readers disagreed under a multiplexed profile scope — gateway/config.py (scope-aware getenv) dropped a process-env GATEWAY_RELAY_URL during the scoped runner reload while gateway/relay's relay_url()/register_relay_adapter()/self-provision (direct os.environ reads) still saw it. Result: adapter registered but Platform.RELAY absent from config, so the connect loop never dialed and direct adapters stayed up. The inverse split (profile-only stamp: config enables RELAY, registration finds no URL) was equally dead. GATEWAY_RELAY_* ROUTING stamps (URL, ENDPOINT, ALLOW_DIRECT_PLATFORMS, PLATFORMS, BOT_IDS, ROUTE_KEYS, INSTANCE_ID, WAKE_URL, DISPLAY_NAME) are now in _GLOBAL_ENV_EXACT: deployment config read from os.environ under any scope, exactly like the API_SERVER listener settings (#69379), so every reader resolves the same value. Relay AUTH material (SECRET, ID, DELIVERY_KEY, IDP_*) is deliberately NOT global — it stays profile-scoped with the fail-closed multiplex guard, mirroring the non-secret/secret line the terminal env blocklist already draws (tools/environments/local.py). The round-1 multiplex regression test asserted the now-rejected semantic (profile-scoped stamps win); it is inverted to pin the global-stamp contract: a process-env stamp survives the profile scope (sweep runs, matching registration), and a profile-only .env stamp does NOT activate relay. --- agent/secret_scope.py | 17 +++++++++ tests/agent/test_secret_scope.py | 60 ++++++++++++++++++++++++++++++++ tests/gateway/test_config.py | 31 ++++++++++------- 3 files changed, 95 insertions(+), 13 deletions(-) diff --git a/agent/secret_scope.py b/agent/secret_scope.py index 919fe3e27b..86f18f5219 100644 --- a/agent/secret_scope.py +++ b/agent/secret_scope.py @@ -114,6 +114,23 @@ _GLOBAL_ENV_EXACT = frozenset({ # profile-scoped. "API_SERVER_ENABLED", "API_SERVER_HOST", "API_SERVER_PORT", "API_SERVER_CORS_ORIGINS", + # Relay-connector ROUTING stamps — deployment config injected into the + # container/process env by managed deploys (the same shape as the + # API_SERVER listener settings above). The scoped runner reload and the + # relay-exclusive sweep in gateway/config.py must keep seeing them, and + # every reader (gateway.config, gateway.relay.relay_url()/registration/ + # self-provision) must resolve the SAME value — a scope-dependent split + # leaves the adapter registered but the platform absent from config (or + # vice versa). Mirrors the non-secret/secret line drawn by the terminal + # env blocklist (tools/environments/local.py): routing hints are global; + # GATEWAY_RELAY_SECRET / GATEWAY_RELAY_ID / GATEWAY_RELAY_DELIVERY_KEY + # and the IDP_* credentials are auth material and deliberately NOT here — + # they stay profile-scoped with the fail-closed multiplex guard. + "GATEWAY_RELAY_URL", "GATEWAY_RELAY_ENDPOINT", + "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", + "GATEWAY_RELAY_PLATFORMS", "GATEWAY_RELAY_BOT_IDS", + "GATEWAY_RELAY_ROUTE_KEYS", "GATEWAY_RELAY_INSTANCE_ID", + "GATEWAY_RELAY_WAKE_URL", "GATEWAY_RELAY_DISPLAY_NAME", }) _GLOBAL_ENV_PREFIXES = ( "HERMES_KANBAN_", diff --git a/tests/agent/test_secret_scope.py b/tests/agent/test_secret_scope.py index f0d76fe654..7e73f12dbc 100644 --- a/tests/agent/test_secret_scope.py +++ b/tests/agent/test_secret_scope.py @@ -287,3 +287,63 @@ class TestApiServerListenerGlobals: finally: ss.reset_secret_scope(token) assert not ss._is_global_env("API_SERVER_KEY") + + +class TestRelayRoutingStampGlobals: + """GATEWAY_RELAY_* ROUTING stamps are deployment config, not profile + secrets: config's relay enablement/sweep and gateway.relay's readers + (relay_url(), registration, self-provision) must resolve the same + process-env value under any scope, or the gateway enters a split-brain + state (adapter registered but Platform.RELAY absent from config, or vice + versa). Auth material (GATEWAY_RELAY_SECRET / _ID / _DELIVERY_KEY and the + IDP_* credentials) stays profile-scoped with the fail-closed guard — + mirroring the API_SERVER_KEY line above and the terminal env blocklist + (tools/environments/local.py).""" + + ROUTING_VARS = ( + "GATEWAY_RELAY_URL", + "GATEWAY_RELAY_ENDPOINT", + "GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", + "GATEWAY_RELAY_PLATFORMS", + "GATEWAY_RELAY_BOT_IDS", + "GATEWAY_RELAY_ROUTE_KEYS", + "GATEWAY_RELAY_INSTANCE_ID", + "GATEWAY_RELAY_WAKE_URL", + "GATEWAY_RELAY_DISPLAY_NAME", + ) + AUTH_VARS = ( + "GATEWAY_RELAY_SECRET", + "GATEWAY_RELAY_ID", + "GATEWAY_RELAY_DELIVERY_KEY", + "GATEWAY_RELAY_IDP_CLIENT_SECRET", + "GATEWAY_RELAY_IDP_CLIENT_ID", + "GATEWAY_RELAY_IDP_TOKEN_URL", + ) + + def test_routing_stamps_read_environ_even_when_scoped_multiplex(self, monkeypatch): + for name in self.ROUTING_VARS: + monkeypatch.setenv(name, f"deploy-{name.lower()}") + ss.set_multiplex_active(True) + token = ss.set_secret_scope({"TELEGRAM_BOT_TOKEN": "scoped"}) + try: + for name in self.ROUTING_VARS: + assert ss.get_secret(name) == f"deploy-{name.lower()}", name + finally: + ss.reset_secret_scope(token) + ss.set_multiplex_active(False) + + def test_relay_auth_material_stays_profile_scoped(self, monkeypatch): + for name in self.AUTH_VARS: + monkeypatch.setenv(name, "cross-profile-credential") + ss.set_multiplex_active(True) + token = ss.set_secret_scope({"OTHER": "x"}) + try: + for name in self.AUTH_VARS: + # A scoped miss must NOT borrow the (potentially + # cross-profile) environ value: relay auth is a credential. + assert ss.get_secret(name) is None, name + finally: + ss.reset_secret_scope(token) + ss.set_multiplex_active(False) + for name in self.AUTH_VARS: + assert not ss._is_global_env(name), name diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index a6daa8d687..3d7834e15d 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -772,10 +772,12 @@ class TestLoadGatewayConfig: def test_relay_exclusive_reads_profile_scoped_env(self, tmp_path, monkeypatch): - """Under a multiplexed profile secret scope, the relay-exclusive - trigger and opt-out must read the PROFILE's values, not process - globals. A process-wide GATEWAY_RELAY_URL must not disable direct - platforms in a profile whose own .env carries no relay stamp.""" + """GATEWAY_RELAY_URL is a process-global deployment stamp (like the + API_SERVER listener vars, #69379): the scoped runner reload in a + multiplexed gateway must keep seeing it, so config's relay enablement + and sweep agree with gateway.relay.relay_url()/register_relay_adapter() + (which read os.environ). A relay URL in a profile's .env is NOT a + supported activation path — the scope is never consulted for globals.""" from agent import secret_scope as ss hermes_home = tmp_path / ".hermes" @@ -790,12 +792,12 @@ class TestLoadGatewayConfig: encoding="utf-8", ) monkeypatch.setenv("HERMES_HOME", str(hermes_home)) - # Process-global stamp that must be INVISIBLE inside the scope. - monkeypatch.setenv("GATEWAY_RELAY_URL", "https://global.example/relay") + # Managed-deploy stamp in the process env; the profile .env has none. + monkeypatch.setenv("GATEWAY_RELAY_URL", "https://deploy.example/relay") profile_dir = tmp_path / "profile-a" profile_dir.mkdir() - (profile_dir / ".env").write_text("", encoding="utf-8") # no relay stamp + (profile_dir / ".env").write_text("", encoding="utf-8") ss.set_multiplex_active(True) tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) @@ -805,11 +807,13 @@ class TestLoadGatewayConfig: ss.reset_secret_scope(tok) ss.set_multiplex_active(False) - # No profile-scoped relay stamp -> no exclusive sweep in this profile. - assert config.platforms[Platform.TELEGRAM].enabled is True + # The deploy stamp survives the profile scope: relay enabled, sweep + # ran — matching what register_relay_adapter() sees in os.environ. + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False - # And the inverse: a profile-scoped stamp triggers the sweep even - # though the process env carries none. + # A profile-only stamp does NOT activate relay: globals read only the + # process env, so config and the relay transport can never disagree. monkeypatch.delenv("GATEWAY_RELAY_URL", raising=False) (profile_dir / ".env").write_text( "GATEWAY_RELAY_URL=https://profile.example/relay\n", encoding="utf-8" @@ -822,8 +826,9 @@ class TestLoadGatewayConfig: ss.reset_secret_scope(tok) ss.set_multiplex_active(False) - assert config.platforms[Platform.RELAY].enabled is True - assert config.platforms[Platform.TELEGRAM].enabled is False + relay_cfg = config.platforms.get(Platform.RELAY) + assert relay_cfg is None or relay_cfg.enabled is False + assert config.platforms[Platform.TELEGRAM].enabled is True def test_relay_exclusive_sweep_log_levels_and_marker_cleanup(self, tmp_path, monkeypatch, caplog): From 3d25fd59b9f7e380e4b644f37008ae2db888cf7b Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 13:35:20 +1000 Subject: [PATCH 7/9] fix(cli): warn when gateway enroll writes relay URLs to a secondary multiplex profile sol-reviewer round-3 IMPORTANT: gateway enroll --connector-url / --wake-url persist GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL into the active profile's .env and tell the user a restart activates them. For a SECONDARY profile of a multiplexed gateway that is silently untrue: the routing stamps are process-global, and a secondary profile's .env is loaded into an isolated secret scope, never exported to os.environ, so the gateway can never read them from there. Enrollment (the credential exchange) still succeeds and the creds are still valid, so warn rather than refuse, pointing at the process environment or the default profile. Single-profile gateways and the launch profile are unaffected (load_hermes_dotenv exports their .env at startup). --- hermes_cli/gateway_enroll.py | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/hermes_cli/gateway_enroll.py b/hermes_cli/gateway_enroll.py index d3c5622225..a4ba9d0e86 100644 --- a/hermes_cli/gateway_enroll.py +++ b/hermes_cli/gateway_enroll.py @@ -37,6 +37,7 @@ import sys import urllib.error import urllib.parse import urllib.request +from pathlib import Path from typing import Optional @@ -275,3 +276,40 @@ def cmd_gateway_enroll(args) -> None: " secret and verifies signed inbound deliveries with the tenant delivery\n" " key. Restart the gateway to pick up the new env." ) + # GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-global deployment + # stamps (agent/secret_scope.py): a multiplexed gateway resolves them from + # the PROCESS environment only, never from a secondary profile's .env + # (which is loaded into an isolated secret scope, not exported). The .env + # write above works for a single-profile gateway and for the profile the + # process is launched under (load_hermes_dotenv exports that .env), so + # warn rather than refuse — but don't let a secondary-profile enroll claim + # a config that will silently never activate. + if explicit_url or explicit_wake_url: + _warn_if_secondary_multiplex_profile() + + +def _warn_if_secondary_multiplex_profile() -> None: + """Warn when relay routing stamps were written to a profile .env that a + multiplexed gateway will never read them from. Best-effort — any failure + to determine the topology stays silent (the write itself succeeded).""" + try: + from gateway.config import load_gateway_config + from hermes_cli.config import get_hermes_home + + home = Path(get_hermes_home()).resolve() + is_secondary = home.parent.name == "profiles" + if not is_secondary: + return + if not getattr(load_gateway_config(), "multiplex_profiles", False): + return + print() + print( + " ⚠ This profile is a SECONDARY profile of a multiplexed gateway.\n" + " GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-level\n" + " deployment settings: the gateway reads them from the process\n" + " environment (or the default profile's .env), not from this\n" + " profile's .env. Set them in the environment the gateway process\n" + " is launched with, or enroll from the default profile." + ) + except Exception: + pass From d97cb8f253f9c26be376c345d1fcccfe13dc414c Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 13:35:20 +1000 Subject: [PATCH 8/9] test(gateway): pin config/registration relay-URL agreement under multiplex scope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sol-reviewer round-3 findings: the regression tests stopped at the config boundary, so config/registration agreement was only manually verified. New TestConfigRegistrationAgreementUnderMultiplexScope exercises both sides under an active profile scope: a process-env stamp yields Platform.RELAY enabled AND relay_url()/ register_relay_adapter() agreement AND a constructed RelayAdapter with a live transport; a profile-only .env stamp is inert on BOTH sides (no half-enabled state). Also narrows the test_config docstring that overclaimed profile .env stamps are unsupported — the launch profile's .env still activates relay via load_hermes_dotenv's os.environ export; only an isolated multiplex scope is never consulted. --- .../gateway/relay/test_relay_registration.py | 96 +++++++++++++++++++ tests/gateway/test_config.py | 7 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/tests/gateway/relay/test_relay_registration.py b/tests/gateway/relay/test_relay_registration.py index 4aceb269c6..819d4e8049 100644 --- a/tests/gateway/relay/test_relay_registration.py +++ b/tests/gateway/relay/test_relay_registration.py @@ -42,3 +42,99 @@ def test_registers_when_url_configured(monkeypatch): assert platform_registry.is_registered("relay") is True + + +class TestConfigRegistrationAgreementUnderMultiplexScope: + """The config loader and the relay registration path must resolve the SAME + GATEWAY_RELAY_URL under an active multiplex profile scope — the routing + stamp is process-global (agent/secret_scope.py), so neither side may see a + value the other doesn't. Regression for the split-brain states: adapter + registered with Platform.RELAY absent from config (process stamp dropped + by the scoped reload), and enabled RELAY config with no adapter + (profile-only stamp invisible to relay_url()).""" + + def test_process_stamp_agrees_on_both_sides_under_scope( + self, tmp_path, monkeypatch + ): + from agent import secret_scope as ss + from gateway.config import Platform, load_gateway_config + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + monkeypatch.setenv("GATEWAY_RELAY_URL", "wss://deploy.example/relay") + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text("", encoding="utf-8") + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + # Registration-side reader agrees with the config side. + assert relay_url() == "wss://deploy.example/relay" + assert register_relay_adapter() is True + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + assert config.platforms[Platform.RELAY].enabled is True + assert config.platforms[Platform.TELEGRAM].enabled is False + # The registered factory actually constructs an adapter with a live + # transport dialing the same URL — the connect loop's contract. + adapter = platform_registry.create_adapter( + "relay", config.platforms[Platform.RELAY] + ) + assert isinstance(adapter, RelayAdapter) + # A URL-configured registration builds a live transport (force=True's + # transport-less posture is the test-only path) — private attr, no + # public accessor on the adapter. + assert adapter._transport is not None + + def test_profile_only_stamp_is_inert_on_both_sides_under_scope( + self, tmp_path, monkeypatch + ): + from agent import secret_scope as ss + from gateway.config import Platform, load_gateway_config + + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + "gateway:\n" + " platforms:\n" + " telegram:\n" + " enabled: true\n" + " bot_token: '123:abc'\n", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + + profile_dir = tmp_path / "profile-a" + profile_dir.mkdir() + (profile_dir / ".env").write_text( + "GATEWAY_RELAY_URL=wss://profile.example/relay\n", encoding="utf-8" + ) + + ss.set_multiplex_active(True) + tok = ss.set_secret_scope(ss.build_profile_secret_scope(profile_dir)) + try: + config = load_gateway_config() + # Both sides agree the stamp is absent: no half-enabled state. + assert relay_url() is None + assert register_relay_adapter() is False + finally: + ss.reset_secret_scope(tok) + ss.set_multiplex_active(False) + + relay_cfg = config.platforms.get(Platform.RELAY) + assert relay_cfg is None or relay_cfg.enabled is False + assert config.platforms[Platform.TELEGRAM].enabled is True diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py index 3d7834e15d..00ec63e1b5 100644 --- a/tests/gateway/test_config.py +++ b/tests/gateway/test_config.py @@ -776,8 +776,11 @@ class TestLoadGatewayConfig: API_SERVER listener vars, #69379): the scoped runner reload in a multiplexed gateway must keep seeing it, so config's relay enablement and sweep agree with gateway.relay.relay_url()/register_relay_adapter() - (which read os.environ). A relay URL in a profile's .env is NOT a - supported activation path — the scope is never consulted for globals.""" + (which read os.environ). A secondary profile's .env stamp does NOT + override the shared process stamp — an isolated multiplex scope is + never consulted for globals. (A single-profile gateway, or the profile + the process is launched under, still activates via its .env because + load_hermes_dotenv exports that file into os.environ at startup.)""" from agent import secret_scope as ss hermes_home = tmp_path / ".hermes" From 6360113a8b1614d0331eacb6bc2fc6102f851d78 Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 14:13:28 +1000 Subject: [PATCH 9/9] fix(cli): read multiplex topology from the default root in enroll warning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sol-reviewer round-4 IMPORTANT (reproduced by execution): the enroll warning read multiplex_profiles via load_gateway_config() under the SECONDARY profile's HERMES_HOME, but the flag normally lives in the DEFAULT root's config.yaml — so the warning never fired in the real topology, preserving the round-3 defect it claimed to fix. The topology decision now mirrors the multiplexer-conflict guard in hermes_cli/gateway.py: secondary detection is the resolved-path relationship to /profiles/ (not a directory-name heuristic — also fixes the round-4 MINOR false positive on unrelated dirs named 'profiles'), and the multiplex flag comes from the GATEWAY_MULTIPLEX_PROFILES env override or a raw read of the default root's config.yaml. The raw read also avoids running the full enablement pass (round-4 MINOR: load_gateway_config() emitted the relay-exclusive sweep's own warnings into enroll output). The warning now replaces the generic 'restart to pick up the new env' line instead of following it (round-4 NIT: the two messages were contradictory), and the helper returns whether it fired. New test file pins all six topology cases, including the exact false-negative reproduction (flag in default root only) and env override in both directions. --- hermes_cli/gateway_enroll.py | 75 ++++++++--- .../test_gateway_enroll_multiplex_warning.py | 117 ++++++++++++++++++ 2 files changed, 172 insertions(+), 20 deletions(-) create mode 100644 tests/hermes_cli/test_gateway_enroll_multiplex_warning.py diff --git a/hermes_cli/gateway_enroll.py b/hermes_cli/gateway_enroll.py index a4ba9d0e86..9f529e625c 100644 --- a/hermes_cli/gateway_enroll.py +++ b/hermes_cli/gateway_enroll.py @@ -271,11 +271,6 @@ def cmd_gateway_enroll(args) -> None: if explicit_wake_url: print(f" GATEWAY_RELAY_WAKE_URL={explicit_wake_url.rstrip('/')}") print() - print( - " The gateway now authenticates its relay WS upgrade with the per-gateway\n" - " secret and verifies signed inbound deliveries with the tenant delivery\n" - " key. Restart the gateway to pick up the new env." - ) # GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-global deployment # stamps (agent/secret_scope.py): a multiplexed gateway resolves them from # the PROCESS environment only, never from a secondary profile's .env @@ -283,33 +278,73 @@ def cmd_gateway_enroll(args) -> None: # write above works for a single-profile gateway and for the profile the # process is launched under (load_hermes_dotenv exports that .env), so # warn rather than refuse — but don't let a secondary-profile enroll claim - # a config that will silently never activate. + # a config that will silently never activate. Emitted BEFORE the generic + # restart line so the two don't contradict each other. + warned_secondary = False if explicit_url or explicit_wake_url: - _warn_if_secondary_multiplex_profile() + warned_secondary = _warn_if_secondary_multiplex_profile() + if not warned_secondary: + print( + " The gateway now authenticates its relay WS upgrade with the per-gateway\n" + " secret and verifies signed inbound deliveries with the tenant delivery\n" + " key. Restart the gateway to pick up the new env." + ) -def _warn_if_secondary_multiplex_profile() -> None: - """Warn when relay routing stamps were written to a profile .env that a - multiplexed gateway will never read them from. Best-effort — any failure - to determine the topology stays silent (the write itself succeeded).""" +def _warn_if_secondary_multiplex_profile() -> bool: + """Warn when relay routing stamps were written to a secondary profile's + .env that a multiplexed gateway will never read them from. Returns True + when the warning fired (the caller suppresses the generic restart text). + + The topology decision is owned by the DEFAULT root, not the active + profile home: ``multiplex_profiles`` normally lives in + ``/config.yaml`` (or the GATEWAY_MULTIPLEX_PROFILES env + override), and the secondary check is the resolved-path relationship to + ``/profiles/`` — mirroring the multiplexer-conflict guard + in hermes_cli/gateway.py. Best-effort: any failure to determine the + topology stays silent (the credential write itself succeeded). + """ try: - from gateway.config import load_gateway_config + from hermes_constants import get_default_hermes_root from hermes_cli.config import get_hermes_home + default_root = Path(get_default_hermes_root()).resolve() home = Path(get_hermes_home()).resolve() - is_secondary = home.parent.name == "profiles" - if not is_secondary: - return - if not getattr(load_gateway_config(), "multiplex_profiles", False): - return - print() + try: + home.relative_to(default_root / "profiles") + except ValueError: + return False # default profile or custom layout — not a secondary + + # Multiplex flag precedence mirrors gateway.config: recognized env + # override wins, else the DEFAULT root's config.yaml (raw read — the + # active profile's load_gateway_config() is the wrong owner AND runs + # the full enablement pass, including the relay-exclusive sweep's own + # log output, which has no place in enroll output). + from gateway.config import _env_multiplex_profiles_override + env_multiplex = _env_multiplex_profiles_override() + if env_multiplex is False: + return False + if env_multiplex is not True: + cfg_path = default_root / "config.yaml" + if not cfg_path.exists(): + return False + from hermes_cli.config import read_user_config_raw + cfg = read_user_config_raw(cfg_path) or {} + if not bool( + cfg.get("multiplex_profiles") + or (cfg.get("gateway", {}) or {}).get("multiplex_profiles") + ): + return False + print( " ⚠ This profile is a SECONDARY profile of a multiplexed gateway.\n" " GATEWAY_RELAY_URL / GATEWAY_RELAY_WAKE_URL are process-level\n" " deployment settings: the gateway reads them from the process\n" " environment (or the default profile's .env), not from this\n" " profile's .env. Set them in the environment the gateway process\n" - " is launched with, or enroll from the default profile." + " is launched with, or enroll from the default profile. The\n" + " relay credentials written above are valid either way." ) + return True except Exception: - pass + return False diff --git a/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py new file mode 100644 index 0000000000..31a4d539b5 --- /dev/null +++ b/tests/hermes_cli/test_gateway_enroll_multiplex_warning.py @@ -0,0 +1,117 @@ +"""Gateway enroll: secondary-multiplex-profile warning for relay routing stamps. + +``hermes gateway enroll --connector-url/--wake-url`` persists GATEWAY_RELAY_URL / +GATEWAY_RELAY_WAKE_URL into the active profile's .env. Those are process-global +deployment stamps (agent/secret_scope.py): a multiplexed gateway reads them from +the process environment only, never from a secondary profile's isolated secret +scope — so an enroll run from a secondary profile must WARN that the written +URLs will not activate from there (sol-reviewer round-4: the first cut read +``multiplex_profiles`` from the SECONDARY profile's config.yaml, where it never +lives, and the warning silently never fired in the real topology). + +The topology decision is owned by the DEFAULT root: path relationship to +``/profiles/`` plus the default root's config.yaml (or the +GATEWAY_MULTIPLEX_PROFILES env override). +""" + +from __future__ import annotations + +import io +from contextlib import redirect_stdout + +import pytest + +import hermes_constants +from hermes_cli.gateway_enroll import _warn_if_secondary_multiplex_profile + + +@pytest.fixture() +def topology(tmp_path, monkeypatch): + """Standard multiplex layout: default root + one secondary profile.""" + root = tmp_path / "root" + (root / "profiles" / "alice").mkdir(parents=True) + monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: root) + monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False) + return root + + +def _run() -> tuple[bool, str]: + buf = io.StringIO() + with redirect_stdout(buf): + fired = _warn_if_secondary_multiplex_profile() + return fired, buf.getvalue() + + +def test_fires_for_secondary_when_default_root_has_multiplex_on(topology, monkeypatch): + """The regression case: flag in the DEFAULT root's config.yaml, absent from + the secondary profile's own config — the warning must still fire.""" + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + + fired, out = _run() + + assert fired is True + assert "SECONDARY profile" in out + + +def test_silent_when_multiplex_off_in_default_root(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: false\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + + fired, out = _run() + + assert fired is False + assert out == "" + + +def test_silent_for_default_profile_even_with_multiplex_on(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology)) + + fired, _ = _run() + + assert fired is False + + +def test_env_override_forces_multiplex_on_without_config_flag(topology, monkeypatch): + (topology / "config.yaml").write_text("{}\n", encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "true") + + fired, _ = _run() + + assert fired is True + + +def test_env_override_off_wins_over_config_flag(topology, monkeypatch): + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + monkeypatch.setenv("HERMES_HOME", str(topology / "profiles" / "alice")) + monkeypatch.setenv("GATEWAY_MULTIPLEX_PROFILES", "false") + + fired, _ = _run() + + assert fired is False + + +def test_silent_for_unrelated_dir_named_profiles(topology, tmp_path, monkeypatch): + """A directory whose parent happens to be named 'profiles' but is OUTSIDE + the default root is not a secondary profile (sol-reviewer round-4 MINOR: + name-based heuristics false-positive on unrelated layouts).""" + (topology / "config.yaml").write_text( + "gateway:\n multiplex_profiles: true\n", encoding="utf-8" + ) + other = tmp_path / "elsewhere" / "profiles" / "x" + other.mkdir(parents=True) + monkeypatch.setenv("HERMES_HOME", str(other)) + + fired, _ = _run() + + assert fired is False