fix(relay): veto the disable at the activation boundary only
Every relay object (adapter, media client, WS transport) is constructed inside the registry factory that register_relay_adapter() installs, and that call plus self_provision_relay()/send_relay_policy() all resolve through relay_url(). So the opt-out has three reachable boundaries: relay_url(), relay_fronted_platforms() (env-sourced, standalone cron) and the force=/url= bypass in register_relay_adapter(). The guards on RelayAdapter.connect, _get_media_client, RelayMediaClient.enabled/download and every WS dial/redial were unreachable unless config flipped on a RUNNING gateway — which the docs in this PR say is unsupported. Half-honoring that flip is worse than not honoring it: inbound kept flowing over the open socket while media downloads silently returned None and the next redial terminated. Drop those five guards, the _RelayDisabled terminal exception they needed, and the legacy-JSON lru_cache that existed only to make a full config merge affordable on the per-message path. The activation-time predicate runs a handful of times per boot; the shared raw-config and managed-scope readers already cache on mtime.
This commit is contained in:
+10
-26
@@ -7,8 +7,6 @@ silently replaced by the nested one. Both overwrite whatever legacy gateway.json
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import copy
|
||||
from functools import lru_cache
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -22,39 +20,25 @@ logger = logging.getLogger("gateway.config")
|
||||
|
||||
|
||||
def load_legacy_gateway_json(home: Path) -> Any:
|
||||
"""Legacy base layer; cache unchanged files, never merged policy or failed reads.
|
||||
|
||||
Return a private copy because platform merging mutates this layer. File identity
|
||||
and ctime also invalidate atomic replacements and same-size timestamp-preserving edits.
|
||||
"""
|
||||
"""Legacy ``gateway.json`` base layer (config.yaml keys always win). Malformed → ``{}`` + warning."""
|
||||
path = home / "gateway.json"
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
st = path.stat()
|
||||
version = (st.st_mtime_ns, st.st_size, st.st_ctime_ns, st.st_dev, st.st_ino)
|
||||
return copy.deepcopy(_read_legacy_gateway_json(path.absolute(), version))
|
||||
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.
|
||||
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:
|
||||
logger.warning("Failed to load %s: %s", path, e)
|
||||
return {}
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def _read_legacy_gateway_json(path: Path, version: tuple) -> Any:
|
||||
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
|
||||
|
||||
|
||||
# --- top-level key bridging ----------------------------------------------------
|
||||
#
|
||||
# Top-level settings are also accepted nested under ``gateway:`` (what ``hermes config set
|
||||
|
||||
@@ -738,11 +738,6 @@ class RelayAdapter(BasePlatformAdapter):
|
||||
|
||||
# ── abstract methods (delegated to the transport) ────────────────────
|
||||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
|
||||
if relay_explicitly_disabled():
|
||||
self._set_fatal_error("relay_disabled", "Relay explicitly disabled in config", retryable=False)
|
||||
return False
|
||||
# ``is_reconnect`` is part of the BasePlatformAdapter.connect contract (the
|
||||
# reconnect watcher passes it; refusing the kwarg would break recovery).
|
||||
# Relay IGNORES it: messages buffered during a gap live in the CONNECTOR's
|
||||
@@ -1702,10 +1697,6 @@ class RelayAdapter(BasePlatformAdapter):
|
||||
"""Lazily build the authenticated /relay/media client from the SAME dial URL and
|
||||
per-gateway creds the WS uses; None when unavailable (media lanes then degrade
|
||||
to their pre-media fallbacks)."""
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
|
||||
if relay_explicitly_disabled():
|
||||
return None
|
||||
if self._media_client is not None:
|
||||
return self._media_client
|
||||
try:
|
||||
|
||||
@@ -60,9 +60,7 @@ class RelayMediaClient:
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
"""True when the client can authenticate (per-gateway creds present)."""
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
|
||||
return bool(self._base_url and self._gateway_id and self._secret) and not relay_explicitly_disabled()
|
||||
return bool(self._base_url and self._gateway_id and self._secret)
|
||||
|
||||
def _bearer(self) -> str:
|
||||
return make_upgrade_token(self._gateway_id, self._secret)
|
||||
@@ -117,9 +115,7 @@ class RelayMediaClient:
|
||||
The bearer is presented only for connector re-host URLs; public URLs
|
||||
(e.g. a Discord CDN pass-through) are fetched without it.
|
||||
"""
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
|
||||
if not url or relay_explicitly_disabled():
|
||||
if not url:
|
||||
return None
|
||||
needs_auth = self.is_relay_media_url(url)
|
||||
if needs_auth and not self.enabled:
|
||||
|
||||
@@ -305,10 +305,6 @@ async def _await_bounded(aw: Awaitable[Any]) -> None:
|
||||
REDIAL_HOLD_MAX_S = 60.0
|
||||
|
||||
|
||||
class _RelayDisabled(RuntimeError):
|
||||
"""Local profile opt-out is terminal, not a transient dial failure."""
|
||||
|
||||
|
||||
class WebSocketRelayTransport:
|
||||
"""RelayTransport over a WebSocket connection the gateway dials to the connector."""
|
||||
|
||||
@@ -412,20 +408,12 @@ class WebSocketRelayTransport:
|
||||
|
||||
# ── lifecycle ────────────────────────────────────────────────────────
|
||||
async def connect(self) -> bool:
|
||||
try:
|
||||
await self._dial_and_start()
|
||||
except _RelayDisabled:
|
||||
return False
|
||||
await self._dial_and_start()
|
||||
return True
|
||||
|
||||
async def _dial_and_start(self) -> None:
|
||||
"""Open the socket, start the reader, send hello(s). Used by connect() and
|
||||
by the reconnect supervisor / fresh-token retry on a re-dial."""
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
|
||||
if relay_explicitly_disabled():
|
||||
logger.info("relay ws disabled by config; not connecting or retrying")
|
||||
raise _RelayDisabled("Relay explicitly disabled in config")
|
||||
self._descriptor_ready = asyncio.get_running_loop().create_future()
|
||||
self._dial_generation += 1
|
||||
# Fresh handshake generation: a reconnected connector re-sends one
|
||||
@@ -835,8 +823,6 @@ class WebSocketRelayTransport:
|
||||
try:
|
||||
await self._dial_and_start()
|
||||
logger.info("relay ws re-dialed with a fresh upgrade token after 4401")
|
||||
except _RelayDisabled:
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - fall back to the backoff supervisor
|
||||
@@ -886,8 +872,6 @@ class WebSocketRelayTransport:
|
||||
await self._dial_and_start()
|
||||
logger.info("relay ws reconnected")
|
||||
return
|
||||
except _RelayDisabled:
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001 - keep retrying on dial failure
|
||||
if self._latch_if_fresh_token_refused(exc):
|
||||
return
|
||||
|
||||
@@ -5,20 +5,17 @@ I/O and unrelated gateway services are replaced. No connector is contacted.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
import gateway.relay as relay
|
||||
from gateway.config import Platform, PlatformConfig, load_gateway_config
|
||||
from gateway.config import Platform, load_gateway_config
|
||||
from gateway.platform_registry import platform_registry
|
||||
from gateway.relay.adapter import RelayAdapter
|
||||
from gateway.relay.descriptor import CapabilityDescriptor, CONTRACT_VERSION
|
||||
from gateway.relay.media import RelayMediaClient
|
||||
from gateway.relay.ws_transport import WebSocketRelayTransport
|
||||
from gateway.run_startup import GatewayStartupMixin
|
||||
|
||||
@@ -291,12 +288,9 @@ def test_managed_layer_agrees_with_native_config(profile, monkeypatch, user_yaml
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("entry", ["url", "provision", "policy", "registration", "forced-registration",
|
||||
"fronted", "adapter-connect", "adapter-reconnect",
|
||||
"transport-connect", "transport-reconnect", "fresh-token", "media-hook",
|
||||
"cached-media-hook", "upload", "download", "public-download"])
|
||||
@pytest.mark.parametrize("entry", ["url", "provision", "policy", "registration", "forced-registration", "fronted"])
|
||||
@pytest.mark.parametrize("spelling", ["top", "nested", "normalized", "legacy-json", "yaml-wins", "gateway-relay", "top-relay", "managed-disable", "sibling-keeps-disable"])
|
||||
async def test_disabled_standalone_paths_have_no_relay_side_effects(profile, monkeypatch, caplog, entry, spelling):
|
||||
async def test_disabled_standalone_paths_have_no_relay_side_effects(profile, monkeypatch, entry, spelling):
|
||||
block = {"enabled": "false" if spelling == "normalized" else False}
|
||||
cfg = {"gateway": {"relay_url": URL}}
|
||||
if spelling == "nested":
|
||||
@@ -330,13 +324,6 @@ async def test_disabled_standalone_paths_have_no_relay_side_effects(profile, mon
|
||||
monkeypatch.setattr("urllib.request.urlopen", http)
|
||||
provision = Mock(return_value={"secret": "b" * 64, "gatewayId": "replaced"})
|
||||
monkeypatch.setattr(relay, "_post_provision", provision)
|
||||
transport = SimpleNamespace(connect=AsyncMock(return_value=True),
|
||||
handshake=AsyncMock(return_value=descriptor()),
|
||||
set_inbound_handler=Mock())
|
||||
adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor(), transport=transport)
|
||||
media = RelayMediaClient("https://connector.example", "shared-gateway", "a" * 64)
|
||||
file = profile / "attachment.txt"
|
||||
file.write_text("attachment", encoding="utf-8")
|
||||
|
||||
if entry == "url":
|
||||
assert relay.relay_url() is None
|
||||
@@ -352,41 +339,6 @@ async def test_disabled_standalone_paths_have_no_relay_side_effects(profile, mon
|
||||
assert not platform_registry.is_registered("relay")
|
||||
elif entry == "fronted":
|
||||
assert relay.relay_fronted_platforms() == set()
|
||||
elif entry in {"adapter-connect", "adapter-reconnect"}:
|
||||
assert await adapter.connect(is_reconnect=entry == "adapter-reconnect") is False
|
||||
transport.connect.assert_not_awaited()
|
||||
transport.set_inbound_handler.assert_not_called()
|
||||
elif entry in {"transport-connect", "transport-reconnect", "fresh-token"}:
|
||||
caplog.set_level(logging.INFO, logger="gateway.relay.ws_transport")
|
||||
ws = WebSocketRelayTransport(URL, "slack", "bot", reconnect_backoff_s=0,
|
||||
gateway_id="shared-gateway", upgrade_secret="a" * 64)
|
||||
dial = AsyncMock()
|
||||
mint = Mock(side_effect=AssertionError("disabled relay minted a token"))
|
||||
monkeypatch.setattr("gateway.relay.auth.make_upgrade_token", mint)
|
||||
monkeypatch.setattr("gateway.relay.ws_transport.websockets.connect", dial)
|
||||
if entry == "transport-connect":
|
||||
assert await ws.connect() is False
|
||||
elif entry == "fresh-token":
|
||||
await asyncio.wait_for(ws._redial_with_fresh_token(), timeout=2)
|
||||
else:
|
||||
await asyncio.wait_for(ws._reconnect_loop(), timeout=2)
|
||||
dial.assert_not_awaited()
|
||||
mint.assert_not_called()
|
||||
assert ws._reader is None
|
||||
assert ws._supervisor is None
|
||||
assert ws._dial_generation == 0
|
||||
assert [(r.levelno, r.message) for r in caplog.records
|
||||
if r.name == "gateway.relay.ws_transport"] == [
|
||||
(logging.INFO, "relay ws disabled by config; not connecting or retrying")]
|
||||
elif entry in {"media-hook", "cached-media-hook"}:
|
||||
if entry == "cached-media-hook":
|
||||
adapter._media_client = media
|
||||
assert adapter._get_media_client() is None
|
||||
elif entry == "upload":
|
||||
assert await media.upload(str(file)) is None
|
||||
else:
|
||||
url = "https://connector.example/relay/media/id" if entry == "download" else "https://cdn.example/file"
|
||||
assert await media.download(url) is None
|
||||
|
||||
http.assert_not_called()
|
||||
provision.assert_not_called()
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
"""Legacy disk caching must never become a cached relay policy decision."""
|
||||
import builtins
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from gateway.config_loader import load_legacy_gateway_json
|
||||
from gateway.relay import relay_explicitly_disabled
|
||||
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
|
||||
|
||||
|
||||
def test_legacy_reads_are_reused_without_stale_policy(tmp_path, monkeypatch, caplog):
|
||||
home = tmp_path / "primary"
|
||||
other = tmp_path / "secondary"
|
||||
managed = tmp_path / "managed"
|
||||
for directory in (home, other, managed):
|
||||
directory.mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))
|
||||
legacy = home / "gateway.json"
|
||||
disabled = json.dumps({"platforms": {"relay": {"enabled": False}}})
|
||||
enabled = json.dumps({"platforms": {"relay": {"enabled": True}}})
|
||||
actual_open = builtins.open
|
||||
opens = []
|
||||
|
||||
def count_open(file, *args, **kwargs):
|
||||
if Path(file).name == "gateway.json":
|
||||
opens.append(Path(file))
|
||||
return actual_open(file, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "open", count_open)
|
||||
caplog.set_level(logging.INFO, logger="gateway.config")
|
||||
assert not relay_explicitly_disabled() # An absent file must not be cached.
|
||||
legacy.write_text(disabled, encoding="utf-8")
|
||||
for _ in range(10):
|
||||
assert relay_explicitly_disabled()
|
||||
assert opens == [legacy]
|
||||
assert len([r for r in caplog.records if "Loaded legacy" in r.message]) == 1
|
||||
|
||||
# Both the marker-bearing parse and nested data belong to each caller.
|
||||
loaded = load_legacy_gateway_json(home)
|
||||
loaded["platforms"]["relay"]["enabled"] = True
|
||||
loaded["platforms"]["relay"]["extra"]["_enabled_explicit"] = False
|
||||
assert relay_explicitly_disabled()
|
||||
assert load_legacy_gateway_json(home)["platforms"]["relay"]["extra"]["_enabled_explicit"]
|
||||
|
||||
(other / "gateway.json").write_text(enabled, encoding="utf-8")
|
||||
token = set_hermes_home_override(other)
|
||||
try:
|
||||
assert not relay_explicitly_disabled()
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
assert relay_explicitly_disabled()
|
||||
assert opens == [legacy, other / "gateway.json"]
|
||||
|
||||
# User and managed policy are recomposed even on a legacy cache hit.
|
||||
user = home / "config.yaml"
|
||||
user.write_text("platforms:\n relay:\n enabled: true\n", encoding="utf-8")
|
||||
assert not relay_explicitly_disabled()
|
||||
overlay = managed / "config.yaml"
|
||||
overlay.write_text("platforms:\n relay:\n enabled: ${CACHE_TEST_RELAY}\n", encoding="utf-8")
|
||||
monkeypatch.setenv("CACHE_TEST_RELAY", "false")
|
||||
assert relay_explicitly_disabled()
|
||||
monkeypatch.setenv("CACHE_TEST_RELAY", "true")
|
||||
assert not relay_explicitly_disabled()
|
||||
overlay.write_text("platforms:\n relay:\n enabled: false\n", encoding="utf-8")
|
||||
assert relay_explicitly_disabled()
|
||||
overlay.unlink()
|
||||
assert not relay_explicitly_disabled()
|
||||
user.unlink()
|
||||
assert relay_explicitly_disabled()
|
||||
assert opens == [legacy, other / "gateway.json"]
|
||||
|
||||
legacy.write_text(enabled, encoding="utf-8")
|
||||
assert not relay_explicitly_disabled()
|
||||
# Atomic replacement must invalidate even with equal mtime and byte length.
|
||||
replacement = home / "replacement.json"
|
||||
replacement.write_text(disabled, encoding="utf-8")
|
||||
replacement.replace(legacy)
|
||||
assert relay_explicitly_disabled()
|
||||
stat = legacy.stat()
|
||||
replacement.write_text(enabled + " ", encoding="utf-8")
|
||||
os.utime(replacement, ns=(stat.st_atime_ns, stat.st_mtime_ns))
|
||||
assert replacement.stat().st_size == stat.st_size
|
||||
replacement.replace(legacy)
|
||||
assert not relay_explicitly_disabled()
|
||||
legacy.unlink()
|
||||
assert not relay_explicitly_disabled()
|
||||
legacy.write_text(disabled, encoding="utf-8")
|
||||
assert relay_explicitly_disabled()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid", ["malformed", "unreadable"])
|
||||
def test_failed_legacy_reads_warn_and_recover(tmp_path, monkeypatch, caplog, invalid):
|
||||
legacy = tmp_path / "gateway.json"
|
||||
valid = json.dumps({"platforms": {"relay": {"enabled": False}}})
|
||||
legacy.write_text(valid, encoding="utf-8")
|
||||
assert load_legacy_gateway_json(tmp_path)["platforms"]["relay"]["enabled"] is False
|
||||
caplog.set_level(logging.WARNING, logger="gateway.config")
|
||||
actual_open = builtins.open
|
||||
unreadable = invalid == "unreadable"
|
||||
attempts = []
|
||||
|
||||
def read(file, *args, **kwargs):
|
||||
if Path(file) == legacy:
|
||||
attempts.append(file)
|
||||
if unreadable:
|
||||
raise PermissionError("synthetic unreadable legacy file")
|
||||
return actual_open(file, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "open", read)
|
||||
legacy.write_text("{" if invalid == "malformed" else valid + " ", encoding="utf-8")
|
||||
for _ in range(2):
|
||||
assert load_legacy_gateway_json(tmp_path) == {}
|
||||
assert len(attempts) == 2
|
||||
assert len([r for r in caplog.records if "Failed to load" in r.message]) == 2
|
||||
unreadable = False
|
||||
# A different recovered value proves we did not resurrect the old parse.
|
||||
legacy.write_text(json.dumps({"platforms": {"relay": {"enabled": True}}}), encoding="utf-8")
|
||||
assert load_legacy_gateway_json(tmp_path)["platforms"]["relay"]["enabled"] is True
|
||||
assert load_legacy_gateway_json(tmp_path)["platforms"]["relay"]["enabled"] is True
|
||||
assert len(attempts) == 3
|
||||
Reference in New Issue
Block a user