From 5583f316a7171c1b705ee48a9a65d1311e4e8686 Mon Sep 17 00:00:00 2001 From: ManniBr Date: Thu, 2 Jul 2026 20:41:30 +0800 Subject: [PATCH 1/2] fix(gateway): isolate multiplexed profile routing Route secondary-profile gateway turns through the owning profile adapter and runtime scope, including streaming/progress delivery paths. Add multiplex regression coverage for served profiles, credential isolation and Private Supervisor Telegram routing. Tests: uv run --with pytest --with pytest-asyncio --with pyyaml pytest tests/gateway/test_multiplex_adapter_registry.py tests/hermes_cli/test_profiles.py::TestProfilesToServe tests/gateway/test_multiplex_phase0.py::TestMultiplexConfigFlag tests/gateway/test_multiplex_http_routing.py tests/gateway/test_multiplex_credential_isolation.py tests/gateway/test_multiplex_profile_authz.py -o addopts='' -q --- gateway/authz_mixin.py | 3 +- gateway/config.py | 127 ++++++-- gateway/platforms/webhook.py | 9 +- gateway/run.py | 169 ++++++----- hermes_cli/profiles.py | 30 +- .../test_multiplex_adapter_registry.py | 272 +++++++++++++++++- .../test_multiplex_credential_isolation.py | 17 ++ tests/gateway/test_multiplex_http_routing.py | 4 +- tests/gateway/test_multiplex_phase0.py | 21 +- tests/gateway/test_multiplex_profile_authz.py | 28 +- tests/hermes_cli/test_profiles.py | 13 + 11 files changed, 582 insertions(+), 111 deletions(-) diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py index 86984913372b..ab910a37a213 100644 --- a/gateway/authz_mixin.py +++ b/gateway/authz_mixin.py @@ -47,10 +47,11 @@ def _authorization_adapter( if not platform: return None profile_name = (profile or "").strip() or None - if profile_name: + if profile_name and profile_name != "default": profile_adapters = getattr(self, "_profile_adapters", None) or {} if profile_name in profile_adapters: return profile_adapters[profile_name].get(platform) + return None adapters = getattr(self, "adapters", None) or {} return adapters.get(platform) diff --git a/gateway/config.py b/gateway/config.py index 7693cef1c27e..19ab47beaab7 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -22,6 +22,27 @@ logger = logging.getLogger(__name__) +def _scoped_env(name: str, default: Optional[str] = None) -> Optional[str]: + """Read a profile-scoped env/secret value when a secret scope is active. + + The multiplexed gateway keeps secondary-profile ``.env`` values out of + process-global ``os.environ``. Gateway config loading therefore must use the + active secret scope for profile credentials such as Telegram bot tokens, + while preserving legacy ``os.getenv`` behaviour for the default profile and + non-multiplexed callers. + """ + try: + from agent.secret_scope import UnscopedSecretError, get_secret + except Exception: + val = os.environ.get(name) + return val if val is not None else default + try: + return get_secret(name, default) + except UnscopedSecretError: + val = os.environ.get(name) + return val if val is not None else default + + def _coerce_bool(value: Any, default: bool = True) -> bool: """Coerce bool-ish config values, preserving a caller-provided default.""" if value is None: @@ -110,6 +131,59 @@ def _normalize_notice_delivery(value: Any, default: str = "public") -> str: return default +def _coerce_profile_allowlist(value: Any) -> List[str]: + """Normalize gateway multiplexer profile allowlist values. + + The allowlist is intentionally fail-closed: malformed values are ignored + rather than causing a fallback to broad profile enumeration. ``default`` is + always served by the owning gateway and is therefore omitted from the + secondary-profile allowlist. + """ + if value is None: + return [] + if isinstance(value, str): + raw_items: list[Any] = [] + for chunk in value.replace("\n", ",").split(","): + raw_items.extend(part for part in chunk.split() if part) + elif isinstance(value, (list, tuple, set)): + raw_items = list(value) + else: + logger.warning( + "Ignoring invalid gateway.multiplex_profile_allowlist=%r " + "(expected list or comma-separated string)", + value, + ) + return [] + + try: + from hermes_cli.profiles import normalize_profile_name, validate_profile_name + except Exception: + logger.warning("Could not import profile validators for multiplexer allowlist") + return [] + + names: List[str] = [] + seen: set[str] = set() + for item in raw_items: + if not isinstance(item, str): + logger.warning( + "Ignoring invalid profile allowlist item %r (expected string)", + item, + ) + continue + try: + name = normalize_profile_name(item) + validate_profile_name(name) + except Exception as exc: + logger.warning("Ignoring invalid profile allowlist item %r: %s", item, exc) + continue + if name == "default": + continue + if name not in seen: + names.append(name) + seen.add(name) + return names + + def _ensure_platform_extra_dict(platforms_data: dict, name: str) -> tuple[dict, dict]: """Get-or-create ``platforms_data[name]`` and its nested ``extra`` dict. @@ -610,11 +684,13 @@ class GatewayConfig: max_concurrent_sessions: Optional[int] = None # Positive int caps simultaneous active chat sessions # Multi-profile multiplexing (opt-in; default off preserves one-gateway-per-profile). - # When True, the default profile's gateway serves inbound messages for every - # profile on the host: profiles are stamped into session keys and (in later - # phases) per-profile adapters/credentials are resolved. When False, the - # gateway behaves exactly as before — single HERMES_HOME, no profile stamping. + # When True, the default profile's gateway serves inbound messages for the + # explicitly allowlisted profiles on the host. Profiles are stamped into + # session keys and per-profile adapters/credentials are resolved. When + # False, the gateway behaves exactly as before — single HERMES_HOME, no + # profile stamping. An empty allowlist is fail-closed (default only). multiplex_profiles: bool = False + multiplex_profile_allowlist: List[str] = field(default_factory=list) # Unauthorized DM policy unauthorized_dm_behavior: str = "pair" # "pair" or "ignore" @@ -730,6 +806,7 @@ def to_dict(self) -> Dict[str, Any]: "thread_sessions_per_user": self.thread_sessions_per_user, "max_concurrent_sessions": self.max_concurrent_sessions, "multiplex_profiles": self.multiplex_profiles, + "multiplex_profile_allowlist": list(self.multiplex_profile_allowlist), "unauthorized_dm_behavior": self.unauthorized_dm_behavior, "streaming": self.streaming.to_dict(), "session_store_max_age_days": self.session_store_max_age_days, @@ -781,6 +858,11 @@ def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig": # Also honor gateway.multiplex_profiles written by # ``hermes config set gateway.multiplex_profiles true``. multiplex_profiles = nested_gateway.get("multiplex_profiles") + multiplex_profile_allowlist = data.get("multiplex_profile_allowlist") + if multiplex_profile_allowlist is None and isinstance(nested_gateway, dict): + multiplex_profile_allowlist = nested_gateway.get( + "multiplex_profile_allowlist" + ) if "max_concurrent_sessions" in data: max_concurrent_raw = data.get("max_concurrent_sessions") max_concurrent_key = "max_concurrent_sessions" @@ -818,6 +900,9 @@ def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig": group_sessions_per_user=_coerce_bool(group_sessions_per_user, True), thread_sessions_per_user=_coerce_bool(thread_sessions_per_user, False), multiplex_profiles=_coerce_bool(multiplex_profiles, False), + multiplex_profile_allowlist=_coerce_profile_allowlist( + multiplex_profile_allowlist + ), max_concurrent_sessions=max_concurrent_sessions, unauthorized_dm_behavior=unauthorized_dm_behavior, streaming=StreamingConfig.from_dict(data.get("streaming", {})), @@ -924,15 +1009,25 @@ def load_gateway_config() -> GatewayConfig: if "thread_sessions_per_user" in yaml_cfg: gw_data["thread_sessions_per_user"] = yaml_cfg["thread_sessions_per_user"] - # Multiplexing flag: accept both the top-level key and the nested - # gateway.multiplex_profiles form (from_dict resolves the nested - # fallback, but surface the top-level key here for parity with the - # other session-scope flags above). + # Multiplexing settings: accept both top-level legacy keys and the + # nested gateway.* form written by `hermes config set gateway.*`. + gateway_section = yaml_cfg.get("gateway") + if not isinstance(gateway_section, dict): + gateway_section = {} if "multiplex_profiles" in yaml_cfg: gw_data["multiplex_profiles"] = yaml_cfg["multiplex_profiles"] + elif "multiplex_profiles" in gateway_section: + gw_data["multiplex_profiles"] = gateway_section["multiplex_profiles"] + if "multiplex_profile_allowlist" in yaml_cfg: + gw_data["multiplex_profile_allowlist"] = yaml_cfg[ + "multiplex_profile_allowlist" + ] + elif "multiplex_profile_allowlist" in gateway_section: + gw_data["multiplex_profile_allowlist"] = gateway_section[ + "multiplex_profile_allowlist" + ] - gateway_section = yaml_cfg.get("gateway") - if isinstance(gateway_section, dict) and "max_concurrent_sessions" in gateway_section: + if "max_concurrent_sessions" in gateway_section: gw_data["max_concurrent_sessions"] = gateway_section["max_concurrent_sessions"] if "max_concurrent_sessions" in yaml_cfg: @@ -1329,19 +1424,19 @@ def _enable_from_env(platform: Platform) -> PlatformConfig: return platform_config # Telegram - telegram_token = os.getenv("TELEGRAM_BOT_TOKEN") + telegram_token = _scoped_env("TELEGRAM_BOT_TOKEN") if telegram_token: telegram_config = _enable_from_env(Platform.TELEGRAM) telegram_config.token = telegram_token # Reply threading mode for Telegram (off/first/all) - telegram_reply_mode = os.getenv("TELEGRAM_REPLY_TO_MODE", "").lower() + telegram_reply_mode = (_scoped_env("TELEGRAM_REPLY_TO_MODE", "") or "").lower() if telegram_reply_mode in {"off", "first", "all"}: if Platform.TELEGRAM not in config.platforms: config.platforms[Platform.TELEGRAM] = PlatformConfig() config.platforms[Platform.TELEGRAM].reply_to_mode = telegram_reply_mode - telegram_fallback_ips = os.getenv("TELEGRAM_FALLBACK_IPS", "") + telegram_fallback_ips = _scoped_env("TELEGRAM_FALLBACK_IPS", "") or "" if telegram_fallback_ips: if Platform.TELEGRAM not in config.platforms: config.platforms[Platform.TELEGRAM] = PlatformConfig() @@ -1349,13 +1444,13 @@ def _enable_from_env(platform: Platform) -> PlatformConfig: ip.strip() for ip in telegram_fallback_ips.split(",") if ip.strip() ] - telegram_home = os.getenv("TELEGRAM_HOME_CHANNEL") + telegram_home = _scoped_env("TELEGRAM_HOME_CHANNEL") if telegram_home and Platform.TELEGRAM in config.platforms: config.platforms[Platform.TELEGRAM].home_channel = HomeChannel( platform=Platform.TELEGRAM, chat_id=telegram_home, - name=os.getenv("TELEGRAM_HOME_CHANNEL_NAME", "Home"), - thread_id=os.getenv("TELEGRAM_HOME_CHANNEL_THREAD_ID") or None, + name=_scoped_env("TELEGRAM_HOME_CHANNEL_NAME", "Home") or "Home", + thread_id=_scoped_env("TELEGRAM_HOME_CHANNEL_THREAD_ID") or None, ) # Discord diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py index 51e93c8a7a9f..6a466b51ebb6 100644 --- a/gateway/platforms/webhook.py +++ b/gateway/platforms/webhook.py @@ -432,7 +432,14 @@ def _resolve_request_profile(self, request: "web.Request"): return None try: from hermes_cli.profiles import profiles_to_serve - served = {name for name, _ in profiles_to_serve(multiplex=True)} + allowlist = getattr(cfg, "multiplex_profile_allowlist", None) + served = { + name + for name, _ in profiles_to_serve( + multiplex=True, + allowlist=allowlist, + ) + } except Exception: return _PROFILE_REJECTED if profile not in served: diff --git a/gateway/run.py b/gateway/run.py index ed257607fe80..36e6b0c18fac 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -1344,9 +1344,9 @@ def _current_max_iterations() -> int: # Platforms that bind a host TCP port (HTTP/webhook listeners). In a profile # multiplexer the default profile owns the single shared listener and serves # every profile through the /p// URL prefix, so a SECONDARY profile -# enabling one of these is always a misconfiguration: it would try to bind a -# port already held by the default's listener. We hard-error on it rather than -# silently dropping the adapter (see _start_one_profile_adapters). +# enabling one of these must not bind its own port. Suppress these adapters on +# secondary profiles rather than failing startup: the default listener remains +# the single owner for those surfaces. # Stored as platform .value strings since the Platform enum is imported below. _PORT_BINDING_PLATFORM_VALUES = frozenset({ "webhook", @@ -1358,6 +1358,13 @@ def _current_max_iterations() -> int: "sms", }) +# Additional single-owner / local-bridge adapters that should only run from the +# primary gateway process. Telegram is intentionally NOT included here; each +# served profile may have its own distinct bot token and polling adapter. +_SECONDARY_SUPPRESSED_PLATFORM_VALUES = _PORT_BINDING_PLATFORM_VALUES | frozenset({ + "signal", +}) + class MultiplexConfigError(RuntimeError): """A profile multiplexer config is invalid (fail-fast at startup). @@ -6225,7 +6232,7 @@ async def _drain_startup_restore_queue(self) -> int: while queue: event = queue.pop(0) source = getattr(event, "source", None) - adapter = self.adapters.get(source.platform) if source is not None else None + adapter = self._adapter_for_source(source) if source is not None else None if adapter is None: logger.debug( "Dropping startup-restore queued message: adapter unavailable for %s", @@ -6331,7 +6338,7 @@ def _schedule_resume_pending_sessions(self, platform=None) -> int: continue source = entry.origin - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter is None: logger.debug( "Skipping auto-resume for %s: adapter not ready for %s", @@ -8195,7 +8202,11 @@ async def _start_secondary_profile_adapters(self) -> int: if fp is not None: claimed[(_plat, fp)] = active - for profile_name, profile_home in profiles_to_serve(multiplex=True): + allowlist = getattr(self.config, "multiplex_profile_allowlist", None) + for profile_name, profile_home in profiles_to_serve( + multiplex=True, + allowlist=allowlist, + ): if profile_name == active: continue # handled by the primary startup loop try: @@ -8245,21 +8256,18 @@ async def _start_one_profile_adapters( for platform, platform_config in profile_cfg.platforms.items(): if not platform_config.enabled: continue - # A secondary profile must NOT enable a port-binding platform: the - # default profile's listener already serves every profile via the - # /p// prefix, so a second bind can only collide. This is a - # config error, not a transient failure — fail fast and loud. - if platform.value in _PORT_BINDING_PLATFORM_VALUES: - raise MultiplexConfigError( - f"Profile '{profile_name}' enables the port-binding platform " - f"'{platform.value}', but gateway.multiplex_profiles is on. The " - f"default profile owns the single shared HTTP listener and " - f"serves every profile through the /p/{profile_name}/ URL " - f"prefix — a secondary profile cannot bind its own port. " - f"Remove platforms.{platform.value} from profile " - f"'{profile_name}'s config.yaml (configure it only on the " - f"default profile)." + # Secondary profiles must not bind host ports or start singleton + # local-bridge adapters. The default gateway owns those shared + # surfaces while profile-scoped chat adapters (Telegram, etc.) may + # still connect under their own credentials. + if platform.value in _SECONDARY_SUPPRESSED_PLATFORM_VALUES: + logger.info( + "Skipping %s adapter for secondary profile '%s' " + "(owned by default gateway)", + platform.value, + profile_name, ) + continue with _profile_runtime_scope(profile_home): adapter = self._create_adapter(platform, platform_config) if not adapter: @@ -8284,7 +8292,7 @@ async def _start_one_profile_adapters( # Stamp every inbound event from this adapter with its profile so # the agent turn (and session key) resolve to the right home. adapter.set_message_handler( - self._make_profile_message_handler(profile_name) + self._make_profile_message_handler(profile_name, profile_home) ) adapter.set_fatal_error_handler(self._handle_adapter_fatal_error) adapter.set_session_store(self.session_store) @@ -8308,15 +8316,27 @@ async def _start_one_profile_adapters( await self._safe_adapter_disconnect(adapter, platform) return connected - def _make_profile_message_handler(self, profile_name: str): - """Return a message handler that stamps source.profile then delegates.""" + def _make_profile_message_handler(self, profile_name: str, profile_home: "Path | str | None" = None): + """Return a secondary-profile handler with profile-scoped runtime. + + The adapter is authoritative for the profile it serves: inbound events + from a secondary bot must not keep a stale/default ``source.profile``. + Run the delegated handler under the routed profile's HERMES_HOME and + secret scope so commands, config, skills, memory, and provider keys all + resolve to that profile instead of the default gateway process. + """ + _profile_home = Path(profile_home) if profile_home is not None else None + async def _handler(event): try: - if getattr(event, "source", None) is not None and not event.source.profile: + if getattr(event, "source", None) is not None: event.source.profile = profile_name except Exception: pass - return await self._handle_message(event) + if _profile_home is None: + return await self._handle_message(event) + with _profile_runtime_scope(_profile_home): + return await self._handle_message(event) return _handler @staticmethod @@ -8334,6 +8354,11 @@ def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]: if isinstance(val, str) and val.strip(): token = val.strip() break + if not token: + cfg = getattr(adapter, "config", None) + val = getattr(cfg, "token", None) + if isinstance(val, str) and val.strip(): + token = val.strip() if not token: return None import hashlib @@ -8498,7 +8523,7 @@ def check( async def _deliver_platform_notice(self, source, content: str) -> None: """Deliver a setup/operational notice using platform-specific privacy rules.""" - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: return @@ -8973,7 +8998,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: has_media = bool(getattr(event, "media_urls", None)) if not queued_text and not has_media: return "Usage: /queue " - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=queued_text, @@ -8994,7 +9019,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: timestamp=event.timestamp, ) self._enqueue_fifo(_quick_key, queued_event, adapter) - depth = self._queue_depth(_quick_key, adapter=self.adapters.get(source.platform)) + depth = self._queue_depth(_quick_key, adapter=self._adapter_for_source(source)) if depth <= 1: return "Queued for the next turn." return f"Queued for the next turn. ({depth} queued)" @@ -9011,7 +9036,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: running_agent = self._running_agents.get(_quick_key) if running_agent is _AGENT_PENDING_SENTINEL: # Agent hasn't started yet — queue as turn-boundary fallback. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=steer_text, @@ -9033,7 +9058,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: return f"⏩ Steer queued — arrives after the next tool call: '{preview}'" return "Steer rejected (empty payload)." # Running agent is missing or lacks steer() — fall back to queue. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: queued_event = MessageEvent( text=steer_text, @@ -9158,7 +9183,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: if event.message_type == MessageType.PHOTO: logger.debug("PRIORITY photo follow-up for session %s — queueing without interrupt", _quick_key) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: merge_pending_message_event(adapter._pending_messages, _quick_key, event) return None @@ -9179,7 +9204,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: time.time() - _started_at, _quick_key, ) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: if self._busy_input_mode == "queue": self._enqueue_fifo(_quick_key, event, adapter) @@ -9202,7 +9227,7 @@ async def _handle_message(self, event: MessageEvent) -> Optional[str]: return EphemeralReply("⚡ Force-stopped. The agent was still starting — session unlocked.") # Queue the message so it will be picked up after the # agent starts. - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: merge_pending_message_event( adapter._pending_messages, @@ -9441,7 +9466,7 @@ async def _do_reset(): else "Learning a skill from this conversation…" ) try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: _ack_meta = self._thread_metadata_for_source(source) await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta) @@ -9495,7 +9520,7 @@ async def _do_reset(): _ack = getattr(_blueprint_result, "text", "") or "" if _ack: try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: _ack_meta = self._thread_metadata_for_source(source) await adapter.send(str(source.chat_id), _ack, metadata=_ack_meta) @@ -10062,7 +10087,7 @@ async def _prepare_inbound_message_text( # before the agent loop runs. Lets the user verify STT quality # in real-time and see the raw whisper output verbatim. if _successful_transcripts: - _echo_adapter = self.adapters.get(source.platform) + _echo_adapter = self._adapter_for_source(source) _echo_meta = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)) if _echo_adapter: for _tx in _successful_transcripts: @@ -10236,7 +10261,7 @@ async def _prepare_inbound_message_text( allowed_root=_msg_cwd, ) if _ctx_result.blocked: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: await _adapter.send( source.chat_id, @@ -10470,7 +10495,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g and platform_name not in policy.notify_exclude_platforms ) if should_notify: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter: if reset_reason == "suspended": reason_text = "previous session was stopped or interrupted" @@ -10858,7 +10883,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g "configuration." ) try: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter and source.chat_id: await _adapter.send(source.chat_id, _warn_msg, metadata=_hyg_meta) except Exception as _werr: @@ -10882,7 +10907,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g "check `auxiliary.compression.model` in config.yaml." ) try: - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter and source.chat_id: await _adapter.send(source.chat_id, _aux_msg, metadata=_hyg_meta) except Exception as _werr: @@ -11038,7 +11063,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # event so deferred post-delivery callbacks can be released by the # same run that registered them. self._bind_adapter_run_generation( - self.adapters.get(source.platform), + self._adapter_for_source(source), session_key, run_generation, ) @@ -11078,7 +11103,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # Stop persistent typing indicator now that the agent is done try: - _typing_adapter = self.adapters.get(source.platform) + _typing_adapter = self._adapter_for_source(source) if _typing_adapter and hasattr(_typing_adapter, "stop_typing"): await _typing_adapter.stop_typing(source.chat_id) except Exception: @@ -11090,7 +11115,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g _quick_key or "?", run_generation, ) - _stale_adapter = self.adapters.get(source.platform) + _stale_adapter = self._adapter_for_source(source) if getattr(type(_stale_adapter), "pop_post_delivery_callback", None) is not None: _stale_adapter.pop_post_delivery_callback( _quick_key, @@ -11595,7 +11620,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # users see the agent "stop responding without explanation." if agent_result.get("already_sent") and not agent_result.get("failed"): if response: - _media_adapter = self.adapters.get(source.platform) + _media_adapter = self._adapter_for_source(source) if _media_adapter: await self._deliver_media_from_response( response, event, _media_adapter, @@ -11606,7 +11631,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g # still surface the runtime metadata on the final reply. if _footer_line: try: - _foot_adapter = self.adapters.get(source.platform) + _foot_adapter = self._adapter_for_source(source) if _foot_adapter: await _foot_adapter.send( source.chat_id, @@ -11622,7 +11647,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g except Exception as e: # Stop typing indicator on error too try: - _err_adapter = self.adapters.get(source.platform) + _err_adapter = self._adapter_for_source(source) if _err_adapter and hasattr(_err_adapter, "stop_typing"): await _err_adapter.stop_typing(source.chat_id) except Exception: @@ -12127,7 +12152,7 @@ def _get_goal_manager_for_event(self, event: "MessageEvent"): async def _send_goal_status_notice(self, source: Any, message: str) -> None: """Send a /goal judge status line back to the originating chat/thread.""" - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None)) return @@ -12154,7 +12179,7 @@ async def _defer_goal_status_notice_after_delivery(self, source: Any, message: s exactly this boundary; when unavailable, fall back to direct awaited delivery rather than silently dropping the notice. """ - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.debug("goal continuation: no adapter for %s", getattr(source, "platform", None)) return @@ -12252,7 +12277,7 @@ async def _post_turn_goal_continuation( # Enqueue via the adapter's FIFO so a user message already in # flight preempts the continuation naturally. try: - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) _quick_key = self._session_key_for_source(source) if adapter and _quick_key: cont_event = MessageEvent( @@ -12750,7 +12775,7 @@ async def _run_background_task( media_urls = media_urls or [] media_types = media_types or [] - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: logger.warning("No adapter for platform %s in background task %s", source.platform, task_id) return @@ -12945,7 +12970,7 @@ def run_sync(): async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict: """Read Telegram private-topic capability flags via Bot API getMe.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None bot = getattr(adapter, "_bot", None) if bot is None or not hasattr(bot, "get_me"): return {"checked": False} @@ -12973,7 +12998,7 @@ def _field(name: str): async def _ensure_telegram_system_topic(self, source: SessionSource) -> None: """Create/pin the managed System topic after /topic activation when possible.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None if adapter is None or not source.chat_id: return @@ -13014,7 +13039,7 @@ async def _ensure_telegram_system_topic(self, source: SessionSource) -> None: async def _send_telegram_topic_setup_image(self, source: SessionSource) -> None: """Send the bundled BotFather Threads Settings screenshot when available.""" - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None if adapter is None or not source.chat_id or not hasattr(adapter, "send_image_file"): return image_path = Path(__file__).resolve().parent / "assets" / "telegram-botfather-threads-settings.jpg" @@ -13066,7 +13091,7 @@ async def _rename_telegram_topic_for_session_title( # Check the class, not the instance — getattr() on MagicMock # auto-creates attributes, so `hasattr(adapter, "_get_dm_topic_info")` # would return True for every test double. - adapter = self.adapters.get(source.platform) if getattr(self, "adapters", None) else None + adapter = self._adapter_for_source(source) if getattr(self, "adapters", None) else None if adapter is not None: get_info = getattr(type(adapter), "_get_dm_topic_info", None) if callable(get_info): @@ -13625,7 +13650,7 @@ async def _request_slash_confirm( # cannot race the send_slash_confirm return. _slash_confirm_mod.register(session_key, confirm_id, command, handler) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)) used_buttons = False @@ -14602,7 +14627,7 @@ async def _dequeue_pending_with_transcription( # Echo raw transcripts back to the user so voice interrupts # feel identical to fresh voice messages. if successful_transcripts: - echo_adapter = self.adapters.get(source.platform) + echo_adapter = self._adapter_for_source(source) echo_meta = {"thread_id": source.thread_id} if source.thread_id else None if echo_adapter: for tx in successful_transcripts: @@ -15415,7 +15440,7 @@ async def _interrupt_and_clear_session( if running_agent and running_agent is not _AGENT_PENDING_SENTINEL: running_agent.interrupt(interrupt_reason) self._invalidate_session_run_generation(session_key, reason=invalidation_reason) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter and hasattr(adapter, "interrupt_session_activity"): await adapter.interrupt_session_activity(session_key, source.chat_id) if adapter and hasattr(adapter, "get_pending_message"): @@ -15869,7 +15894,7 @@ def _run_still_current() -> bool: if _streaming_enabled: try: from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: _pause_typing_before_finalize = None if source.platform == Platform.TELEGRAM and hasattr(_adapter, "pause_typing_for_chat"): @@ -15920,7 +15945,7 @@ def _pause_typing_before_finalize( stream_task = asyncio.create_task(_stream_consumer.run()) # Send typing indicator - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: try: await _adapter.send_typing(source.chat_id, metadata=_thread_metadata) @@ -16319,7 +16344,7 @@ def voice_ack_callback(call_id, tool_name, args): _cleanup_progress = bool( resolve_display_setting(user_config, platform_key, "cleanup_progress") ) - _cleanup_adapter = self.adapters.get(source.platform) if _cleanup_progress else None + _cleanup_adapter = self._adapter_for_source(source) if _cleanup_progress else None if _cleanup_adapter is not None and ( type(_cleanup_adapter).delete_message is BasePlatformAdapter.delete_message ): @@ -16440,7 +16465,7 @@ def progress_callback(event_type: str, tool_name: str = None, preview: str = Non _code_block_full = None _code_block_short = None try: - _progress_adapter = self.adapters.get(source.platform) + _progress_adapter = self._adapter_for_source(source) except Exception: _progress_adapter = None if ( @@ -16630,7 +16655,7 @@ async def send_progress_messages(): if not progress_queue: return - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if not adapter: return @@ -17005,7 +17030,7 @@ def _event_callback_sync(event_type: str, context: dict) -> None: logger.debug("event_callback hook error: %s", _e) # Bridge sync status_callback → async adapter.send for context pressure - _status_adapter = self.adapters.get(source.platform) + _status_adapter = self._adapter_for_source(source) _status_chat_id = source.chat_id if source.platform == Platform.FEISHU and source.thread_id and event_message_id: # Feishu topics only keep messages inside the topic when they are @@ -17151,7 +17176,7 @@ def run_sync(): if _want_stream_deltas or _want_interim_consumer: try: from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if _adapter: _pause_typing_before_finalize = None if source.platform == Platform.TELEGRAM and hasattr(_adapter, "pause_typing_for_chat"): @@ -18318,7 +18343,7 @@ async def monitor_for_interrupt(): try: # Re-resolve adapter each iteration so reconnects don't # leave us holding a stale reference. - _adapter = self.adapters.get(source.platform) + _adapter = self._adapter_for_source(source) if not _adapter: continue # Check if adapter has a pending interrupt for this session. @@ -18415,7 +18440,7 @@ async def monitor_for_interrupt(): async def _notify_long_running(): if _NOTIFY_INTERVAL is None: return # Notifications disabled (gateway_notify_interval: 0) - _notify_adapter = self.adapters.get(source.platform) + _notify_adapter = self._adapter_for_source(source) if not _notify_adapter: return # Track the heartbeat message id so we can edit-in-place on @@ -18556,7 +18581,7 @@ def _stream_confirmed_final_delivery( # Backup interrupt check: if the monitor task died or # missed the interrupt, catch it here. if not _interrupt_detected.is_set() and session_key: - _backup_adapter = self.adapters.get(source.platform) + _backup_adapter = self._adapter_for_source(source) _backup_agent = agent_holder[0] if (_backup_adapter and _backup_agent and hasattr(_backup_adapter, 'has_pending_interrupt') @@ -18596,7 +18621,7 @@ def _stream_confirmed_final_delivery( if (not _warning_fired and _agent_warning is not None and _idle_secs >= _agent_warning): _warning_fired = True - _warn_adapter = self.adapters.get(source.platform) + _warn_adapter = self._adapter_for_source(source) if _warn_adapter: _elapsed_warn = int(_agent_warning // 60) or 1 _remaining_mins = int((_agent_timeout - _agent_warning) // 60) or 1 @@ -18616,7 +18641,7 @@ def _stream_confirmed_final_delivery( break # Backup interrupt check (same as unlimited path). if not _interrupt_detected.is_set() and session_key: - _backup_adapter = self.adapters.get(source.platform) + _backup_adapter = self._adapter_for_source(source) _backup_agent = agent_holder[0] if (_backup_adapter and _backup_agent and hasattr(_backup_adapter, 'has_pending_interrupt') @@ -18733,7 +18758,7 @@ def _stream_confirmed_final_delivery( # Check if we were interrupted OR have a queued message (/queue). result = result_holder[0] - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) # Get pending message from adapter. # Use session_key (not source.chat_id) to match adapter's storage keys. @@ -18864,7 +18889,7 @@ def _stream_confirmed_final_delivery( "queueing message instead of recursing.", _interrupt_depth, session_key, ) - adapter = self.adapters.get(source.platform) + adapter = self._adapter_for_source(source) if adapter and pending_event: merge_pending_message_event(adapter._pending_messages, session_key, pending_event) elif adapter and hasattr(adapter, 'queue_message'): @@ -18968,7 +18993,7 @@ def _stream_confirmed_final_delivery( # Restart typing indicator so the user sees activity while # the follow-up turn runs. The outer _process_message_background # typing task is still alive but may be stale. - _followup_adapter = self.adapters.get(source.platform) + _followup_adapter = self._adapter_for_source(source) if _followup_adapter: try: await _followup_adapter.send_typing( diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py index 7f7f3b262e5a..1cceaa2f71fb 100644 --- a/hermes_cli/profiles.py +++ b/hermes_cli/profiles.py @@ -927,7 +927,10 @@ def list_profiles() -> List[ProfileInfo]: return profiles -def profiles_to_serve(multiplex: bool) -> List[Tuple[str, Path]]: +def profiles_to_serve( + multiplex: bool, + allowlist: Optional[List[str]] = None, +) -> List[Tuple[str, Path]]: """Return the ``(profile_name, hermes_home)`` pairs a gateway should serve. This is the single chokepoint for "which profiles does the inbound gateway @@ -937,8 +940,13 @@ def profiles_to_serve(multiplex: bool) -> List[Tuple[str, Path]]: profile — byte-for-byte the single-profile behavior the gateway has always had. The name is ``"default"`` for the default profile or the active named profile's id. - - ``multiplex=True``: returns the default profile plus every valid named - profile under ``profiles/``, each paired with its own HERMES_HOME. + - ``multiplex=True, allowlist=None``: returns the default profile plus every + valid named profile under ``profiles/``, each paired with its own + HERMES_HOME. This preserves the original broad-enumeration helper + behaviour for callers/tests that deliberately want it. + - ``multiplex=True, allowlist=[...]``: returns the default profile plus only + the valid, existing named profiles in the allowlist. An empty allowlist is + fail-closed and returns only default. Intentionally lightweight (a directory scan + name validation only): no per-profile config reads, gateway-running probes, or skill counts like @@ -953,6 +961,22 @@ def profiles_to_serve(multiplex: bool) -> List[Tuple[str, Path]]: serve: List[Tuple[str, Path]] = [("default", _get_default_hermes_home())] + if allowlist is not None: + seen: set[str] = {"default"} + for raw in allowlist: + try: + name = normalize_profile_name(str(raw)) + validate_profile_name(name) + except Exception: + continue + if name in seen: + continue + profile_dir = get_profile_dir(name) + if profile_dir.is_dir(): + serve.append((name, profile_dir)) + seen.add(name) + return serve + profiles_root = _get_profiles_root() if profiles_root.is_dir(): for entry in sorted(profiles_root.iterdir()): diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.py index 7ecca64dfee0..c43a00a0b277 100644 --- a/tests/gateway/test_multiplex_adapter_registry.py +++ b/tests/gateway/test_multiplex_adapter_registry.py @@ -1,4 +1,12 @@ """Phase 3: secondary-profile adapter registry + same-token conflict detection.""" +from pathlib import Path +import asyncio +import sys +import threading +import types +from types import SimpleNamespace +from unittest.mock import AsyncMock + import pytest from gateway.run import GatewayRunner @@ -32,6 +40,15 @@ def __init__(self): self.bot_token = "alt-token" assert GatewayRunner._adapter_credential_fingerprint(_AltAdapter()) is not None + def test_reads_config_token(self): + class _Cfg: + token = "config-token" + + class _ConfigAdapter: + config = _Cfg() + + assert GatewayRunner._adapter_credential_fingerprint(_ConfigAdapter()) is not None + class TestProfileMessageHandler: @pytest.mark.asyncio @@ -57,7 +74,7 @@ class _Evt: assert seen["profile"] == "coder" @pytest.mark.asyncio - async def test_does_not_override_existing_profile(self): + async def test_overrides_existing_profile_from_secondary_adapter(self): runner = GatewayRunner.__new__(GatewayRunner) seen = {} @@ -69,21 +86,224 @@ async def _fake_handle(event): handler = runner._make_profile_message_handler("coder") class _Src: - profile = "writer" # already stamped (e.g. by URL prefix) + profile = "default" # stale process/default profile on adapter event class _Evt: source = _Src() await handler(_Evt()) - assert seen["profile"] == "writer" + assert seen["profile"] == "coder" + + @pytest.mark.asyncio + async def test_runs_delegated_handler_under_profile_home(self, tmp_path, monkeypatch): + from hermes_constants import get_hermes_home + + default_home = tmp_path / "default" + profile_home = tmp_path / "profiles" / "coder" + default_home.mkdir(parents=True) + profile_home.mkdir(parents=True) + (profile_home / ".env").write_text("TELEGRAM_BOT_TOKEN=profile-token\n", encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(default_home)) + + runner = GatewayRunner.__new__(GatewayRunner) + seen = {} + + async def _fake_handle(event): + seen["profile"] = event.source.profile + seen["home"] = Path(get_hermes_home()) + return "ok" + + runner._handle_message = _fake_handle + handler = runner._make_profile_message_handler("coder", profile_home) + + class _Src: + profile = "default" + + class _Evt: + source = _Src() + + result = await handler(_Evt()) + assert result == "ok" + assert seen == {"profile": "coder", "home": profile_home} -class TestPortBindingHardError: - """A secondary profile enabling a port-binding platform aborts startup.""" +class TestProfileOutboundAdapterSelection: + @pytest.mark.asyncio + async def test_streaming_turn_uses_profile_owned_adapter(self, monkeypatch): + """Streaming delivery must not borrow the default same-platform adapter.""" + import gateway.run as gateway_run + from gateway.config import GatewayConfig, Platform, StreamingConfig + from gateway.session import SessionSource + + class _Adapter: + SUPPORTS_MESSAGE_EDITING = True + MAX_MESSAGE_LENGTH = 4096 + + def __init__(self, name): + self.name = name + self._pending_messages = {} + self.typing_calls = 0 + + def message_len_fn(self, text): + return len(text) + + def get_pending_message(self, _session_key): + return None + + def has_pending_interrupt(self, _session_key): + return False + + async def send_typing(self, *_args, **_kwargs): + self.typing_calls += 1 + + def register_post_delivery_callback(self, *_args, **_kwargs): + pass + + def pause_typing_for_chat(self, *_args, **_kwargs): + pass + + class _StreamConsumer: + instances = [] + + def __init__(self, *, adapter, **_kwargs): + self.adapter = adapter + self.deltas = [] + self.final_response_sent = False + self.final_content_delivered = False + self._done = False + self.instances.append(self) + + async def run(self): + while not self._done: + await asyncio.sleep(0.01) + + def on_delta(self, text): + self.deltas.append(text) + self.final_response_sent = True + self.final_content_delivered = True + + def on_commentary(self, text): + self.on_delta(text) + + def on_segment_break(self): + pass + + def finish(self): + self._done = True + + class _Agent: + def __init__(self, **kwargs): + self.session_id = kwargs["session_id"] + self.model = kwargs["model"] + self.tools = [] + self.context_compressor = SimpleNamespace( + last_prompt_tokens=12, + context_length=4096, + ) + self.session_prompt_tokens = 12 + self.session_completion_tokens = 3 + self.stream_delta_callback = None + self.interim_assistant_callback = None + self.tool_progress_callback = None + self.status_callback = None + self.notice_callback = None + self.notice_clear_callback = None + self.event_callback = None + self.background_review_callback = None + self.clarify_callback = None + self.gateway_approval_callback = None + self.reasoning_config = None + self.service_tier = None + self.request_overrides = {} + + def run_conversation(self, user_message, conversation_history=None, **_kwargs): + if self.stream_delta_callback: + self.stream_delta_callback("hello") + return { + "final_response": "hello", + "messages": [ + {"role": "user", "content": user_message}, + {"role": "assistant", "content": "hello"}, + ], + "api_calls": 1, + "completed": True, + "history_offset": len(conversation_history or []), + } + + def interrupt(self, *_args, **_kwargs): + pass + + fake_run_agent = types.ModuleType("run_agent") + fake_run_agent.AIAgent = _Agent + monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent) + monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "0") + monkeypatch.setattr(gateway_run, "_load_gateway_config", lambda: { + "display": {"tool_progress": "off", "interim_assistant_messages": False}, + }) + monkeypatch.setattr("gateway.stream_consumer.GatewayStreamConsumer", _StreamConsumer) + + import hermes_cli.tools_config as tools_config + monkeypatch.setattr(tools_config, "_get_platform_tools", lambda *_args, **_kwargs: {"core"}) + + default_adapter = _Adapter("default") + profile_adapter = _Adapter("private-supervisor") + runner = object.__new__(gateway_run.GatewayRunner) + runner.adapters = {Platform.TELEGRAM: default_adapter} + runner._profile_adapters = {"private-supervisor": {Platform.TELEGRAM: profile_adapter}} + runner.config = GatewayConfig(multiplex_profiles=True) + runner.config.streaming = StreamingConfig(enabled=True, transport="edit", edit_interval=0.01) + runner.hooks = SimpleNamespace(loaded_hooks=False, emit=AsyncMock()) + runner.session_store = SimpleNamespace(_entries={}) + runner._session_db = None + runner._agent_cache = {} + runner._agent_cache_lock = threading.Lock() + runner._running_agents = {} + runner._running_agents_ts = {} + runner._session_run_generation = {} + runner._session_model_overrides = {} + runner._pending_model_notes = {} + runner._pending_skills_reload_notes = {} + runner._prefill_messages = [] + runner._ephemeral_system_prompt = "" + runner._reasoning_config = None + runner._provider_routing = {} + runner._fallback_model = None + runner._draining = False + runner._resolve_session_agent_runtime = lambda **_kwargs: ("test-model", {"api_key": "token"}) + runner._resolve_session_reasoning_config = lambda **_kwargs: None + runner._resolve_turn_agent_config = lambda message, model, runtime: {"model": model, "runtime": runtime} + runner._load_service_tier = lambda: None + runner._agent_config_signature = lambda *_args, **_kwargs: ("sig",) + runner._extract_cache_busting_config = lambda _config: () + runner._thread_metadata_for_source = lambda *_args, **_kwargs: None + + source = SessionSource( + platform=Platform.TELEGRAM, + chat_id="12345", + chat_type="dm", + user_id="u1", + profile="private-supervisor", + ) + + result = await runner._run_agent_inner( + message="hi", + context_prompt="", + history=[], + source=source, + session_id="sid", + session_key="agent:private-supervisor:telegram:dm:12345", + ) + + assert result["final_response"] == "hello" + assert _StreamConsumer.instances + assert _StreamConsumer.instances[0].adapter is profile_adapter + + +class TestSecondarySuppressedAdapters: + """Secondary profiles skip listener/singleton adapters and keep startup alive.""" @pytest.mark.asyncio - async def test_secondary_webhook_raises(self, monkeypatch): - from gateway.run import MultiplexConfigError + async def test_secondary_webhook_skipped(self, monkeypatch): from gateway.config import GatewayConfig, Platform, PlatformConfig runner = GatewayRunner.__new__(GatewayRunner) @@ -98,11 +318,34 @@ async def test_secondary_webhook_raises(self, monkeypatch): monkeypatch.setattr( "gateway.config.load_gateway_config", lambda: reviewer_cfg ) + created = [] + monkeypatch.setattr(runner, "_create_adapter", lambda p, c: created.append(p)) + + connected = await runner._start_one_profile_adapters("reviewer", "/tmp/x", {}) + assert connected == 0 + assert created == [] + + @pytest.mark.asyncio + async def test_secondary_signal_skipped(self, monkeypatch): + from gateway.config import GatewayConfig, Platform, PlatformConfig - with pytest.raises(MultiplexConfigError) as ei: - await runner._start_one_profile_adapters("reviewer", "/tmp/x", {}) - assert "webhook" in str(ei.value) - assert "reviewer" in str(ei.value) + runner = GatewayRunner.__new__(GatewayRunner) + runner.config = GatewayConfig(multiplex_profiles=True) + runner._profile_adapters = {} + + reviewer_cfg = GatewayConfig(multiplex_profiles=True) + reviewer_cfg.platforms = { + Platform.SIGNAL: PlatformConfig(enabled=True, extra={"http_url": "http://127.0.0.1:8080"}), + } + monkeypatch.setattr( + "gateway.config.load_gateway_config", lambda: reviewer_cfg + ) + created = [] + monkeypatch.setattr(runner, "_create_adapter", lambda p, c: created.append(p)) + + connected = await runner._start_one_profile_adapters("reviewer", "/tmp/x", {}) + assert connected == 0 + assert created == [] @pytest.mark.asyncio async def test_secondary_non_binding_platform_ok(self, monkeypatch): @@ -127,10 +370,11 @@ async def test_secondary_non_binding_platform_ok(self, monkeypatch): connected = await runner._start_one_profile_adapters("reviewer", "/tmp/x", {}) assert connected == 0 # nothing connected, but no MultiplexConfigError - def test_port_binding_set_covers_known_listeners(self): - from gateway.run import _PORT_BINDING_PLATFORM_VALUES + def test_suppressed_set_covers_known_listeners(self): + from gateway.run import _SECONDARY_SUPPRESSED_PLATFORM_VALUES # Every adapter that binds a TCP port must be in the guard set. for p in ("webhook", "api_server", "msgraph_webhook", "feishu", "wecom_callback", "bluebubbles", "sms"): - assert p in _PORT_BINDING_PLATFORM_VALUES + assert p in _SECONDARY_SUPPRESSED_PLATFORM_VALUES + assert "signal" in _SECONDARY_SUPPRESSED_PLATFORM_VALUES diff --git a/tests/gateway/test_multiplex_credential_isolation.py b/tests/gateway/test_multiplex_credential_isolation.py index 7659efc39840..8b1b265b59a8 100644 --- a/tests/gateway/test_multiplex_credential_isolation.py +++ b/tests/gateway/test_multiplex_credential_isolation.py @@ -63,6 +63,23 @@ def test_getenv_global_var_still_reads_environ(self, monkeypatch): assert _getenv("HERMES_MAX_ITERATIONS") == "42" +class TestGatewayConfigUsesScope: + """Gateway platform credentials must use the active profile secret scope.""" + + def test_telegram_token_reads_scope(self, monkeypatch): + from gateway.config import Platform, load_gateway_config + + monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "default-token") + ss.set_multiplex_active(True) + tok = ss.set_secret_scope({"TELEGRAM_BOT_TOKEN": "profile-token"}) + try: + cfg = load_gateway_config() + finally: + ss.reset_secret_scope(tok) + + assert cfg.platforms[Platform.TELEGRAM].token == "profile-token" + + class TestMcpInterpolationUsesScope: """MCP config ${VAR} interpolation resolves through the secret scope.""" diff --git a/tests/gateway/test_multiplex_http_routing.py b/tests/gateway/test_multiplex_http_routing.py index e144030c3512..25c6043e7a89 100644 --- a/tests/gateway/test_multiplex_http_routing.py +++ b/tests/gateway/test_multiplex_http_routing.py @@ -60,7 +60,7 @@ def test_known_profile_accepted(self, monkeypatch): adapter, Req, _REJ, served = self._adapter(multiplex=True) monkeypatch.setattr( "hermes_cli.profiles.profiles_to_serve", - lambda multiplex: [(n, None) for n in served], + lambda multiplex, allowlist=None: [(n, None) for n in served], ) assert adapter._resolve_request_profile(Req("coder")) == "coder" @@ -68,6 +68,6 @@ def test_unknown_profile_rejected(self, monkeypatch): adapter, Req, REJ, served = self._adapter(multiplex=True) monkeypatch.setattr( "hermes_cli.profiles.profiles_to_serve", - lambda multiplex: [(n, None) for n in served], + lambda multiplex, allowlist=None: [(n, None) for n in served], ) assert adapter._resolve_request_profile(Req("ghost")) is REJ diff --git a/tests/gateway/test_multiplex_phase0.py b/tests/gateway/test_multiplex_phase0.py index 0297b08494c9..43ed2d4a4a88 100644 --- a/tests/gateway/test_multiplex_phase0.py +++ b/tests/gateway/test_multiplex_phase0.py @@ -107,6 +107,7 @@ class TestMultiplexConfigFlag: def test_default_is_false(self): assert GatewayConfig().multiplex_profiles is False + assert GatewayConfig().multiplex_profile_allowlist == [] def test_to_dict_includes_flag(self): assert GatewayConfig().to_dict()["multiplex_profiles"] is False @@ -119,13 +120,31 @@ def test_from_dict_nested_gateway(self): cfg = GatewayConfig.from_dict({"gateway": {"multiplex_profiles": True}}) assert cfg.multiplex_profiles is True + def test_from_dict_nested_gateway_allowlist(self): + cfg = GatewayConfig.from_dict( + { + "gateway": { + "multiplex_profiles": True, + "multiplex_profile_allowlist": ["Coder", "writer", "default"], + } + } + ) + assert cfg.multiplex_profiles is True + assert cfg.multiplex_profile_allowlist == ["coder", "writer"] + def test_from_dict_coerces_truthy_string(self): cfg = GatewayConfig.from_dict({"multiplex_profiles": "true"}) assert cfg.multiplex_profiles is True def test_roundtrip(self): - cfg = GatewayConfig.from_dict(GatewayConfig(multiplex_profiles=True).to_dict()) + cfg = GatewayConfig.from_dict( + GatewayConfig( + multiplex_profiles=True, + multiplex_profile_allowlist=["coder"], + ).to_dict() + ) assert cfg.multiplex_profiles is True + assert cfg.multiplex_profile_allowlist == ["coder"] class TestSessionStoreProfileResolution: diff --git a/tests/gateway/test_multiplex_profile_authz.py b/tests/gateway/test_multiplex_profile_authz.py index 514bda7cc9cb..56d4a618314f 100644 --- a/tests/gateway/test_multiplex_profile_authz.py +++ b/tests/gateway/test_multiplex_profile_authz.py @@ -127,6 +127,32 @@ def test_adapter_for_source_resolves_secondary_profile_adapter(monkeypatch): ) is default_adapter +def test_unknown_stamped_profile_does_not_fallback_to_default_adapter(monkeypatch): + """Unknown non-default source.profile must fail closed for source-bound sends.""" + runner, default_adapter, _secondary_adapter = _make_multiplex_runner(monkeypatch) + + source = SessionSource( + platform=Platform.WECOM, + user_id="attacker", + chat_id="dm-chat", + user_name="attacker", + chat_type="dm", + profile="missing-profile", + ) + + assert runner._adapter_for_source(source) is None + assert runner._adapter_for_source( + SessionSource( + platform=Platform.WECOM, + user_id="allowed-user", + chat_id="dm-chat", + user_name="allowed-user", + chat_type="dm", + profile=None, + ) + ) is default_adapter + + def test_secondary_allowlist_dm_behavior_ignores_unauthorized(monkeypatch): """Unauthorized-DM behavior must read the secondary adapter's dm_policy.""" runner, _default_adapter, secondary_adapter = _make_multiplex_runner(monkeypatch) @@ -156,4 +182,4 @@ def test_secondary_open_policy_fails_startup_guard(monkeypatch): violation = _own_policy_open_startup_violation(secondary_cfg) assert violation is not None assert "wecom" in violation - assert "open policy" in violation \ No newline at end of file + assert "open policy" in violation diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.py index 608a10eabbf6..882211096b75 100644 --- a/tests/hermes_cli/test_profiles.py +++ b/tests/hermes_cli/test_profiles.py @@ -1719,6 +1719,19 @@ def test_on_returns_default_plus_all_named(self, profile_env): assert serve["default"] == _get_default_hermes_home() assert serve["coder"] == get_profile_dir("coder") + def test_on_allowlist_restricts_named_profiles(self, profile_env): + create_profile("coder", no_alias=True) + create_profile("writer", no_alias=True) + create_profile("reviewer", no_alias=True) + serve = dict(profiles_to_serve(multiplex=True, allowlist=["coder", "writer"])) + assert set(serve) == {"default", "coder", "writer"} + assert serve["coder"] == get_profile_dir("coder") + + def test_on_empty_allowlist_returns_just_default(self, profile_env): + create_profile("coder", no_alias=True) + serve = profiles_to_serve(multiplex=True, allowlist=[]) + assert [n for n, _ in serve] == ["default"] + def test_on_default_always_first(self, profile_env): create_profile("coder", no_alias=True) serve = profiles_to_serve(multiplex=True) From 5fef769b0b2bb19a5a289ad37dc209db9d0e9867 Mon Sep 17 00:00:00 2001 From: ManniBr Date: Fri, 3 Jul 2026 22:11:42 +0800 Subject: [PATCH 2/2] fix(gateway): scope adapter auth callbacks to profiles --- gateway/run.py | 6 +- .../test_multiplex_adapter_registry.py | 67 +++++++++++++++++++ tests/gateway/test_multiplex_profile_authz.py | 17 ++++- 3 files changed, 86 insertions(+), 4 deletions(-) diff --git a/gateway/run.py b/gateway/run.py index 36e6b0c18fac..7715dadf8e39 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -8298,7 +8298,9 @@ async def _start_one_profile_adapters( adapter.set_session_store(self.session_store) adapter.set_busy_session_handler(self._handle_active_session_busy_message) adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id) - adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform)) + adapter.set_authorization_check( + self._make_adapter_auth_check(adapter.platform, profile=profile_name) + ) adapter._busy_text_mode = self._busy_text_mode try: @@ -8487,6 +8489,7 @@ def _create_adapter( def _make_adapter_auth_check( self, platform: Platform, + profile: Optional[str] = None, ) -> Callable[[str, Optional[str], Optional[str]], bool]: """Build a platform-bound auth callback for adapter use. @@ -8512,6 +8515,7 @@ def check( chat_id=chat_id or "", chat_type=chat_type or "group", user_id=user_id, + profile=profile, ) return self._is_user_authorized(source) return check diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.py index c43a00a0b277..9ca2c7c0ffc0 100644 --- a/tests/gateway/test_multiplex_adapter_registry.py +++ b/tests/gateway/test_multiplex_adapter_registry.py @@ -370,8 +370,75 @@ async def test_secondary_non_binding_platform_ok(self, monkeypatch): connected = await runner._start_one_profile_adapters("reviewer", "/tmp/x", {}) assert connected == 0 # nothing connected, but no MultiplexConfigError + @pytest.mark.asyncio + async def test_secondary_adapter_auth_callback_is_profile_bound(self, monkeypatch, tmp_path): + """Secondary adapter auth callbacks must be bound to their served profile.""" + from gateway.config import GatewayConfig, Platform, PlatformConfig + + class _Adapter: + platform = Platform.TELEGRAM + token = "t" + + def set_message_handler(self, handler): + self.message_handler = handler + + def set_fatal_error_handler(self, handler): + self.fatal_error_handler = handler + + def set_session_store(self, store): + self.session_store = store + + def set_busy_session_handler(self, handler): + self.busy_session_handler = handler + + def set_topic_recovery_fn(self, handler): + self.topic_recovery_fn = handler + + def set_authorization_check(self, callback): + self.authorization_check = callback + + runner = GatewayRunner.__new__(GatewayRunner) + runner.config = GatewayConfig(multiplex_profiles=True) + runner._profile_adapters = {} + runner.session_store = object() + runner._busy_text_mode = "final" + runner._handle_adapter_fatal_error = AsyncMock() + runner._handle_active_session_busy_message = AsyncMock() + runner._recover_telegram_topic_thread_id = lambda _source: None + + profile_cfg = GatewayConfig(multiplex_profiles=True) + profile_cfg.platforms = { + Platform.TELEGRAM: PlatformConfig(enabled=True, token="t"), + } + monkeypatch.setattr("gateway.config.load_gateway_config", lambda: profile_cfg) + + adapter = _Adapter() + monkeypatch.setattr(runner, "_create_adapter", lambda _platform, _config: adapter) + monkeypatch.setattr(runner, "_connect_adapter_with_timeout", AsyncMock(return_value=True)) + + captured = {} + + def _auth_factory(platform, profile=None): + captured["platform"] = platform + captured["profile"] = profile + return lambda _user_id, _chat_type=None, _chat_id=None: True + + monkeypatch.setattr(runner, "_make_adapter_auth_check", _auth_factory) + + connected = await runner._start_one_profile_adapters( + "reviewer", + tmp_path / "profiles" / "reviewer", + {}, + ) + + assert connected == 1 + assert captured == {"platform": Platform.TELEGRAM, "profile": "reviewer"} + assert adapter.authorization_check("same-user", "dm", "same-chat") is True + assert runner._profile_adapters["reviewer"][Platform.TELEGRAM] is adapter + def test_suppressed_set_covers_known_listeners(self): from gateway.run import _SECONDARY_SUPPRESSED_PLATFORM_VALUES + # Every adapter that binds a TCP port must be in the guard set. for p in ("webhook", "api_server", "msgraph_webhook", "feishu", "wecom_callback", "bluebubbles", "sms"): diff --git a/tests/gateway/test_multiplex_profile_authz.py b/tests/gateway/test_multiplex_profile_authz.py index 56d4a618314f..f71d6e14f616 100644 --- a/tests/gateway/test_multiplex_profile_authz.py +++ b/tests/gateway/test_multiplex_profile_authz.py @@ -20,7 +20,7 @@ def _clear_auth_env(monkeypatch) -> None: def _make_multiplex_runner(monkeypatch): - """Runner with default allowlist WeCom and secondary open-policy WeCom.""" + """Runner where default profile trusts intake and secondary profile denies.""" from gateway.run import GatewayRunner _clear_auth_env(monkeypatch) @@ -50,8 +50,8 @@ def _make_multiplex_runner(monkeypatch): return runner, default_adapter, secondary_adapter -def test_secondary_open_policy_not_authorized_by_default_allowlist(monkeypatch): - """Secondary-profile open intake must not inherit default allowlist trust.""" +def test_secondary_profile_denial_not_overridden_by_default_allowlist(monkeypatch): + """Secondary-profile denial must not inherit default allowlist trust.""" runner, _default_adapter, _secondary_adapter = _make_multiplex_runner(monkeypatch) source = SessionSource( @@ -68,6 +68,17 @@ def test_secondary_open_policy_not_authorized_by_default_allowlist(monkeypatch): assert runner._is_user_authorized(source) is False +def test_adapter_auth_callback_uses_profile_scoped_authorization(monkeypatch): + """Secondary adapter callback must evaluate the routed profile's policy.""" + runner, _default_adapter, _secondary_adapter = _make_multiplex_runner(monkeypatch) + + default_callback = runner._make_adapter_auth_check(Platform.WECOM) + secondary_callback = runner._make_adapter_auth_check(Platform.WECOM, profile="coder") + + assert default_callback("same-user", "dm", "same-chat") is True + assert secondary_callback("same-user", "dm", "same-chat") is False + + def test_default_profile_still_trusts_own_allowlist(monkeypatch): """Default-profile allowlist trust is unchanged when profile is unstamped.""" runner, _default_adapter, _secondary_adapter = _make_multiplex_runner(monkeypatch)