Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: canonicalize router peer IDs at session boundaries
Antonio Ojea91997a67dc61
diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.tsindex e5334bb3..c61accc7 100644--- a/sdk/js/src/session.test.ts+++ b/sdk/js/src/session.test.ts@@ -698,6 +698,15 @@ test("selectRouters filters by selector, orders by prefer and load, and clampGoAassert.equal(fallback.length, 1);assert.equal(fallback[0]?.peerId, "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB");+ // Non-canonical CIDv1 peerId in RouterInfo is canonicalized at the boundary.+ const cidv1 = "bafzaajaiaejcaa5ba677htqqxyoxbxiy45f4bglh4tldbg5fbvpr3xegmqjfkmny";+ const cidCandidates = candidatesFromRouterInfos(+ [create(RouterInfoSchema, { peerId: cidv1, addresses: ["/ip4/127.0.0.1/tcp/5001"] })],+ [],+ );+ assert.equal(cidCandidates.length, 1);+ assert.equal(cidCandidates[0]?.peerId, "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB");+// Retry-after clamping: default 5m when absent/non-positive, cap at 1h.assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, {})), ROUTER_SHUN_DURATION_MS);assert.equal(clampGoAwayRetryAfterMs(create(RouterGoAwaySchema, { retryAfter: durationFromMs(0) })), ROUTER_SHUN_DURATION_MS);diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.tsindex 6474b19c..579c403f 100644--- a/sdk/js/src/session.ts+++ b/sdk/js/src/session.ts@@ -371,18 +371,28 @@ export class MeshSession {/** Whether peerId is currently one of the routers this member holds. */isHeldRouter(peerId: string): boolean {- return this.#heldRouterIds.has(peerId);+ try {+ return this.#heldRouterIds.has(canonicalPeerId(peerId));+ } catch {+ return false;+ }}/** Handles a /mesh/goaway/1.0.0 message from a held router: shuns it, detaches it, and tops up from the catalog. */async handleGoAway(peerId: string, msg: RouterGoAway, retryAfterMs: number): Promise<void> {- if (!this.#heldRouterIds.has(peerId)) {+ let canonical: string;+ try {+ canonical = canonicalPeerId(peerId);+ } catch {+ return;+ }+ if (!this.#heldRouterIds.has(canonical)) {return;}const reason = goAwayReasonName(msg.reason);this.goAwayReceived.set(reason, (this.goAwayReceived.get(reason) ?? 0) + 1);- this.#shunRouter(peerId, retryAfterMs);- await this.#detachRouter(peerId);+ this.#shunRouter(canonical, retryAfterMs);+ await this.#detachRouter(canonical);await this.keepRelay().catch(() => {});}diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.pyindex cf715693..f1add048 100644--- a/sdk/python/src/agent_mesh/session.py+++ b/sdk/python/src/agent_mesh/session.py@@ -347,7 +347,11 @@ class MeshSession:def is_held_router(self, peer_id: str) -> bool:"""Whether peer_id is currently in this member's held router set."""- return peer_id in self._held_router_ids+ try:+ canonical = canonical_peer_id(peer_id)+ except ValueError:+ return False+ return canonical in self._held_router_idsdef _want_routers(self) -> int:if self.pinned_router_addresses is not None:@@ -383,12 +387,16 @@ class MeshSession:not in the held set; otherwise records the reason, shuns the router forretry_after seconds, drops it from the held set, and tops up from thecatalog immediately."""- if peer_id not in self._held_router_ids:+ try:+ canonical = canonical_peer_id(peer_id)+ except ValueError:+ return False+ if canonical not in self._held_router_ids:return Falsereason = go_away_reason_name(msg.reason)self.go_away_received[reason] = self.go_away_received.get(reason, 0) + 1- self._shun_router(peer_id, retry_after)- await self._detach_router(peer_id)+ self._shun_router(canonical, retry_after)+ await self._detach_router(canonical)await self.top_up_routers()self._relay_trigger.set()return True@@ -1251,7 +1259,11 @@ async def _current_router_info(mesh: "AgentMesh", router: AdmittedRouter) -> tuprouter."""listed: list[multiaddr.Multiaddr] = []for r in getattr(mesh, "routers", ()):- if r.peer_id == router.peer_id:+ try:+ r_peer_id = canonical_peer_id(r.peer_id)+ except ValueError:+ continue+ if r_peer_id == router.peer_id:for raw in r.addresses:try:ma = multiaddr.Multiaddr(raw)diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.pyindex d8d214ea..c762e642 100644--- a/sdk/python/tests/test_session.py+++ b/sdk/python/tests/test_session.py@@ -950,6 +950,15 @@ def test_select_routers_filters_orders_and_clamps_retry_after():assert len(fallback) == 1assert fallback[0].peer_id == "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"+ # Non-canonical CIDv1 peer_id in RouterInfo is canonicalized at the boundary.+ cidv1 = "bafzaajaiaejcaa5ba677htqqxyoxbxiy45f4bglh4tldbg5fbvpr3xegmqjfkmny"+ cid_candidates = candidates_from_router_infos(+ [pb.RouterInfo(peer_id=cidv1, addresses=["/ip4/127.0.0.1/tcp/5001"])],+ [],+ )+ assert len(cid_candidates) == 1+ assert cid_candidates[0].peer_id == "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"+assert clamp_go_away_retry_after(pb.RouterGoAway()) == ROUTER_SHUN_DURATIONassert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=0))) == ROUTER_SHUN_DURATIONassert clamp_go_away_retry_after(pb.RouterGoAway(retry_after=Duration(seconds=-5))) == ROUTER_SHUN_DURATION