Skip to content

The agent that grows with you

fix(relay): preserve legacy opt-out without standalone bootstrap

Victor Kyriazakosf2de10287288
diff --git a/gateway/config_loader.py b/gateway/config_loader.py
index df8f5f63826..e076336ba79 100644
--- a/gateway/config_loader.py
+++ b/gateway/config_loader.py
@@ -27,6 +27,14 @@ def load_legacy_gateway_json(home: Path) -> Any:
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f) or {}
+ # Relay accepts a legacy opt-out as authoritative, just like YAML.
+ # Preserve that intent through credential activation and the exclusive
+ # native-adapter sweep, even when config.yaml is missing. Other legacy
+ # platforms retain their existing env-driven enablement semantics.
+ platforms = data.get("platforms") if isinstance(data, dict) else None
+ relay = platforms.get("relay") if isinstance(platforms, dict) else None
+ if isinstance(relay, dict) and "enabled" in relay:
+ _dict_slot(relay, "extra")["_enabled_explicit"] = True
logger.info("Loaded legacy %s — consider moving settings to config.yaml", path)
return data
except Exception as e:
diff --git a/gateway/relay/__init__.py b/gateway/relay/__init__.py
index 14cc29b68a1..f0fbfa7c7d2 100644
--- a/gateway/relay/__init__.py
+++ b/gateway/relay/__init__.py
@@ -82,8 +82,14 @@ def relay_explicitly_disabled() -> bool:
bridge_platform_shared_keys, load_legacy_gateway_json, merge_platform_sections,
)
from hermes_constants import get_hermes_home
-
- cfg = _load_cfg()
+ from hermes_cli.config import read_raw_config
+ from hermes_cli.managed_scope import apply_managed_overlay
+
+ # Do not import gateway.run here: standalone routing must not bootstrap
+ # runtime flags, config-to-env bridges or dotenv. The shared cached reader
+ # resolves the context-local home; the same managed overlay is used by the
+ # runtime loader, without introducing CLI defaults into platform precedence.
+ cfg = apply_managed_overlay(read_raw_config())
data = load_legacy_gateway_json(get_hermes_home())
platforms = merge_platform_sections(cfg, cfg.get("gateway"), data)
gateway = cfg.get("gateway") or {}
diff --git a/tests/gateway/relay/test_cold_opt_out.py b/tests/gateway/relay/test_cold_opt_out.py
new file mode 100644
index 00000000000..fcf7ac768ba
--- /dev/null
+++ b/tests/gateway/relay/test_cold_opt_out.py
@@ -0,0 +1,66 @@
+"""Standalone relay routing must not bootstrap the gateway or reload secrets."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import textwrap
+
+import pytest
+import yaml
+
+
[email protected]("case", ["native", "url-only", "disabled", "managed", "scoped", "scoped-json"])
+def test_cold_fronted_platforms_is_read_only(tmp_path, case):
+ home = tmp_path / "primary"
+ home.mkdir()
+ scoped = tmp_path / "secondary"
+ scoped.mkdir()
+ managed = tmp_path / "managed"
+ managed.mkdir()
+ config = {"platforms": {"relay": {"enabled": True}}}
+ if case == "disabled":
+ config["platforms"]["relay"]["enabled"] = False
+ if case not in {"native", "url-only"}:
+ (home / "config.yaml").write_text(yaml.safe_dump(config))
+ if case == "managed":
+ (managed / "config.yaml").write_text("platforms:\n relay:\n enabled: false\n")
+ if case == "scoped":
+ (scoped / "config.yaml").write_text("platforms:\n relay:\n enabled: false\n")
+ elif case == "scoped-json":
+ (scoped / "gateway.json").write_text(json.dumps({"platforms": {"relay": {"enabled": False}}}))
+ for root in (home, scoped):
+ (root / ".env").write_text("GATEWAY_RELAY_SECRET=dotenv-only-test-secret\n")
+ # Allowlist only: never inherit live credentials, profile selectors, or
+ # pytest's imported modules. HOME and cwd are temporary as well as HERMES_HOME.
+ env = {k: os.environ[k] for k in ("PATH", "SYSTEMROOT", "WINDIR") if k in os.environ}
+ env.update({"HOME": str(tmp_path), "USERPROFILE": str(tmp_path),
+ "HERMES_HOME": str(home), "HERMES_MANAGED_DIR": str(managed),
+ "PYTHONPATH": str(Path(__file__).resolve().parents[3]),
+ "PYTHONDONTWRITEBYTECODE": "1", "PYTHONUTF8": "1"})
+ if case != "native":
+ env.update({"GATEWAY_RELAY_URL": "wss://connector.example/relay",
+ "GATEWAY_RELAY_PLATFORMS": "slack",
+ "GATEWAY_RELAY_SECRET": "inherited-test-secret"})
+ code = textwrap.dedent("""
+ import json, os, sys
+ from hermes_constants import set_hermes_home_override
+ if sys.argv[1].startswith("scoped"):
+ set_hermes_home_override(sys.argv[2])
+ before = dict(os.environ)
+ assert "gateway.run" not in sys.modules
+ from gateway.relay import relay_fronted_platforms
+ fronted = relay_fronted_platforms()
+ changed = {k: [before.get(k), os.environ.get(k)]
+ for k in before.keys() | os.environ.keys()
+ if before.get(k) != os.environ.get(k)}
+ print(json.dumps({"fronted": sorted(fronted),
+ "bootstrapped": "gateway.run" in sys.modules,
+ "changed_env": changed}))
+ """)
+ child = subprocess.run([sys.executable, "-c", code, case, str(scoped)],
+ cwd=tmp_path, env=env, text=True, capture_output=True, timeout=45)
+ assert child.returncode == 0, child.stderr
+ observed = json.loads(child.stdout.splitlines()[-1])
+ assert observed == {"fronted": ["slack"] if case == "url-only" else [],
+ "bootstrapped": False, "changed_env": {}}
diff --git a/tests/gateway/relay/test_explicit_disable.py b/tests/gateway/relay/test_explicit_disable.py
index 651696180e3..ce366e36469 100644
--- a/tests/gateway/relay/test_explicit_disable.py
+++ b/tests/gateway/relay/test_explicit_disable.py
@@ -51,7 +51,10 @@ def configure(home, state, source, monkeypatch):
"slack": {"require_mention": False}}
if state is not None:
cfg["platforms"]["relay"] = {"enabled": state, "extra": {"relay_url": URL}}
- if source == "env":
+ if source == "legacy-json":
+ (home / "gateway.json").write_text(json.dumps({"platforms": cfg.pop("platforms")}))
+ monkeypatch.setenv("GATEWAY_RELAY_URL", URL)
+ elif source == "env":
monkeypatch.setenv("GATEWAY_RELAY_URL", URL)
elif source == "managed":
managed = home / "managed"
@@ -96,7 +99,8 @@ async def test_production_startup_respects_profile_opt_out(profile, monkeypatch,
monkeypatch.setattr(WebSocketRelayTransport, "connect", relay_connect)
monkeypatch.setattr(WebSocketRelayTransport, "handshake", AsyncMock(return_value=descriptor()))
monkeypatch.setattr(RelayAdapter, "_start_revocation_monitor", lambda self: None)
- native = SimpleNamespace(connect=AsyncMock(return_value=True), send_path_degraded=False)
+ native = SimpleNamespace(connect=AsyncMock(return_value=True), send_path_degraded=False,
+ send=AsyncMock(return_value={"success": True}))
# Execute start(), including real relay bootstrap, prefilter, connect and
# aggregation. Suppress only unrelated recovery/watchers/status services.
@@ -152,6 +156,16 @@ async def test_production_startup_respects_profile_opt_out(profile, monkeypatch,
)
assert error is None
assert resolved[1] is runner.config.platforms[Platform.SLACK]
+ # Deliver through the native adapter published by real startup, not just
+ # a helper predicate. Standalone routing above must also remain enabled.
+ resolved, error = _resolve_target_transport(
+ {"id": "native-job"}, Platform.SLACK, "slack", {"chat_id": "channel"},
+ runner.adapters, runner.config,
+ )
+ assert error is None
+ assert not resolved[0].is_relay
+ assert await resolved[0].send(Platform.SLACK, "channel", "native receipt", {}) == {"success": True}
+ native.send.assert_awaited_once_with("channel", "native receipt", metadata={})
else:
assert platform_registry.is_registered("relay")
assert provision.call_count == (0 if pinned else 1)
@@ -173,6 +187,40 @@ async def test_production_startup_respects_profile_opt_out(profile, monkeypatch,
assert "relay-fronted" in error
[email protected]("pinned", [False, True], ids=["unprovisioned", "inherited-secret"])
+async def test_legacy_json_disable_preserves_startup_and_native_delivery(profile, monkeypatch, pinned):
+ await test_production_startup_respects_profile_opt_out(
+ profile, monkeypatch, False, "legacy-json", pinned,
+ )
+
+
[email protected]("yaml_state", ["absent", "empty", "sibling", "enabled"])
[email protected]("disabled", [False, "false"])
+def test_legacy_json_disable_agrees_with_normalized_config(profile, monkeypatch, yaml_state, disabled):
+ (profile / "gateway.json").write_text(json.dumps({"platforms": {
+ "relay": {"enabled": disabled},
+ "slack": {"enabled": True, "token": "native-test-token"},
+ "telegram": {"enabled": False},
+ }}))
+ cfg = {}
+ if yaml_state == "sibling":
+ cfg = {"platforms": {"relay": {"extra": {"relay_url": URL}}}}
+ elif yaml_state == "enabled":
+ cfg = {"platforms": {"relay": {"enabled": True}}}
+ if yaml_state != "absent":
+ (profile / "config.yaml").write_text(yaml.safe_dump(cfg))
+ monkeypatch.setenv("GATEWAY_RELAY_URL", URL)
+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "native-telegram-test-token")
+ # Other legacy platforms keep their existing credential-driven enablement.
+ monkeypatch.setenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS", "true")
+ config = load_gateway_config()
+ assert relay.relay_explicitly_disabled() is (yaml_state != "enabled")
+ assert config.platforms[Platform.RELAY].enabled is (yaml_state == "enabled")
+ assert config.platforms[Platform.SLACK].enabled
+ assert config.platforms[Platform.TELEGRAM].enabled
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("entry", ["url", "provision", "policy", "registration", "forced-registration",
"fronted", "adapter-connect", "adapter-reconnect",