The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): honor explicit profile disable before automatic relay activity
Victor Kyriazakos9c576fc69dc1
diff --git a/gateway/config_env.py b/gateway/config_env.pyindex a1e80ec0be2..b5cf0c5e0e2 100644--- a/gateway/config_env.py+++ b/gateway/config_env.py@@ -450,7 +450,11 @@ def _relay(config: GatewayConfig) -> None:relay_url_yaml = str(existing_relay.extra.get("relay_url") or "").strip() if existing_relay else ""relay_url_val = relay_url_env or relay_url_yamlif relay_url_val:- _enable_from_env(config, Platform.RELAY).extra["relay_url"] = relay_url_val.rstrip("/")+ relay_config = _enable_from_env(config, Platform.RELAY)+ relay_config.extra["relay_url"] = relay_url_val.rstrip("/")+ # An opted-out relay does not own this profile's native connections.+ if not relay_config.enabled:+ returnif not relay_url_env or is_truthy_value(getenv("GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS")):returndiff --git a/gateway/relay/__init__.py b/gateway/relay/__init__.pyindex 2366cf943cf..14cc29b68a1 100644--- a/gateway/relay/__init__.py+++ b/gateway/relay/__init__.py@@ -6,7 +6,8 @@ hands it at handshake, and the production ``WebSocketRelayTransport``. The publiAPI MAY CHANGE without a deprecation cycle until >=2 real Class-1 platforms haveshaken out the schema (``docs/relay-connector-contract.md``). Activation isconfig-driven: the relay platform is registered when a connector relay URL is set-(``GATEWAY_RELAY_URL`` env or ``gateway.relay_url``), like ``gateway.proxy_url``.+(``GATEWAY_RELAY_URL`` env or ``gateway.relay_url``), like ``gateway.proxy_url``,+unless the effective relay platform configuration explicitly disables it."""from __future__ import annotations@@ -69,8 +70,39 @@ def _env_or_cfg_url(env_var: str, cfg_key: str) -> Optional[str]:return _env_or_cfg(env_var, cfg_key).rstrip("/") or None+def relay_explicitly_disabled() -> bool:+ """The profile's normalized opt-out, before any URL/credential activation.++ Reuse the gateway's platform merge and boolean normalization without running+ its env/plugin side effects. Absence is not a disable: URL-only deployments+ predate the platform flag. The raw loader includes managed configuration.+ """+ from gateway.config import Platform, PlatformConfig+ from gateway.config_loader import (+ bridge_platform_shared_keys, load_legacy_gateway_json, merge_platform_sections,+ )+ from hermes_constants import get_hermes_home++ cfg = _load_cfg()+ data = load_legacy_gateway_json(get_hermes_home())+ platforms = merge_platform_sections(cfg, cfg.get("gateway"), data)+ gateway = cfg.get("gateway") or {}+ bridge_platform_shared_keys(+ cfg, gateway.get("platforms") if isinstance(gateway, dict) else None,+ data, platforms, [Platform.RELAY],+ )+ block = platforms.get("relay")+ return (+ isinstance(block, dict)+ and "enabled" in block+ and not PlatformConfig.from_dict(block).enabled+ )++def relay_url() -> Optional[str]:- """The connector relay endpoint URL, or None. A non-empty value activates the relay platform."""+ """Effective connector URL; an explicit platform disable vetoes even an env URL."""+ if relay_explicitly_disabled():+ return Nonereturn _env_or_cfg_url("GATEWAY_RELAY_URL", "relay_url")@@ -97,6 +129,8 @@ def relay_fronted_platforms() -> set[str]:Same env source the live adapter's identity set comes from, so config-timevalidation (cron delivery preflight) and fire-time routing can never disagree —and it needs no live adapter, so a standalone scheduler can use it."""+ if relay_explicitly_disabled():+ return set()return {p for p, _ in relay_platform_identities() if p != "relay"}@@ -591,9 +625,12 @@ def send_relay_policy() -> bool:def register_relay_adapter(force: bool = False, url: Optional[str] = None) -> bool:"""Register the generic ``relay`` platform when a relay URL is configured (or- ``force=True`` for tests: transport-less adapter). Returns True if registered.+ ``force=True`` for tests: transport-less adapter). Neither overrides an+ explicit profile disable. Returns True if registered.With a URL the factory builds a live ``WebSocketRelayTransport``; the adapternegotiates the real ``CapabilityDescriptor`` at ``connect()``."""+ if relay_explicitly_disabled():+ return Falseresolved_url = url if url is not None else relay_url()if not (force or resolved_url):return Falsediff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 111959bb32c..b2ac6d753a6 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -738,6 +738,11 @@ 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@@ -1697,6 +1702,10 @@ class RelayAdapter(BasePlatformAdapter):"""Lazily build the authenticated /relay/media client from the SAME dial URL andper-gateway creds the WS uses; None when unavailable (media lanes then degradeto their pre-media fallbacks)."""+ from gateway.relay import relay_explicitly_disabled++ if relay_explicitly_disabled():+ return Noneif self._media_client is not None:return self._media_clienttry:diff --git a/gateway/relay/media.py b/gateway/relay/media.pyindex 4b957f41659..0045424f143 100644--- a/gateway/relay/media.py+++ b/gateway/relay/media.py@@ -60,7 +60,9 @@ class RelayMediaClient:@propertydef enabled(self) -> bool:"""True when the client can authenticate (per-gateway creds present)."""- return bool(self._base_url and self._gateway_id and self._secret)+ from gateway.relay import relay_explicitly_disabled++ return bool(self._base_url and self._gateway_id and self._secret) and not relay_explicitly_disabled()def _bearer(self) -> str:return make_upgrade_token(self._gateway_id, self._secret)@@ -115,7 +117,9 @@ 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."""- if not url:+ from gateway.relay import relay_explicitly_disabled++ if not url or relay_explicitly_disabled():return Noneneeds_auth = self.is_relay_media_url(url)if needs_auth and not self.enabled:diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex f6bdaa97d5b..55ea2bcf5ca 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -305,6 +305,10 @@ 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."""@@ -408,12 +412,19 @@ class WebSocketRelayTransport:# ── lifecycle ────────────────────────────────────────────────────────async def connect(self) -> bool:- await self._dial_and_start()+ try:+ await self._dial_and_start()+ except _RelayDisabled:+ return Falsereturn Trueasync def _dial_and_start(self) -> None:"""Open the socket, start the reader, send hello(s). Used by connect() andby the reconnect supervisor / fresh-token retry on a re-dial."""+ from gateway.relay import relay_explicitly_disabled++ if relay_explicitly_disabled():+ 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@@ -823,6 +834,8 @@ class WebSocketRelayTransport:try:await self._dial_and_start()logger.info("relay ws re-dialed with a fresh upgrade token after 4401")+ except _RelayDisabled:+ returnexcept asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 - fall back to the backoff supervisor@@ -872,6 +885,8 @@ class WebSocketRelayTransport:await self._dial_and_start()logger.info("relay ws reconnected")return+ except _RelayDisabled:+ returnexcept Exception as exc: # noqa: BLE001 - keep retrying on dial failureif self._latch_if_fresh_token_refused(exc):returndiff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 29fd2c252fd..47f02b3141c 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -869,7 +869,8 @@ class GatewayStartupMixin:with _log_suppressed(logging.WARNING, "plugin discovery failed at gateway startup", exc_info=True):from hermes_cli.plugins import discover_pluginsdiscover_plugins()- # Generic relay adapter only if GATEWAY_RELAY_URL / gateway.relay_url is set; no URL -> no-op.+ # Relay entrypoints share the effective profile opt-out, including when a+ # deployment injects a URL. No URL or explicitly disabled -> no side effects.try:from gateway.relay import (register_relay_adapter, relay_url, self_provision_relay, send_relay_policydiff --git a/tests/gateway/relay/test_explicit_disable.py b/tests/gateway/relay/test_explicit_disable.pynew file mode 100644index 00000000000..651696180e3--- /dev/null+++ b/tests/gateway/relay/test_explicit_disable.py@@ -0,0 +1,267 @@+"""Explicit relay opt-out must dominate ambient deployment credentials.++Real profile files and production startup/standalone entrypoints; only external+I/O and unrelated gateway services are replaced. No connector is contacted.+"""+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+import json+import os++import pytest+import yaml++import gateway.relay as relay+from gateway.config import Platform, PlatformConfig, 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++URL = "wss://connector.example/relay"+CREDENTIALS = {+ "GATEWAY_RELAY_ID": "shared-gateway",+ "GATEWAY_RELAY_INSTANCE_ID": "shared-instance",+ "GATEWAY_RELAY_DELIVERY_KEY": "inherited-delivery-key",+}+++def profile(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ # Keep the runtime loader on the same real profile as load_gateway_config.+ monkeypatch.setattr("gateway.run._hermes_home", tmp_path)+ for key in list(os.environ):+ if key.startswith("GATEWAY_RELAY_"):+ monkeypatch.delenv(key)+ for key, value in CREDENTIALS.items():+ monkeypatch.setenv(key, value)+ monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", "slack")+ monkeypatch.setattr("hermes_cli.plugins.discover_plugins", lambda: None)+ monkeypatch.setattr(GatewayStartupMixin, "_register_config_hooks", lambda *a, **k: None)+ platform_registry.unregister("relay")+ yield tmp_path+ platform_registry.unregister("relay")+++def configure(home, state, source, monkeypatch):+ cfg = {"platforms": {"slack": {"enabled": True, "token": "native-test-token"}},+ "slack": {"require_mention": False}}+ if state is not None:+ cfg["platforms"]["relay"] = {"enabled": state, "extra": {"relay_url": URL}}+ if source == "env":+ monkeypatch.setenv("GATEWAY_RELAY_URL", URL)+ elif source == "managed":+ managed = home / "managed"+ managed.mkdir()+ (managed / "config.yaml").write_text(yaml.safe_dump({"gateway": {"relay_url": URL}}))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ else:+ cfg["gateway"] = {"relay_url": URL}+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")+++def descriptor():+ return CapabilityDescriptor(contract_version=CONTRACT_VERSION, platform="slack",+ label="Relay", max_message_length=4096,+ supports_draft_streaming=False, supports_edit=True,+ supports_threads=False, markdown_dialect="plain", len_unit="chars")++[email protected]("state", [False, True, None], ids=["disabled", "enabled", "legacy"])[email protected]("source", ["yaml", "env", "managed"])[email protected]("pinned", [False, True], ids=["unprovisioned", "inherited-secret"])+async def test_production_startup_respects_profile_opt_out(profile, monkeypatch, state, source, pinned):+ configure(profile, state, source, monkeypatch)+ if state is True:+ # The winning top-level enable must override a lower-priority disable.+ path = profile / "config.yaml"+ cfg = yaml.safe_load(path.read_text())+ cfg.setdefault("gateway", {})["platforms"] = {"relay": {"enabled": False}}+ path.write_text(yaml.safe_dump(cfg))+ if pinned:+ monkeypatch.setenv("GATEWAY_RELAY_SECRET", "a" * 64)+ before = {k: v for k, v in os.environ.items() if k.startswith("GATEWAY_RELAY_")}+ token = Mock(return_value="identity-token")+ provision = Mock(return_value={"gatewayId": "provisioned-gateway", "secret": "b" * 64,+ "deliveryKey": "new-delivery-key"})+ policy = Mock(return_value=200)+ monkeypatch.setattr(relay, "_resolve_relay_identity_token", token)+ monkeypatch.setattr(relay, "_post_provision", provision)+ monkeypatch.setattr(relay, "_post_policy", policy)+ relay_connect = AsyncMock(return_value=True)+ 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)++ # Execute start(), including real relay bootstrap, prefilter, connect and+ # aggregation. Suppress only unrelated recovery/watchers/status services.+ runner = GatewayStartupMixin()+ runner.config = load_gateway_config()+ runner.adapters = {}+ runner._failed_platforms = {}+ runner.delivery_router = SimpleNamespace(adapters={})+ for name in ("_start_install_faulthandler", "_start_log_startup_environment",+ "_start_startup_warmup", "_wire_adapter_handlers", "_update_platform_runtime_status",+ "_wire_teams_pipeline_runtime", "_install_plugin_message_injector",+ "_update_runtime_status", "_start_spawn_background_watchers"):+ monkeypatch.setattr(runner, name, Mock(), raising=False)+ runner._start_check_access_policy = lambda: False+ runner._abort_startup_if_shutdown_requested = AsyncMock(return_value=False)+ runner._multiplex_on = lambda: False+ runner._startup_should_abort = lambda: False++ async def recover():+ runner._start_register_plugins_relay_hooks()++ async def connect(adapter, platform):+ return await adapter.connect()++ async def secondary(count, skipped):+ return False, count++ runner._start_recover_previous_run = recover+ runner._connect_initial_adapter_with_timeout = connect+ runner._start_secondary_profiles = secondary+ runner._start_finish_wiring = AsyncMock()+ runner._start_handle_no_connections = lambda *args: False+ runner._publish_primary_adapter = lambda p, a: runner.adapters.__setitem__(p, a)+ runner._create_adapter = lambda p, c: (platform_registry.create_adapter("relay", c)+ if p == Platform.RELAY else native)+ assert await runner.start() is True++ if state is False:+ token.assert_not_called()+ provision.assert_not_called()+ policy.assert_not_called()+ relay_connect.assert_not_awaited()+ assert not platform_registry.is_registered("relay")+ assert Platform.RELAY not in runner.adapters+ assert Platform.RELAY not in runner._failed_platforms+ assert {k: v for k, v in os.environ.items() if k.startswith("GATEWAY_RELAY_")} == before+ native.connect.assert_awaited_once()+ assert runner.adapters[Platform.SLACK] is native+ from cron.scheduler_delivery import _resolve_target_transport++ resolved, error = _resolve_target_transport(+ {"id": "native-job"}, Platform.SLACK, "slack", {"chat_id": "channel"}, {}, runner.config,+ )+ assert error is None+ assert resolved[1] is runner.config.platforms[Platform.SLACK]+ else:+ assert platform_registry.is_registered("relay")+ assert provision.call_count == (0 if pinned else 1)+ assert token.call_count == provision.call_count+ policy.assert_called_once()+ # Existing env-exclusive behavior is unchanged. YAML activation is additive.+ assert native.connect.await_count == (0 if source == "env" else 1)+ # The env path already auto-enables relay in the platform loader.+ if source == "env" or state is True:+ relay_connect.assert_awaited_once()+ assert Platform.RELAY in runner.adapters+ if source == "env":+ from cron.scheduler_delivery import _resolve_target_transport++ resolved, error = _resolve_target_transport(+ {"id": "relay-job"}, Platform.SLACK, "slack", {"chat_id": "channel"}, {}, runner.config,+ )+ assert resolved is None+ assert "relay-fronted" in error++[email protected]("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"])[email protected]("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, entry, spelling):+ block = {"enabled": "false" if spelling == "normalized" else False}+ cfg = {"gateway": {"relay_url": URL}}+ if spelling == "nested":+ cfg["gateway"]["platforms"] = {"relay": block}+ elif spelling == "gateway-relay":+ cfg["gateway"]["relay"] = block+ cfg["platforms"] = {"relay": {"enabled": True}}+ elif spelling == "top-relay":+ cfg["relay"] = block+ cfg["gateway"]["relay"] = {"enabled": True}+ elif spelling == "legacy-json":+ (profile / "gateway.json").write_text(json.dumps({"platforms": {"relay": block}}))+ elif spelling == "managed-disable":+ cfg["platforms"] = {"relay": {"enabled": True}}+ managed = profile / "managed"+ managed.mkdir()+ (managed / "config.yaml").write_text(yaml.safe_dump({"platforms": {"relay": block}}))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))+ elif spelling == "sibling-keeps-disable":+ cfg["gateway"]["platforms"] = {"relay": block}+ cfg["platforms"] = {"relay": {"extra": {"relay_url": URL}}}+ else:+ cfg["platforms"] = {"relay": block}+ if spelling == "yaml-wins":+ cfg["gateway"]["platforms"] = {"relay": {"enabled": True}}+ (profile / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")+ monkeypatch.setenv("GATEWAY_RELAY_URL", URL)+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://identity.example/token")+ before = {k: v for k, v in os.environ.items() if k.startswith("GATEWAY_RELAY_")}+ http = Mock(side_effect=AssertionError("disabled relay attempted HTTP"))+ 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+ elif entry == "provision":+ assert relay.self_provision_relay() is False+ elif entry == "policy":+ monkeypatch.setenv("GATEWAY_RELAY_SECRET", "a" * 64)+ before["GATEWAY_RELAY_SECRET"] = "a" * 64+ monkeypatch.setenv("SLACK_ALLOW_BOTS", "all")+ assert relay.send_relay_policy() is False+ elif entry in {"registration", "forced-registration"}:+ assert relay.register_relay_adapter(url=URL, force=entry == "forced-registration") is False+ 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"}:+ ws = WebSocketRelayTransport(URL, "slack", "bot", reconnect_backoff_s=0)+ dial = AsyncMock()+ monkeypatch.setattr("gateway.relay.ws_transport.websockets.connect", dial)+ if entry == "transport-connect":+ assert await ws.connect() is False+ elif entry == "fresh-token":+ await ws._redial_with_fresh_token()+ else:+ await ws._reconnect_loop()+ dial.assert_not_awaited()+ assert ws._reader is None+ assert ws._supervisor is None+ 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()+ assert {k: v for k, v in os.environ.items() if k.startswith("GATEWAY_RELAY_")} == beforediff --git a/website/docs/user-guide/messaging/relay.md b/website/docs/user-guide/messaging/relay.mdindex d12ae3edc56..8767cfdece2 100644--- a/website/docs/user-guide/messaging/relay.md+++ b/website/docs/user-guide/messaging/relay.md@@ -96,12 +96,34 @@ environment.## Configuration-Relay activates when a connector relay URL is configured — there is no-separate feature flag. Deployments that don't set it are unaffected.+Relay activation remains URL-based for compatibility, unless the effective+platform configuration explicitly disables it:++```yaml+platforms:+ relay:+ enabled: false+```++- **Explicit disable wins.** `enabled: false` prevents automatic identity-token+ resolution, provisioning, credential mutation, registration, policy calls,+ connection attempts, reconnects, and relay media handling, even with an+ injected `gateway.relay_url` or `GATEWAY_RELAY_URL`.+- **Native platforms remain available.** A disabled relay does not suppress+ native messaging adapters or claim standalone delivery destinations through+ inherited relay identity variables. Inherited credentials are left unchanged.+- **Existing activation is preserved.** `enabled: true` still requires a+ connector URL. Omitting `enabled` keeps the existing URL-based behavior.++The decision uses the gateway's merged platform configuration, including managed+settings and supported nested platform sections. Restart the gateway after+changing this setting. This is not a live teardown mechanism for an already-open+socket. The explicit `hermes gateway enroll` command remains available while+runtime relay is disabled.| Setting | Where | Meaning ||---------|-------|---------|-| `GATEWAY_RELAY_URL` | env (`~/.hermes/.env`) | Connector relay WebSocket URL. Presence enables the relay platform. |+| `GATEWAY_RELAY_URL` | env (`~/.hermes/.env`) | Connector relay WebSocket URL. Enables relay unless explicitly disabled in platform configuration. || `gateway.relay_url` | `config.yaml` | Same as above, config-file form (env takes precedence). || `GATEWAY_RELAY_ID` | env | This gateway instance's id (written by `enroll`). || `GATEWAY_RELAY_SECRET` | env | Per-gateway secret authenticating the WebSocket upgrade (written by `enroll`). |