Skip to content

Agent Mesh

sdk: canonicalize peer IDs at the boundary, as the Go node does

Antonio Ojeadc585427465f
diff --git a/sdk/js/src/identity.test.ts b/sdk/js/src/identity.test.ts
index dbd6ed4e..52150d2a 100644
--- a/sdk/js/src/identity.test.ts
+++ b/sdk/js/src/identity.test.ts
@@ -17,7 +17,7 @@ import { readFileSync } from "node:fs";
import { test } from "node:test";
import { decodeBase58, encodeBase58 } from "./base58.ts";
import { enrollChallenge } from "./challenges.ts";
-import { Identity, libp2pPublicKey, peerIdFromPublicKey, verifyEd25519 } from "./identity.ts";
+import { Identity, canonicalPeerId, libp2pPublicKey, peerIdFromPublicKey, verifyEd25519 } from "./identity.ts";
interface Vector {
seed: string;
@@ -74,6 +74,16 @@ test("libp2pPublicKey refuses the wrong size", () => {
assert.throws(() => libp2pPublicKey(new Uint8Array(33)), /32 bytes/);
});
+test("canonicalPeerId is the base58 form for every encoding libp2p accepts", () => {
+ // The CIDv1 form of a known ed25519 peer, as `peer.ToCid(id).String()` prints it.
+ const base58 = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB";
+ const cidv1 = "bafzaajaiaejcaa5ba677htqqxyoxbxiy45f4bglh4tldbg5fbvpr3xegmqjfkmny";
+ assert.equal(canonicalPeerId(base58), base58);
+ assert.equal(canonicalPeerId(cidv1), base58);
+ assert.throws(() => canonicalPeerId("not-a-peer"), /is not a peer ID/);
+ assert.throws(() => canonicalPeerId(""), /is not a peer ID/);
+});
+
test("base58btc round-trips and keeps leading zeros", () => {
const cases: Uint8Array[] = [new Uint8Array(0), Uint8Array.of(0), Uint8Array.of(0, 0, 1, 2), hex("00ff"), hex("deadbeef")];
for (const c of cases) {
diff --git a/sdk/js/src/identity.ts b/sdk/js/src/identity.ts
index b7ea122f..1744d8a2 100644
--- a/sdk/js/src/identity.ts
+++ b/sdk/js/src/identity.ts
@@ -16,6 +16,7 @@
// derives, so the same key works in the SDK, in sam-node and on the wire.
import { createPrivateKey, createPublicKey, sign, verify, type KeyObject } from "node:crypto";
+import { peerIdFromString } from "@libp2p/peer-id";
import { encodeBase58 } from "./base58.ts";
const PUBLIC_KEY_SIZE = 32;
@@ -66,6 +67,21 @@ export function peerIdFromPublicKey(publicKeyRaw: Uint8Array): string {
return encodeBase58(concat(IDENTITY_MULTIHASH_PREFIX, libp2pPublicKey(publicKeyRaw)));
}
+/**
+ * The base58btc form of a peer ID written in any encoding libp2p accepts
+ * (base58btc multihash, CIDv1). Every key, ban set and comparison in SAM is
+ * on this form, as peer.ID.String() in Go; a string read off the wire or
+ * from a caller goes through here before it is used as one. Throws when the
+ * text is not a peer ID at all.
+ */
+export function canonicalPeerId(text: string): string {
+ try {
+ return peerIdFromString(text).toString();
+ } catch (err) {
+ throw new Error(`${JSON.stringify(text)} is not a peer ID: ${err instanceof Error ? err.message : String(err)}`);
+ }
+}
+
export class Identity {
readonly #privateKey: KeyObject;
readonly #publicKey: KeyObject;
diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.ts
index a5fc1441..2713def9 100644
--- a/sdk/js/src/index.ts
+++ b/sdk/js/src/index.ts
@@ -13,7 +13,7 @@
// limitations under the License.
export { AgentMesh, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions } from "./mesh.ts";
-export { Identity, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts";
+export { Identity, canonicalPeerId, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts";
export {
ControlPlaneClient,
ControlPlaneError,
diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts
index 0d93a4e5..a24bcfb9 100644
--- a/sdk/js/src/session.ts
+++ b/sdk/js/src/session.ts
@@ -19,6 +19,7 @@ import { peerIdFromString } from "@libp2p/peer-id";
import { isMultiaddr, multiaddr, type Multiaddr } from "@multiformats/multiaddr";
import { AUTH_HANDLER_OPTIONS, AUTH_PROTOCOL, MCP_PROTOCOL, authenticateWithPeer, authStreamHandler } from "./auth.ts";
import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";
+import { canonicalPeerId } from "./identity.ts";
import { isServiceType, parseServiceTarget, serviceCID, type ServiceType } from "./discovery.ts";
import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions } from "./host.ts";
import { openMCPSession, type MCPSession, type MCPSessionOptions } from "./mcp.ts";
@@ -189,17 +190,19 @@ export class MeshSession {
/** The addresses connect() dials for a peer, in the order libp2p tries them. */
dialTargets(peer: Peer): { peerId: string | undefined; addrs: Multiaddr[] } {
if (typeof peer === "string" && !peer.startsWith("/")) {
- return { peerId: peer, addrs: this.relayedAddresses(peer) };
+ const peerId = canonicalPeerId(peer);
+ return { peerId, addrs: this.relayedAddresses(peerId) };
}
if (typeof peer === "string" || isMultiaddr(peer)) {
const ma = typeof peer === "string" ? multiaddr(peer) : peer;
return { peerId: targetPeerOf(ma), addrs: [ma] };
}
+ const peerId = canonicalPeerId(peer.peerId);
const advertised = peer.addrs.map((text) => {
const ma = multiaddr(text);
- return targetPeerOf(ma) === undefined ? ma.encapsulate(`/p2p/${peer.peerId}`) : ma;
+ return targetPeerOf(ma) === undefined ? ma.encapsulate(`/p2p/${peerId}`) : ma;
});
- return { peerId: peer.peerId, addrs: [...advertised, ...this.relayedAddresses(peer.peerId)] };
+ return { peerId, addrs: [...advertised, ...this.relayedAddresses(peerId)] };
}
/** `<router>/p2p-circuit/p2p/<peer>` through every router that admitted this member. */
@@ -312,7 +315,7 @@ export class MeshSession {
async #syncOnce(): Promise<ControlPlaneSync> {
const result = await this.mesh.syncControlPlane();
if (result.bannedPeerIds !== undefined) {
- const { banned } = this.banned.reconcile(result.bannedPeerIds, result.fetchedAt);
+ const { banned } = this.banned.reconcile(canonicalPeerIds(result.bannedPeerIds), result.fetchedAt);
await Promise.all(banned.map((peerId) => this.#evict(peerId)));
}
if (this.#serving) {
@@ -574,8 +577,21 @@ export async function joinMesh(mesh: AgentMesh, options: JoinOptions = {}): Prom
return new MeshSession(mesh, node, admitted, authenticatedPeers, banned, options);
}
-/** The peer a multiaddr ends at: its trailing `/p2p/<id>`, or undefined for a relay address with no target yet. */
+/** The peer a multiaddr ends at, in canonical form: its trailing `/p2p/<id>`, or undefined for a relay address with no target yet. */
function targetPeerOf(ma: Multiaddr): string | undefined {
const last = ma.getComponents().at(-1);
- return last?.name === "p2p" ? last.value : undefined;
+ return last?.name === "p2p" && last.value !== undefined ? canonicalPeerId(last.value) : undefined;
+}
+
+/** Canonicalizes a list from the control plane, dropping entries that are not peer IDs. */
+function canonicalPeerIds(ids: string[]): string[] {
+ const out: string[] = [];
+ for (const id of ids) {
+ try {
+ out.push(canonicalPeerId(id));
+ } catch {
+ // Not a peer ID; it can match nothing, so it bans nothing.
+ }
+ }
+ return out;
}
diff --git a/sdk/js/src/sync.test.ts b/sdk/js/src/sync.test.ts
index 9f9ae5fe..8c43e78a 100644
--- a/sdk/js/src/sync.test.ts
+++ b/sdk/js/src/sync.test.ts
@@ -25,6 +25,7 @@ import { circuitRelayServer, circuitRelayTransport } from "@libp2p/circuit-relay
import { privateKeyFromProtobuf } from "@libp2p/crypto/keys";
import { identify } from "@libp2p/identify";
import type { Libp2p } from "@libp2p/interface";
+import { peerIdFromString } from "@libp2p/peer-id";
import { tcp } from "@libp2p/tcp";
import { tls } from "@libp2p/tls";
import { createLibp2p } from "libp2p";
@@ -190,15 +191,25 @@ test("a mesh event verifies only under a trusted key and only when fresh", () =>
return toBinary(MeshEventSchema, { ...event, signature: key.identity.sign(unsigned) });
};
const now = new Date();
- const banned = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: "12D3KooWx", eventTime: timestampFromMs(now.getTime()) }));
- assert.equal(verifyMeshEvent(banned, [key.pub], now)?.peerId, "12D3KooWx");
+ const target = Identity.generate().peerId;
+ const banned = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: target, eventTime: timestampFromMs(now.getTime()) }));
+ assert.equal(verifyMeshEvent(banned, [key.pub], now)?.peerId, target);
assert.equal(verifyMeshEvent(banned, [new SigningKey().pub], now), undefined, "untrusted key");
const tampered = new Uint8Array(banned);
tampered[tampered.length - 1] = (tampered[tampered.length - 1] ?? 0) ^ 1;
assert.equal(verifyMeshEvent(tampered, [key.pub], now), undefined, "tampered signature");
- const stale = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: "12D3KooWx", eventTime: timestampFromMs(now.getTime() - EVENT_FRESHNESS_MS - 1) }));
+ const stale = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: target, eventTime: timestampFromMs(now.getTime() - EVENT_FRESHNESS_MS - 1) }));
assert.equal(verifyMeshEvent(stale, [key.pub], now), undefined, "stale");
assert.equal(verifyMeshEvent(new Uint8Array([1, 2, 3]), [key.pub], now), undefined, "garbage");
+
+ // The ban set is keyed on the base58 form; an event naming the peer in
+ // its CIDv1 form bans the same peer, and one naming no peer bans nobody.
+ const cidForm = peerIdFromString(target).toCID().toString();
+ assert.notEqual(cidForm, target);
+ const bannedByCID = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: cidForm, eventTime: timestampFromMs(now.getTime()) }));
+ assert.equal(verifyMeshEvent(bannedByCID, [key.pub], now)?.peerId, target);
+ const bannedNobody = sign(create(MeshEventSchema, { type: MeshEvent_Type.BANNED, peerId: "not-a-peer", eventTime: timestampFromMs(now.getTime()) }));
+ assert.equal(verifyMeshEvent(bannedNobody, [key.pub], now), undefined, "not a peer id");
});
test("a pull learns a key rotation and refreshes the credential under the new key", async () => {
@@ -273,13 +284,23 @@ test("a banned peer is hung up on and refused at the gate and the handshake", as
// Its token still verifies, and it is still refused: a new connection at the gate ...
await assert.rejects(peer.dial(relayed).then((c) => authenticateWithPeer(c, frame, [cp.current.pub])));
- // ... and outbound, before any dial.
+ // ... and outbound, before any dial, however the peer is named.
+ const cidForm = peerIdFromString(peerIdentity.peerId).toCID().toString();
await assert.rejects(session.connect(`${routerAddr}/p2p-circuit/p2p/${peerIdentity.peerId}`), /banned/);
+ await assert.rejects(session.connect(`${routerAddr}/p2p-circuit/p2p/${cidForm}`), /banned/);
+ await assert.rejects(session.connect(cidForm), /banned/);
+ await assert.rejects(session.connect({ peerId: cidForm, addrs: [] }), /banned/);
- // Lifted by the control plane: the next pull unbans it.
+ // Lifted by the control plane: the next pull unbans it. A ban list that
+ // names the peer in its CIDv1 form bans the same peer.
cp.banned = [];
await session.sync();
assert.deepEqual(session.banned.peers(), []);
+ cp.banned = [cidForm, "not-a-peer"];
+ await session.sync();
+ assert.deepEqual(session.banned.peers(), [peerIdentity.peerId]);
+ cp.banned = [];
+ await session.sync();
} finally {
await peer.stop();
await session.close();
diff --git a/sdk/js/src/sync.ts b/sdk/js/src/sync.ts
index c720ec68..4a8bdf33 100644
--- a/sdk/js/src/sync.ts
+++ b/sdk/js/src/sync.ts
@@ -18,7 +18,7 @@
import { fromBinary, toBinary } from "@bufbuild/protobuf";
import { timestampMs, type Timestamp } from "@bufbuild/protobuf/wkt";
-import { verifyEd25519 } from "./identity.ts";
+import { canonicalPeerId, verifyEd25519 } from "./identity.ts";
import { MeshEvent_Type, MeshEventSchema, type MeshEvent } from "./gen/sam_pb.ts";
/** The GossipSub topic the control plane publishes mesh events on (api.GossipEvents). */
@@ -83,13 +83,14 @@ export class BanSet {
}
/** A MeshEvent that verified: signed by a trusted key and carrying a fresh event_time. */
+/** A MeshEvent that verified: signed by a trusted key, carrying a fresh event_time, its peer id in canonical form. */
export type VerifiedMeshEvent = MeshEvent & { eventTime: Timestamp };
/**
* Verifies a MeshEvent as sam-node's verifyEvent does: the signature covers
* the deterministic encoding of the event with the signature cleared, under
* any trusted control plane key. Returns the event, or undefined when it
- * does not verify or is not fresh.
+ * does not verify, is not fresh, or bans something that is not a peer ID.
*/
export function verifyMeshEvent(data: Uint8Array, trustedKeys: Uint8Array[], now: Date = new Date()): VerifiedMeshEvent | undefined {
let event: MeshEvent;
@@ -110,6 +111,14 @@ export function verifyMeshEvent(data: Uint8Array, trustedKeys: Uint8Array[], now
if (skew > EVENT_FRESHNESS_MS) {
return undefined;
}
+ if (event.type === MeshEvent_Type.BANNED) {
+ // Canonicalized after the signature check, which covers the bytes as sent.
+ try {
+ return { ...event, peerId: canonicalPeerId(event.peerId) } as VerifiedMeshEvent;
+ } catch {
+ return undefined;
+ }
+ }
return event as VerifiedMeshEvent;
}
diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.py
index 518a2683..3fdf0c1e 100644
--- a/sdk/python/src/agent_mesh/__init__.py
+++ b/sdk/python/src/agent_mesh/__init__.py
@@ -31,7 +31,7 @@ from .controlplane import (
)
from .credential import MeshCredential, decode_auth_response, encode_auth_frame
from .discovery import DHT_PROTOCOL, DiscoveredProvider, find_providers, parse_service_target, provide, service_key
-from .identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519
+from .identity import Identity, canonical_peer_id, libp2p_public_key, peer_id_from_public_key, verify_ed25519
from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_labels
from .mesh import AgentMesh, ControlPlaneSync
from .relay import dial_through_relay, reserve_relay
@@ -96,6 +96,7 @@ __all__ = [
"auth_stream_handler",
"authenticate_with_peer",
"authorize_caller",
+ "canonical_peer_id",
"decode_auth_response",
"dial_through_relay",
"encode_auth_frame",
diff --git a/sdk/python/src/agent_mesh/identity.py b/sdk/python/src/agent_mesh/identity.py
index aec1cb90..c85fdfe0 100644
--- a/sdk/python/src/agent_mesh/identity.py
+++ b/sdk/python/src/agent_mesh/identity.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import os
+import multiaddr
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
@@ -48,6 +49,19 @@ def peer_id_from_public_key(public_key_raw: bytes) -> str:
return base58.encode(_IDENTITY_MULTIHASH_PREFIX + libp2p_public_key(public_key_raw))
+def canonical_peer_id(text: str) -> str:
+ """The base58btc form of a peer ID written in any encoding libp2p accepts
+ (base58btc multihash, CIDv1). Every key, ban set and comparison in SAM is
+ on this form, as peer.ID.String() in Go; a string read off the wire or from
+ a caller goes through here before it is used as one. Raises ValueError when
+ the text is not a peer ID at all."""
+ # py-multiaddr's p2p codec decodes both encodings and prints base58btc.
+ try:
+ return multiaddr.Multiaddr("/p2p/" + text).value_for_protocol("p2p")
+ except Exception as err: # noqa: BLE001 - the library raises its own parse error types
+ raise ValueError(f"{text!r} is not a peer ID: {err}") from err
+
+
def verify_ed25519(public_key_raw: bytes, data: bytes, signature: bytes) -> bool:
"""Verifies an ed25519 signature with a raw 32-byte public key."""
if len(public_key_raw) != PUBLIC_KEY_SIZE:
diff --git a/sdk/python/src/agent_mesh/relay.py b/sdk/python/src/agent_mesh/relay.py
index 709896b8..9896027e 100644
--- a/sdk/python/src/agent_mesh/relay.py
+++ b/sdk/python/src/agent_mesh/relay.py
@@ -34,6 +34,7 @@ from libp2p.peer.id import ID
from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
from ._proto import circuit_pb2 as circuit
+from .identity import canonical_peer_id
logger = logging.getLogger("agent_mesh")
@@ -52,7 +53,7 @@ def split_circuit_address(addr: multiaddr.Multiaddr) -> tuple[multiaddr.Multiadd
target = tail.removeprefix("/p2p/")
if not target:
raise ValueError(f"{addr} names no target peer after /p2p-circuit")
- return multiaddr.Multiaddr(relay_text), ID.from_base58(target)
+ return multiaddr.Multiaddr(relay_text), ID.from_base58(canonical_peer_id(target))
async def reserve_relay(host: IHost, relay_peer_id: ID) -> circuit.Reservation:
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
index 6d227263..fd3066f4 100644
--- a/sdk/python/src/agent_mesh/session.py
+++ b/sdk/python/src/agent_mesh/session.py
@@ -43,6 +43,7 @@ from .authorizer import ProviderAuthorizerOptions
from .biscuit import ROLE_ROUTER, VerifiedBiscuit, require_role
from .discovery import DiscoveredProvider, ServiceType, find_providers, parse_service_target, provide, service_key
from .host import create_mesh_host
+from .identity import canonical_peer_id
from .mcp_client import ToolCallResult, ToolInfo, open_mcp_session, tool_call_result
from .relay import STOP_PROTOCOL, dial_through_relay, reserve_relay, split_circuit_address, stop_stream_handler
from .serve import (
@@ -82,6 +83,23 @@ DEFAULT_CONTROL_PLANE_SYNC_JITTER = 2.0
Peer = Union[DiscoveredProvider, str, multiaddr.Multiaddr]
+def parse_peer_id(text: str) -> ID:
+ """The libp2p peer ID for a string in any encoding libp2p accepts."""
+ return ID.from_base58(canonical_peer_id(text))
+
+
+def canonical_peer_ids(ids: Sequence[str]) -> list[str]:
+ """Canonicalizes a list from the control plane, dropping entries that are
+ not peer IDs: they can match nothing, so they ban nothing."""
+ out: list[str] = []
+ for text in ids:
+ try:
+ out.append(canonical_peer_id(text))
+ except ValueError:
+ continue
+ return out
+
+
class _MeshsubNoise(logging.Filter):
"""py-libp2p's pubsub opens a meshsub stream to every new peer and the host
logs an error for each one that does not answer. Peers that leave during
@@ -156,9 +174,9 @@ class MeshSession:
if isinstance(peer, multiaddr.Multiaddr) or (isinstance(peer, str) and peer.startswith("/")):
return await self._connect_addr(multiaddr.Multiaddr(str(peer)))
if isinstance(peer, str):
- target, advertised = ID.from_base58(peer), []
+ target, advertised = parse_peer_id(peer), []
else:
- target, advertised = ID.from_base58(peer.peer_id), [multiaddr.Multiaddr(a) for a in peer.addrs]
+ target, advertised = parse_peer_id(peer.peer_id), [multiaddr.Multiaddr(a) for a in peer.addrs]
self._refuse_banned(target)
if target in self.host.get_connected_peers():
return target
@@ -273,9 +291,9 @@ class MeshSession:
async with self._sync_lock:
result = await trio.to_thread.run_sync(self.mesh.sync_control_plane)
if result.banned_peer_ids is not None:
- newly_banned, _ = self.banned.reconcile(result.banned_peer_ids, result.fetched_at)
- for peer_id in newly_banned:
- await self._evict(peer_id)
+ newly_banned, _ = self.banned.reconcile(canonical_peer_ids(result.banned_peer_ids), result.fetched_at)
+ for peer in newly_banned:
+ await self._evict(peer)
if self._serving:
try:
await self.sync_policy()
@@ -287,11 +305,11 @@ class MeshSession:
"""Asks for a pull soon, after a random delay so a fleet told at once does not pull at once."""
self._sync_trigger.set()
- async def _evict(self, peer_id: str) -> None:
+ async def _evict(self, banned_peer: str) -> None:
"""Drops a banned peer: its admission and its connections."""
- self.authenticated_peers.pop(peer_id, None)
+ self.authenticated_peers.pop(banned_peer, None)
try:
- await self.host.disconnect(ID.from_base58(peer_id))
+ await self.host.disconnect(ID.from_base58(banned_peer))
except Exception: # noqa: BLE001 - not connected, or already gone
pass
diff --git a/sdk/python/src/agent_mesh/sync.py b/sdk/python/src/agent_mesh/sync.py
index 70841576..460ca142 100644
--- a/sdk/python/src/agent_mesh/sync.py
+++ b/sdk/python/src/agent_mesh/sync.py
@@ -22,7 +22,7 @@ import time
from typing import Optional, Sequence
from ._proto import sam_pb2 as pb
-from .identity import verify_ed25519
+from .identity import canonical_peer_id, verify_ed25519
# The GossipSub topic the control plane publishes mesh events on (api.GossipEvents).
GOSSIP_EVENTS_TOPIC = "/sam/mesh/events/v1"
@@ -71,8 +71,9 @@ class BanSet:
def verify_mesh_event(data: bytes, trusted_keys: Sequence[bytes], now_ms: Optional[int] = None) -> Optional[pb.MeshEvent]:
"""Verifies a MeshEvent as sam-node's verifyEvent does: the signature covers
the deterministic encoding of the event with the signature cleared, under
- any trusted control plane key. Returns the event, or None when it does not
- verify or is not fresh."""
+ any trusted control plane key. Returns the event, with a banned peer's id in
+ canonical form, or None when it does not verify, is not fresh, or bans
+ something that is not a peer ID."""
try:
event = pb.MeshEvent.FromString(data)
except Exception: # noqa: BLE001 - undecodable is unverifiable
@@ -87,4 +88,10 @@ def verify_mesh_event(data: bytes, trusted_keys: Sequence[bytes], now_ms: Option
now_ms = int(time.time() * 1000) if now_ms is None else now_ms
if not event.HasField("event_time") or abs(now_ms - event.event_time.ToMilliseconds()) > EVENT_FRESHNESS_MS:
return None
+ if event.type == pb.MeshEvent.BANNED:
+ # Canonicalized after the signature check, which covers the bytes as sent.
+ try:
+ event.peer_id = canonical_peer_id(event.peer_id)
+ except ValueError:
+ return None
return event
diff --git a/sdk/python/tests/test_identity.py b/sdk/python/tests/test_identity.py
index 78edba2b..ba472b8a 100644
--- a/sdk/python/tests/test_identity.py
+++ b/sdk/python/tests/test_identity.py
@@ -19,7 +19,7 @@ import pytest
from agent_mesh import base58
from agent_mesh.challenges import enroll_challenge
-from agent_mesh.identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519
+from agent_mesh.identity import Identity, canonical_peer_id, libp2p_public_key, peer_id_from_public_key, verify_ed25519
VECTORS = json.loads((Path(__file__).resolve().parents[2] / "testdata" / "identity_vectors.json").read_text())["vectors"]
@@ -64,6 +64,17 @@ def test_libp2p_public_key_refuses_wrong_size():
libp2p_public_key(b"\x00" * 33)
+def test_canonical_peer_id_is_the_base58_form_for_every_encoding():
+ # The CIDv1 form of a known ed25519 peer, as `peer.ToCid(id).String()` prints it.
+ b58 = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"
+ cidv1 = "bafzaajaiaejcaa5ba677htqqxyoxbxiy45f4bglh4tldbg5fbvpr3xegmqjfkmny"
+ assert canonical_peer_id(b58) == b58
+ assert canonical_peer_id(cidv1) == b58
+ for bad in ("not-a-peer", ""):
+ with pytest.raises(ValueError, match="is not a peer ID"):
+ canonical_peer_id(bad)
+
+
@pytest.mark.parametrize("data", [b"", b"\x00", b"\x00\x00\x01\x02", bytes.fromhex("00ff"), bytes.fromhex("deadbeef")])
def test_base58_round_trips(data):
assert base58.decode(base58.encode(data)) == data
diff --git a/sdk/python/tests/test_sync.py b/sdk/python/tests/test_sync.py
index bcf46907..545f2f6d 100644
--- a/sdk/python/tests/test_sync.py
+++ b/sdk/python/tests/test_sync.py
@@ -26,12 +26,15 @@ import biscuit_auth as ba
import multiaddr
import pytest
import trio
+from cid import make_cid
from libp2p.peer.peerinfo import info_from_p2p_addr
+from agent_mesh import base58
from agent_mesh._proto import sam_pb2 as pb
from agent_mesh.auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer
from agent_mesh.biscuit import ROLE_ROUTER, verify_peer_biscuit
from agent_mesh.controlplane import ROLE_NODE
+from agent_mesh.discovery import DiscoveredProvider
from agent_mesh.identity import Identity
from agent_mesh.mesh import AgentMesh
from agent_mesh.relay import HOP_PROTOCOL as RELAY_HOP_PROTOCOL
@@ -164,16 +167,31 @@ def test_mesh_event_verifies_only_under_a_trusted_key_and_only_when_fresh():
return event.SerializeToString(deterministic=True)
now_ms = int(time.time() * 1000)
- banned = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id="12D3KooWx", event_time=_ts_ms(now_ms)))
- assert verify_mesh_event(banned, [key.pub], now_ms).peer_id == "12D3KooWx"
+ target = Identity.generate().peer_id
+ banned = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id=target, event_time=_ts_ms(now_ms)))
+ assert verify_mesh_event(banned, [key.pub], now_ms).peer_id == target
assert verify_mesh_event(banned, [SigningKey().pub], now_ms) is None
tampered = bytearray(banned)
tampered[-1] ^= 1
assert verify_mesh_event(bytes(tampered), [key.pub], now_ms) is None
- stale = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id="12D3KooWx", event_time=_ts_ms(now_ms - EVENT_FRESHNESS_MS - 1)))
+ stale = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id=target, event_time=_ts_ms(now_ms - EVENT_FRESHNESS_MS - 1)))
assert verify_mesh_event(stale, [key.pub], now_ms) is None
assert verify_mesh_event(b"\x01\x02\x03", [key.pub], now_ms) is None
+ # The ban set is keyed on the base58 form; an event naming the peer in its
+ # CIDv1 form bans the same peer, and one naming no peer bans nobody.
+ banned_by_cid = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id=cid_form(target), event_time=_ts_ms(now_ms)))
+ assert verify_mesh_event(banned_by_cid, [key.pub], now_ms).peer_id == target
+ banned_nobody = sign(pb.MeshEvent(type=pb.MeshEvent.BANNED, peer_id="not-a-peer", event_time=_ts_ms(now_ms)))
+ assert verify_mesh_event(banned_nobody, [key.pub], now_ms) is None
+
+
+def cid_form(peer_id: str) -> str:
+ """The CIDv1 base32 encoding of a peer ID, as `peer.ToCid(id).String()` prints it."""
+ encoded = make_cid(1, "libp2p-key", base58.decode(peer_id)).encode("base32").decode()
+ assert encoded != peer_id
+ return encoded
+
def test_pull_learns_a_key_rotation_and_refreshes_the_credential():
async def main():
@@ -245,11 +263,25 @@ def test_banned_peer_is_disconnected_and_refused():
await peer.connect(info_from_p2p_addr(member_addr))
with pytest.raises(Exception):
await authenticate_with_peer(peer, session.host.get_id(), frame, [cp.current.pub])
- # ... and outbound, before any dial.
+ # ... and outbound, before any dial, however the peer is named.
+ cid = cid_form(peer_identity.peer_id)
with pytest.raises(PermissionError, match="banned"):
await session.connect(f"{cp.router_addr}/p2p-circuit/p2p/{peer_identity.peer_id}")
+ with pytest.raises(PermissionError, match="banned"):
+ await session.connect(f"{cp.router_addr}/p2p-circuit/p2p/{cid}")
+ with pytest.raises(PermissionError, match="banned"):
+ await session.connect(cid)
+ with pytest.raises(PermissionError, match="banned"):
+ await session.connect(DiscoveredProvider(peer_id=cid))
- # Lifted by the control plane: the next pull unbans it.
+ # Lifted by the control plane: the next pull unbans it. A ban
+ # list that names the peer in its CIDv1 form bans the same peer.
+ cp.banned = []
+ await session.sync()
+ assert session.banned.peers() == []
+ cp.banned = [cid, "not-a-peer"]
+ await session.sync()
+ assert session.banned.peers() == [peer_identity.peer_id]
cp.banned = []
await session.sync()
assert session.banned.peers() == []