The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): authorize send_message targets and surface egress declines (P5) (#99220)
Ben Barclay866332bfb52c
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 987a81a1953..111959bb32c 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -26,6 +26,12 @@ from gateway.platforms.base import ()from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcomefrom gateway.relay.descriptor import CapabilityDescriptor+from gateway.relay.egress import (+ EGRESS_DECLINE_CODE,+ decline_error,+ is_egress_decline,+ log_decline,+)from gateway.relay.media import RelayMediaClientfrom gateway.relay.transport import RelayTransportfrom gateway.session import SessionSource@@ -118,6 +124,7 @@ class RelayAdapter(BasePlatformAdapter):# platforms on one WS and a reply must egress through the platform the# inbound came from. Empty for a single-platform gateway (connector default).self._platform_by_chat: Dict[str, str] = {}+ # Chats the connector has refused (see the terminal-decline latch).# chat_id -> (thread_id, initial_name) of the auto-thread the CONNECTOR# created for our latest send; read by the semantic thread-rename lane.self._auto_thread_by_chat: Dict[str, Tuple[str, str]] = {}@@ -353,10 +360,22 @@ class RelayAdapter(BasePlatformAdapter):return Noneasync def _outbound(self, chat_id: str, action: Dict[str, Any]) -> Dict[str, Any]:- """Send one outbound frame tagged with the chat's underlying platform."""- return await self._transport.send_outbound( # type: ignore[union-attr]+ """Send one outbound frame tagged with the chat's underlying platform.++ P5(b): the second frame path (the first is ``_gated_op``). Lanes that+ return bool/None by contract — typing, delete, thread create/rename —+ come through here, and a silent degrade made an AUTHORIZATION refusal+ indistinguishable from "op unsupported" in the logs. The return+ contract is unchanged; the refusal is recorded.+ """+ op = str(action.get("op", "?"))+ result = await self._transport.send_outbound( # type: ignore[union-attr]action, platform=self._platform_by_chat.get(str(chat_id)))+ if isinstance(result, dict):+ if not result.get("success") and is_egress_decline(result):+ log_decline(op, chat_id, result)+ return resultasync def _gated_op(self,@@ -366,6 +385,7 @@ class RelayAdapter(BasePlatformAdapter):decline_level: Optional[int] = logging.WARNING,subject: Any = None,platform: Optional[str] = None,+ surface_declines: bool = False,) -> Optional[Dict[str, Any]]:"""Emit one best-effort, op-gated frame; None when the caller must fall back.@@ -384,6 +404,24 @@ class RelayAdapter(BasePlatformAdapter):logger.debug("relay %s transport failure", op, exc_info=True)return Noneif not result.get("success"):+ # P5(b): an AUTHORIZATION decline is not lane unavailability. This+ # helper's `None` means "lane absent — do your fallback", and the+ # fallbacks re-address the SAME chat by another route (media -> a+ # text notice, prompt -> numbered text). The connector authorized+ # that destination and REFUSED it, so degrading launders a security+ # decision into "op unsupported" and delivers the content anyway.+ # Callers whose fallback would leak pass surface_declines=True and+ # turn this into a failed lane; cosmetic ops (typing, card stop)+ # keep the old None contract.+ if is_egress_decline(result):+ # Every lane records an authorization decline — the cosmetic+ # ones (typing, delete, thread create/rename, card stop) still+ # degrade to None, but a silent degrade made a security refusal+ # indistinguishable from "op unsupported" in the logs.+ log_decline(op, chat_id if subject is None else subject, result)+ if surface_declines:+ return result+ return Noneif decline_level is not None:logger.log(decline_level, "relay %s declined for %s: %s",@@ -457,13 +495,35 @@ class RelayAdapter(BasePlatformAdapter):if result.get("ambiguous"):# Ack lost (transport timeout, returned rather than raised): same# contract as the except branch — keep interception armed.- return SendResult(success=False, error=str(result.get("error") or "draft ack lost"))+ #+ # RAW BODY PRESERVED. Dropping it made `declined_send` fall through+ # to the error-text branch, and an ambiguous result whose text+ # happens to carry the decline marker ("... egress declined: ack+ # lost") then read as a DEFINITE refusal and terminated the run.+ # Ambiguous means the frame may well have been delivered, so it is+ # a transport outcome, never an authorization one.+ return SendResult(+ success=False,+ error=str(result.get("error") or "draft ack lost"),+ raw_response=result,+ )# DEFINITE connector rejection: disarm. The stream consumer falls back to# edit-based streaming and its turn-final must go out as a REAL send, not a# seal on a stream the connector just declared unusable.if self._open_draft_by_chat.get(chat_key) == draft_id:self._open_draft_by_chat.pop(chat_key, None)- return SendResult(success=False, error=str(result.get("error") or "draft failed"))+ # P5(b): carry the structured body. The stream consumer reads a bare+ # draft failure as "draft transport unusable", disables drafts, and+ # falls through to a plain send — a second op against the chat the+ # connector just refused. Verified end to end with the real+ # GatewayStreamConsumer: ops were ['draft', 'send'].+ if is_egress_decline(result):+ log_decline("draft", chat_id, result)+ return SendResult(+ success=False,+ error=str(result.get("error") or decline_error(result) or "draft failed"),+ raw_response=result,+ )async def _seal_open_draft(self,@@ -516,11 +576,28 @@ class RelayAdapter(BasePlatformAdapter):self._sealed_draft_by_chat.pop(draft_key, None)raiseif result is None:- return SendResult(success=False, error="draft seal ambiguous after retry (transport ack lost)")+ # Same ambiguity contract as send_draft: the retry's ack was lost,+ # so the seal may have been applied. Marked explicitly rather than+ # left to text inference.+ return SendResult(+ success=False,+ error="draft seal ambiguous after retry (transport ack lost)",+ raw_response={"success": False, "ambiguous": True},+ )if result.get("success"):# The connector returns the stream's ts as the message identity.return SendResult(success=True, message_id=str(result.get("message_id") or "") or None)- return SendResult(success=False, error=str(result.get("error") or "draft seal failed"))+ # P5(b): carry the structured body. Without it the caller cannot tell a+ # lane failure (fall through to a plain send, correct) from an+ # AUTHORIZATION decline (a plain send re-delivers the very content the+ # connector refused, to the same chat).+ if is_egress_decline(result):+ log_decline("draft_seal", chat_id, result)+ return SendResult(+ success=False,+ error=str(result.get("error") or decline_error(result) or "draft seal failed"),+ raw_response=result,+ )async def _absorb_into_open_draft(self, chat_id: str, content: str, metadata: Dict[str, Any], interim: bool@@ -542,6 +619,17 @@ class RelayAdapter(BasePlatformAdapter):seal = await self._seal_open_draft(chat_id, content, metadata, draft_key=key)if seal.success:return seal+ # An AUTHORIZATION decline is not a lane failure. Falling through here+ # re-sends the sealed content as a plain `send` into the destination the+ # connector just refused — review demonstrated the leak end to end+ # (ops: draft(partial) -> send(SECRET)). Surface the refusal instead.+ if is_egress_decline(getattr(seal, "raw_response", None)):+ logger.warning(+ "relay draft seal DECLINED for %s — not falling back to a plain "+ "send (the destination is not approved for this connection)",+ chat_id,+ )+ return seallogger.warning("relay seal failed (%s); delivering turn-final as plain send", seal.error)return None@@ -601,7 +689,17 @@ class RelayAdapter(BasePlatformAdapter):return resultif result.get("success"):return SendResult(success=True)- return SendResult(success=False, error=str(result.get("error") or "task_card failed"))+ # P5(b): carry the structured body. The TurnRunner reads a bare failure+ # as "card lane unavailable" and sends fallback TEXT to the same chat —+ # the same decline-laundering fixed for media and prompt, in a sibling+ # content lane.+ if is_egress_decline(result):+ log_decline("task_card", chat_id, result)+ return SendResult(+ success=False,+ error=str(result.get("error") or decline_error(result) or "task_card failed"),+ raw_response=result,+ )async def stop_native_task_card_progress(self,@@ -614,7 +712,14 @@ class RelayAdapter(BasePlatformAdapter):result = await self._card_frame(chat_id, "task_card_stop", reply_to, dict(metadata or {}))if isinstance(result, SendResult):return result- return SendResult(success=bool(result.get("success")))+ # P5(b): carry the connector's reason. Dropping `error` reported a+ # refusal as a bare failure, which reads as "the card lane is broken"+ # rather than "this destination was refused".+ return SendResult(+ success=bool(result.get("success")),+ error=result.get("error"),+ raw_response=result,+ )async def abandon_open_draft(self, chat_id: str, content: str, metadata: Optional[Dict[str, Any]] = None,@@ -1216,6 +1321,9 @@ class RelayAdapter(BasePlatformAdapter):},platform=platform_value,)+ if isinstance(result, dict):+ if not result.get("success") and is_egress_decline(result):+ log_decline("send", chat_id, result)return _send_result(result, raw_response=result)def _format_hints(@@ -1463,9 +1571,15 @@ class RelayAdapter(BasePlatformAdapter):"metadata": self._text_metadata(chat_id, metadata),},)+ # P5(b): carry the structured body. THREE separate callers read a bare+ # edit failure as "editing is unavailable" and re-send the content as a+ # NEW message to the same chat (stream edit-fallback, queued-response+ # reconciliation, task-card fallback edit). The edit lane is the ninth+ # place a decline could be laundered into a different op.return SendResult(success=bool(result.get("success")), message_id=result.get("message_id") or message_id,error=result.get("error"),+ raw_response=result,)async def delete_message(self, chat_id: str, message_id: str) -> bool:@@ -1567,7 +1681,15 @@ class RelayAdapter(BasePlatformAdapter):},platform=follow_up_platform,)- return _send_result(result)+ # CARRY THE STRUCTURED DECLINE. This lane is addressed by `session_key`,+ # not `chat_id`, so it has no latch identity — the latch is per chat and+ # inventing one from a session key would be exactly the text-derived+ # identity that blocker 2 was about. What it must NOT do is discard the+ # connector's verdict: dropping `raw_response` is precisely how the+ # `edit_message` lane laundered declines into a plain send.+ if isinstance(result, dict) and not result.get("success") and is_egress_decline(result):+ log_decline("follow_up", session_key, result)+ return _send_result(result, raw_response=result)# ── Phase 2 media ─────────────────────────────────────────────────────@@ -1637,11 +1759,20 @@ class RelayAdapter(BasePlatformAdapter):}if filename:action["filename"] = filename- # A structured connector decline (size cap, platform rejection) is logged;- # the caller's fallback still delivers the caption/notice.- result = await self._gated_op(chat_id, action)+ # A capacity decline (size cap, platform rejection) is logged and the+ # caller's fallback still delivers the caption/notice; an+ # AUTHORIZATION decline must NOT degrade that way (surface_declines).+ result = await self._gated_op(chat_id, action, surface_declines=True)if result is None:return None+ if not result.get("success"):+ # An AUTHORIZATION refusal, surfaced by _gated_op. Returning None+ # would hand the caller back to its fallback — a DIFFERENT op+ # against the SAME destination the connector just refused. Report+ # a failed lane instead, carrying the decline verbatim.+ return SendResult(+ success=False, error=decline_error(result), raw_response=result+ )return SendResult(success=True, message_id=result.get("message_id"), raw_response=result)# Each media override tries the native ``send_media`` lane, then falls back to@@ -1798,9 +1929,17 @@ class RelayAdapter(BasePlatformAdapter):}if timeout_s is not None:action["timeout_s"] = int(timeout_s)- result = await self._gated_op(chat_id, action)+ result = await self._gated_op(chat_id, action, surface_declines=True)if result is None:return None+ if not result.get("success"):+ # An AUTHORIZATION refusal, surfaced by _gated_op. Returning None+ # would hand the caller back to its fallback — a DIFFERENT op+ # against the SAME destination the connector just refused. Report+ # a failed lane instead, carrying the decline verbatim.+ return SendResult(+ success=False, error=decline_error(result), raw_response=result+ )return SendResult(success=True, message_id=result.get("message_id"), raw_response=result)async def _mint_and_send_prompt(@@ -1820,7 +1959,12 @@ class RelayAdapter(BasePlatformAdapter):chat_id, prompt_kind=prompt_kind, text=text, prompt_id=prompt_id, options=options,metadata=metadata,)- if result is None:+ if result is None or not getattr(result, "success", False):+ # P5(b): a DECLINE now returns a failed SendResult rather than+ # None, and the registration must come down on that path too. A+ # prompt card the connector refused never rendered, so leaving it+ # pending lets the user's next unrelated message be captured as the+ # answer to a prompt they never saw.self._pending_prompts.pop(prompt_id, None)return resultdiff --git a/gateway/relay/egress.py b/gateway/relay/egress.pynew file mode 100644index 00000000000..a491841687b--- /dev/null+++ b/gateway/relay/egress.py@@ -0,0 +1,585 @@+"""Gateway-side relay EGRESS AUTHORIZATION (P5).++Two halves of one security surface, kept together because they are the same+concern seen from both ends of the wire:++**(a) Target hygiene.** The ``send_message`` model tool takes a free-form+``target`` string (``'platform:chat_id'``). Nothing stopped a model from+naming an arbitrary chat id and having the gateway emit an outbound frame for+it. The connector now refuses such a frame (its egress-authorization floor),+but the gateway must not *silently* ask: a destination the gateway has no+record of is refused HERE, with a visible tool error naming the target.+:func:`authorize_relay_target` is that guard; :func:`attested_relay_targets`+is the set of destinations this gateway can show a provenance for (operator+home channel, channel directory, its own gateway session origins).++**(b) Decline visibility.** The connector answers an unauthorized destination+with a DEFINITE, non-ambiguous failure whose text is deliberately UNIFORM+(``"<platform> egress declined: target is not an approved destination for+this connection"``) — it must not leak whether the destination belongs to+another tenant or to nobody. :func:`is_egress_decline` recognises THAT a+decline happened; it never tries to parse WHY. Egress lanes that legitimately+degrade a *transport drop* (advisory progress, cosmetic reactions, media+falling back to a text notice) must NOT degrade a decline — a refusal that+turns into a different op, or into a wrong "op unavailable" reason, is a+security event laundered into an apparent success.+"""++from __future__ import annotations++import logging+from typing import Any, Dict, Optional, Set++logger = logging.getLogger(__name__)++# The connector stamps this on a structured decline (preferred signal).+EGRESS_DECLINE_CODE = "egress_declined"++# Fallback signal: the connector's uniform decline sentence. Matched+# case-insensitively on this fragment ONLY — the rest of the sentence is+# deliberately uninformative (finding F-005) and must not be parsed.+EGRESS_DECLINE_MARKER = "egress declined:"++# Transport-ambiguity text. A lost ack means the frame MAY have been delivered,+# so it is never an authorization refusal. Needed because the text-only branch+# of `declined_send` sees no structured `ambiguous` flag to check.+_AMBIGUOUS_MARKER = "ack lost"+++def is_egress_decline(result: Any) -> bool:+ """True when *result* is the connector REFUSING the destination.++ A decline is distinguished from every other outbound failure by three+ properties, all required:++ * it failed (``success`` is falsey),+ * it is DEFINITE — an ``ambiguous`` result (lost ack, mid-write drop) says+ the frame may well have been applied, so it is a transport outcome, not+ an authorization one,+ * it carries the connector's decline code, or its uniform decline text.+ """+ if not isinstance(result, dict):+ return False+ if result.get("success"):+ return False+ if result.get("ambiguous"):+ return False+ if str(result.get("code") or "") == EGRESS_DECLINE_CODE:+ return True+ return EGRESS_DECLINE_MARKER in str(result.get("error") or "").lower()+++def declined_send(result: Any) -> bool:+ """True when a SEND RESULT object carries a destination refusal.++ ``is_egress_decline`` classifies a raw connector DICT. Callers hold a+ ``SendResult``, and eight call sites each hand-rolled the unwrapping — with+ two different answers. Six checked only ``raw_response``; two also checked+ the error text. That disagreement was a real defect, not mere repetition:+ a connector that answers with the uniform decline SENTENCE and no+ structured code (the documented contract for older connectors, see+ ``_approval_send_outcome``) was classified as an ordinary failure by those+ six, so the lane treated a refusal as "editing unavailable" and retried.++ Measured: text-only decline -> six-site check False, two-site check True.++ Both shapes are authoritative, so both are checked here, once:++ * ``raw_response`` when the connector sent a structured body,+ * otherwise the error text against the uniform decline marker.++ The latch in ``RelayAdapter`` already catches both (it classifies the+ transport dict directly), which is why the inconsistency cost verdicts and+ futile retries rather than leaked content. This helper makes the gateway+ lanes agree with the wire.+ """+ raw = getattr(result, "raw_response", None)+ if isinstance(raw, dict):+ return is_egress_decline(raw)+ error = getattr(result, "error", None)+ if not error:+ return False+ if _AMBIGUOUS_MARKER in str(error).lower():+ # DEFENCE IN DEPTH for a lost `ambiguous` flag. The text branch exists+ # only for connectors that send no structured body, so it cannot see+ # `ambiguous` — and a projection that drops `raw_response` therefore+ # turned "ack lost" into a definite refusal, terminating the run for a+ # frame that may well have been delivered. Any error text that says the+ # ack was lost is treated as a transport outcome, never authorization.+ return False+ return is_egress_decline({"success": False, "error": error})+++def decline_error(result: Any) -> str:+ """The connector's decline text, verbatim, for surfacing to the caller.++ Verbatim on purpose: the gateway's job is to report faithfully THAT a+ decline happened, not to explain or re-word it.+ """+ if isinstance(result, dict):+ error = result.get("error")+ if error:+ return str(error)+ return "relay egress declined"+++def log_decline(op: str, chat_id: Any, result: Any) -> None:+ """Record a decline on a lane whose contract cannot carry an error.++ Cosmetic lanes (typing, reactions, delete, thread ops) return ``bool`` /+ ``None`` by contract and legitimately degrade. A decline there is still a+ security-relevant event, so it is logged at WARNING rather than vanishing+ into the lane's debug-level best-effort handling.+ """+ logger.warning(+ "relay %s DECLINED for %s: %s", op, chat_id, decline_error(result)+ )+++# ---------------------------------------------------------------------------+# (a) target attestation+# ---------------------------------------------------------------------------++class RelayRouteUnknown(RuntimeError):+ """Relay routing could not be determined — callers must FAIL CLOSED.++ Distinct from "no relay is configured", which is an empty set and means the+ guard does not apply. This is "we could not find out", and the two must not+ share a return value: an empty set here says "not relay-routed", which+ skips authorization entirely.+ """+++def _is_missing_gateway_relay(exc: ImportError) -> bool:+ """True only when the gateway relay package ITSELF is absent.++ `ImportError.name` is the module that could not be found. A nested+ dependency failing is a broken installation, not "there is no relay here",+ and the two must not share a verdict.+ """+ # Absence is ModuleNotFoundError WITH a name; anything else is a fault.+ if not isinstance(exc, ModuleNotFoundError):+ return False+ return getattr(exc, "name", None) in (+ "gateway",+ "gateway.relay",+ "gateway.relay.egress",+ )+++def _live_relay_fronted() -> Optional[Set[str]]:+ """The connected relay adapter's OWN fronted set.++ Returns None ONLY for genuine absence — no runner, or no relay adapter in+ it. A live adapter that cannot answer raises `RelayRouteUnknown`.++ ABSENCE vs FAULT, again. `None` here means "fall back to the config+ snapshot", so letting a FAULT return it re-created the bypass this function+ exists to close: with a live adapter whose `fronts_platform()` raised and an+ empty/stale config snapshot, the guard concluded "not relay-routed" and+ authorized an unattested destination, while `resolve_delivery_transport`+ asks that same adapter and still routes over the relay. Measured:+ `relay_routed=False`, verdict `None`.+ """+ # FAIL CLOSED BY DEFAULT. Five review rounds found this same defect at five+ # different boundaries — the call, the attribute lookup, a non-callable+ # attribute, the nested imports, and the adapter-registry `.get()` — because+ # the old shape asked "did something go wrong?" and answered `None`, which+ # MEANS "no live adapter, use the config snapshot". Every new statement was+ # a new chance to fail open, so the fix kept relocating instead of closing.+ #+ # Inverted here: every `return None` is guarded by an explicit narrow check+ # that cannot itself be the fault, and the outer handler turns anything else+ # into `RelayRouteUnknown`. So a statement added inside this function is+ # fail-CLOSED by default; previously it was fail-open by default.+ try:+ try:+ from gateway.config import Platform+ from gateway.run import _gateway_runner_ref+ except ImportError as exc:+ # Only the gateway package being genuinely absent is benign; a+ # nested dependency failing to load is a broken install, i.e. a+ # fault. Same rule as `_relay_fronted` below.+ if _is_missing_gateway_relay(exc):+ return None+ raise++ runner = _gateway_runner_ref()+ if runner is None:+ return None # no gateway runner in this process (CLI, cron)++ registry = getattr(runner, "adapters", None)+ if not registry:+ return None # a runner with no adapters at all++ relay = registry.get(Platform.RELAY)+ if relay is None:+ return None # native-only deployment: nothing fronts anything++ # A PRESENT adapter must answer. Anything below this line that fails is+ # a fault, never an absence.+ fronts = relay.fronts_platform+ return {+ str(p.value).strip().lower()+ for p in Platform+ if str(getattr(p, "value", "")).lower() != "relay" and fronts(p)+ }+ except Exception as exc: # noqa: BLE001 - anything unproven is UNKNOWN+ logger.exception("could not determine the live relay adapter's fronted set")+ raise RelayRouteUnknown(+ "the connected relay adapter could not report which platforms it "+ "fronts, so this destination's routing could not be determined"+ ) from exc+++def _relay_fronted() -> Set[str]:+ """Platforms the connector fronts for this gateway.++ ABSENCE vs FAULT is the whole point of the split below. No gateway relay+ module means there is no relay egress to authorize, so an empty set is the+ honest answer. Any OTHER failure — a config read that raised, a broken+ dependency inside the module — means routing is UNKNOWN, and returning an+ empty set there silently reclassifies a relay platform as native and+ bypasses the guard. Review demonstrated exactly that: with discovery+ raising, an unattested target was authorized.+ """+ try:+ from gateway.relay import relay_fronted_platforms+ except ImportError as exc:+ # Only the ABSENCE of the relay module itself is benign. An ImportError+ # naming a nested dependency means an installed module failed to load —+ # a FAULT — and returning an empty set there reclassifies every relay+ # platform as native. Review probed this with+ # `ImportError.name = "gateway.relay.dependency"` and got an authorized+ # verdict, so `except ImportError` alone was not the fix it looked like.+ if not _is_missing_gateway_relay(exc):+ raise RelayRouteUnknown(+ f"relay module failed to import: {exc}"+ ) from exc+ return set()++ # PREFER THE LIVE ADAPTER'S OWN ANSWER. `resolve_delivery_transport` asks+ # the CONNECTED relay adapter (`fronts_platform`, from the identity set sent+ # at handshake); reconstructing routing from mutable environment state is a+ # DIFFERENT snapshot, and the two disagree whenever GATEWAY_RELAY_PLATFORMS+ # changes or is momentarily absent after connect. Review probed exactly+ # that: guard said "not relay-routed", delivery routed relay, and the guard+ # was skipped for a relay send. Same source, same answer.+ live = _live_relay_fronted()+ if live is not None:+ return live+ try:+ # CASE-NORMALIZED. `relay_routed_platform` lowercases the requested+ # name, so an un-normalized set made a mixed-case configured platform+ # ("Discord") miss the membership test and look native — an+ # attestation bypass on a string comparison.+ return {str(p).strip().lower() for p in relay_fronted_platforms()}+ except Exception as exc: # noqa: BLE001 - routing unknown; never assume native+ raise RelayRouteUnknown(+ f"relay route discovery failed: {exc}"+ ) from exc+++def _has_live_native_adapter(platform_name: str) -> bool:+ """Whether THIS process runs a native (non-relay) adapter for the platform.++ Mirrors ``gateway/delivery.resolve_delivery_transport``'s precedence: a+ concrete native adapter always wins, so a platform served natively here is+ not a relay egress and this guard does not apply to it.+ """+ try:+ from gateway.config import Platform+ from gateway.run import _gateway_runner_ref++ runner = _gateway_runner_ref()+ if runner is None:+ return False+ adapters = getattr(runner, "adapters", None) or {}+ platform = Platform(platform_name)+ if adapters.get(platform) is None:+ return False+ # MATCH `resolve_delivery_transport` EXACTLY. A native adapter that is+ # explicitly DISABLED never shadows Relay there, so treating mere+ # presence as "native" made the guard believe a send was native while+ # delivery actually routed it over the relay — the guard then skipped+ # authorization for a relay send. Two independent routing classifiers+ # are unsafe; this one now answers the same question the router does.+ from gateway.config import load_gateway_config++ # NO `except: return True` HERE. I wrote one, and it recreated the very+ # bypass this method was fixed for: a config read that fails would+ # declare the platform native while the router — reading the real+ # config — sends over the relay, so the guard is skipped for a relay+ # send. A routing question we cannot answer is UNKNOWN, and the caller+ # turns that into a refusal.+ try:+ native_config = load_gateway_config().platforms.get(platform)+ except Exception as exc: # noqa: BLE001 - routing unknown; never assume native+ raise RelayRouteUnknown(+ f"native-adapter config lookup failed for {platform_name}: {exc}"+ ) from exc+ return native_config is None or bool(getattr(native_config, "enabled", True))+ except RelayRouteUnknown:+ # Routing is UNKNOWN, not "no native adapter" — must not be flattened+ # into False here, which would send the caller down the relay-guard+ # path on a guess. Propagate; authorize_relay_target turns it into a+ # refusal.+ raise+ except Exception: # noqa: BLE001 - no runner (cron/CLI) ⇒ no native adapter+ return False+++def relay_routed_platform(platform_name: str) -> bool:+ """Whether a send to *platform_name* would egress over the relay connector.++ True for the generic ``relay`` plane itself, and for any logical platform+ the connector fronts for this gateway that has no live native adapter in+ this process.+ """+ name = str(platform_name or "").strip().lower()+ if not name:+ return False+ if name == "relay":+ return True+ if name not in _relay_fronted():+ return False+ return not _has_live_native_adapter(name)+++def _home_channel_id(platform_name: str) -> Optional[str]:+ try:+ from gateway.config import Platform, load_gateway_config++ home = load_gateway_config().get_home_channel(Platform(platform_name))+ return str(home.chat_id) if home and home.chat_id else None+ except Exception: # noqa: BLE001 - config absence must never break a send+ return None+++def _directory_ids(platform_name: str) -> Set[str]:+ try:+ from gateway.channel_directory import load_directory++ entries = load_directory().get("platforms", {}).get(platform_name) or []+ except Exception: # noqa: BLE001+ return set()+ ids: Set[str] = set()+ for entry in entries:+ if isinstance(entry, dict) and entry.get("id"):+ ids.add(str(entry["id"]))+ return ids+++def _session_ids(platform_name: str) -> Set[str]:+ """Chat ids this gateway has actually held a session in for the platform."""+ try:+ from gateway.channel_directory import _build_from_sessions++ entries = _build_from_sessions(platform_name) or []+ except Exception: # noqa: BLE001+ return set()+ ids: Set[str] = set()+ for entry in entries:+ if isinstance(entry, dict) and entry.get("id"):+ raw = str(entry["id"])+ ids.add(raw)+ # RECOVER THE CHAT FROM THE STRUCTURED FIELD, NEVER BY SPLITTING.+ # `_session_entry_id` builds the id as f"{chat_id}:{thread_id}"+ # when a thread exists, and the entry still carries `thread_id`+ # separately — so the parent is knowable exactly. Splitting on ":"+ # was a guess that INVENTED attestations: a Matrix room id+ # `!room:server.org` attested a bare `!room` no session ever used.+ # An allow-list of "platforms whose ids have no native colon" would+ # only have narrowed the guess; the structured field removes it.+ if entry.get("thread_id"):+ suffix = f":{entry['thread_id']}"+ if raw.endswith(suffix):+ ids.add(raw[: -len(suffix)])+ return ids+++def attested_relay_targets(platform_name: str) -> Set[str]:+ """Chat ids this gateway can show a provenance for on *platform_name*.++ Three provenances, all of them things the gateway already knows rather+ than things a model can invent:++ * the operator-configured home channel,+ * the channel directory built from live adapters/session origins,+ * this gateway's own gateway-session origins.++ For the generic ``relay`` plane the union spans every platform the+ connector fronts: a relay session is filed under its LOGICAL platform+ (``source = "discord"``), so attesting ``relay`` against only ``relay``+ would refuse chats the agent is demonstrably already talking in.+ """+ name = str(platform_name or "").strip().lower()+ names = {name}+ if name == "relay":+ names |= _relay_fronted()+ attested: Set[str] = set()+ for candidate in names:+ home = _home_channel_id(candidate)+ if home:+ attested.add(home)+ attested |= _directory_ids(candidate)+ attested |= _session_ids(candidate)+ return attested+++_UNSET = object()+++def _has_native_credential(platform_name: str) -> bool:+ """Whether the gateway itself holds a token that can send to *platform_name*.++ `_send_to_platform` sends Telegram natively via `pconfig.token`, entirely+ outside the connector. When that credential exists, no connector-side+ authorization happens, so the unresolved-handle exemption has no basis.+ Faults answer True — the SAFE direction, since it only ever withdraws an+ exemption and falls back to the ordinary attestation check.+ """+ try:+ from gateway.config import Platform, load_gateway_config++ config = load_gateway_config()+ pconfig = config.platforms.get(Platform(platform_name))+ return bool(pconfig and pconfig.enabled and getattr(pconfig, "token", None))+ except Exception: # noqa: BLE001 - a fault must not GRANT the exemption+ logger.debug("native-credential probe failed; withdrawing the exemption", exc_info=True)+ return True+++def _is_unresolved_handle(platform_name: str, target: str, native_token: Any = _UNSET) -> bool:+ """Whether *target* is a NAME the gateway cannot compare against an id.++ Provenance records RESOLVED destinations (numeric chat ids). A Telegram+ public `@username` is not a destination yet — the Bot API resolves it at+ send time — so comparing it to a set of numeric ids can only ever refuse,+ no matter how legitimately the user configured it.++ Deliberately narrow: `@`-prefixed Telegram targets only. A numeric id, a+ `-100…` supergroup, or any other platform's form is a resolved destination+ and stays fully guarded.+ """+ if platform_name != "telegram" or not target.startswith("@"):+ return False+ # AND THE SEND MUST ACTUALLY REACH THE CONNECTOR. The carve-out's entire+ # justification is "the connector holds the token and authorizes this".+ # That is false whenever the tool sends NATIVELY: `_send_to_platform`+ # calls `_send_telegram(pconfig.token, ...)` directly, so with a native+ # Telegram token configured, an unattested @handle went out with the+ # gateway's own credential and no connector ever saw it. Review probed it:+ # the numeric control was refused, the handle was delivered.+ #+ # So the exemption survives only when there is NO native credential able to+ # send this handle. `_send_to_platform` reaches for `pconfig.token`; if that+ # exists, delivery never involves the connector.+ if native_token is not _UNSET:+ # The caller passed the token from the SAME config snapshot it will+ # dispatch with; that is authoritative and race-free.+ return not native_token+ return not _has_native_credential(platform_name)+++def authorize_relay_target(+ platform_name: str, chat_id: Any, thread_id: Any = None, *, native_token: Any = _UNSET+) -> Optional[str]:+ """Return an error string when this relay destination may not be named.++ ``None`` means the send may proceed. Non-relay platforms are never+ restricted here — their own adapters own their authorization.++ THREAD IDS ARE PART OF THE DESTINATION, not a formatting detail. On Discord+ the thread is the literal REST target+ (``POST /channels/{thread_id}/messages``), so authorizing only the parent+ let an attested channel vouch for an arbitrary caller-supplied thread. The+ thread must therefore carry its own attestation — a session in the parent+ is not evidence of a session in the thread.+ """+ try:+ routed = relay_routed_platform(platform_name)+ except RelayRouteUnknown as exc:+ # Routing could not be determined. "Not relay-routed" would skip this+ # guard entirely, so an unknown route must refuse rather than assume+ # the safe-looking default. Returned as a refusal string (not raised)+ # because every caller treats this function's output as the verdict.+ logger.warning(+ "relay routing unknown for %s — refusing the send: %s",+ platform_name,+ exc,+ )+ return (+ f"Refusing to send to '{platform_name}': relay routing could not "+ "be determined, so this destination could not be verified."+ )+ if not routed:+ return None+ target = str(chat_id or "").strip()+ if not target:+ return None+ name = str(platform_name).strip().lower()+ attested = attested_relay_targets(name)+ if target in attested:+ # The CHAT is attested. If the caller also named a thread, that thread+ # is the real destination on thread-addressed platforms, so it needs an+ # attestation OF ITS OWN, BOUND TO THIS PARENT.+ #+ # A bare `thread in attested` arm used to satisfy this, and it proved+ # nothing about parentage: any attested chat whose id happened to equal+ # the requested thread id vouched for it. Measured — attested+ # `{"-100A", "7"}`, request `(-100A, thread 7)` → authorized, though no+ # session ever existed in thread 7 of -100A.+ #+ # The bound form is always available, so nothing legitimate needs the+ # bare one: `_session_entry_id` records a threaded origin as+ # f"{chat_id}:{thread_id}", and a platform whose thread IS its own+ # channel (a Discord thread addressed directly) arrives as `chat_id`+ # and is authorized by the `target in attested` check above.+ thread = str(thread_id or "").strip()+ if thread and thread != target:+ if f"{target}:{thread}" in attested:+ return None+ return (+ f"Refusing to send to relay target '{name}:{target}:{thread}': "+ f"the parent chat is attested but this gateway has no record of "+ f"the thread, and on this platform the thread IS the delivery "+ f"destination."+ )+ return None+ # ── Telegram `@username`: authorized by the CONNECTOR, not here ─────────+ #+ # Checked AFTER attestation, so a handle that IS attested takes the normal+ # path; this only catches the case that would otherwise be a false refusal.+ #+ # WHY THE GATEWAY CANNOT ANSWER THIS: the guard fires only when there is no+ # live native adapter (`_has_live_native_adapter`), i.e. on relay-fronted+ # deployments — and on exactly those the CONNECTOR holds the bot token, not+ # this process. There is no local way to turn `@channel` into the numeric id+ # provenance stores, so refusing here is not "fail closed", it is "fail+ # always". It regressed the public-channel username support added in #53573.+ #+ # WHY THAT IS SAFE, NOT A HOLE: the destination is still authorized, one+ # layer out. The connector's Telegram egress floor (gg#238, merged 743a7c2)+ # classifies and refuses unauthorized destinations after ITS resolution,+ # which is the layer that closed the reported vulnerability in the first+ # place. This carve-out drops handles from two guards to one — the+ # authoritative one — rather than to zero.+ #+ # FOLLOW-UP (option 2, deliberately not done here): resolve the handle+ # before authorizing, so both layers apply. That needs a resolution+ # round-trip through the connector — new wire surface — so it belongs in+ # its own phase, not bolted onto this one.+ if _is_unresolved_handle(name, target, native_token):+ logger.debug(+ "relay target '%s:%s' is an unresolved handle — deferring "+ "authorization to the connector's egress floor",+ name,+ target,+ )+ return None+ return (+ f"Refusing to send to unattested relay target '{name}:{target}': "+ "this gateway has no record of that destination. Use "+ "send_message(action='list') to see the targets it can reach."+ )diff --git a/gateway/run.py b/gateway/run.pyindex 9b35d7ff444..c907ba4187e 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -730,6 +730,40 @@ def _approval_send_outcome(future, timeout: float) -> str:return "failed"if getattr(result, "success", False):return "sent"+ # P5(b): a connector DECLINE is not a lane failure. The connector+ # authorized the destination and refused it; re-sending the same content as+ # plain text into that same chat is the exfiltration the egress guard+ # exists to stop. `failed` is the cue to fall back, so a decline needs its+ # own verdict — callers must surface it and send nothing further.+ #+ # CLASSIFY THE STRUCTURED RESPONSE, NOT THE ERROR STRING. The adapter+ # preserves the connector's own dict in `raw_response`; rebuilding a dict+ # from `error` alone loses two things review demonstrated:+ # * a decline carrying `code: egress_declined` and NO text renders as+ # "relay egress declined" — no marker colon — so the string check+ # missed it and the fallback fired into the refused chat;+ # * `ambiguous: True` (lost ack, mid-write drop) was flattened into a+ # DEFINITE failure, which re-sends a card that may well have posted.+ # I fixed the text-marker path and tested only the text-marker path.+ from gateway.relay.egress import declined_send++ _raw = getattr(result, "raw_response", None)+ if isinstance(_raw, dict) and _raw.get("ambiguous"):+ # The frame may have been applied. Same physics as a scheduling+ # timeout: possibly-delivered, so never re-send. Checked BEFORE the+ # decline classification because an ambiguous result is a transport+ # outcome, not an authorization one, and this lane has three verdicts+ # rather than the boolean the shared helper answers.+ logger.warning("Prompt send AMBIGUOUS (lost ack): %s", _raw.get("error"))+ return "ambiguous"+ if declined_send(result):+ # Both shapes, one classifier: a structured body, or the uniform+ # decline sentence from an older connector.+ logger.warning(+ "Prompt send DECLINED by connector egress guard: %s",+ getattr(result, "error", None),+ )+ return "declined"logger.warning("Prompt send failed: %s", getattr(result, "error", None) or "unknown error")return "failed"@@ -740,6 +774,18 @@ def _clarify_send_disposition(fut, *, session_key: str, clarify_mod) -> "str | NOnly a DEFINITIVE failure tears down the registration; ``ambiguous`` (card may have posted) stays armedand proceeds to the bounded wait, whose response timeout covers a lost card."""outcome = _approval_send_outcome(fut, timeout=15)+ if outcome == "declined":+ # P5(b): a connector DECLINE is MORE definitive than a failure — the+ # destination was authorized and refused, so the card cannot arrive and+ # no late reply can resolve it. Without this branch `declined` fell+ # through to the bounded wait and the agent blocked until+ # clarify_timeout (indefinitely when that is configured non-positive).+ logger.warning(+ "Clarify prompt DECLINED by the connector's egress guard; "+ "clearing registration"+ )+ clarify_mod.clear_session(session_key)+ return "[clarify prompt could not be delivered: destination refused]"if outcome == "failed":# Undeliverable: clear the registration and return the sentinel so the agent falls back, not hangs.logger.warning("Clarify send failed definitively; clearing registration")diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex b1ff9315167..0acfda137ae 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -1204,6 +1204,29 @@ class GatewayBusySessionMixin:)if button_result and getattr(button_result, "success", False):return None # buttons rendered — no redundant text ack+ # P5(b): distinguish a connector egress DECLINE from a lane+ # failure. On a decline the connector refused this destination,+ # so returning `message` as the direct reply would deliver the+ # very content it refused, as text, to the same chat. Suppress+ # the fallback and tear down the registration — no card+ # rendered, so a later reply must not be captured as an answer+ # to an invisible prompt.+ #+ # Classify the STRUCTURED response (see _approval_send_outcome):+ # a code-only decline has no marker colon in its rendered text,+ # and an ambiguous result must not be treated as a definite+ # refusal.+ from gateway.relay.egress import declined_send++ _confirm_err = getattr(button_result, "error", None)+ if declined_send(button_result):+ logger.warning(+ "slash-confirm DECLINED by the connector's egress "+ "guard for %s on %s — suppressing the text fallback: %s",+ command, source.platform, _confirm_err,+ )+ _slash_confirm_mod.clear(session_key)+ return Noneexcept Exception as exc:logger.debug("send_slash_confirm failed for %s on %s: %s", command, source.platform, exc)# Text fallback — the prompt message itself is the direct reply.diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 94a9c8346d1..ccc3772aad7 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1184,6 +1184,14 @@ class GatewayInboundMixin:if _admitted is None:return Noneevent, source, is_internal = _admitted+ # TERMINAL-DECLINE LATCH TEARDOWN. Deliberately placed AFTER admission,+ # not on the adapter's raw inbound: profile routing, the ignored-channel+ # guard, plugin hooks and user authorization all reject events above,+ # and a rejected event must not be able to clear a refusal belonging to+ # an active turn. This is also the single entry point every lane shares+ # — Discord interaction passthrough builds its own MessageEvent and+ # calls handle_message directly, so a teardown on the relay's inbound+ # handler left those turns muted._paused_notice = self._hm_estop_gate(event, source, is_internal)if _paused_notice is not None:diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex e2a9baaed7c..f5084100571 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -341,6 +341,19 @@ class GatewayNotificationsMixin:"Queued-lane final reconciled by editing message %s in place (no duplicate send).",_sc_msg_id,)+ else:+ # P5(b): a DECLINE is not "editing unavailable". The+ # send below re-delivers the whole response to the+ # chat the connector just refused.+ from gateway.relay.egress import declined_send++ if declined_send(_edit_res):+ logger.warning(+ "Queued-lane reconcile edit DECLINED by the "+ "connector's egress guard; not falling back "+ "to a send (the destination is not approved)."+ )+ returnexcept Exception as _qe:logger.debug("Queued-lane reconcile edit failed (%s); falling back to send.", _qe)if not _reconciled:diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 7d7284e420c..b9ba066790e 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -35,6 +35,16 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)logger = logging.getLogger("gateway.run")+class _ExecApprovalDeclined(RuntimeError):+ """The connector refused the approval card's destination.++ Raised (not returned) so it propagates out of `_approval_notify_sync` to+ `_await_gateway_decision`, whose notify-failure path drops the central+ approval queue entry and unblocks the waiting tool. A plain return+ suppressed the text fallback but left that entry pending.+ """++class TurnRunner:"""Per-turn collaborator carrying ``GatewayRunner._run_agent_inner``'s tool-progress callbacks."""@@ -288,6 +298,11 @@ class TurnRunner:task_order: List[str] = dataclasses.field(default_factory=list)fallback_msg_id: Optional[str] = Nonenative_failed: bool = False+ # TERMINAL authorization refusal, distinct from native_failed: the+ # connector refused this destination, so no later publication in this+ # turn may re-deliver the task text through the text fallback. Declared+ # rather than set dynamically so the state is visible where it lives.+ egress_declined: bool = Falseanonymous_seq: int = 0@staticmethod@@ -331,12 +346,28 @@ class TurnRunner:async def _task_card_send_or_edit_fallback(self, st) -> None:ctx = self._ctxtext = st.fallback_text()+ from gateway.relay.egress import declined_send++ if getattr(st, "egress_declined", False):+ returnif st.fallback_msg_id:result = await st.adapter.edit_message(chat_id=ctx.source.chat_id, message_id=st.fallback_msg_id, content=text, metadata=ctx._progress_metadata,)if getattr(result, "success", False):return+ # P5(b): R5-4 made a declined native CARD terminal but left this+ # editable-text fallback: a declined edit fell through to+ # _send_progress_text and re-sent the same task text to the refused+ # chat. The decline must set the terminal state here too.+ if declined_send(result):+ logger.warning(+ "Task-card fallback edit DECLINED by the connector's egress "+ "guard; suppressing progress delivery for the rest of this "+ "turn (the destination is not approved)"+ )+ st.egress_declined = True+ returnresult = await self._send_progress_text(st, text)if getattr(result, "success", False) and getattr(result, "message_id", None):st.fallback_msg_id = str(result.message_id)@@ -345,6 +376,10 @@ class TurnRunner:ctx = self._ctxif not st.tasks:return+ if getattr(st, "egress_declined", False):+ # The connector refused this destination earlier in the turn; every+ # later publication would re-deliver the same task text there.+ returnif not st.native_failed:result = await st.adapter.send_native_task_card_progress(chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title="Hermes is working",@@ -352,6 +387,26 @@ class TurnRunner:)if getattr(result, "success", False):return+ # P5(b): an AUTHORIZATION decline is not a broken card lane. The+ # fallback below sends the same task text to the same chat, which+ # turns a refused card into delivered plain text. Stop the lane+ # without re-delivering; the refusal is already logged.+ from gateway.relay.egress import declined_send++ if declined_send(result):+ # TERMINAL, and stored SEPARATELY from native_failed. Reusing+ # native_failed suppressed exactly ONE update: the next progress+ # event skipped this branch (the lane is already "failed") and+ # went straight to the text fallback. A refusal does not expire+ # after one tick.+ st.egress_declined = True+ st.native_failed = True+ logger.warning(+ "Slack native task-card progress DECLINED by the connector's "+ "egress guard — suppressing the text fallback for the rest "+ "of this turn (the destination is not approved)"+ )+ returnst.native_failed = Truelogger.warning("Slack native task-card progress failed; falling back "@@ -1270,7 +1325,37 @@ class TurnRunner:"stays armed for a late tap)")return+ if outcome == "declined":+ # P5(b): the connector AUTHORIZED this destination and+ # refused it. The text fallback below re-sends the same+ # content to the same chat, which would turn a refused+ # button card into a delivered plain-text one — the exact+ # leak the egress guard exists to stop. A decline is+ # definitive, so unlike `ambiguous` the registration is+ # torn down; unlike `failed`, nothing is re-sent.+ logger.warning(+ "Button-based approval DECLINED by the connector's "+ "egress guard — not falling back to text (the "+ "destination is not approved for this connection)"+ )+ # RAISE, do not return. This function is the notify_cb for+ # `_await_gateway_decision`, which already has a correct+ # undeliverable path: a raising notify drops the queue entry+ # and returns `notify_failed`, unblocking the tool. Returning+ # quietly suppressed the text fallback (right) but left the+ # CENTRAL approval entry pending (wrong) — the dangerous+ # command then blocked until the approval timeout. My earlier+ # comment claimed the registration was torn down; only the+ # adapter's private prompt map was.+ raise _ExecApprovalDeclined(+ "exec approval undeliverable: connector egress declined "+ "this destination"+ )logger.warning("Button-based approval failed (send returned error), falling back to text")+ except _ExecApprovalDeclined:+ # Must escape this handler: the fallback below is a text send to+ # the destination the connector just refused.+ raiseexcept Exception as e:logger.warning("Button-based approval failed, falling back to text: %s", e)# Plain-text prompt with the adapter's typed prefix (e.g. `!approve`): typed "/" is blockeddiff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 24befeb43a6..dbd1d5e2cec 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -164,6 +164,10 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiself._use_draft_streaming = Falseself._draft_id: Optional[int] = Noneself._draft_failures = 0+ # TERMINAL authorization refusal for THIS RUN (see _send_draft_frame).+ # Per-run state, constructed fresh each turn, so a refusal can never+ # mute a healthy destination on a later turn.+ self._egress_declined = Falseself._use_native_streaming = Falseself._native_stream_opened = False # seed sent: bubble open, zero contentself._native_last_pushed_len = 0 # throttle under WeCom's 30 frames/mindiff --git a/gateway/stream_consumer_fallback.py b/gateway/stream_consumer_fallback.pyindex e8362809237..283fc02df14 100644--- a/gateway/stream_consumer_fallback.py+++ b/gateway/stream_consumer_fallback.py@@ -80,6 +80,16 @@ class StreamFallbackMixin:async def _send_fallback_final(self, text: str) -> None:"""Send the final continuation after streaming edits stop working (one flood retryper chunk)."""+ if getattr(self, "_egress_declined", False):+ # The connector refused this destination earlier in the run. The+ # whole point of this path is to deliver the unseen tail as a NEW+ # message, which is exactly the re-addressing the egress guard+ # exists to stop.+ logger.warning(+ "suppressing the fallback continuation: the connector already "+ "declined this destination for this run"+ )+ return# Balance fences BEFORE computing the continuation so the closing fence# reaches the user even when only the tail is delivered.final_text = ensure_closed_code_fences(self._clean_for_display(text))diff --git a/gateway/stream_consumer_transport.py b/gateway/stream_consumer_transport.pyindex c01bd34d61d..0bbb2b442a8 100644--- a/gateway/stream_consumer_transport.py+++ b/gateway/stream_consumer_transport.py@@ -174,6 +174,19 @@ class StreamTransportMixin:if getattr(result, "success", False):self._last_sent_text = text # parity with the edit-based no-op skipreturn True+ # P5(b): an AUTHORIZATION decline is terminal for the whole run, not+ # merely "drafts are unusable". Disabling drafts alone routes the+ # turn-final to _first_send — a plain send into the chat the+ # connector just refused. Verified: ops were ['draft', 'send'].+ from gateway.relay.egress import declined_send++ if declined_send(result):+ logger.warning(+ "send_draft DECLINED by the connector's egress guard; "+ "suppressing every later send for this run (the destination "+ "is not approved for this connection)"+ )+ self._egress_declined = Truelogger.debug("send_draft returned success=False, disabling draft transport: %s",getattr(result, "error", "unknown"))self._draft_failures += 1@@ -417,6 +430,15 @@ class StreamTransportMixin:async def _first_send(self, text: str, *, finalize: bool) -> bool:"""First send, threaded to the user's message (correct topic/thread)."""+ if getattr(self, "_egress_declined", False):+ # The connector refused this destination earlier in the run (see+ # _send_draft_frame). This is where every fallback path converges,+ # so the check belongs here rather than at each caller.+ logger.warning(+ "suppressing the plain-send fallback: the connector already "+ "declined this destination for this run"+ )+ return Falseresult = await self.adapter.send(chat_id=self.chat_id, content=text, reply_to=self._initial_reply_to_id,metadata=self._metadata_for_send(final=finalize, expect_edits=not finalize))@@ -487,6 +509,22 @@ class StreamTransportMixin:) -> bool:"""Classify a failed edit: partial overflow, flood backoff, or fallback mode. AlwaysFalse; the caller's finalize path may still deliver the tail."""+ # P5(b): an AUTHORIZATION decline is terminal for the run. Every branch+ # below treats a failed edit as "editing is unavailable" and hands the+ # unseen tail to the fallback, which SENDS it as a new message to the+ # chat the connector just refused. Measured: ops were+ # ['edit', 'edit', 'send'].+ from gateway.relay.egress import declined_send++ if declined_send(result):+ logger.warning(+ "edit DECLINED by the connector's egress guard; suppressing "+ "every later send for this run (the destination is not "+ "approved for this connection)"+ )+ self._egress_declined = True+ self._edit_supported = False+ return Falseturn_final = finalize and is_turn_finalif (turn_final and self.cfg.cursor and self._last_sent_text.endswith(self.cfg.cursor)and self._visible_prefix() == text):diff --git a/tests/gateway/relay/test_relay_egress_declines.py b/tests/gateway/relay/test_relay_egress_declines.pynew file mode 100644index 00000000000..b3c9780ba10--- /dev/null+++ b/tests/gateway/relay/test_relay_egress_declines.py@@ -0,0 +1,958 @@+"""P5(b): connector egress DECLINES surface as real errors, not swallowed successes.++The connector's egress-authorization floor answers an unauthorized destination+with a DEFINITE failure whose text is deliberately uniform (finding F-005 — the+caller must not learn *why*). The gateway's job is to report faithfully THAT it+happened. The failure mode these tests pin is specific: several relay lanes+degrade a *transport drop* by design, and that same degradation used to swallow+an *authorization refusal* — either into a wrong reason ("prompt op+unavailable") or, worse, into a DIFFERENT op re-addressed at the very chat the+connector just refused (media falling back to a plain text notice).++Most lanes below drive the REAL `RelayAdapter` built from the REAL descriptor;+the only substitution is the transport, which is what the connector is. The+exceptions are explicit: the stream-consumer tests construct+`StreamTransportMixin` / `StreamFallbackMixin` doubles and inject a `SendResult`+directly, because the behaviour under test belongs to the CALLER of the adapter,+not to the adapter itself.+"""++from __future__ import annotations++import asyncio+import logging+import os+from types import SimpleNamespace+from typing import Any, Dict, List, Optional++import pytest++from gateway.config import PlatformConfig+from gateway.relay.adapter import RelayAdapter+from gateway.relay.descriptor import CONTRACT_VERSION, CapabilityDescriptor+from gateway.relay.egress import (+ EGRESS_DECLINE_CODE,+ decline_error,+ is_egress_decline,+)++DECLINE_TEXT = (+ "discord egress declined: target is not an approved destination for this connection"+)+DECLINE: Dict[str, Any] = {"success": False, "error": DECLINE_TEXT}++ALL_OPS = (+ "send",+ "edit",+ "typing",+ "delete",+ "react",+ "send_media",+ "prompt",+ "draft",+ "task_card",+ "task_card_stop",+ "thread_create",+ "thread_rename",+)+++class DecliningConnector:+ """A connector that refuses EVERY destination, like the real egress floor."""++ def __init__(self, descriptor: CapabilityDescriptor) -> None:+ self._descriptor = descriptor+ self.ops: List[str] = []+ self._identities = [(descriptor.platform, "b1")]++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ return True++ async def disconnect(self) -> None:+ return None++ async def handshake(self) -> CapabilityDescriptor:+ return self._descriptor++ def set_inbound_handler(self, handler) -> None:+ return None++ def set_passthrough_handler(self, handler) -> None:+ return None++ async def send_outbound(+ self, action: Dict[str, Any], *, platform: Optional[str] = None+ ) -> Dict[str, Any]:+ self.ops.append(str(action.get("op")))+ return dict(DECLINE)++ async def send_follow_up(+ self, action: Dict[str, Any], *, platform: Optional[str] = None+ ) -> Dict[str, Any]:+ return dict(DECLINE)++ async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:+ return {"name": chat_id, "type": "dm"}++ async def send_interrupt(self, session_key, reason=None) -> None:+ return None++ async def go_idle(self, timeout_s: float = 10.0) -> bool:+ return True+++def relay():+ descriptor = CapabilityDescriptor(+ contract_version=CONTRACT_VERSION,+ platform="discord",+ label="Relay",+ max_message_length=4096,+ supports_draft_streaming=True,+ supports_edit=True,+ supports_threads=True,+ markdown_dialect="plain",+ len_unit="chars",+ supported_ops=ALL_OPS,+ )+ connector = DecliningConnector(descriptor)+ adapter = RelayAdapter(+ PlatformConfig(enabled=True, extra={}), descriptor, transport=connector+ )+ return adapter, connector+++# ── the classifier itself ────────────────────────────────────────────────++def test_decline_is_recognised_by_code_and_by_uniform_text():+ # The wire contract, pinned as a LITERAL. Asserting against the imported+ # constant is a tautology — it cannot fail when the constant changes, and+ # review mutation M05 survived exactly there. The connector stamps this+ # exact string (gateway-gateway routedEgressGuard); changing either side+ # alone is a silent cross-repo break, so the literal is the point.+ assert EGRESS_DECLINE_CODE == "egress_declined"+ assert is_egress_decline({"success": False, "code": "egress_declined"}) is True+ assert is_egress_decline({"success": False, "code": EGRESS_DECLINE_CODE}) is True++ assert is_egress_decline(DECLINE) is True++ # M10: the `.lower()` in is_egress_decline was untested, so making the+ # marker match case-SENSITIVE survived — a connector emitting "Egress+ # declined:" would silently stop being classified as a decline and start+ # falling back into the refused chat. Every fixture happened to be+ # lowercase, which is what hid it.+ for variant in (+ "Discord Egress Declined: target is not approved",+ "EGRESS DECLINED: target is not approved",+ "discord EGRESS declined: target is not approved",+ ):+ assert is_egress_decline({"success": False, "error": variant}) is True, variant++++def test_an_ambiguous_failure_is_not_a_decline():+ """A lost ack may well have been APPLIED — it is a transport outcome.++ Classifying it as a decline would convert the relay's deliberate+ optimistic-retry behaviour into a hard error on a message that landed.+ """+ assert (+ is_egress_decline(+ {"success": False, "error": DECLINE_TEXT, "ambiguous": True}+ )+ is False+ )+++def test_an_ordinary_failure_is_not_a_decline():+ assert is_egress_decline({"success": False, "error": "file too large"}) is False+ assert is_egress_decline({"success": True}) is False+ assert is_egress_decline(None) is False+++def test_decline_error_is_the_connector_text_verbatim():+ """No re-wording, no reason-parsing: the uniform sentence, unchanged."""+ assert decline_error(DECLINE) == DECLINE_TEXT+++# ── lanes that must report the decline to their caller ───────────────────++def test_send_reports_the_decline(relay):+ adapter, connector = relay+ result = asyncio.run(adapter.send("C1", "hi"))++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["send"]+++def test_media_decline_does_not_fall_back_to_a_text_send(relay):+ """The worst swallow: a refused destination re-addressed by a different op.++ `_send_media` returning None hands the caller back to+ `BasePlatformAdapter.send_image`, which sends the URL as TEXT — into the+ very chat the connector just refused. The lane must report the refusal+ instead, and emit exactly ONE op.+ """+ adapter, connector = relay+ result = asyncio.run(adapter.send_image("C1", "https://x/y.png", caption="cap"))++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["send_media"]+++def test_exec_approval_decline_is_not_reported_as_op_unavailable(relay):+ """"prompt op unavailable" is a WRONG reason that triggers a text fallback.++ The whole observable: the refusal reaches the caller verbatim, exactly one+ op is emitted, and the minted prompt is UNREGISTERED — a prompt left+ pending for a card that was never delivered would silently capture the+ user's next reply in that chat as an approval press.+ """+ adapter, connector = relay+ result = asyncio.run(adapter.send_exec_approval("C1", "rm -rf /", "sk1"))++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["prompt"]+ assert adapter._pending_prompts == {}+++def test_slash_confirm_decline_is_not_reported_as_op_unavailable(relay):+ adapter, connector = relay+ result = asyncio.run(+ adapter.send_slash_confirm("C1", "Title", "Body", "sk1", "cf1")+ )++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["prompt"]+ assert adapter._pending_prompts == {}+++def test_clarify_decline_does_not_fall_back_to_a_numbered_text_send(relay):+ """The base class's numbered-text clarify would `send()` into the refused chat."""+ adapter, connector = relay+ result = asyncio.run(+ adapter.send_clarify("C1", "Which?", ["a", "b"], "cl1", "sk1")+ )++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["prompt"]+ assert adapter._pending_prompts == {}+++def test_a_delivered_prompt_stays_registered(relay, monkeypatch):+ """Guard the converse: the cleanup must not unregister a LIVE prompt."""+ adapter, connector = relay++ async def _ok(action, *, platform=None):+ connector.ops.append(str(action.get("op")))+ return {"success": True, "message_id": "pm1"}++ monkeypatch.setattr(connector, "send_outbound", _ok)+ result = asyncio.run(adapter.send_exec_approval("C1", "ls", "sk1"))++ assert result.success is True+ assert connector.ops == ["prompt"]+ assert len(adapter._pending_prompts) == 1+++def test_task_card_stop_decline_carries_the_error(relay):+ """The stop lane discarded the error entirely (`success=` only)."""+ adapter, connector = relay+ result = asyncio.run(adapter.stop_native_task_card_progress("C1"))++ assert result.success is False+ assert result.error == DECLINE_TEXT+ assert connector.ops == ["task_card_stop"]+++# ── lanes that legitimately degrade, but must still SAY so ───────────────++ "lane,call,expected",+ [+ ("typing", lambda a: a.send_typing("C1"), None),+ ("delete", lambda a: a.delete_message("C1", "m1"), False),+ ("thread_create", lambda a: a.create_handoff_thread("C1", "n"), None),+ ("thread_rename", lambda a: a.rename_thread("T1", "n"), False),+ ],+)+def test_cosmetic_lane_degrades_but_logs_the_decline_at_warning(+ relay, caplog, lane, call, expected+):+ """These return bool/None by contract; a refusal must not vanish silently."""+ adapter, _connector = relay+ with caplog.at_level(logging.WARNING, logger="gateway.relay.egress"):+ assert asyncio.run(call(adapter)) == expected++ declines = [+ r+ for r in caplog.records+ if r.name == "gateway.relay.egress" and "DECLINED" in r.getMessage()+ ]+ assert len(declines) == 1+ assert DECLINE_TEXT in declines[0].getMessage()+++# ── round-2 review survivors: lines the docstrings call load-bearing ────────+#+# M25 and M21 both survived because nothing exercised them, while the code+# around them explains at length why they matter. A comment is not a guard.+++def test_thread_qualified_session_id_attests_the_bare_chat():+ """M25: session ids may be "chat:thread"; the connector authorizes the CHAT.++ `_session_ids` deliberately adds BOTH forms. Without the split, a gateway+ whose session origin is `-100999:77` cannot send to `-100999` — the chat it+ is demonstrably already talking in.+ """+ import gateway.channel_directory as cd+ import gateway.relay.egress as eg++ original = cd._build_from_sessions+ try:+ # Real entries carry `thread_id` alongside the composed id+ # (`_session_entry_id` builds f"{chat_id}:{thread_id}"), and the parent+ # is now recovered from that field rather than by splitting on ":" —+ # splitting invented attestations for ids whose colon is part of the+ # address (Matrix). The PROPERTY below is unchanged.+ cd._build_from_sessions = lambda _p: [{"id": "-100999:77", "thread_id": "77"}]+ ids = eg._session_ids("telegram")+ finally:+ cd._build_from_sessions = original++ assert "-100999:77" in ids, "the qualified form must stay attested"+ assert "-100999" in ids, "the bare chat must be attested (M25)"+++def test_relay_plane_attests_the_union_of_fronted_platforms():+ """M21: a relay session is filed under its LOGICAL platform.++ `attested_relay_targets("relay")` must span every fronted platform, or the+ generic plane refuses chats the agent is already in — the exact failure the+ docstring warns about.+ """+ import gateway.channel_directory as cd+ import gateway.relay.egress as eg++ orig_dir = cd.load_directory+ orig_env = os.environ.get("GATEWAY_RELAY_PLATFORMS")+ try:+ # Drive the REAL `relay_fronted_platforms()` through its env source —+ # the `GATEWAY_RELAY_PLATFORMS` deploy stamp. My first version patched+ # `_relay_fronted` itself, so the mutation that emptied it survived:+ # the test was asserting against its own stub instead of production.+ os.environ["GATEWAY_RELAY_PLATFORMS"] = "discord,slack"+ cd.load_directory = lambda: {+ "platforms": {+ "discord": [{"id": "C-DISCORD"}],+ "slack": [{"id": "C-SLACK"}],+ "relay": [],+ }+ }+ targets = eg.attested_relay_targets("relay")+ finally:+ cd.load_directory = orig_dir+ if orig_env is None:+ os.environ.pop("GATEWAY_RELAY_PLATFORMS", None)+ else:+ os.environ["GATEWAY_RELAY_PLATFORMS"] = orig_env++ assert "C-DISCORD" in targets and "C-SLACK" in targets, (+ "the relay plane must union the fronted platforms (M21)"+ )+++# ── B-2: Telegram `@username` is authorized by the CONNECTOR ────────────────+#+# Provenance stores RESOLVED numeric chat ids; a public `@channel` is not a+# destination until the Bot API resolves it at send time. Comparing the two+# could only ever refuse, which regressed the username support added in+# #53573. The guard fires only on relay-fronted deployments, where the+# CONNECTOR holds the bot token — so the gateway has no way to resolve it, and+# the connector's own egress floor (gg#238) is the layer that authorizes it.+#+# These tests pin the carve-out's EDGES. It must not widen.+++def _relay_env(monkeypatch, platform="telegram", directory=None):+ import gateway.channel_directory as cd++ monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", platform)+ monkeypatch.setattr(+ cd, "load_directory", lambda: {"platforms": {platform: directory or []}}+ )+ monkeypatch.setattr(cd, "_build_from_sessions", lambda _p: [])+ import gateway.relay.egress as eg++ monkeypatch.setattr(eg, "_home_channel_id", lambda _p: None)+ monkeypatch.setattr(eg, "_has_live_native_adapter", lambda _p: False)+ return eg+++def test_telegram_username_defers_to_the_connector(monkeypatch):+ """The regression case: a public handle must not be refused here."""+ eg = _relay_env(monkeypatch)+ assert eg.authorize_relay_target("telegram", "@some_public_channel") is None+++def test_numeric_telegram_target_is_still_guarded(monkeypatch):+ """The carve-out must not leak to resolved ids — the guard's whole point."""+ eg = _relay_env(monkeypatch)+ denial = eg.authorize_relay_target("telegram", "-1009999999999")+ assert denial is not None and "-1009999999999" in denial+++def test_carve_out_is_telegram_only(monkeypatch):+ """Another platform's `@` form is NOT a Telegram handle.++ Matrix targets `@user:server.org`; Slack has `@handle` pseudo-ids. Neither+ is resolved by the Telegram Bot API, so neither may ride this exemption.+ """+ eg = _relay_env(monkeypatch, platform="matrix")+ denial = eg.authorize_relay_target("matrix", "@someone:server.org")+ assert denial is not None, "the carve-out widened beyond telegram"+++def test_attested_handle_takes_the_normal_path(monkeypatch):+ """Order check: attestation is consulted BEFORE the carve-out.++ A handle that IS attested must pass as attested, not as an exemption —+ otherwise the carve-out would be masking whether attestation still works.++ Both paths return None, so asserting the verdict cannot tell them apart:+ my first version of this test passed happily with the carve-out moved+ ABOVE the attestation lookup. Observe the MECHANISM instead — attestation+ must actually be consulted — which is the difference between the two+ orderings.+ """+ eg = _relay_env(monkeypatch, directory=[{"id": "@known_channel"}])++ consulted: list[str] = []+ real = eg.attested_relay_targets+ monkeypatch.setattr(+ eg,+ "attested_relay_targets",+ lambda p: (consulted.append(p), real(p))[1],+ )++ assert eg.authorize_relay_target("telegram", "@known_channel") is None+ assert consulted == ["telegram"], (+ "attestation was skipped — the carve-out is short-circuiting it"+ )+ assert "@known_channel" in real("telegram")+++def test_username_like_but_not_prefixed_is_guarded(monkeypatch):+ """No `@`, no exemption — a bare name is still an unattested target."""+ eg = _relay_env(monkeypatch)+ assert eg.authorize_relay_target("telegram", "some_public_channel") is not None+++# ── code-only declines: the wire shape that has NO marker colon ─────────────+#+# Review's finding: every case above declines with marker TEXT, so deleting+# `raw_response=result` from the production return path left all 34 tests+# green. The structured `code` is documented as the PREFERRED signal precisely+# because a connector may send no prose at all, and a caller that rebuilds+# `{"success": False, "error": ...}` from `error` alone cannot see it.++CODE_ONLY_DECLINE: Dict[str, Any] = {"success": False, "code": EGRESS_DECLINE_CODE}+++class CodeOnlyDecliningConnector(DecliningConnector):+ """Refuses with a structured code and NO error prose."""++ async def send_outbound(+ self, action: Dict[str, Any], *, platform: Optional[str] = None+ ) -> Dict[str, Any]:+ self.ops.append(str(action.get("op")))+ return dict(CODE_ONLY_DECLINE)+++def code_only_relay():+ descriptor = CapabilityDescriptor(+ contract_version=CONTRACT_VERSION,+ platform="discord",+ label="Relay",+ max_message_length=4096,+ supports_draft_streaming=True,+ supports_edit=True,+ supports_threads=True,+ markdown_dialect="plain",+ len_unit="chars",+ supported_ops=ALL_OPS,+ )+ connector = CodeOnlyDecliningConnector(descriptor)+ adapter = RelayAdapter(+ PlatformConfig(enabled=True, extra={}), descriptor, transport=connector+ )+ return adapter, connector+++def test_code_only_prompt_decline_reaches_the_caller_as_a_decline(code_only_relay):+ """The REAL adapter's SendResult must carry the structured decline through.++ Drives the production `send_exec_approval` -> `_send_prompt` path and feeds+ its real SendResult to the real `_approval_send_outcome`, rather than+ hand-building a SimpleNamespace. With `raw_response` dropped, the verdict+ degrades to "failed" — the cue that triggers the text fallback into the+ chat the connector just refused.+ """+ from gateway.run import _approval_send_outcome++ adapter, connector = code_only_relay+ result = asyncio.run(+ adapter.send_exec_approval("C1", "rm -rf /", "sk1", description="danger")+ )++ assert result is not None+ assert result.success is False+ assert connector.ops == ["prompt"]+ # The structured body must survive to the caller.+ assert isinstance(result.raw_response, dict)+ assert is_egress_decline(result.raw_response)++ class _Fut:+ def result(self, timeout=None):+ return result++ assert _approval_send_outcome(_Fut(), timeout=1) == "declined"+ # A prompt that never rendered must not stay pending.+ assert adapter._pending_prompts == {}+++def test_code_only_media_decline_does_not_fall_back(code_only_relay):+ """Same wire shape on the media lane: a failed lane, never a silent None."""+ adapter, connector = code_only_relay+ result = asyncio.run(+ adapter.send_image("C1", "https://example.invalid/a.png", caption="hi")+ )+ assert result is not None+ assert result.success is False+ assert connector.ops == ["send_media"]+ assert isinstance(result.raw_response, dict)+ assert is_egress_decline(result.raw_response)++def _code_only_adapter():+ descriptor = CapabilityDescriptor(+ contract_version=CONTRACT_VERSION,+ platform="discord",+ label="Relay",+ max_message_length=4096,+ supports_draft_streaming=True,+ supports_edit=True,+ supports_threads=True,+ markdown_dialect="plain",+ len_unit="chars",+ supported_ops=ALL_OPS,+ )+ connector = CodeOnlyDecliningConnector(descriptor)+ adapter = RelayAdapter(+ PlatformConfig(enabled=True, extra={}), descriptor, transport=connector+ )+ return adapter, connector+++# ── sibling content lanes that also re-address the same chat ────────────────+++def test_declined_draft_seal_does_not_replay_as_a_plain_send():+ """Review round 3, finding 1 — a real content leak, reproduced end to end.++ On a stream-is-the-message platform (Slack) the turn-final is converted+ into draft(final=True). When the connector REFUSES that seal, the old code+ read it as a lane failure and delivered the same content through `send` —+ ops were [draft(partial), draft(final,SECRET), send(SECRET)].+ """+ descriptor = CapabilityDescriptor(+ contract_version=CONTRACT_VERSION,+ platform="slack", # stream-is-the-message; discord would not arm a seal+ label="Relay",+ max_message_length=4096,+ supports_draft_streaming=True,+ supports_edit=True,+ supports_threads=True,+ markdown_dialect="plain",+ len_unit="chars",+ supported_ops=ALL_OPS,+ )++ class SealDecliner(DecliningConnector):+ async def send_outbound(self, action, *, platform=None):+ op = str(action.get("op"))+ self.ops.append(op)+ if op == "draft" and not action.get("final"):+ return {"success": True, "message_id": "m1"} # stream opens+ return dict(CODE_ONLY_DECLINE) # the SEAL is refused++ connector = SealDecliner(descriptor)+ adapter = RelayAdapter(+ PlatformConfig(enabled=True, extra={}), descriptor, transport=connector+ )++ asyncio.run(adapter.send_draft("C1", 1, "partial"))+ asyncio.run(adapter.send("C1", "SECRET", metadata={}))++ # The seal was attempted and refused; the content must NOT be replayed.+ assert connector.ops == ["draft", "draft"]+ assert "send" not in connector.ops+++def test_declined_task_card_progress_carries_the_decline_to_its_caller():+ """Review round 3, finding 6 — the same laundering, in the card lane.++ The TurnRunner reads a bare failure as "card lane unavailable" and sends+ fallback TEXT to the same chat, so the decline must reach it structured.+ """+ adapter, connector = _code_only_adapter()+ result = asyncio.run(+ adapter.send_native_task_card_progress(+ "C1", [{"text": "step one"}], title="Working"+ )+ )+ assert result.success is False+ assert connector.ops == ["task_card"]+ assert is_egress_decline(result.raw_response)+++def test_declined_INITIAL_draft_is_not_retried_as_a_plain_send():+ """R5-3: the round-3 fix covered a declined SEAL, not a declined OPEN.++ `send_draft` logged the decline but returned a bare failure, so the stream+ consumer read it as "draft transport unusable", disabled drafts, and fell+ through to `_first_send`. Measured through the real adapter + real+ StreamTransportMixin: ops were ['draft', 'send'].+ """+ from gateway.platforms.base import SendResult+ from gateway.stream_consumer_transport import StreamTransportMixin++ adapter, connector = _code_only_adapter()++ class _Consumer(StreamTransportMixin):+ def __init__(self):+ self.adapter = adapter+ self.chat_id = "C1"+ self._draft_id = 1+ self._use_draft_streaming = True+ self._draft_failures = 0+ self._initial_reply_to_id = None+ self._already_sent = False+ self._last_sent_text = ""+ self._edit_supported = True++ def _draft_metadata(self):+ return {}++ def _metadata_for_send(self, **k):+ return {}++ def _visible_prefix(self):+ return ""++ def _enter_fallback_mode(self, *a):+ return None++ def _adopt_message_id(self, mid):+ return None++ def _track_preview_ids_from_result(self, r):+ return None++ consumer = _Consumer()+ assert asyncio.run(consumer._send_draft_frame("partial")) is False+ # The turn-final must NOT be replayed into the refused chat.+ assert asyncio.run(consumer._first_send("SECRET", finalize=True)) is False+ assert connector.ops == ["draft"]+++def test_edit_message_carries_the_structured_decline():+ """R6-2 root cause: `edit_message` dropped the connector response.++ THREE callers read a bare edit failure as "editing is unavailable" and+ re-send the content as a NEW message to the same chat (stream edit+ fallback, queued reconciliation, task-card fallback). One dropped field,+ three leaks — so the fix belongs here, at the source.+ """+ adapter, connector = _code_only_adapter()+ result = asyncio.run(adapter.edit_message("C1", "m1", "SECRET"))++ assert result.success is False+ assert connector.ops == ["edit"]+ assert is_egress_decline(result.raw_response)+++def test_declined_stream_edit_does_not_send_the_unseen_tail():+ """R6-2: the stream consumer's edit-failure funnel.++ A refused edit put the consumer into ordinary fallback mode, which delivers+ the unseen tail as a plain send. Measured: ops were ['edit', 'edit', 'send'].++ THE DOUBLE IS DELIBERATELY COMPLETE. An earlier version implemented only the+ guarded path, so removing either guard raised AttributeError inside the fake+ (`_is_flood_error`, `_clean_for_display`) and the test went red for the wrong+ reason, proving nothing. Each guard now dies on its OWN observable, and the+ two are different — state for the first, the wire for the second:++ remove the _on_edit_failure decline check+ -> assert consumer._egress_declined is True+ (execution stops here; this mutant never reaches the fallback)+ remove the _send_fallback_final early return+ -> AssertionError: the unseen tail reached the wire: ['send']+ """+ from gateway.platforms.base import SendResult+ from gateway.stream_consumer_fallback import StreamFallbackMixin+ from gateway.stream_consumer_transport import StreamTransportMixin++ adapter, connector = _code_only_adapter()++ class _Consumer(StreamFallbackMixin, StreamTransportMixin):+ def __init__(self):+ self.adapter = adapter+ self.chat_id = "C1"+ self._egress_declined = False+ self._edit_supported = True+ self._message_id = "m1"+ self._last_sent_text = ""+ self._final_content_delivered = False+ self._draft_id = None+ self._use_draft_streaming = False+ self._draft_failures = 0+ self._fallback_prefix = ""+ self._flood_strikes = 0+ self._current_edit_interval = 1.0+ self._last_edit_time = 0.0+ self.thread_id = None+ self.cfg = SimpleNamespace(cursor=None)++ # ── reached only when a guard is REMOVED; present so the mutant+ # reaches the wire instead of dying inside the double ──+ def _is_flood_error(self, *a, **kw):+ return False++ def _clean_for_display(self, text):+ return text++ def _notify_new_message(self, *a, **kw):+ return None++ async def _try_strip_cursor(self, *a, **kw):+ return None++ def _visible_prefix(self):+ return ""++ def _record_turn_final_payload(self, text):+ return None++ def _enter_fallback_mode(self, *a):+ return None++ def _draft_metadata(self):+ return {}++ def _send_metadata(self, *a, **kw):+ return {}++ def _metadata_for_send(self, *a, **kw):+ return {}++ consumer = _Consumer()+ declined = SendResult(+ success=False, error="declined", raw_response=dict(CODE_ONLY_DECLINE)+ )++ asyncio.run(+ consumer._on_edit_failure(declined, "tail", finalize=True, is_turn_final=True)+ )+ assert consumer._egress_declined is True++ # Drive the real fallback: this is the lane that re-sent the tail.+ asyncio.run(consumer._send_fallback_final("SECRET-TAIL"))++ # The decline arrived as an injected SendResult, so no frame was sent for+ # it; the invariant is that the fallback put NOTHING on the wire.+ assert connector.ops == [], f"the unseen tail reached the wire: {connector.ops}"+++# ── holes found by attacking the latch itself ──────────────────────────────+++def test_follow_up_carries_the_structured_decline():+ """`send_follow_up` is addressed by session_key, so it has no latch identity+ — but it must still not DISCARD the connector's verdict, which is exactly+ how the edit lane laundered declines into a plain send."""+ adapter, connector = _code_only_adapter()++ async def _declining_follow_up(action, *, platform=None):+ connector.ops.append("follow_up")+ return dict(CODE_ONLY_DECLINE)++ connector.send_follow_up = _declining_follow_up++ result = asyncio.run(adapter.send_follow_up("sess-1", "discord.interaction_token", "SECRET"))++ assert not result.success+ assert is_egress_decline(result.raw_response)+++# ── one classifier for SendResult declines ─────────────────────────────────+++def test_declined_send_accepts_both_wire_shapes():+ """Eight gateway lanes hand-rolled this unwrapping with TWO answers.++ Six checked only `raw_response`; two also checked the error text. A+ connector answering with the uniform decline SENTENCE and no structured+ code — the documented contract for older connectors — was therefore+ classified as an ordinary failure by those six, so the lane treated a+ refusal as "editing unavailable" and retried through another op.++ Measured before the fix: text-only decline -> six-site False, two-site True.+ """+ from gateway.platforms.base import SendResult+ from gateway.relay.egress import declined_send++ # Structured body.+ assert declined_send(+ SendResult(success=False, error="x", raw_response=dict(CODE_ONLY_DECLINE))+ )+ # Uniform decline sentence only — the shape six lanes used to miss.+ assert declined_send(+ SendResult(success=False, error="egress declined: destination not approved")+ )+ # AMBIGUOUS is a transport outcome, never an authorization one: the frame+ # may have been applied, so it must not be classified as a refusal.+ assert not declined_send(+ SendResult(+ success=False,+ error="lost ack",+ raw_response={"success": False, "ambiguous": True, "code": EGRESS_DECLINE_CODE},+ )+ )+ # Ordinary failures stay ordinary — over-refusal is the larger risk now.+ assert not declined_send(SendResult(success=False, error="rate limited"))+ assert not declined_send(SendResult(success=True, message_id="m1"))+++def test_declined_draft_frame_is_terminal_for_the_run():+ """Covers `_send_draft_frame`, whose decline check SURVIVED mutation.++ A declined draft frame must set `_egress_declined`, not merely disable+ drafts: disabling drafts alone routes the turn-final to `_first_send`,+ which is a plain send into the chat the connector just refused.++ Also asserts the text-only wire shape here specifically — this lane is one+ of the six that used to read `raw_response` only, so before the shared+ classifier it missed exactly this reply.+ """+ from gateway.platforms.base import SendResult+ from gateway.stream_consumer_transport import StreamTransportMixin++ class _Adapter:+ def __init__(self, result):+ self._result = result+ self.draft_calls = 0++ async def send_draft(self, **kwargs):+ self.draft_calls += 1+ return self._result++ class _Consumer(StreamTransportMixin):+ def __init__(self, adapter):+ self.adapter = adapter+ self.chat_id = "C1"+ self._draft_id = "d1"+ self._use_draft_streaming = True+ self._draft_failures = 0+ self._last_sent_text = None+ self._egress_declined = False++ def _draft_metadata(self):+ return {}++ # Text-only decline: no structured body at all.+ adapter = _Adapter(SendResult(success=False, error="egress declined: not approved"))+ consumer = _Consumer(adapter)+ assert asyncio.run(consumer._send_draft_frame("partial")) is False+ assert consumer._egress_declined is True++ # CONTROL: an ordinary draft failure disables drafts WITHOUT going terminal,+ # otherwise this fix silently becomes "one flaky frame mutes the chat".+ adapter2 = _Adapter(SendResult(success=False, error="rate limited"))+ consumer2 = _Consumer(adapter2)+ assert asyncio.run(consumer2._send_draft_frame("partial")) is False+ assert consumer2._egress_declined is False+ assert consumer2._use_draft_streaming is False+++# ── round 10 blockers ──────────────────────────────────────────────────────+++def test_ambiguous_draft_result_never_reads_as_a_decline():+ """AMBIGUOUS is a transport outcome: the frame may well have been+ delivered, so it must never terminate the run.++ The ambiguous projection discarded `raw_response`, so `declined_send` fell+ through to the error-text branch — and an ambiguous result whose text+ happens to carry the decline marker ("... egress declined: ack lost") read+ as a DEFINITE refusal.+ """+ from gateway.relay.egress import declined_send++ descriptor = CapabilityDescriptor(+ contract_version=CONTRACT_VERSION,+ platform="discord",+ label="Relay",+ max_message_length=4096,+ supports_draft_streaming=True,+ supports_edit=True,+ supports_threads=True,+ markdown_dialect="plain",+ len_unit="chars",+ supported_ops=ALL_OPS,+ )++ class _Ambiguous(DecliningConnector):+ async def send_outbound(self, action, *, platform=None):+ self.ops.append(str(action.get("op")))+ return {+ "success": False,+ "ambiguous": True,+ "error": "discord egress declined: ack lost",+ }++ connector = _Ambiguous(descriptor)+ adapter = RelayAdapter(+ PlatformConfig(enabled=True, extra={}), descriptor, transport=connector+ )++ result = asyncio.run(adapter.send_draft("C1", "d1", "partial"))++ assert result.raw_response is not None, "the ambiguous body must be carried"+ assert result.raw_response.get("ambiguous") is True+ assert not declined_send(result), "ambiguous must not classify as a decline"+++def test_declined_send_ignores_ack_lost_text_without_a_structured_body():+ """DEFENCE IN DEPTH for a projection that loses the `ambiguous` flag.++ The text-only branch cannot see `ambiguous`, so any error text saying the+ ack was lost is a transport outcome — never authorization.+ """+ from gateway.platforms.base import SendResult+ from gateway.relay.egress import declined_send++ assert not declined_send(+ SendResult(success=False, error="discord egress declined: ack lost")+ )+ # CONTROL: a genuine text-only decline is still detected.+ assert declined_send(+ SendResult(success=False, error="egress declined: destination not approved")+ )diff --git a/tests/gateway/test_decline_fallback_suppression.py b/tests/gateway/test_decline_fallback_suppression.pynew file mode 100644index 00000000000..7e38ed6308a--- /dev/null+++ b/tests/gateway/test_decline_fallback_suppression.py@@ -0,0 +1,365 @@+"""Caller-level fallback suppression — the branches that actually stop the leak.++Review round 3 deleted BOTH production branches these cover and every existing+test still passed (36 and 38 respectively). The suites exercised+`_approval_send_outcome` and `RelayAdapter` but never drove the real callers,+so nothing observed whether a text send followed a decline — which is the+entire security property.++Every case here pairs a DECLINE with an ordinary-FAILURE control. Without the+control a test cannot distinguish "suppressed the fallback" from "never had a+fallback": a caller that always stays silent would pass the decline case.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any, Dict, List, Optional++import pytest++from gateway.platforms.base import SendResult+from gateway.relay.egress import EGRESS_DECLINE_CODE++CODE_ONLY_DECLINE: Dict[str, Any] = {"success": False, "code": EGRESS_DECLINE_CODE}+++# ── exec approval ───────────────────────────────────────────────────────────+++class _Adapter:+ """Records every plain text send the caller attempts."""++ typed_command_prefix = "/"++ def __init__(self, approval_result: SendResult) -> None:+ self._approval_result = approval_result+ self.text_sends: List[str] = []++ def pause_typing_for_chat(self, chat_id: str) -> None:+ return None++ def resume_typing_for_chat(self, chat_id: str) -> None:+ return None++ async def send_exec_approval(self, *a: Any, **k: Any) -> SendResult:+ return self._approval_result++ async def send(self, chat_id: str, message: str, **k: Any) -> SendResult:+ self.text_sends.append(message)+ return SendResult(success=True, message_id="m1")+++def _runner(adapter: _Adapter):+ """A TurnRunner driven through its real _approval_notify_sync."""+ from gateway.run_turn_runner import TurnRunner++ runner = object.__new__(TurnRunner)+ ctx = SimpleNamespace(+ _status_adapter=adapter,+ _status_chat_id="C1",+ _status_thread_metadata={},+ _session_key="sk1",+ session_key="sk1",+ source=SimpleNamespace(chat_id="C1", platform="discord", session_key="sk1"),+ )+ runner._ctx = ctx++ class _Fut:+ def __init__(self, result): self._r = result+ def result(self, timeout=None): return self._r++ runner._schedule = lambda coro, _label: _Fut(asyncio.run(coro))+ runner._close_native_stream_boundary = lambda _why: None+ return runner+++APPROVAL = {"command": "rm -rf /", "description": "danger", "pattern_key": "k"}+++def test_exec_approval_decline_does_not_send_the_text_fallback():+ from gateway.run_turn_runner import _ExecApprovalDeclined++ adapter = _Adapter(+ SendResult(success=False, error="declined", raw_response=CODE_ONLY_DECLINE)+ )+ runner = _runner(adapter)++ # Raises (not returns) so `_await_gateway_decision`'s notify-failure path+ # drops the CENTRAL approval entry and unblocks the waiting tool.+ with pytest.raises(_ExecApprovalDeclined):+ runner._approval_notify_sync(dict(APPROVAL))++ assert adapter.text_sends == []+++def test_exec_approval_ORDINARY_failure_still_falls_back_to_text():+ """The control. An ordinary failure MUST still reach the user."""+ adapter = _Adapter(SendResult(success=False, error="slack 500"))+ runner = _runner(adapter)++ runner._approval_notify_sync(dict(APPROVAL))++ assert len(adapter.text_sends) == 1+ assert "rm -rf /" in adapter.text_sends[0]+++# ── slash confirm ───────────────────────────────────────────────────────────+++class _ConfirmAdapter:+ def __init__(self, result: SendResult) -> None:+ self._result = result++ async def send_slash_confirm(self, **k: Any) -> SendResult:+ return self._result+++def _busy(adapter: _ConfirmAdapter):+ from gateway.run_busy import GatewayBusySessionMixin++ busy = object.__new__(GatewayBusySessionMixin)+ busy._adapter_for_source = lambda _s: adapter+ busy._thread_metadata_for_source = lambda _s, _a: {}+ busy._reply_anchor_for_event = lambda _e: None+ busy._session_key_for_source = lambda _s: "sk1"+ return busy+++def _event():+ return SimpleNamespace(+ source=SimpleNamespace(chat_id="C1", platform="discord", user_id="u1")+ )+++def _run_confirm(busy) -> Optional[str]:+ return asyncio.run(+ busy._request_slash_confirm(+ event=_event(),+ command="/wipe",+ title="Confirm",+ message="really wipe?",+ handler=lambda choice: "done",+ )+ )+++def test_slash_confirm_decline_returns_none_and_clears_state():+ from tools import slash_confirm as mod++ adapter = _ConfirmAdapter(+ SendResult(success=False, error="declined", raw_response=CODE_ONLY_DECLINE)+ )+ reply = _run_confirm(_busy(adapter))++ # None = "no text ack": returning the message would post the prompt as+ # plain text into the chat the connector just refused.+ assert reply is None+ # And the registration must not survive a card that never rendered.+ assert mod.get_pending("sk1") in (None, {}, [])+++def test_slash_confirm_ORDINARY_failure_returns_the_text_fallback():+ """The control. A broken card lane must still ask the user."""+ adapter = _ConfirmAdapter(SendResult(success=False, error="discord 500"))+ reply = _run_confirm(_busy(adapter))++ assert reply == "really wipe?"+++# ── task-card progress ──────────────────────────────────────────────────────+#+# Round 4 finding: the round-3 fix added the production branch AND a test, but+# the test stopped at RelayAdapter — it proved raw_response is carried and+# never called the caller that owns the security property. Deleting the real+# branch left 30 tests green. Same lesson as #7, one lane over: a component in+# the path proves nothing until a case drives THE CALLER.+++class _CardAdapter:+ def __init__(self, progress_result: SendResult) -> None:+ self._progress_result = progress_result+ self.fallbacks: List[str] = []++ async def send_native_task_card_progress(self, **k: Any) -> SendResult:+ return self._progress_result+++def _card_runner(adapter: _CardAdapter):+ from gateway.run_turn_runner import TurnRunner++ runner = object.__new__(TurnRunner)+ runner._ctx = SimpleNamespace(+ source=SimpleNamespace(chat_id="C1", platform="slack"),+ _progress_reply_to=None,+ _progress_metadata={},+ )++ async def _fallback(st):+ adapter.fallbacks.append("fallback")++ runner._task_card_send_or_edit_fallback = _fallback+ return runner+++def _card_state(adapter: _CardAdapter):+ return SimpleNamespace(+ tasks=[{"text": "step"}],+ native_failed=False,+ visible_tasks=lambda: [{"text": "step"}],+ fallback_text=lambda: "step",+ adapter=adapter,+ )+++def test_declined_task_card_progress_does_not_send_the_text_fallback():+ adapter = _CardAdapter(+ SendResult(success=False, error="declined", raw_response=CODE_ONLY_DECLINE)+ )+ runner = _card_runner(adapter)+ st = _card_state(adapter)++ asyncio.run(runner._task_card_publish(st))++ assert adapter.fallbacks == []+ assert st.native_failed is True+++def test_ORDINARY_task_card_failure_still_sends_the_text_fallback():+ """Control: a genuinely broken card lane must still reach the user."""+ adapter = _CardAdapter(SendResult(success=False, error="slack 500"))+ runner = _card_runner(adapter)+ st = _card_state(adapter)++ asyncio.run(runner._task_card_publish(st))++ assert adapter.fallbacks == ["fallback"]+ assert st.native_failed is True+++def test_task_card_decline_suppression_persists_across_updates():+ """R5-4: my round-4 fix suppressed exactly ONE update.++ It set `native_failed`, which the entry gate already uses for an ordinary+ broken lane — so the NEXT progress event skipped the decline branch and+ went straight to the text fallback. Measured: [] then ['send'].+ A refusal does not expire after one tick.+ """+ adapter = _CardAdapter(+ SendResult(success=False, error="declined", raw_response=CODE_ONLY_DECLINE)+ )+ runner = _card_runner(adapter)+ st = _card_state(adapter)++ asyncio.run(runner._task_card_publish(st))+ asyncio.run(runner._task_card_publish(st))+ asyncio.run(runner._task_card_publish(st))++ assert adapter.fallbacks == []+++def test_ORDINARY_failure_still_falls_back_on_every_later_update():+ """Control: a broken card lane must keep reaching the user each update."""+ adapter = _CardAdapter(SendResult(success=False, error="slack 500"))+ runner = _card_runner(adapter)+ st = _card_state(adapter)++ asyncio.run(runner._task_card_publish(st))+ asyncio.run(runner._task_card_publish(st))++ assert len(adapter.fallbacks) == 2+++# ── the edit lane (round 6): one dropped raw_response, three leaks ──────────+++class _EditAdapter:+ """Records every op; the edit is refused with a code-only decline."""++ def __init__(self) -> None:+ self.ops: List[str] = []++ @staticmethod+ def extract_media(text):+ return [], text++ async def edit_message(self, **k: Any) -> SendResult:+ self.ops.append("edit")+ return SendResult(+ success=False, error="declined", raw_response=CODE_ONLY_DECLINE+ )++ async def send(self, *a: Any, **k: Any) -> SendResult:+ self.ops.append("send")+ return SendResult(success=True, message_id="m1")+++def test_queued_reconcile_decline_does_not_fall_back_to_a_send():+ """R6-3: `_deliver_queued_first_response` re-sent the WHOLE response.++ Its reconcile-by-edit falls through to `adapter.send` on any failure, so a+ refused edit delivered the full text to the refused chat. Measured:+ [('edit', 'SECRET'), ('send', 'SECRET')].+ """+ from gateway.run_notifications import GatewayNotificationsMixin++ adapter = _EditAdapter()+ mixin = object.__new__(GatewayNotificationsMixin)+ source = SimpleNamespace(chat_id="C1", platform="discord")+ consumer = SimpleNamespace(message_id="m0", _turn_split_delivery=False)++ asyncio.run(+ mixin._deliver_queued_first_response(+ "SECRET", source, adapter, stream_consumer=consumer, deliver_media=False+ )+ )++ assert adapter.ops == ["edit"]+++def test_queued_reconcile_ORDINARY_edit_failure_still_sends():+ """Control: a genuinely un-editable message must still be delivered."""+ from gateway.run_notifications import GatewayNotificationsMixin++ class _Ordinary(_EditAdapter):+ async def edit_message(self, **k: Any) -> SendResult:+ self.ops.append("edit")+ return SendResult(success=False, error="message too old")++ adapter = _Ordinary()+ mixin = object.__new__(GatewayNotificationsMixin)+ source = SimpleNamespace(chat_id="C1", platform="discord")+ consumer = SimpleNamespace(message_id="m0", _turn_split_delivery=False)++ asyncio.run(+ mixin._deliver_queued_first_response(+ "SECRET", source, adapter, stream_consumer=consumer, deliver_media=False+ )+ )++ assert adapter.ops == ["edit", "send"]+++def test_task_card_fallback_edit_decline_does_not_send_progress_text():+ """R6-4: R5-4 covered the native card, not the editable-text fallback."""+ adapter = _EditAdapter()+ runner = object.__new__(__import__("gateway.run_turn_runner", fromlist=["x"]).TurnRunner)+ runner._ctx = SimpleNamespace(+ source=SimpleNamespace(chat_id="C1", platform="slack"),+ _progress_metadata={},+ )+ sent = []+ runner._send_progress_text = lambda st, text: sent.append(text)+ st = SimpleNamespace(+ fallback_msg_id="m0",+ fallback_text=lambda: "task text",+ adapter=adapter,+ egress_declined=False,+ )++ asyncio.run(runner._task_card_send_or_edit_fallback(st))++ assert adapter.ops == ["edit"]+ assert sent == []+ assert st.egress_declined is Truediff --git a/tests/gateway/test_prompt_decline_no_fallback.py b/tests/gateway/test_prompt_decline_no_fallback.pynew file mode 100644index 00000000000..e12490d5c3d--- /dev/null+++ b/tests/gateway/test_prompt_decline_no_fallback.py@@ -0,0 +1,257 @@+"""P5(b) at the CALLER: a connector egress decline must not fall back.++The adapter-level tests prove the decline REACHES the caller. These prove the+caller ACTS on it. Review round 1 blocker B-3: `_approval_send_outcome` had+only sent/failed/ambiguous, so a decline collapsed into `failed` — which is+precisely the cue to run the plain-text fallback into the chat the connector+had just refused. The adapter fix improved the error STRING while the+user-visible behaviour stayed identical to base.++These tests drive the real `gateway.run` classifier and the real+`tools.slash_confirm` registry; only the SendResult (the connector's answer)+is constructed.+"""++from __future__ import annotations++import concurrent.futures+from types import SimpleNamespace++import pytest++DECLINE_ERROR = (+ "discord egress declined: target is not an approved destination for this connection"+)+LANE_ERROR = "relay prompt op unavailable"+++def _future(result):+ fut: concurrent.futures.Future = concurrent.futures.Future()+ fut.set_result(result)+ return fut+++def _result(*, success: bool, error: str | None = None):+ return SimpleNamespace(success=success, error=error, message_id=None)+++# ── the classifier ──────────────────────────────────────────────────────────+++def test_decline_is_not_classified_as_failed():+ """`failed` is the fallback cue; a decline must not wear it."""+ from gateway.run import _approval_send_outcome++ outcome = _approval_send_outcome(+ _future(_result(success=False, error=DECLINE_ERROR)), timeout=5+ )+ assert outcome == "declined"+++def test_genuine_lane_failure_still_falls_back():+ """The guard must not swallow real failures: those still re-ask."""+ from gateway.run import _approval_send_outcome++ outcome = _approval_send_outcome(+ _future(_result(success=False, error=LANE_ERROR)), timeout=5+ )+ assert outcome == "failed"+++def test_success_and_timeout_verdicts_unchanged():+ """No collateral change to the two settled verdicts."""+ from gateway.run import _approval_send_outcome++ assert (+ _approval_send_outcome(_future(_result(success=True)), timeout=5) == "sent"+ )++ pending: concurrent.futures.Future = concurrent.futures.Future()+ assert _approval_send_outcome(pending, timeout=0.05) == "ambiguous"+++ "error",+ [+ DECLINE_ERROR,+ "slack egress declined: destination not permitted",+ # Case-insensitivity is part of the contract (`.lower()` in+ # is_egress_decline), so a connector that capitalises still classifies.+ "WhatsApp Egress Declined: target refused",+ ],+)+def test_decline_recognised_across_lanes(error):+ """The verdict follows the decline CONTRACT, not one lane's wording.++ The contract is `EGRESS_DECLINE_MARKER` ("egress declined:") or a+ structured `code`; an invented sentence like "EGRESS_DECLINED: ..." is NOT+ a decline and must not be treated as one. My first version of this test+ asserted that invented form and failed — the test was wrong, not the code.+ """+ from gateway.run import _approval_send_outcome++ assert (+ _approval_send_outcome(_future(_result(success=False, error=error)), timeout=5)+ == "declined"+ )+++def test_non_decline_error_text_is_not_laundered_into_declined():+ """Fail-closed the other way: only the real contract yields `declined`.++ Without this, a permissive marker check would silence genuine failures —+ turning a lane outage into a silent no-fallback.+ """+ from gateway.run import _approval_send_outcome++ for error in (+ "connection reset by peer",+ "declined", # bare word, not the marker sentence+ "egress declined", # no colon: not the uniform marker+ ):+ assert (+ _approval_send_outcome(+ _future(_result(success=False, error=error)), timeout=5+ )+ == "failed"+ ), error+++# ── the STRUCTURED response, not the rendered string ────────────────────────+#+# Round-2 review: I fixed the text-marker path and tested only the text-marker+# path. The adapter preserves the connector's own dict in `raw_response`, and+# classifying the error STRING instead loses two contracts.+++def _result_raw(raw, *, error=None):+ from gateway.relay.egress import decline_error++ return SimpleNamespace(+ success=False, error=error if error is not None else decline_error(raw),+ raw_response=raw,+ )+++def test_code_only_decline_is_declined_not_failed():+ """A decline carrying `code` and NO text must not fall back.++ `decline_error()` renders it as "relay egress declined" — no marker colon —+ so a string-based check returns `failed`, which is the fallback cue. This+ is the shape the connector actually sends when it has no human text.+ """+ from gateway.run import _approval_send_outcome++ raw = {"success": False, "code": "egress_declined"}+ assert _approval_send_outcome(_future(_result_raw(raw)), timeout=5) == "declined"+++def test_ambiguous_result_is_never_a_definite_failure():+ """Lost ack ≠ refusal ≠ failure.++ `is_egress_decline` deliberately excludes `ambiguous`, because the frame+ may well have been applied. Flattening it into `failed` re-sends a card+ that may already be on the user's screen — the duplicate-card bug the+ ambiguous verdict was introduced to prevent.+ """+ from gateway.run import _approval_send_outcome++ raw = {"success": False, "ambiguous": True, "error": "lost ack"}+ assert _approval_send_outcome(_future(_result_raw(raw)), timeout=5) == "ambiguous"+++def test_ambiguous_wins_over_decline_text():+ """An ambiguous result carrying decline text is STILL ambiguous.++ Order matters: a mid-write drop whose partial error happens to contain the+ marker must not be reported as a definite refusal.+ """+ from gateway.run import _approval_send_outcome++ raw = {+ "success": False,+ "ambiguous": True,+ "error": "discord egress declined: target is not approved",+ }+ assert _approval_send_outcome(_future(_result_raw(raw)), timeout=5) == "ambiguous"+++def test_structured_lane_failure_still_falls_back():+ """A structured NON-decline failure keeps its fallback."""+ from gateway.run import _approval_send_outcome++ raw = {"success": False, "error": "connection reset"}+ assert _approval_send_outcome(_future(_result_raw(raw)), timeout=5) == "failed"+++def test_legacy_connector_without_raw_response_still_classified():+ """No `raw_response` (older connector) falls back to the wire sentence."""+ from gateway.run import _approval_send_outcome++ legacy = SimpleNamespace(success=False, error=DECLINE_ERROR, raw_response=None)+ assert _approval_send_outcome(_future(legacy), timeout=5) == "declined"+++def test_declined_clarify_aborts_instead_of_waiting_for_a_reply():+ """Review round 3, finding 4.++ `_clarify_send_disposition` handled `failed` and `ambiguous`; `declined`+ fell through to `wait_for_response`, so the agent blocked until+ clarify_timeout for a card that was REFUSED and can never be answered.+ A decline is more definitive than a failure, not less.+ """+ from types import SimpleNamespace++ from gateway.relay.egress import EGRESS_DECLINE_CODE+ from gateway.run import _clarify_send_disposition++ cleared = []+ clarify_mod = SimpleNamespace(+ clear_session=lambda sk: cleared.append(sk),+ get_clarify_timeout=lambda: 600,+ wait_for_response=lambda *a, **k: pytest.fail(+ "waited for a reply to a prompt the connector refused"+ ),+ )++ class _Fut:+ def result(self, timeout=None):+ return SimpleNamespace(+ success=False,+ error=None,+ raw_response={"success": False, "code": EGRESS_DECLINE_CODE},+ )++ abort = _clarify_send_disposition(+ _Fut(), session_key="sk1", clarify_mod=clarify_mod+ )+ assert abort is not None+ assert cleared == ["sk1"]+++def test_ambiguous_clarify_still_waits():+ """Control: a possibly-delivered card must STAY armed for a late reply."""+ from types import SimpleNamespace++ from gateway.run import _clarify_send_disposition++ cleared = []+ clarify_mod = SimpleNamespace(+ clear_session=lambda sk: cleared.append(sk),+ get_clarify_timeout=lambda: 600,+ wait_for_response=lambda *a, **k: "answer",+ )++ class _Fut:+ def result(self, timeout=None):+ return SimpleNamespace(+ success=False,+ error="lost ack",+ raw_response={"success": False, "error": "x", "ambiguous": True},+ )++ assert (+ _clarify_send_disposition(_Fut(), session_key="sk1", clarify_mod=clarify_mod)+ is None+ )+ assert cleared == []diff --git a/tests/tools/test_send_message_relay_target_authz.py b/tests/tools/test_send_message_relay_target_authz.pynew file mode 100644index 00000000000..87ec2503c00--- /dev/null+++ b/tests/tools/test_send_message_relay_target_authz.py@@ -0,0 +1,1423 @@+"""P5(a): `send_message` cannot silently name an arbitrary relay target.++The `target` tool parameter is free-form (`'platform:chat_id'`), so before+this guard a model could name ANY chat id and the gateway would emit an+outbound relay frame for it — authenticating the sender while never+authorizing the destination. These tests drive the REAL `send_message_tool`+entrypoint through the REAL production wiring (`gateway.relay.egress`,+`gateway.channel_directory`, `gateway.relay.relay_fronted_platforms`) against+a temp HERMES_HOME; nothing under test is constructed by the test itself.+"""++from __future__ import annotations++import json++import pytest++from gateway.config import Platform+from tools.send_message_tool import send_message_tool++ATTESTED_CHAT = "111111111111111111"+ARBITRARY_CHAT = "999999999999999999"+HOME_CHAT = "222222222222222222"+++def relay_env(tmp_path, monkeypatch):+ """A gateway whose ONLY reachable Discord destinations are attested.++ Mirrors the production shape: `GATEWAY_RELAY_PLATFORMS` is the deploy+ stamp `gateway.relay.relay_fronted_platforms()` reads, the channel+ directory json is the file `channel_directory.load_directory()` reads, and+ no live native adapter exists in this process (so the relay owns egress+ for `discord`, exactly as `gateway/delivery.resolve_delivery_transport`+ decides it).+ """+ import gateway.channel_directory as cd++ monkeypatch.setenv("GATEWAY_RELAY_URL", "wss://connector.example/relay")+ monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", "discord")+ monkeypatch.setenv("GATEWAY_RELAY_BOT_IDS", json.dumps({"discord": {"botId": "b1"}}))++ directory = tmp_path / "channel_directory.json"+ directory.write_text(+ json.dumps(+ {+ "updated_at": None,+ "platforms": {+ "discord": [+ {"id": ATTESTED_CHAT, "name": "bot-home", "type": "channel"}+ ]+ },+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(cd, "DIRECTORY_PATH", directory)+ monkeypatch.setattr(cd, "CHANNEL_ALIASES_PATH", tmp_path / "channel_aliases.json")+ # No gateway-session origins for discord in this temp home.+ monkeypatch.setattr(cd, "_build_from_sessions", lambda _platform: [])+ return directory+++def _send(target: str, sent):+ """Invoke the real tool, recording any egress it attempts."""+ from types import SimpleNamespace+ from unittest.mock import patch++ import asyncio++ discord_cfg = SimpleNamespace(enabled=True, token="t", extra={})+ config = SimpleNamespace(+ platforms={Platform.DISCORD: discord_cfg},+ get_home_channel=lambda _p: SimpleNamespace(chat_id=HOME_CHAT),+ )++ async def _record(platform, pconfig, chat_id, message, **kwargs):+ sent.append(chat_id)+ return {"success": True, "message_id": "m1"}++ with patch("gateway.config.load_gateway_config", return_value=config), patch(+ "tools.interrupt.is_interrupted", return_value=False+ ), patch("model_tools._run_async", side_effect=lambda c: asyncio.run(c)), patch(+ "tools.send_message_tool._send_to_platform", side_effect=_record+ ), patch(+ "gateway.mirror.mirror_to_session", return_value=False+ ):+ return json.loads(+ send_message_tool(+ {"action": "send", "target": target, "message": "hello"}+ )+ )+++def test_arbitrary_relay_chat_id_is_refused_and_never_egresses(relay_env):+ """The whole observable: refused, naming THAT target, and ZERO egress."""+ sent: list[str] = []+ result = _send(f"discord:{ARBITRARY_CHAT}", sent)++ assert result == {+ "error": (+ f"Refusing to send to unattested relay target 'discord:{ARBITRARY_CHAT}': "+ "this gateway has no record of that destination. Use "+ "send_message(action='list') to see the targets it can reach."+ )+ }+ assert sent == []+++def test_attested_directory_chat_id_still_sends(relay_env):+ """The guard must not destroy the feature: an attested chat goes through."""+ sent: list[str] = []+ result = _send(f"discord:{ATTESTED_CHAT}", sent)++ assert result == {"success": True, "message_id": "m1"}+ assert sent == [ATTESTED_CHAT]+++def test_home_channel_is_attested(relay_env):+ """The operator-configured home channel is a provenance, not a guess."""+ sent: list[str] = []+ result = _send("discord", sent)++ assert result["success"] is True+ assert sent == [HOME_CHAT]+++def test_session_origin_chat_is_attested(relay_env, monkeypatch):+ """A chat this gateway actually holds a session in is reachable."""+ import gateway.channel_directory as cd++ monkeypatch.setattr(+ cd,+ "_build_from_sessions",+ lambda platform: (+ [{"id": ARBITRARY_CHAT, "name": "seen", "type": "channel"}]+ if platform == "discord"+ else []+ ),+ )+ sent: list[str] = []+ result = _send(f"discord:{ARBITRARY_CHAT}", sent)++ assert result["success"] is True+ assert sent == [ARBITRARY_CHAT]+++def test_platform_not_fronted_by_relay_is_untouched(relay_env, monkeypatch):+ """Non-relay platforms keep their own adapters' authorization, unchanged."""+ monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", "telegram")+ monkeypatch.setenv(+ "GATEWAY_RELAY_BOT_IDS", json.dumps({"telegram": {"botId": "b1"}})+ )+ sent: list[str] = []+ result = _send(f"discord:{ARBITRARY_CHAT}", sent)++ assert result["success"] is True+ assert sent == [ARBITRARY_CHAT]+++def test_live_native_adapter_takes_precedence_over_the_relay_guard(+ relay_env, monkeypatch+):+ """A platform served by a live NATIVE adapter here is not a relay egress.++ Same precedence `gateway/delivery.resolve_delivery_transport` applies: a+ concrete native adapter always wins over the relay, so this guard must not+ fire for it.+ """+ from types import SimpleNamespace++ import gateway.run++ runner = SimpleNamespace(adapters={Platform.DISCORD: object()})+ monkeypatch.setattr(gateway.run, "_gateway_runner_ref", lambda: runner)+ sent: list[str] = []+ result = _send(f"discord:{ARBITRARY_CHAT}", sent)++ assert result["success"] is True+ assert sent == [ARBITRARY_CHAT]+++def test_react_refuses_an_arbitrary_relay_target(relay_env):+ """Reactions are outbound acts too — same floor, same refusal."""+ result = json.loads(+ send_message_tool(+ {+ "action": "react",+ "target": f"discord:{ARBITRARY_CHAT}",+ "emoji": "👍",+ }+ )+ )+ assert result == {+ "error": (+ f"Refusing to send to unattested relay target 'discord:{ARBITRARY_CHAT}': "+ "this gateway has no record of that destination. Use "+ "send_message(action='list') to see the targets it can reach."+ )+ }++# ── B-1: the guard must authorize the RESOLVED destination ──────────────────+#+# Slack `@handle` / `U...` targets are internal PSEUDO-ids+# (`user_name:ben`, `user:U...`) until `_resolve_slack_user_target` opens the+# DM and returns the real `D...` conversation. Provenances only ever hold+# resolved ids, so authorizing the pseudo-id compares a handle against a set+# of channel ids and refuses every Slack DM — an OUTAGE caused by a security+# fix. Review round 1 found this; reproduced before fixing.+#+# These tests are the falsifiable floor for the guard's POSITION: they pass+# only while authorization happens AFTER resolution.++SLACK_DM = "D01234567AB"+SLACK_USER = "U01234567AB"+++def slack_relay_env(tmp_path, monkeypatch):+ """A relay-fronted Slack gateway whose attested destination is a DM id."""+ import gateway.channel_directory as cd++ monkeypatch.setenv("GATEWAY_RELAY_URL", "wss://connector.example/relay")+ monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", "slack")+ monkeypatch.setenv("GATEWAY_RELAY_BOT_IDS", json.dumps({"slack": {"botId": "b1"}}))++ directory = tmp_path / "channel_directory.json"+ directory.write_text(+ json.dumps(+ {+ "updated_at": None,+ # The DM conversation id — what resolution produces, and the+ # only form any provenance ever stores.+ "platforms": {"slack": [{"id": SLACK_DM, "name": "ben", "type": "im"}]},+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(cd, "DIRECTORY_PATH", directory)+ monkeypatch.setattr(cd, "CHANNEL_ALIASES_PATH", tmp_path / "channel_aliases.json")+ monkeypatch.setattr(cd, "_build_from_sessions", lambda _platform: [])+ return directory+++def _send_slack(target: str, sent, *, resolves_to: str | None = SLACK_DM):+ """Invoke the real tool with the REAL Slack resolution step in the path.++ Only `conversations.open` is faked (a network call). The ordering of the+ guard against the resolver is production's.+ """+ import asyncio+ from types import SimpleNamespace+ from unittest.mock import patch++ slack_cfg = SimpleNamespace(enabled=True, token="xoxb-t", extra={})+ config = SimpleNamespace(+ platforms={Platform.SLACK: slack_cfg},+ get_home_channel=lambda _p: SimpleNamespace(chat_id=SLACK_DM),+ )++ async def _record(platform, pconfig, chat_id, message, **kwargs):+ sent.append(chat_id)+ return {"success": True, "message_id": "m1"}++ async def _resolve(_token, target_ref):+ # Stands in for the Slack API call only; returns what production's+ # resolver returns — the opened DM channel id.+ return (resolves_to, None)++ with patch("gateway.config.load_gateway_config", return_value=config), patch(+ "tools.interrupt.is_interrupted", return_value=False+ ), patch("model_tools._run_async", side_effect=lambda c: asyncio.run(c)), patch(+ "tools.send_message_tool._send_to_platform", side_effect=_record+ ), patch(+ "tools.send_message_tool._resolve_slack_user_target", side_effect=_resolve+ ), patch(+ "gateway.mirror.mirror_to_session", return_value=False+ ):+ return json.loads(+ send_message_tool({"action": "send", "target": target, "message": "hello"})+ )+++ "target",+ [f"slack:@ben", f"slack:{SLACK_USER}", f"slack:<@{SLACK_USER}>"],+)+def test_slack_user_targets_resolve_then_authorize(slack_relay_env, target):+ """An attested DM must SEND regardless of which alias names it.++ Fails if the guard runs before resolution: the pseudo-id+ (`user_name:ben` / `user:U...`) is not in any provenance, so the send is+ refused and `sent` stays empty.+ """+ sent: list[str] = []+ result = _send_slack(target, sent)++ assert result == {"success": True, "message_id": "m1"}+ # The whole observable: it egressed, and to the RESOLVED destination.+ assert sent == [SLACK_DM]+++def test_slack_user_target_resolving_to_unattested_dm_is_refused(slack_relay_env):+ """Moving the guard must not disable it.++ A handle that resolves to a DM this gateway cannot attest is still+ refused — and the refusal names the RESOLVED id, which is the destination+ that was actually authorized.+ """+ sent: list[str] = []+ unattested = "D99999999XX"+ result = _send_slack("slack:@stranger", sent, resolves_to=unattested)++ assert result == {+ "error": (+ f"Refusing to send to unattested relay target 'slack:{unattested}': "+ "this gateway has no record of that destination. Use "+ "send_message(action='list') to see the targets it can reach."+ )+ }+ assert sent == []+++# ── the guard must FAIL CLOSED on its own fault ─────────────────────────────+#+# Round-2 review: `_authorize_relay_target` wrapped BOTH the import and the+# call in one `except Exception: return None`, and None means AUTHORIZED. So+# any runtime bug inside the guard silently switched the whole P5(a) boundary+# off — the most expensive possible failure mode for an authorization check.+++def test_guard_fault_refuses_rather_than_authorizing(relay_env, monkeypatch):+ """A guard that cannot answer must refuse, and must not egress."""+ import gateway.relay.egress as eg+ from tools import send_message_tool as smt++ def _boom(*_a, **_k):+ raise RuntimeError("bug inside the guard")++ monkeypatch.setattr(eg, "authorize_relay_target", _boom)++ denial = smt._authorize_relay_target("discord", ATTESTED_CHAT)+ assert denial is not None, "a faulting guard authorized the send"+ assert "authorization check failed" in denial++ # And end to end: nothing may egress.+ sent: list[str] = []+ result = _send(f"discord:{ATTESTED_CHAT}", sent)+ assert "error" in result+ assert sent == []+++def test_missing_gateway_package_still_allows(relay_env, monkeypatch):+ """The tolerated case survives: no gateway ⇒ no relay egress to authorize.++ This is the distinction the original code collapsed. Keeping it tested+ stops a future "make it fail closed" change from breaking the CLI-only+ install.+ """+ import builtins++ from tools import send_message_tool as smt++ real_import = builtins.__import__++ def _no_gateway(name, *a, **k):+ if name.startswith("gateway.relay.egress"):+ # The shape real absence takes: ModuleNotFoundError WITH a name.+ # A bare ImportError is not something a missing module produces,+ # and treating it as absence was a fail-open (round 4, blocker 1).+ raise ModuleNotFoundError("no gateway package", name="gateway")+ return real_import(name, *a, **k)++ monkeypatch.setattr(builtins, "__import__", _no_gateway)+ assert smt._authorize_relay_target("discord", ARBITRARY_CHAT) is None+++# ── fail-open boundaries: ABSENCE is not FAULT ─────────────────────────────+++def test_route_discovery_fault_refuses_rather_than_authorizing(relay_env, monkeypatch):+ """A fault while determining relay routing must DENY, not fall through.++ `_relay_fronted` used to swallow every exception and return an empty set,+ which `relay_routed_platform` reads as "not relay-routed" — skipping the+ guard entirely. Review injected a discovery fault and watched an+ unattested target get authorized.+ """+ import gateway.relay as gr+ from tools.send_message_tool import _authorize_relay_target++ def boom():+ raise RuntimeError("config unreadable while listing fronted platforms")++ monkeypatch.setattr(gr, "relay_fronted_platforms", boom)+ denial = _authorize_relay_target("discord", "999")+ assert denial is not None+ assert "could not be" in denial+++def test_missing_relay_module_still_authorizes(relay_env, monkeypatch):+ """The converse: genuine ABSENCE must keep working (no gateway ⇒ no relay).++ Without this, "fail closed on faults" would silently become "refuse+ everything in CLI/cron contexts", which is the outage the original broad+ except was there to avoid.+ """+ import gateway.relay as gr+ from tools.send_message_tool import _authorize_relay_target++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ assert _authorize_relay_target("discord", "999") is None+++def test_relay_module_import_fault_refuses(monkeypatch):+ """A module that EXISTS but fails to import is a fault, not an absence."""+ import builtins++ import tools.send_message_tool as smt++ real_import = builtins.__import__++ def fake_import(name, *a, **kw):+ if name == "gateway.relay.egress":+ raise RuntimeError("broken dependency inside an installed gateway")+ return real_import(name, *a, **kw)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ denial = smt._authorize_relay_target("discord", "999")+ assert denial is not None+ assert "could not be" in denial++[email protected]("configured", ["discord", "Discord", "DISCORD", " discord "])+def test_relay_fronted_matching_is_case_insensitive(relay_env, monkeypatch, configured):+ """Review round 3, finding 3 — an attestation bypass on a string compare.++ `relay_routed_platform` lowercases the REQUESTED name but `_relay_fronted`+ returned configured names verbatim, so a platform configured as "Discord"+ missed the membership test and looked native — skipping the guard entirely.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {configured})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())+ assert eg.authorize_relay_target("discord", "999") is not None++[email protected]("requested", ["Discord", "DISCORD", " discord "])+def test_requested_platform_name_is_also_normalised(relay_env, monkeypatch, requested):+ """The OTHER half of round 3, finding 3 — and it was never covered.++ The test above varies the CONFIGURED name while always requesting+ lowercase "discord", so it only pins `_relay_fronted`'s normalisation.+ Removing `.lower()` from the REQUESTED name in `relay_routed_platform`+ (and in `authorize_relay_target`) therefore survived the whole suite.++ SCOPE, precisely: `send_message` itself cannot reach this, because+ `_resolve_tool_target` lowercases the platform at+ tools/send_message_tool.py:47 before the guard is called. This pins the+ HELPERS' own contract for every other caller — the gateway lanes, and any+ future entry point that does not pre-normalise. Both functions are public+ within the package and must not assume a lowercased argument.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())++ assert eg.relay_routed_platform(requested) is True+ assert eg.authorize_relay_target(requested, "999") is not None++[email protected]("requested", ["Discord", "DISCORD"])+def test_mixed_case_request_still_reaches_attested_targets(relay_env, monkeypatch, requested):+ """Control: normalising the requested name must not refuse real traffic.++ The attestation store is keyed by the LOWERCASE platform. If the lookup in+ `attested_relay_targets` / `authorize_relay_target` stops normalising, a+ mixed-case request misses its own attested set and is refused — an OUTAGE+ for legitimate traffic rather than a bypass. Both directions matter, so the+ lookup name is asserted, not just the routing decision.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ seen = []++ def _attested(platform):+ seen.append(platform)+ return {"999"} if platform == "discord" else set()++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", _attested)++ assert eg.authorize_relay_target(requested, "999") is None+ # The store was queried with the NORMALISED name.+ assert seen and all(p == "discord" for p in seen), seen++[email protected]("requested", ["Discord", "DISCORD", " discord "])+def test_attested_lookup_normalises_before_querying_the_sources(relay_env, monkeypatch, requested):+ """`attested_relay_targets` does its OWN normalisation, and every other+ test monkeypatches this function away — so that `.lower()` was covered by+ nothing. Dropping it made a mixed-case platform find an EMPTY attested set+ (its sources are keyed lowercase), refusing legitimate traffic.++ Asserted against the real function with only its leaf sources stubbed.+ """+ import gateway.relay.egress as eg++ monkeypatch.setattr(eg, "_home_channel_id", lambda n: None)+ monkeypatch.setattr(eg, "_directory_ids", lambda n: {"999"} if n == "discord" else set())+ monkeypatch.setattr(eg, "_session_ids", lambda n: set())++ assert eg.attested_relay_targets(requested) == {"999"}+++def test_attested_target_still_allowed_when_config_case_differs(relay_env, monkeypatch):+ """Control: normalizing must not start refusing legitimate traffic."""+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"Discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"999"})+ assert eg.authorize_relay_target("discord", "999") is None+++def test_nested_dependency_importerror_refuses(monkeypatch):+ """Review round 3, finding 2 — `except ImportError` was still fail-open.++ An ImportError naming a NESTED module means an installed gateway failed to+ load (broken dependency). That is a fault, not "there is no relay here",+ and returning None means authorized.+ """+ import builtins++ import tools.send_message_tool as smt++ real_import = builtins.__import__++ def fake_import(name, *a, **kw):+ if name == "gateway.relay.egress":+ raise ModuleNotFoundError(+ "No module named 'gateway.relay.dependency'",+ name="gateway.relay.dependency",+ )+ return real_import(name, *a, **kw)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ denial = smt._authorize_relay_target("discord", "999")+ assert denial is not None+++def test_absent_gateway_module_importerror_still_authorizes(monkeypatch):+ """Control: genuine absence (CLI/cron) must keep working."""+ import builtins++ import tools.send_message_tool as smt++ real_import = builtins.__import__++ def fake_import(name, *a, **kw):+ if name == "gateway.relay.egress":+ raise ModuleNotFoundError("No module named 'gateway'", name="gateway")+ return real_import(name, *a, **kw)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ assert smt._authorize_relay_target("discord", "999") is None+++def test_nameless_importerror_refuses(monkeypatch):+ """Round 4, blocker 1 — a bare ImportError is a FAULT, not absence.++ Genuine absence raises ModuleNotFoundError with `.name` set (verified+ against the interpreter). A plain ImportError therefore comes from an+ import hook or a module that failed while initializing, and authorizing on+ it means any such fault silently disables the boundary.+ """+ import builtins++ import tools.send_message_tool as smt++ real_import = builtins.__import__++ def fake_import(name, *a, **kw):+ if name == "gateway.relay.egress":+ raise ImportError("something went wrong during init")+ return real_import(name, *a, **kw)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ assert smt._authorize_relay_target("discord", "999") is not None+++def test_session_attestation_does_not_invent_a_matrix_room_prefix(monkeypatch):+ """Round 4, blocker 2 — the attestation set must not FABRICATE ids.++ `_session_ids` split every id on the first colon to recover "chat" from+ "chat:thread". Matrix room ids contain a colon natively+ (`!room:server.org`), so the split attested a bare `!room` that no session+ ever used — the guard vouching for a destination on its own invention.+ """+ import gateway.channel_directory as cd+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"matrix"})+ # A Matrix room with NO thread: the colon is part of the address itself.+ monkeypatch.setattr(+ cd,+ "_build_from_sessions",+ lambda p: [{"id": "!owned:server.org", "thread_id": None}],+ )++ # The real session id is still attested...+ assert eg.authorize_relay_target("matrix", "!owned:server.org") is None+ # ...but the invented prefix is not.+ assert eg.authorize_relay_target("matrix", "!owned") is not None+++def test_session_attestation_still_recovers_a_slack_thread_parent(monkeypatch):+ """Control: thread-parent recovery must keep working.++ Slack session ids are genuinely `chat:thread` and the connector authorizes+ the CHAT, so failing to recover the parent would refuse legitimate replies.+ """+ import gateway.channel_directory as cd+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"slack"})+ # A genuinely thread-qualified entry carries thread_id separately, which is+ # how the parent is recovered — no string guessing.+ monkeypatch.setattr(+ cd,+ "_build_from_sessions",+ lambda p: [{"id": "C123:1700000000.1", "thread_id": "1700000000.1"}],+ )++ assert eg.authorize_relay_target("slack", "C123") is None+++def test_egress_module_own_import_boundary_fails_closed(monkeypatch):+ """Round 4, non-blocking finding: `gateway/relay/egress.py` has its OWN+ import boundary (`_relay_fronted` -> `from gateway.relay import ...`), and+ the existing nested-ImportError test intercepts the EARLIER import in+ tools/send_message_tool.py, so this one was never exercised.+ """+ import builtins++ import gateway.relay.egress as eg++ real_import = builtins.__import__++ def fake_import(name, *a, **kw):+ if name == "gateway.relay" and "relay_fronted_platforms" in (kw.get("fromlist") or a[2] if len(a) > 2 else []):+ raise ModuleNotFoundError("broken dep", name="gateway.relay.broken_dep")+ return real_import(name, *a, **kw)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ with pytest.raises(eg.RelayRouteUnknown):+ eg._relay_fronted()+++def test_matrix_thread_parent_is_recovered_without_splitting_the_room_id(monkeypatch):+ """The case the allow-list could never have handled correctly.++ A Matrix room id contains a colon AND the session can be thread-qualified:+ `!room:server.org:$thread`. Splitting on the FIRST colon yields `!room`+ (invented); using the structured `thread_id` yields the real room.+ """+ import gateway.channel_directory as cd+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"matrix"})+ monkeypatch.setattr(+ cd,+ "_build_from_sessions",+ lambda p: [{"id": "!room:server.org:$thr", "thread_id": "$thr"}],+ )++ assert eg.authorize_relay_target("matrix", "!room:server.org") is None+ assert eg.authorize_relay_target("matrix", "!room") is not None+++# ── round 5 ────────────────────────────────────────────────────────────────+++def test_disabled_native_adapter_is_not_treated_as_native(monkeypatch):+ """R5-1: the guard and the delivery router must not disagree about routing.++ `resolve_delivery_transport` ignores a native adapter whose config is+ DISABLED and routes over Relay. `_has_live_native_adapter` treated mere+ presence in the adapter map as native, so the guard skipped authorization+ for a send that actually went over the relay.+ """+ from types import SimpleNamespace++ import gateway.relay.egress as eg+ from gateway.config import Platform++ monkeypatch.setattr(+ eg,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.DISCORD: object()}),+ raising=False,+ )+ import gateway.run as gr_run++ monkeypatch.setattr(gr_run, "_gateway_runner_ref", eg._gateway_runner_ref, raising=False)+ monkeypatch.setattr(+ eg,+ "load_gateway_config",+ lambda: SimpleNamespace(+ platforms={Platform.DISCORD: SimpleNamespace(enabled=False)}+ ),+ raising=False,+ )+ import gateway.config as gc++ monkeypatch.setattr(+ gc,+ "load_gateway_config",+ lambda: SimpleNamespace(+ platforms={Platform.DISCORD: SimpleNamespace(enabled=False)}+ ),+ )+ assert eg._has_live_native_adapter("discord") is False+++def test_enabled_native_adapter_is_still_native(monkeypatch):+ """Control: an ENABLED native adapter must keep bypassing the relay guard."""+ from types import SimpleNamespace++ import gateway.config as gc+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ ref = lambda: SimpleNamespace(adapters={Platform.DISCORD: object()}) # noqa: E731+ monkeypatch.setattr(gr_run, "_gateway_runner_ref", ref, raising=False)+ monkeypatch.setattr(+ gc,+ "load_gateway_config",+ lambda: SimpleNamespace(+ platforms={Platform.DISCORD: SimpleNamespace(enabled=True)}+ ),+ )+ assert eg._has_live_native_adapter("discord") is True+++def test_arbitrary_thread_under_an_attested_parent_is_refused(relay_env, monkeypatch):+ """R5-2: on Discord the THREAD is the REST destination.++ `POST /channels/{thread_id}/messages` — so an attested parent channel must+ not vouch for a caller-supplied thread the gateway has never seen.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"111"})+ assert eg.authorize_relay_target("discord", "111", "999") is not None+++def test_attested_thread_is_allowed(relay_env, monkeypatch):+ """Control: a thread the gateway HAS a provenance for must still send.++ Only the BOUND `chat:thread` form counts. This test used to also accept a+ bare `{"111", "999"}` and so pinned a real defect: an unrelated attested+ chat whose id equalled the requested thread id authorized that thread. The+ bound form is what `_session_entry_id` actually records, so nothing+ legitimate is lost.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"111", "111:999"})+ assert eg.authorize_relay_target("discord", "111", "999") is None+++def test_unrelated_attested_chat_does_not_vouch_for_a_thread(relay_env, monkeypatch):+ """An attested chat id equal to the requested THREAD id proves nothing.++ Reproduced against the pre-fix code: attested `{"-100A", "7"}` plus a+ request for thread `7` under parent `-100A` returned None (authorized),+ though no session ever existed in that thread. `7` is a sibling CHAT, not+ a thread of `-100A`.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"-100A", "7"})+ denial = eg.authorize_relay_target("discord", "-100A", "7")+ assert denial is not None and "no record of" in denial+++def test_a_thread_attested_under_another_parent_is_refused(relay_env, monkeypatch):+ """`B:55` must not authorize thread 55 under parent A."""+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(+ eg, "attested_relay_targets", lambda p: {"-100A", "-100B", "-100B:55"}+ )+ assert eg.authorize_relay_target("discord", "-100A", "55") is not None+ # Control: the same thread under its OWN parent still sends.+ assert eg.authorize_relay_target("discord", "-100B", "55") is None+++def test_tool_guard_forwards_the_thread_id(monkeypatch):+ """The wrapper must PASS thread_id, not just accept it.++ Mutating `_authorize_relay_target` to drop the argument survived every+ other test here — they all call `authorize_relay_target` directly, so+ nothing observed what the tool wrapper forwards. Same gap as the caller+ findings: testing the callee never proves the caller uses it.+ """+ import tools.send_message_tool as smt++ seen = {}++ def fake_authorize(platform_name, chat_id, thread_id=None):+ seen["args"] = (platform_name, chat_id, thread_id)+ return None++ import gateway.relay.egress as eg++ monkeypatch.setattr(eg, "authorize_relay_target", fake_authorize)+ smt._authorize_relay_target("discord", "111", "999")+ assert seen["args"] == ("discord", "111", "999")+++def test_config_read_fault_refuses_rather_than_assuming_native(monkeypatch):+ """R6-1: my own R5-1 fix reintroduced the bypass it was closing.++ `_has_live_native_adapter` caught a `load_gateway_config()` failure and+ returned True, so a config fault declared the platform native while the+ ROUTER — reading the real config — would send over the relay. Routing we+ cannot determine is UNKNOWN, and unknown must refuse.+ """+ from types import SimpleNamespace++ import gateway.config as gc+ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.DISCORD: object()}),+ raising=False,+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())++ def boom():+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(gc, "load_gateway_config", boom)+ assert eg.authorize_relay_target("discord", "999") is not None+++def test_healthy_config_with_enabled_native_still_bypasses_the_guard(monkeypatch):+ """Control: the guard must not start refusing native platforms."""+ from types import SimpleNamespace++ import gateway.config as gc+ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.DISCORD: object()}),+ raising=False,+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())+ monkeypatch.setattr(+ gc,+ "load_gateway_config",+ lambda: SimpleNamespace(+ platforms={Platform.DISCORD: SimpleNamespace(enabled=True)}+ ),+ )+ assert eg.authorize_relay_target("discord", "999") is None+++def test_guard_uses_the_live_adapter_not_stale_env_discovery(monkeypatch):+ """R7-1: the guard and the delivery router read DIFFERENT snapshots.++ `resolve_delivery_transport` asks the CONNECTED relay adapter+ (`fronts_platform`, from the handshake identity set). The guard rebuilt+ routing from `GATEWAY_RELAY_PLATFORMS`. When that env is stale or+ momentarily empty the guard said "native", the router sent over the relay,+ and the guard was skipped for a relay send.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ class _LiveRelay:+ def fronts_platform(self, p):+ return getattr(p, "value", p) == "discord"++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.RELAY: _LiveRelay()}),+ raising=False,+ )+ # Env discovery is empty/stale — the disagreement condition.+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())++ assert eg.relay_routed_platform("discord") is True+ assert eg.authorize_relay_target("discord", "999") is not None+++def test_guard_falls_back_to_config_when_no_live_adapter(monkeypatch):+ """Control: with no live runner (CLI/cron) the config path must still work."""+ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run++ monkeypatch.setattr(gr_run, "_gateway_runner_ref", lambda: None, raising=False)+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: set())++ assert eg.authorize_relay_target("discord", "999") is not None+++def test_a_live_adapter_that_cannot_answer_is_a_fault_not_an_absence(monkeypatch):+ """A LIVE relay adapter whose `fronts_platform()` raises must fail closed.++ This was a real bypass. `_live_relay_fronted` caught every exception and+ returned None, which means "no live adapter — use the config snapshot". So+ a live adapter that could not report its routing PLUS an empty/stale config+ snapshot made the guard conclude "not relay-routed" and authorize an+ unattested destination, while `resolve_delivery_transport` asks that same+ adapter and still routes over the relay. Measured before the fix:+ `relay_routed=False`, verdict `None` for chat `999`.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ class Exploding:+ def fronts_platform(self, platform):+ raise RuntimeError("descriptor lookup failed")++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.RELAY: Exploding()}),+ raising=False,+ )+ # An EMPTY config snapshot: the fallback the fault used to reach.+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+ with pytest.raises(eg.RelayRouteUnknown):+ eg.relay_routed_platform("discord")++ # And the tool-facing guard must refuse rather than authorize.+ from tools.send_message_tool import _authorize_relay_target++ denial = _authorize_relay_target("discord", "999")+ assert denial is not None+ assert "could not" in denial or "unavailable" in denial or "refus" in denial.lower()+++def test_a_missing_relay_adapter_is_still_an_absence(monkeypatch):+ """Positive control for the split above: genuine ABSENCE keeps the config path.++ A runner with no relay adapter at all must NOT raise — otherwise the fix+ above would have turned every native-only deployment into a hard failure.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run++ monkeypatch.setattr(+ gr_run, "_gateway_runner_ref", lambda: SimpleNamespace(adapters={}), raising=False+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ assert eg._live_relay_fronted() is None+ assert eg.relay_routed_platform("discord") is True+ assert eg.authorize_relay_target("discord", "123") is None+ assert eg.authorize_relay_target("discord", "999") is not None+++def test_a_raising_fronts_platform_attribute_is_a_fault_not_an_absence(monkeypatch):+ """Reading the attribute can raise, and that is still a FAULT.++ Reviewer finding, reproduced before fixing. `fronts_platform` may be a+ property or descriptor, so the LOOKUP itself can raise — and the lookup+ used to sit inside the absence handler, which returned None and degraded+ to the config snapshot:++ live=None, routed=False, verdict=None ← unattested target authorized++ The earlier test only made an already-retrieved METHOD raise, so it could+ not catch this. Only `relay is None` is absence now; everything about a+ present adapter, attribute access included, is a fault.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ class RaisingAttr:+ @property+ def fronts_platform(self):+ raise RuntimeError("attribute access failed")++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.RELAY: RaisingAttr()}),+ raising=False,+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+ with pytest.raises(eg.RelayRouteUnknown):+ eg.relay_routed_platform("discord")+++def test_an_adapter_without_fronts_platform_is_a_fault(monkeypatch):+ """A present adapter missing the method entirely cannot answer either.++ It used to return None (→ config fallback). A relay adapter that cannot+ say what it fronts is a broken adapter, not an absent one.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.RELAY: object()}),+ raising=False,+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+++def test_an_adapter_registry_that_cannot_be_read_is_a_fault(monkeypatch):+ """Reviewer finding, round 2: `.get()` on the registry can raise too.++ This was the FIFTH boundary in this one function where "something went+ wrong" became `None`, i.e. "no live adapter, use the config snapshot".+ Probed before the fix: relay_present=True, live=None, routed=False,+ verdict=None — unattested `discord:999` authorized.++ The function is now inverted: each `return None` sits behind an explicit+ narrow check, and anything else raises. That is why this test and the one+ below are grouped with the other fault cases rather than patching a sixth+ boundary.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ class HostileRegistry(dict):+ def get(self, key, default=None):+ raise RuntimeError("registry read failed")++ class Runner:+ def __init__(self):+ self.adapters = HostileRegistry({Platform.RELAY: object()})++ monkeypatch.setattr(gr_run, "_gateway_runner_ref", Runner, raising=False)+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+ with pytest.raises(eg.RelayRouteUnknown):+ eg.relay_routed_platform("discord")+++def test_an_unreadable_adapters_attribute_is_a_fault(monkeypatch):+ """`.adapters` may itself be a property that raises."""+ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run++ class Hostile:+ @property+ def adapters(self):+ raise RuntimeError("adapters unavailable")++ monkeypatch.setattr(gr_run, "_gateway_runner_ref", Hostile, raising=False)+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+++def test_a_runner_with_no_relay_key_is_still_an_absence(monkeypatch):+ """Control: a runner holding only NATIVE adapters is an absence, not a fault.++ Without this control the inversion above could have turned every+ native-only gateway into a hard failure.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.TELEGRAM: object()}),+ raising=False,+ )+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"discord"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ assert eg._live_relay_fronted() is None+ assert eg.authorize_relay_target("discord", "123") is None+ assert eg.authorize_relay_target("discord", "999") is not None+++def test_a_healthy_live_adapter_is_unaffected_by_the_fault_handling(monkeypatch):+ """Liveness control: the ordinary path must still answer from the adapter.++ Every other test here drives a failure. This one proves the fault handling+ did not swallow the success case: a healthy adapter's own answer wins, the+ attested target sends, and the unattested one is refused.+ """+ from types import SimpleNamespace++ import gateway.relay as gr+ import gateway.relay.egress as eg+ import gateway.run as gr_run+ from gateway.config import Platform++ class Healthy:+ def fronts_platform(self, platform):+ return str(getattr(platform, "value", "")).lower() == "discord"++ monkeypatch.setattr(+ gr_run,+ "_gateway_runner_ref",+ lambda: SimpleNamespace(adapters={Platform.RELAY: Healthy()}),+ raising=False,+ )+ # The config snapshot DISAGREES on purpose: the live adapter must win.+ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ assert eg._live_relay_fronted() == {"discord"}+ assert eg.relay_routed_platform("discord") is True+ assert eg.authorize_relay_target("discord", "123") is None+ assert eg.authorize_relay_target("discord", "999") is not None+++def test_a_broken_gateway_import_inside_the_live_probe_is_a_fault(monkeypatch):+ """A nested ImportError in the live probe must not degrade to the config path.++ Found by spot-check, not by the reviewer. `_live_relay_fronted` imports+ `gateway.config` and `gateway.run` inside its own try; before this, ANY+ ImportError there returned None, which means "no live adapter — use the+ config snapshot". So a broken installation plus an empty snapshot+ authorized an unattested destination. Probed with a healthy-adapter+ positive control in the same run:++ healthy_routed=True, healthy_refuses_unattested=True+ fault_routed=False, fault_verdict=None ← authorized++ `_relay_fronted` below already made exactly this distinction for its own+ import; this is the same rule one function up.+ """+ import builtins++ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: set())+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ real_import = builtins.__import__++ def broken(name, *args, **kwargs):+ if name == "gateway.config":+ raise ImportError("cannot import name Platform from gateway.config")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", broken)++ with pytest.raises(eg.RelayRouteUnknown):+ eg._live_relay_fronted()+++def test_a_genuinely_absent_gateway_package_is_still_an_absence(monkeypatch):+ """Control for the test above: real absence must stay benign.++ `ModuleNotFoundError` naming the gateway package itself means there is no+ relay egress to authorize. If this raised, a CLI-only install would fail+ every send instead of using its native credential.+ """+ import builtins++ import gateway.relay.egress as eg++ real_import = builtins.__import__++ def absent(name, *args, **kwargs):+ if name == "gateway.run":+ raise ModuleNotFoundError("No module named 'gateway'", name="gateway")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", absent)++ assert eg._live_relay_fronted() is None+++# ── the Telegram @handle exemption must not cover a NATIVE send ────────────+++def test_handle_exemption_withdrawn_when_a_native_token_exists(monkeypatch):+ """The exemption's justification is "the connector authorizes this".++ That is false when the gateway holds its own Telegram token:+ `_send_to_platform` calls `_send_telegram(pconfig.token, ...)` directly and+ no connector is involved. Measured before the fix: the numeric control was+ refused while `@unattested_public` was DELIVERED with the gateway's own+ credential.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"telegram"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})+ monkeypatch.setattr(eg, "_has_native_credential", lambda p: True)++ assert eg.authorize_relay_target("telegram", "@unattested_public") is not None+ # Controls: the ordinary guard is unchanged in both directions.+ assert eg.authorize_relay_target("telegram", "999") is not None+ assert eg.authorize_relay_target("telegram", "123") is None+++def test_handle_exemption_survives_when_only_the_connector_can_send(monkeypatch):+ """The converse control — without it the fix is just "refuse everything".++ Relay-only is the configuration the exemption exists for: the connector+ holds the token and resolves the handle, so it authorizes the destination.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"telegram"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})+ monkeypatch.setattr(eg, "_has_native_credential", lambda p: False)++ assert eg.authorize_relay_target("telegram", "@public_channel") is None+ # A resolved destination stays fully guarded even in this mode.+ assert eg.authorize_relay_target("telegram", "999") is not None+++def test_native_credential_probe_fault_withdraws_the_exemption(monkeypatch):+ """A fault must not GRANT an exemption — the safe direction is to withdraw+ it and fall back to the ordinary attestation check."""+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"telegram"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})++ import gateway.config as gcfg++ def _boom(*a, **kw):+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(gcfg, "load_gateway_config", _boom)+ assert eg._has_native_credential("telegram") is True+ assert eg.authorize_relay_target("telegram", "@anything") is not None+++# ── one config snapshot for authorization AND dispatch ─────────────────────+++def test_dispatch_snapshot_token_withdraws_the_exemption(monkeypatch):+ """Authorization must use the SAME token dispatch will send with.++ Reviewer probe: the guard reloaded config independently, so a transition+ where the authorization snapshot had no token but the retained dispatch+ snapshot did produced a native send to an unattested handle.+ """+ import gateway.relay as gr+ import gateway.relay.egress as eg++ monkeypatch.setattr(gr, "relay_fronted_platforms", lambda: {"telegram"})+ monkeypatch.setattr(eg, "attested_relay_targets", lambda p: {"123"})+ # The independent reload is STALE and says connector-only.+ monkeypatch.setattr(eg, "_has_native_credential", lambda p: False)++ # Dispatch will use this token, so the exemption must not be granted.+ assert eg.authorize_relay_target(+ "telegram", "@unattested", native_token="123456:dispatch-token"+ ) is not None+ # Converse: a genuinely tokenless dispatch still exempts the handle.+ assert eg.authorize_relay_target("telegram", "@public", native_token=None) is None+ # Controls unchanged in both modes.+ assert eg.authorize_relay_target("telegram", "999", native_token=None) is not None+ assert eg.authorize_relay_target("telegram", "123", native_token="t") is None+++def test_tool_guard_forwards_the_dispatch_token(monkeypatch):+ """CALLER-LEVEL. The test above drives the callee directly, so it passes+ even if the tool never forwards its snapshot — the gap that has produced+ four blockers on this branch. This asserts the wiring itself.+ """+ import tools.send_message_tool as smt++ seen = {}++ def _spy(platform_name, chat_id, thread_id=None, *, native_token=smt._TOKEN_UNSET):+ seen["native_token"] = native_token+ return None++ monkeypatch.setattr("gateway.relay.egress.authorize_relay_target", _spy)+ smt._authorize_relay_target("telegram", "@x", None, native_token="123:tok")+ assert seen["native_token"] == "123:tok"+++def test_a_caller_that_omits_the_snapshot_does_not_get_the_exemption(monkeypatch):+ """A forgotten argument must not silently look like "no native token"."""+ import tools.send_message_tool as smt++ seen = {}++ def _spy(platform_name, chat_id, thread_id=None, **kwargs):+ seen["kwargs"] = kwargs+ return None++ monkeypatch.setattr("gateway.relay.egress.authorize_relay_target", _spy)+ smt._authorize_relay_target("telegram", "@x")+ # No native_token forwarded at all -> the guard runs its own probe.+ assert "native_token" not in seen["kwargs"]+++def test_tool_guard_forwards_thread_id(monkeypatch):+ """CALLER-LEVEL: the tool must pass thread_id INTO the guard.++ thread_id is part of the DESTINATION — on Discord the thread is the literal+ REST target, so an attested parent must not vouch for an arbitrary thread.+ Every other test in this file calls `authorize_relay_target` directly, so+ they all pass even when the tool drops the argument on the floor: the+ mutation `_authorize_relay_target(platform_name, chat_id, None, ...)`+ survived the ENTIRE tests/tools suite (146 passed).+ """+ import tools.send_message_tool as smt++ seen = {}++ def _spy(platform_name, chat_id, thread_id=None, **kwargs):+ seen["thread_id"] = thread_id+ # Refuse, so the send stops here and the test asserts only the wiring.+ return "refused-for-test"++ from gateway.config import Platform, PlatformConfig++ monkeypatch.setattr(smt, "_authorize_relay_target", _spy)+ monkeypatch.setattr(+ smt, "_resolve_tool_target", lambda target: ("discord", "C1", "T99", None)+ )+ # Get past config resolution so execution actually reaches the guard.+ monkeypatch.setattr(+ smt,+ "_resolve_platform_config",+ lambda name, config: (+ Platform.DISCORD,+ PlatformConfig(enabled=True, token="t", extra={}),+ None,+ None,+ ),+ )++ smt._handle_send({"target": "discord:C1:T99", "message": "hi"})++ assert seen.get("thread_id") == "T99", "the tool dropped thread_id before the guard"diff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex 28eec9706ab..cfaf016ae77 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -60,6 +60,97 @@ def _handle_list():return json.dumps(_error(f"Failed to load channel directory: {e}"))+_TOKEN_UNSET = object()+++def _authorize_relay_target(platform_name: str, chat_id, thread_id=None, *,+ native_token=_TOKEN_UNSET) -> str | None:+ """Relay egress-authorization guard (P5a); None when the send may proceed.++ Thin delegate to ``gateway.relay.egress`` so the tool keeps working in+ environments where the gateway package can't be imported.++ THE TWO FAILURES ARE NOT THE SAME, and conflating them disabled the+ boundary. A missing gateway module means there is no relay egress to+ authorize, so proceeding is correct. A fault INSIDE the guard means+ authorization did not happen — and returning None there means "authorized",+ so a single runtime bug in the guard silently switched the whole P5(a)+ boundary off. Review found this by making the guard raise and watching the+ send go through.++ So: the import is tolerated, the CALL is not. A guard that cannot answer+ refuses, which is the only safe polarity for an authorization check.+ """+ try:+ from gateway.relay.egress import authorize_relay_target+ except ImportError as exc:+ # ABSENCE ONLY, and absence means the gateway relay module ITSELF is+ # missing — `exc.name` says which module was not found. An ImportError+ # naming a NESTED dependency is a broken installation, i.e. a fault,+ # and returning None here means "authorized". Review probed exactly+ # that (`ImportError.name = "gateway.relay.dependency"`) and got an+ # authorized verdict, so `except ImportError` alone was still fail-open.+ # ABSENCE has one shape and it is checkable: a genuinely missing module+ # raises ModuleNotFoundError with `.name` set to the module that was not+ # found (verified: `import gateway.relay.x` -> ModuleNotFoundError,+ # name="gateway.relay.x"). So a plain ImportError, or a nameless one, is+ # an unattributable FAULT — never proof that there is no relay here.+ # I previously admitted the nameless case to protect the CLI/cron path;+ # that reasoning was wrong, because that path does not produce one.+ _missing = getattr(exc, "name", None)+ if not isinstance(exc, ModuleNotFoundError) or _missing not in (+ "gateway",+ "gateway.relay",+ "gateway.relay.egress",+ ):+ logger.exception(+ "relay egress module failed to import for %s — refusing the send",+ platform_name,+ )+ return (+ f"Refusing to send to relay target '{platform_name}': the egress "+ "authorization module could not be loaded, so this destination "+ "could not be verified."+ )+ logger.debug("relay target authorization unavailable", exc_info=True)+ return None+ except Exception: # noqa: BLE001 - the module is THERE and broke; FAIL CLOSED+ logger.exception(+ "relay egress module failed to import for %s — refusing the send",+ platform_name,+ )+ return (+ f"Refusing to send to relay target '{platform_name}': the egress "+ "authorization module could not be loaded, so this destination "+ "could not be verified."+ )++ try:+ # ONE SNAPSHOT. `native_token` is the token from the SAME pconfig the+ # dispatch below will actually send with. Letting the guard reload+ # config independently allowed a transition where authorization saw a+ # connector-only setup (exemption granted) while dispatch still held a+ # native token and sent the unattested handle itself.+ if native_token is _TOKEN_UNSET:+ # A caller that forgets the snapshot must NOT silently look like+ # "no native token", which would grant the @handle exemption.+ return authorize_relay_target(platform_name, chat_id, thread_id)+ return authorize_relay_target(+ platform_name, chat_id, thread_id, native_token=native_token+ )+ except Exception: # noqa: BLE001 - the guard faulted; FAIL CLOSED+ logger.exception(+ "relay target authorization FAILED for %s — refusing the send",+ platform_name,+ )+ return (+ f"Refusing to send to relay target '{platform_name}': the egress "+ "authorization check failed, so this destination could not be "+ "verified. This is a bug — the send was blocked rather than "+ "allowed through unchecked."+ )++def _handle_react(args, remove=False):"""Attach (``remove=True``: retract) an emoji reaction via the live gateway adapter; nostandalone fallback because reacting needs the adapter's live message-id state."""@@ -83,6 +174,16 @@ def _handle_react(args, remove=False):except Exception:return tool_error(f"No chat specified and no home channel set for {platform_name}. "f"Use '{platform_name}:chat_id'.")+ # P5(a): same egress-authorization floor as the send path — a reaction is+ # an outbound act against a named destination, so an unattested relay+ # target must be refused here too, not just on `send`.+ # The react path has no pconfig snapshot of its own; it dispatches through+ # the LIVE adapter below, never through a native token, so the guard does+ # its own credential probe here.+ _relay_denial = _authorize_relay_target(platform_name, chat_id, _thread_id)+ if _relay_denial:+ return tool_error(_relay_denial)+_, adapter = _live_adapter(platform)if adapter is None:return tool_error(f"Reactions require a live {platform_name} adapter in the running "@@ -136,6 +237,21 @@ def _handle_send(args):chat_id, resolve_err = _slack_dm_chat_id(pconfig, chat_id)if resolve_err:return json.dumps(resolve_err)+ # POSITION IS LOAD-BEARING — this must stay BELOW Slack user→DM resolution.+ # `_parse_target_ref` emits internal pseudo-ids (`user_name:ben`,+ # `user:U...`) that no provenance can ever contain, because provenances+ # record RESOLVED conversation ids. Authorizing above the resolver compared+ # a handle against a set of `D...` ids and refused every Slack DM — a fix+ # that caused the outage it was meant to prevent. Pinned by+ # test_slack_user_targets_resolve_then_authorize; moving this call back up+ # turns those cases red.+ # thread_id is part of the DESTINATION: on Discord the thread is the literal+ # REST target, so an attested parent must not vouch for an arbitrary thread.+ _relay_denial = _authorize_relay_target(platform_name, chat_id, thread_id,+ native_token=getattr(pconfig, "token", None))+ if _relay_denial:+ return tool_error(_relay_denial)+try:from model_tools import _run_async# Only custom plugin handlers receive the complete typed request.