Skip to content

The agent that grows with you

fix(gateway): relayed bot DM into an auth-gated gateway is attributed to the relaying principal, not refused

John Paul Soliva8820cfb7a23b
diff --git a/tests/honcho_plugin/test_a2a_sessions.py b/tests/honcho_plugin/test_a2a_sessions.py
index 29db6450e4e..c632bdab94c 100644
--- a/tests/honcho_plugin/test_a2a_sessions.py
+++ b/tests/honcho_plugin/test_a2a_sessions.py
@@ -180,3 +180,53 @@ class TestConfigFlag:
def test_defaults_on(self, tmp_path, monkeypatch):
assert self._config(tmp_path, monkeypatch, {}).a2a_sessions is True
+
+
+class TestRelayedDmFromALoggedInClient:
+ """A relayed dm whose sender a logged-in client named is attributed to that client's principal —
+ server-derived, unspoofable, and still a BOT author. That last part is what the recipient's memory
+ routes on: the turn lands in the relay principal's own a2a session, never the human's, and the
+ conclusion / profile / mirror guards stay closed for it (#107598 review)."""
+
+ RELAY = None
+
+ @classmethod
+ def setup_class(cls):
+ from tools.bot_relay import relaying_principal_author
+ cls.RELAY = relaying_principal_author("principal:dashboard:0123456789abcdef0123456789abcdef")
+
+ def test_author_shape_is_a_bot_with_a_principal_derived_id(self):
+ assert self.RELAY["is_bot"] is True
+ assert self.RELAY["id"] == "bot:principal:dashboard:0123456789abcdef0123456789abcdef/relay"
+ assert self.RELAY["name"] == "relayed teammate"
+
+ def test_turn_lands_in_its_own_a2a_session_never_the_humans(self):
+ provider = _provider()
+ provider._manager.resolve_author_peer_id.return_value = "relay"
+
+ _sync(provider, turn_author=self.RELAY)
+
+ keys = [c[0][0] for c in provider._manager.get_or_create.call_args_list]
+ assert keys == [provider._a2a_session_key(self.RELAY)]
+ assert "Bot-Chat" not in keys
+
+ def test_memory_writes_stay_refused_during_the_turn(self):
+ provider = _provider()
+ provider._turn_author = dict(self.RELAY)
+ provider._manager.create_conclusion.return_value = True
+ assert provider._bot_turn_write_refusal() is not None
+ assert "error" in json.loads(provider._tool_conclude({"conclusion": "likes tea"}))
+ provider.on_memory_write("add", "user", "likes tea")
+ assert provider._memwrite_thread is None
+ provider._manager.create_conclusion.assert_not_called()
+
+ def test_an_unattributed_turn_would_have_been_the_humans(self):
+ """The failure mode this guards against: with no author, the same turn goes to the human session."""
+ provider = _provider()
+ provider._manager.resolve_author_peer_id.return_value = None
+
+ _sync(provider, turn_author=None)
+
+ assert [c[0][0] for c in provider._manager.get_or_create.call_args_list] == ["Bot-Chat"]
+ provider._turn_author = {}
+ assert provider._bot_turn_write_refusal() is None
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index 91dd8129520..d3d5ac18c3e 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -366,7 +366,12 @@ SENDER_AUTHOR = {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}
{"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER},
], ids=["no identity", "server-internal identity"])
def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, fake_runs, bound_client, identity):
- """The Desktop and server-internal callers carry no login identity; their sender fields become the author."""
+ """A caller with no identity, or one holding the ``?internal=`` credential, keeps its sender fields.
+
+ NOT the Desktop: it mints a ws-ticket carrying the signed-in ``{user_id, provider}`` on every
+ gateway that requires sign-in, so it is a login identity — see
+ ``test_a_signed_in_ws_ticket_is_a_login_identity_so_the_desktop_is_one``.
+ """
from agent.turn_author import TURN_AUTHOR_ENV
calls, _outcomes = fake_runs
@@ -377,21 +382,79 @@ def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, fake_r
assert [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls] == [SENDER_AUTHOR]
-def test_deliver_refuses_a_sender_from_a_logged_in_client(home, fake_runs, bound_client):
- """A browser login never relays for another connection, so its from_* fields are refused before any turn runs.
- Without sender fields the same client still delivers, unattributed."""
+def test_deliver_from_a_logged_in_client_is_attributed_to_its_principal_never_to_the_claimed_sender(
+ home, fake_runs, bound_client):
+ """A logged-in client's sender fields are not trusted — but the dm is neither refused nor left unattributed.
+
+ Refusing the CALL (the original guard) took cross-machine relay offline for every auth-gated gateway,
+ because the Desktop is itself a logged-in client there. Dropping the AUTHOR instead made the turn the
+ human's to the recipient's memory (Honcho routes an unattributed turn into the human session and allows
+ conclusion / profile / mirror writes). So the author is derived from the caller's minted identity:
+ stable, unspoofable, and still a bot — whether or not the client named a sender.
+ """
+ import json
+
from agent.turn_author import TURN_AUTHOR_ENV
calls, _outcomes = fake_runs
bound_client.auth_identity = {"user_id": "alice", "provider": "google"}
- for sender in ({"from_profile": "scout"}, {"from_connection": "cloud-1"}, SENDER):
- err = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **sender})
- assert err["error"]["code"] == 4095
- assert not calls
+ shapes = ({"from_profile": "scout"}, {"from_connection": "cloud-1"}, SENDER, {})
+ for rid, sender in enumerate(shapes):
+ _result(srv._methods["bot_relay.deliver"](rid, {"profile": "ops", "message": "ping", **sender}))
+
+ assert len(calls) == len(shapes), "every relayed dm from a logged-in client must still run its turn"
+ authors = [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls]
+ assert all(a["is_bot"] is True for a in authors), "a relayed dm stays bot-authored for the recipient's memory"
+ assert all(a["id"].startswith("bot:principal:dashboard:") and a["id"].endswith("/relay") for a in authors)
+ assert all(a["name"] == "relayed teammate" for a in authors)
+ assert SENDER_AUTHOR not in authors, "the claimed sender must not become the author"
+ assert len({a["id"] for a in authors}) == 1, "one signed-in principal, one author — with or without sender fields"
+
+ bound_client.auth_identity = {"user_id": "bob", "provider": "google"}
+ _result(srv._methods["bot_relay.deliver"](9, {"profile": "ops", "message": "ping", **SENDER}))
+ assert json.loads(calls[-1]["env"][TURN_AUTHOR_ENV])["id"] != authors[0]["id"], "a different principal is a different author"
+
+
+def test_live_delivery_from_a_logged_in_client_carries_the_principal_author(home, monkeypatch, bound_client):
+ """The live Bot Chat path (``prompt.submit``) gets the principal-derived bot author as a ``DeliveryAuthor``."""
+ from tools.bot_relay import DeliveryAuthor
+
+ submitted = []
+ monkeypatch.setitem(
+ srv._methods, "prompt.submit",
+ lambda rid, p: submitted.append(p) or srv._ok(rid, {"status": "streaming"}))
+ monkeypatch.setattr(srv, "_profile_home", lambda name: home / "profiles" / name)
+ monkeypatch.setitem(srv._sessions, "live-ops", {
+ "profile_home": str(home / "profiles" / "ops"), "pending_title": "Bot Chat", "history": []})
+ bound_client.auth_identity = {"user_id": "alice", "provider": "google"}
+
+ _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **SENDER}))
+
+ assert len(submitted) == 1 and submitted[0]["text"] == "ping"
+ author = submitted[0]["_turn_author"]
+ assert isinstance(author, DeliveryAuthor)
+ assert author.author["is_bot"] is True and author.author["id"].startswith("bot:principal:dashboard:")
+ assert author.author != SENDER_AUTHOR
+
+
+def test_a_signed_in_ws_ticket_is_a_login_identity_so_the_desktop_is_one(monkeypatch, tmp_path):
+ """The root cause, pinned: the Desktop's own credential produces a login identity.
+
+ It fetches ``POST /api/auth/ws-ticket``, which mints the ticket from the signed-in session
+ (``hermes_cli/dashboard_auth/routes.py``); consuming it yields that user's identity, which is a
+ login identity. So any relay rule that keys on "is this caller logged in" also catches the
+ Desktop, and cross-connection relay is exactly what the Desktop exists to do.
+ """
+ from hermes_cli.dashboard_auth import ws_tickets
+ from tui_gateway.methods_browser_control import _is_authenticated_identity
+
+ monkeypatch.setattr(ws_tickets, "_TICKET_STORE_PATH", tmp_path / "tickets.json", raising=False)
+ consumed = ws_tickets.consume_ticket(ws_tickets.mint_ticket(user_id="alice", provider="google"))
- _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": "ping"}))
- assert len(calls) == 1 and TURN_AUTHOR_ENV not in calls[0]["env"]
+ assert _is_authenticated_identity({"user_id": consumed["user_id"], "provider": consumed["provider"]})
+ assert not _is_authenticated_identity(
+ {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}), "only ?internal= is exempt"
@pytest.mark.parametrize("subdir", ["profiles/ops", "dev"])
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index badc8c07144..af382af5e16 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -492,6 +492,19 @@ def _delivery_child_session_env_names() -> "tuple[str, ...]":
return tuple(_VAR_MAP)
+def relaying_principal_author(principal: str) -> dict:
+ """The author of a relayed DM whose sender fields cannot be trusted: a logged-in client named them.
+
+ Server-derived and unspoofable — the id is built from the caller's minted identity digest, never from
+ anything the client sent — and still a BOT author, because the recipient's memory routes on that:
+ Honcho writes a bot-authored turn into the bot's own a2a session and refuses conclusion / profile /
+ mirror writes for it, while an unattributed turn is treated as the human's (#107598 review). The
+ human-facing signature stays in the message text the sender composed."""
+ from agent.turn_author import bot_author_id
+
+ return {"id": bot_author_id("relay", str(principal or "").strip()), "name": "relayed teammate", "is_bot": True}
+
+
def delivery_env(author: Optional[dict], profile_home: "str | Path | None" = None) -> dict[str, str]:
"""Environment for one delivery turn's ``hermes -p <profile>`` child. The dispatcher's own
HERMES_TURN_AUTHOR is dropped first so a delivery without an author never inherits the author of the turn
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index 4ffb0ed27ff..9aea6360a46 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -100,14 +100,26 @@ def _(rid, params: dict, _root=_relay_root, _run=_run_delivery,
and _session_live_title(
record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")
# The sender fields are whatever the relaying client says. The author labels memory only and grants nothing.
- from tools.bot_relay import DeliveryAuthor, delivery_env, delivery_turn_author
- from tui_gateway.methods_browser_control import _is_authenticated_identity
+ from tools.bot_relay import (
+ DeliveryAuthor, delivery_env, delivery_turn_author, relaying_principal_author)
+ from tui_gateway.methods_browser_control import _is_authenticated_identity, _principal_digest
sender_fields = ("from_profile", "from_handle", "from_connection")
- # A logged-in browser never relays for another connection; only the Desktop and server-internal callers do.
- if (any(params.get(k) for k in sender_fields)
- and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):
- return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")
- author = delivery_turn_author(*(params.get(k) for k in sender_fields))
+ identity = getattr(current_transport(), "auth_identity", None)
+ if _is_authenticated_identity(identity):
+ # A logged-in client's sender fields are NOT trusted — but the delivery is not refused
+ # either: the Desktop is itself a logged-in client on every gateway that requires sign-in
+ # (it mints a ws-ticket carrying the signed-in {user_id, provider} —
+ # hermes_cli/dashboard_auth/routes.py), so refusing took cross-connection relay offline
+ # for exactly the auth-gated gateways it serves; only ``?internal=`` callers are
+ # identity-exempt and the Desktop cannot present one. Nor is the author dropped: an
+ # unattributed turn is the HUMAN's to the recipient's memory (Honcho routes it into the
+ # human session and allows conclusion / profile / mirror writes), so a bot DM must stay
+ # bot-authored. The author is derived from the caller's minted identity instead — stable,
+ # unspoofable, and ``is_bot`` — whether or not the client named a sender. The human-facing
+ # "Message from 🤖 …" signature stays in the text the sender composed.
+ author = relaying_principal_author(_principal_digest(identity))
+ else:
+ author = delivery_turn_author(*(params.get(k) for k in sender_fields))
if live_sid:
# queued=True: a teammate's DM runs as the NEXT turn and never interrupts or steers a
# turn in flight (the default busy mode does); arrivals queue in order.