egress.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. """Gateway-side relay EGRESS AUTHORIZATION (P5).
  2. Two halves of one security surface, kept together because they are the same
  3. concern seen from both ends of the wire:
  4. **(a) Target hygiene.** The ``send_message`` model tool takes a free-form
  5. ``target`` string (``'platform:chat_id'``). Nothing stopped a model from
  6. naming an arbitrary chat id and having the gateway emit an outbound frame for
  7. it. The connector now refuses such a frame (its egress-authorization floor),
  8. but the gateway must not *silently* ask: a destination the gateway has no
  9. record of is refused HERE, with a visible tool error naming the target.
  10. :func:`authorize_relay_target` is that guard; :func:`attested_relay_targets`
  11. is the set of destinations this gateway can show a provenance for (operator
  12. home channel, channel directory, its own gateway session origins).
  13. **(b) Decline visibility.** The connector answers an unauthorized destination
  14. with a DEFINITE, non-ambiguous failure whose text is deliberately UNIFORM
  15. (``"<platform> egress declined: target is not an approved destination for
  16. this connection"``) — it must not leak whether the destination belongs to
  17. another tenant or to nobody. :func:`is_egress_decline` recognises THAT a
  18. decline happened; it never tries to parse WHY. Egress lanes that legitimately
  19. degrade a *transport drop* (advisory progress, cosmetic reactions, media
  20. falling back to a text notice) must NOT degrade a decline — a refusal that
  21. turns into a different op, or into a wrong "op unavailable" reason, is a
  22. security event laundered into an apparent success.
  23. """
  24. from __future__ import annotations
  25. import logging
  26. from typing import Any, Dict, Optional, Set
  27. logger = logging.getLogger(__name__)
  28. # The connector stamps this on a structured decline (preferred signal).
  29. EGRESS_DECLINE_CODE = "egress_declined"
  30. # Fallback signal: the connector's uniform decline sentence. Matched
  31. # case-insensitively on this fragment ONLY — the rest of the sentence is
  32. # deliberately uninformative (finding F-005) and must not be parsed.
  33. EGRESS_DECLINE_MARKER = "egress declined:"
  34. # Transport-ambiguity text. A lost ack means the frame MAY have been delivered,
  35. # so it is never an authorization refusal. Needed because the text-only branch
  36. # of `declined_send` sees no structured `ambiguous` flag to check.
  37. _AMBIGUOUS_MARKER = "ack lost"
  38. def is_egress_decline(result: Any) -> bool:
  39. """True when *result* is the connector REFUSING the destination.
  40. A decline is distinguished from every other outbound failure by three
  41. properties, all required:
  42. * it failed (``success`` is falsey),
  43. * it is DEFINITE — an ``ambiguous`` result (lost ack, mid-write drop) says
  44. the frame may well have been applied, so it is a transport outcome, not
  45. an authorization one,
  46. * it carries the connector's decline code, or its uniform decline text.
  47. """
  48. if not isinstance(result, dict):
  49. return False
  50. if result.get("success"):
  51. return False
  52. if result.get("ambiguous"):
  53. return False
  54. if str(result.get("code") or "") == EGRESS_DECLINE_CODE:
  55. return True
  56. return EGRESS_DECLINE_MARKER in str(result.get("error") or "").lower()
  57. def declined_send(result: Any) -> bool:
  58. """True when a SEND RESULT object carries a destination refusal.
  59. ``is_egress_decline`` classifies a raw connector DICT. Callers hold a
  60. ``SendResult``, and eight call sites each hand-rolled the unwrapping — with
  61. two different answers. Six checked only ``raw_response``; two also checked
  62. the error text. That disagreement was a real defect, not mere repetition:
  63. a connector that answers with the uniform decline SENTENCE and no
  64. structured code (the documented contract for older connectors, see
  65. ``_approval_send_outcome``) was classified as an ordinary failure by those
  66. six, so the lane treated a refusal as "editing unavailable" and retried.
  67. Measured: text-only decline -> six-site check False, two-site check True.
  68. Both shapes are authoritative, so both are checked here, once:
  69. * ``raw_response`` when the connector sent a structured body,
  70. * otherwise the error text against the uniform decline marker.
  71. The latch in ``RelayAdapter`` already catches both (it classifies the
  72. transport dict directly), which is why the inconsistency cost verdicts and
  73. futile retries rather than leaked content. This helper makes the gateway
  74. lanes agree with the wire.
  75. """
  76. raw = getattr(result, "raw_response", None)
  77. if isinstance(raw, dict):
  78. return is_egress_decline(raw)
  79. error = getattr(result, "error", None)
  80. if not error:
  81. return False
  82. if _AMBIGUOUS_MARKER in str(error).lower():
  83. # DEFENCE IN DEPTH for a lost `ambiguous` flag. The text branch exists
  84. # only for connectors that send no structured body, so it cannot see
  85. # `ambiguous` — and a projection that drops `raw_response` therefore
  86. # turned "ack lost" into a definite refusal, terminating the run for a
  87. # frame that may well have been delivered. Any error text that says the
  88. # ack was lost is treated as a transport outcome, never authorization.
  89. return False
  90. return is_egress_decline({"success": False, "error": error})
  91. def decline_error(result: Any) -> str:
  92. """The connector's decline text, verbatim, for surfacing to the caller.
  93. Verbatim on purpose: the gateway's job is to report faithfully THAT a
  94. decline happened, not to explain or re-word it.
  95. """
  96. if isinstance(result, dict):
  97. error = result.get("error")
  98. if error:
  99. return str(error)
  100. return "relay egress declined"
  101. def log_decline(op: str, chat_id: Any, result: Any) -> None:
  102. """Record a decline on a lane whose contract cannot carry an error.
  103. Cosmetic lanes (typing, reactions, delete, thread ops) return ``bool`` /
  104. ``None`` by contract and legitimately degrade. A decline there is still a
  105. security-relevant event, so it is logged at WARNING rather than vanishing
  106. into the lane's debug-level best-effort handling.
  107. """
  108. logger.warning(
  109. "relay %s DECLINED for %s: %s", op, chat_id, decline_error(result)
  110. )
  111. # ---------------------------------------------------------------------------
  112. # (a) target attestation
  113. # ---------------------------------------------------------------------------
  114. class RelayRouteUnknown(RuntimeError):
  115. """Relay routing could not be determined — callers must FAIL CLOSED.
  116. Distinct from "no relay is configured", which is an empty set and means the
  117. guard does not apply. This is "we could not find out", and the two must not
  118. share a return value: an empty set here says "not relay-routed", which
  119. skips authorization entirely.
  120. """
  121. def _is_missing_gateway_relay(exc: ImportError) -> bool:
  122. """True only when the gateway relay package ITSELF is absent.
  123. `ImportError.name` is the module that could not be found. A nested
  124. dependency failing is a broken installation, not "there is no relay here",
  125. and the two must not share a verdict.
  126. """
  127. # Absence is ModuleNotFoundError WITH a name; anything else is a fault.
  128. if not isinstance(exc, ModuleNotFoundError):
  129. return False
  130. return getattr(exc, "name", None) in (
  131. "gateway",
  132. "gateway.relay",
  133. "gateway.relay.egress",
  134. )
  135. def _live_relay_fronted() -> Optional[set[str]]:
  136. """The connected relay adapter's OWN fronted set.
  137. Returns None ONLY for genuine absence — no runner, or no relay adapter in
  138. it. A live adapter that cannot answer raises `RelayRouteUnknown`.
  139. ABSENCE vs FAULT, again. `None` here means "fall back to the config
  140. snapshot", so letting a FAULT return it re-created the bypass this function
  141. exists to close: with a live adapter whose `fronts_platform()` raised and an
  142. empty/stale config snapshot, the guard concluded "not relay-routed" and
  143. authorized an unattested destination, while `resolve_delivery_transport`
  144. asks that same adapter and still routes over the relay. Measured:
  145. `relay_routed=False`, verdict `None`.
  146. """
  147. # FAIL CLOSED BY DEFAULT. Five review rounds found this same defect at five
  148. # different boundaries — the call, the attribute lookup, a non-callable
  149. # attribute, the nested imports, and the adapter-registry `.get()` — because
  150. # the old shape asked "did something go wrong?" and answered `None`, which
  151. # MEANS "no live adapter, use the config snapshot". Every new statement was
  152. # a new chance to fail open, so the fix kept relocating instead of closing.
  153. #
  154. # Inverted here: every `return None` is guarded by an explicit narrow check
  155. # that cannot itself be the fault, and the outer handler turns anything else
  156. # into `RelayRouteUnknown`. So a statement added inside this function is
  157. # fail-CLOSED by default; previously it was fail-open by default.
  158. try:
  159. try:
  160. from gateway.config import Platform
  161. from gateway.run import _gateway_runner_ref
  162. except ImportError as exc:
  163. # Only the gateway package being genuinely absent is benign; a
  164. # nested dependency failing to load is a broken install, i.e. a
  165. # fault. Same rule as `_relay_fronted` below.
  166. if _is_missing_gateway_relay(exc):
  167. return None
  168. raise
  169. runner = _gateway_runner_ref()
  170. if runner is None:
  171. return None # no gateway runner in this process (CLI, cron)
  172. registry = getattr(runner, "adapters", None)
  173. if not registry:
  174. return None # a runner with no adapters at all
  175. relay = registry.get(Platform.RELAY)
  176. if relay is None:
  177. return None # native-only deployment: nothing fronts anything
  178. # A PRESENT adapter must answer. Anything below this line that fails is
  179. # a fault, never an absence.
  180. fronts = relay.fronts_platform
  181. return {
  182. str(p.value).strip().lower()
  183. for p in Platform
  184. if str(getattr(p, "value", "")).lower() != "relay" and fronts(p)
  185. }
  186. except Exception as exc:
  187. logger.exception("could not determine the live relay adapter's fronted set")
  188. raise RelayRouteUnknown(
  189. "the connected relay adapter could not report which platforms it "
  190. "fronts, so this destination's routing could not be determined"
  191. ) from exc
  192. def _relay_fronted() -> set[str]:
  193. """Platforms the connector fronts for this gateway.
  194. ABSENCE vs FAULT is the whole point of the split below. No gateway relay
  195. module means there is no relay egress to authorize, so an empty set is the
  196. honest answer. Any OTHER failure — a config read that raised, a broken
  197. dependency inside the module — means routing is UNKNOWN, and returning an
  198. empty set there silently reclassifies a relay platform as native and
  199. bypasses the guard. Review demonstrated exactly that: with discovery
  200. raising, an unattested target was authorized.
  201. """
  202. try:
  203. from gateway.relay import relay_fronted_platforms
  204. except ImportError as exc:
  205. # Only the ABSENCE of the relay module itself is benign. An ImportError
  206. # naming a nested dependency means an installed module failed to load —
  207. # a FAULT — and returning an empty set there reclassifies every relay
  208. # platform as native. Review probed this with
  209. # `ImportError.name = "gateway.relay.dependency"` and got an authorized
  210. # verdict, so `except ImportError` alone was not the fix it looked like.
  211. if not _is_missing_gateway_relay(exc):
  212. raise RelayRouteUnknown(
  213. f"relay module failed to import: {exc}"
  214. ) from exc
  215. return set()
  216. # PREFER THE LIVE ADAPTER'S OWN ANSWER. `resolve_delivery_transport` asks
  217. # the CONNECTED relay adapter (`fronts_platform`, from the identity set sent
  218. # at handshake); reconstructing routing from mutable environment state is a
  219. # DIFFERENT snapshot, and the two disagree whenever GATEWAY_RELAY_PLATFORMS
  220. # changes or is momentarily absent after connect. Review probed exactly
  221. # that: guard said "not relay-routed", delivery routed relay, and the guard
  222. # was skipped for a relay send. Same source, same answer.
  223. live = _live_relay_fronted()
  224. if live is not None:
  225. return live
  226. try:
  227. # CASE-NORMALIZED. `relay_routed_platform` lowercases the requested
  228. # name, so an un-normalized set made a mixed-case configured platform
  229. # ("Discord") miss the membership test and look native — an
  230. # attestation bypass on a string comparison.
  231. return {str(p).strip().lower() for p in relay_fronted_platforms()}
  232. except Exception as exc:
  233. raise RelayRouteUnknown(
  234. f"relay route discovery failed: {exc}"
  235. ) from exc
  236. def _has_live_native_adapter(platform_name: str) -> bool:
  237. """Whether THIS process runs a native (non-relay) adapter for the platform.
  238. Mirrors ``gateway/delivery.resolve_delivery_transport``'s precedence: a
  239. concrete native adapter always wins, so a platform served natively here is
  240. not a relay egress and this guard does not apply to it.
  241. """
  242. try:
  243. from gateway.config import Platform
  244. from gateway.run import _gateway_runner_ref
  245. runner = _gateway_runner_ref()
  246. if runner is None:
  247. return False
  248. adapters = getattr(runner, "adapters", None) or {}
  249. platform = Platform(platform_name)
  250. if adapters.get(platform) is None:
  251. return False
  252. # MATCH `resolve_delivery_transport` EXACTLY. A native adapter that is
  253. # explicitly DISABLED never shadows Relay there, so treating mere
  254. # presence as "native" made the guard believe a send was native while
  255. # delivery actually routed it over the relay — the guard then skipped
  256. # authorization for a relay send. Two independent routing classifiers
  257. # are unsafe; this one now answers the same question the router does.
  258. from gateway.config import load_gateway_config
  259. # NO `except: return True` HERE. I wrote one, and it recreated the very
  260. # bypass this method was fixed for: a config read that fails would
  261. # declare the platform native while the router — reading the real
  262. # config — sends over the relay, so the guard is skipped for a relay
  263. # send. A routing question we cannot answer is UNKNOWN, and the caller
  264. # turns that into a refusal.
  265. try:
  266. native_config = load_gateway_config().platforms.get(platform)
  267. except Exception as exc:
  268. raise RelayRouteUnknown(
  269. f"native-adapter config lookup failed for {platform_name}: {exc}"
  270. ) from exc
  271. return native_config is None or bool(getattr(native_config, "enabled", True))
  272. except RelayRouteUnknown:
  273. # Routing is UNKNOWN, not "no native adapter" — must not be flattened
  274. # into False here, which would send the caller down the relay-guard
  275. # path on a guess. Propagate; authorize_relay_target turns it into a
  276. # refusal.
  277. raise
  278. except Exception:
  279. return False
  280. def relay_routed_platform(platform_name: str) -> bool:
  281. """Whether a send to *platform_name* would egress over the relay connector.
  282. True for the generic ``relay`` plane itself, and for any logical platform
  283. the connector fronts for this gateway that has no live native adapter in
  284. this process.
  285. """
  286. name = str(platform_name or "").strip().lower()
  287. if not name:
  288. return False
  289. if name == "relay":
  290. return True
  291. if name not in _relay_fronted():
  292. return False
  293. return not _has_live_native_adapter(name)
  294. def _home_channel_id(platform_name: str) -> Optional[str]:
  295. try:
  296. from gateway.config import Platform, load_gateway_config
  297. home = load_gateway_config().get_home_channel(Platform(platform_name))
  298. return str(home.chat_id) if home and home.chat_id else None
  299. except Exception:
  300. return None
  301. def _directory_ids(platform_name: str) -> set[str]:
  302. try:
  303. from gateway.channel_directory import load_directory
  304. entries = load_directory().get("platforms", {}).get(platform_name) or []
  305. except Exception:
  306. return set()
  307. ids: set[str] = set()
  308. for entry in entries:
  309. if isinstance(entry, dict) and entry.get("id"):
  310. ids.add(str(entry["id"]))
  311. return ids
  312. def _session_ids(platform_name: str) -> set[str]:
  313. """Chat ids this gateway has actually held a session in for the platform."""
  314. try:
  315. from gateway.channel_directory import _build_from_sessions
  316. entries = _build_from_sessions(platform_name) or []
  317. except Exception:
  318. return set()
  319. ids: set[str] = set()
  320. for entry in entries:
  321. if isinstance(entry, dict) and entry.get("id"):
  322. raw = str(entry["id"])
  323. ids.add(raw)
  324. # RECOVER THE CHAT FROM THE STRUCTURED FIELD, NEVER BY SPLITTING.
  325. # `_session_entry_id` builds the id as f"{chat_id}:{thread_id}"
  326. # when a thread exists, and the entry still carries `thread_id`
  327. # separately — so the parent is knowable exactly. Splitting on ":"
  328. # was a guess that INVENTED attestations: a Matrix room id
  329. # `!room:server.org` attested a bare `!room` no session ever used.
  330. # An allow-list of "platforms whose ids have no native colon" would
  331. # only have narrowed the guess; the structured field removes it.
  332. if entry.get("thread_id"):
  333. suffix = f":{entry['thread_id']}"
  334. if raw.endswith(suffix):
  335. ids.add(raw[: -len(suffix)])
  336. return ids
  337. def attested_relay_targets(platform_name: str) -> set[str]:
  338. """Chat ids this gateway can show a provenance for on *platform_name*.
  339. Three provenances, all of them things the gateway already knows rather
  340. than things a model can invent:
  341. * the operator-configured home channel,
  342. * the channel directory built from live adapters/session origins,
  343. * this gateway's own gateway-session origins.
  344. For the generic ``relay`` plane the union spans every platform the
  345. connector fronts: a relay session is filed under its LOGICAL platform
  346. (``source = "discord"``), so attesting ``relay`` against only ``relay``
  347. would refuse chats the agent is demonstrably already talking in.
  348. """
  349. name = str(platform_name or "").strip().lower()
  350. names = {name}
  351. if name == "relay":
  352. names |= _relay_fronted()
  353. attested: set[str] = set()
  354. for candidate in names:
  355. home = _home_channel_id(candidate)
  356. if home:
  357. attested.add(home)
  358. attested |= _directory_ids(candidate)
  359. attested |= _session_ids(candidate)
  360. return attested
  361. _UNSET = object()
  362. def _has_native_credential(platform_name: str) -> bool:
  363. """Whether the gateway itself holds a token that can send to *platform_name*.
  364. `_send_to_platform` sends Telegram natively via `pconfig.token`, entirely
  365. outside the connector. When that credential exists, no connector-side
  366. authorization happens, so the unresolved-handle exemption has no basis.
  367. Faults answer True — the SAFE direction, since it only ever withdraws an
  368. exemption and falls back to the ordinary attestation check.
  369. """
  370. try:
  371. from gateway.config import Platform, load_gateway_config
  372. config = load_gateway_config()
  373. pconfig = config.platforms.get(Platform(platform_name))
  374. return bool(pconfig and pconfig.enabled and getattr(pconfig, "token", None))
  375. except Exception:
  376. logger.debug("native-credential probe failed; withdrawing the exemption", exc_info=True)
  377. return True
  378. def _is_unresolved_handle(platform_name: str, target: str, native_token: Any = _UNSET) -> bool:
  379. """Whether *target* is a NAME the gateway cannot compare against an id.
  380. Provenance records RESOLVED destinations (numeric chat ids). A Telegram
  381. public `@username` is not a destination yet — the Bot API resolves it at
  382. send time — so comparing it to a set of numeric ids can only ever refuse,
  383. no matter how legitimately the user configured it.
  384. Deliberately narrow: `@`-prefixed Telegram targets only. A numeric id, a
  385. `-100…` supergroup, or any other platform's form is a resolved destination
  386. and stays fully guarded.
  387. """
  388. if platform_name != "telegram" or not target.startswith("@"):
  389. return False
  390. # AND THE SEND MUST ACTUALLY REACH THE CONNECTOR. The carve-out's entire
  391. # justification is "the connector holds the token and authorizes this".
  392. # That is false whenever the tool sends NATIVELY: `_send_to_platform`
  393. # calls `_send_telegram(pconfig.token, ...)` directly, so with a native
  394. # Telegram token configured, an unattested @handle went out with the
  395. # gateway's own credential and no connector ever saw it. Review probed it:
  396. # the numeric control was refused, the handle was delivered.
  397. #
  398. # So the exemption survives only when there is NO native credential able to
  399. # send this handle. `_send_to_platform` reaches for `pconfig.token`; if that
  400. # exists, delivery never involves the connector.
  401. if native_token is not _UNSET:
  402. # The caller passed the token from the SAME config snapshot it will
  403. # dispatch with; that is authoritative and race-free.
  404. return not native_token
  405. return not _has_native_credential(platform_name)
  406. def authorize_relay_target(
  407. platform_name: str, chat_id: Any, thread_id: Any = None, *, native_token: Any = _UNSET
  408. ) -> Optional[str]:
  409. """Return an error string when this relay destination may not be named.
  410. ``None`` means the send may proceed. Non-relay platforms are never
  411. restricted here — their own adapters own their authorization.
  412. THREAD IDS ARE PART OF THE DESTINATION, not a formatting detail. On Discord
  413. the thread is the literal REST target
  414. (``POST /channels/{thread_id}/messages``), so authorizing only the parent
  415. let an attested channel vouch for an arbitrary caller-supplied thread. The
  416. thread must therefore carry its own attestation — a session in the parent
  417. is not evidence of a session in the thread.
  418. """
  419. try:
  420. routed = relay_routed_platform(platform_name)
  421. except RelayRouteUnknown as exc:
  422. # Routing could not be determined. "Not relay-routed" would skip this
  423. # guard entirely, so an unknown route must refuse rather than assume
  424. # the safe-looking default. Returned as a refusal string (not raised)
  425. # because every caller treats this function's output as the verdict.
  426. logger.warning(
  427. "relay routing unknown for %s — refusing the send: %s",
  428. platform_name,
  429. exc,
  430. )
  431. return (
  432. f"Refusing to send to '{platform_name}': relay routing could not "
  433. "be determined, so this destination could not be verified."
  434. )
  435. if not routed:
  436. return None
  437. target = str(chat_id or "").strip()
  438. if not target:
  439. return None
  440. name = str(platform_name).strip().lower()
  441. attested = attested_relay_targets(name)
  442. if target in attested:
  443. # The CHAT is attested. If the caller also named a thread, that thread
  444. # is the real destination on thread-addressed platforms, so it needs an
  445. # attestation OF ITS OWN, BOUND TO THIS PARENT.
  446. #
  447. # A bare `thread in attested` arm used to satisfy this, and it proved
  448. # nothing about parentage: any attested chat whose id happened to equal
  449. # the requested thread id vouched for it. Measured — attested
  450. # `{"-100A", "7"}`, request `(-100A, thread 7)` → authorized, though no
  451. # session ever existed in thread 7 of -100A.
  452. #
  453. # The bound form is always available, so nothing legitimate needs the
  454. # bare one: `_session_entry_id` records a threaded origin as
  455. # f"{chat_id}:{thread_id}", and a platform whose thread IS its own
  456. # channel (a Discord thread addressed directly) arrives as `chat_id`
  457. # and is authorized by the `target in attested` check above.
  458. thread = str(thread_id or "").strip()
  459. if thread and thread != target:
  460. if f"{target}:{thread}" in attested:
  461. return None
  462. return (
  463. f"Refusing to send to relay target '{name}:{target}:{thread}': "
  464. f"the parent chat is attested but this gateway has no record of "
  465. f"the thread, and on this platform the thread IS the delivery "
  466. f"destination."
  467. )
  468. return None
  469. # ── Telegram `@username`: authorized by the CONNECTOR, not here ─────────
  470. #
  471. # Checked AFTER attestation, so a handle that IS attested takes the normal
  472. # path; this only catches the case that would otherwise be a false refusal.
  473. #
  474. # WHY THE GATEWAY CANNOT ANSWER THIS: the guard fires only when there is no
  475. # live native adapter (`_has_live_native_adapter`), i.e. on relay-fronted
  476. # deployments — and on exactly those the CONNECTOR holds the bot token, not
  477. # this process. There is no local way to turn `@channel` into the numeric id
  478. # provenance stores, so refusing here is not "fail closed", it is "fail
  479. # always". It regressed the public-channel username support added in #53573.
  480. #
  481. # WHY THAT IS SAFE, NOT A HOLE: the destination is still authorized, one
  482. # layer out. The connector's Telegram egress floor (gg#238, merged 743a7c2)
  483. # classifies and refuses unauthorized destinations after ITS resolution,
  484. # which is the layer that closed the reported vulnerability in the first
  485. # place. This carve-out drops handles from two guards to one — the
  486. # authoritative one — rather than to zero.
  487. #
  488. # FOLLOW-UP (option 2, deliberately not done here): resolve the handle
  489. # before authorizing, so both layers apply. That needs a resolution
  490. # round-trip through the connector — new wire surface — so it belongs in
  491. # its own phase, not bolted onto this one.
  492. if _is_unresolved_handle(name, target, native_token):
  493. logger.debug(
  494. "relay target '%s:%s' is an unresolved handle — deferring "
  495. "authorization to the connector's egress floor",
  496. name,
  497. target,
  498. )
  499. return None
  500. return (
  501. f"Refusing to send to unattested relay target '{name}:{target}': "
  502. "this gateway has no record of that destination. Use "
  503. "send_message(action='list') to see the targets it can reach."
  504. )