Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: only a node passes the egress gate, and a malformed floor fails the runner
Tomas Tormoea8bfefb6194
diff --git a/sdk/README.md b/sdk/README.mdindex cbca7984..fba48d7d 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -477,8 +477,8 @@ holds against the control plane's records.`MeshTransport`) verifies the provider with or without a floor, throughthe mutual `/sam/auth/1.0.0` handshake, as `sam-node`'s `VerifyPeerLabels`does before its egress proxy sends anything; a positive verdict is kept- per peer for five minutes (`labelGateTTL`), a miss never. Refusals are- `LabelsNotSatisfiedError`, which names the floor.+ per peer for five minutes (`labelGateTTL`); a refusal is not kept. An+ unmet floor is a `LabelsNotSatisfiedError` naming the floor.- `session.listTools(peer, service)` and `session.callTool(peer, service,tool, args)` on top of that.- Tests. Unit: each SDK calls a tool on an in-process provider that servesdiff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.tsindex 9fae3f01..54a12f6f 100644--- a/sdk/js/src/conformance-join.ts+++ b/sdk/js/src/conformance-join.ts@@ -78,14 +78,23 @@ function emit(obj: unknown): void {process.stdout.write(JSON.stringify(obj) + "\n");}-/** Labels from an environment variable written "k=v,k2=v2". */+/**+ * Labels from an environment variable written "k=v,k2=v2"; a pair without+ * "=" is refused (parseRequiredLabels), so a typo never switches a floor off.+ */function labelsFromEnv(name: string): Record<string, string> {- return Object.fromEntries(- (process.env[name] ?? "")- .split(",")- .filter((pair) => pair.includes("="))- .map((pair) => pair.split("=", 2) as [string, string]),- );+ const out: Record<string, string> = {};+ for (const pair of (process.env[name] ?? "").split(",")) {+ if (pair.trim() === "") {+ continue;+ }+ const eq = pair.indexOf("=");+ if (eq === -1) {+ throw new Error(`${name}: invalid label ${JSON.stringify(pair.trim())}: expected key=value`);+ }+ out[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();+ }+ return out;}function failure(cmd: string | undefined, err: unknown): unknown {diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.tsindex 1d04bb10..1b000131 100644--- a/sdk/js/src/session.test.ts+++ b/sdk/js/src/session.test.ts@@ -388,6 +388,8 @@ test("an egress floor stated at join is held on the HTTP path, and the providerb.addFact(wasm.Fact.fromString("expiration(2035-01-01T00:00:00Z)"));return b.build(forged.getPrivateKey()).toBytes();});+ // Enrolled and attesting the floor, but not a node: a router hosts no service.+ const notANode = await serve((peerId) => mint(peerId, ROLE_ROUTER, undefined, { region: "eu" }));const addrOf = (host: Libp2p) => (host.getMultiaddrs()[0] as ReturnType<typeof multiaddr>).toString();const sessions: MeshSession[] = [];const join = async (options: JoinOptions): Promise<MeshSession> => {@@ -418,7 +420,9 @@ test("an egress floor stated at join is held on the HTTP path, and the provider// A banned provider is refused before any handshake.plain.banned.add(provider.peerId.toString(), Date.now());await assert.rejects(plain.request(addrOf(provider), "a2a://agent", "/card"), /banned/);+ // Only nodes host services, as sam-node's checkPeerLabels requires.+ await assert.rejects(held.request(addrOf(notANode), "a2a://agent", "/card"), /lacks expected role "sam:role:node"/);} finally {- await Promise.all([...sessions.map((s) => s.close()), provider.stop(), impostor.stop()]);+ await Promise.all([...sessions.map((s) => s.close()), provider.stop(), impostor.stop(), notANode.stop()]);}});diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.tsindex 5c30f4ec..5274fbb1 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, authenticateWithPeer, authStreamHandler } from "./auth.ts";import { ROLE_ROUTER, requireRole, type VerifiedBiscuit } from "./biscuit.ts";+import { ROLE_NODE } from "./controlplane.ts";import { canonicalPeerId } from "./identity.ts";import { isServiceType, parseServiceTarget, serviceCID } from "./discovery.ts";import { createMeshHost, listenThroughRelay, type MeshHost, type MeshHostOptions, type RelayListener } from "./host.ts";@@ -637,7 +638,7 @@ export class MeshSession {/*** The connection an HTTP call goes out on, its peer verified as an enrolled- * member holding the floor before anything is sent (sam-node's VerifyPeerLabels).+ * node holding the floor before anything is sent (sam-node's VerifyPeerLabels).*/async #egressConnection(peer: Peer, signal?: AbortSignal): Promise<Connection> {const conn = await this.connect(peer, signal);@@ -647,6 +648,8 @@ export class MeshSession {return conn;}const provider = await authenticateWithPeer(conn, this.mesh.authFrame(), this.mesh.credential.controlPlaneKeys);+ // Only nodes host services; a router's or an admin's credential is a member, not a provider.+ requireRole(provider, ROLE_NODE);requireEgressLabels(provider, this.#egressRequireLabels);this.#egressVerdicts.set(peerId, new Date(Date.now() + EGRESS_VERDICT_TTL_MS));return conn;diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.pyindex 3543e0e3..7e52dad1 100644--- a/sdk/python/src/agent_mesh/conformance_join.py+++ b/sdk/python/src/agent_mesh/conformance_join.py@@ -70,8 +70,17 @@ def _emit(obj: dict) -> None:def _labels_from_env(name: str) -> dict[str, str]:- """Labels from an environment variable written "k=v,k2=v2"."""- return dict(pair.split("=", 1) for pair in os.environ.get(name, "").split(",") if "=" in pair)+ """Labels from an environment variable written "k=v,k2=v2"; a pair without+ "=" is refused (parseRequiredLabels), so a typo never switches a floor off."""+ out: dict[str, str] = {}+ for pair in os.environ.get(name, "").split(","):+ if not pair.strip():+ continue+ key, sep, value = pair.partition("=")+ if not sep:+ raise SystemExit(f"{name}: invalid label {pair.strip()!r}: expected key=value")+ out[key.strip()] = value.strip()+ return outdef _root_cause(err: BaseException) -> BaseException:diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.pyindex 648a4b8f..6d1ef571 100644--- a/sdk/python/src/agent_mesh/session.py+++ b/sdk/python/src/agent_mesh/session.py@@ -40,6 +40,7 @@ from ._proto import sam_pb2 as pbfrom .auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peerfrom .authorizer import ProviderAuthorizerOptionsfrom .biscuit import ROLE_ROUTER, VerifiedBiscuit, require_role+from .controlplane import ROLE_NODEfrom .discovery import DiscoveredProvider, find_peer, find_providers, parse_service_target, service_keyfrom .host import create_mesh_host, dial, dial_addrs, peer_infofrom .httpx_transport import MESH_PATH_PREFIX@@ -522,12 +523,14 @@ class MeshSession:)async def _egress_peer(self, peer: Peer) -> ID:- """The peer an HTTP call goes out to, verified as an enrolled member+ """The peer an HTTP call goes out to, verified as an enrolled nodeholding the floor before anything is sent (sam-node's VerifyPeerLabels)."""peer_id = await self.connect(peer)if self._egress_verdicts.get(str(peer_id), 0.0) > time.monotonic():return peer_idprovider = await authenticate_with_peer(self.host, peer_id, self.mesh.auth_frame(), self.mesh.credential.control_plane_keys)+ # Only nodes host services; a router's or an admin's credential is a member, not a provider.+ require_role(provider, ROLE_NODE)require_egress_labels(provider, self.egress_require_labels)self._egress_verdicts[str(peer_id)] = time.monotonic() + EGRESS_VERDICT_TTLreturn peer_iddiff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.pyindex a26afacc..fdbe5e8e 100644--- a/sdk/python/tests/test_session.py+++ b/sdk/python/tests/test_session.py@@ -452,6 +452,8 @@ def test_an_egress_floor_stated_at_join_is_held_on_the_http_path():_, impostor_addr = await start_provider(nursery, lambda p: ba.BiscuitBuilder("node({p}); expiration(2035-01-01T00:00:00Z);", {"p": p}).build(forged.private_key).to_bytes(), handshakes)+ # Enrolled and attesting the floor, but not a node: a router hosts no service.+ _, not_a_node_addr = await start_provider(nursery, lambda p: mint(p, ROLE_ROUTER, labels={"region": "eu"}), handshakes)def join(**options):mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt", transport=fake_control_plane([router_addr]))@@ -482,6 +484,9 @@ def test_an_egress_floor_stated_at_join_is_held_on_the_http_path():plain.banned.add(str(provider.get_id()), int(time.time() * 1000))with pytest.raises(PermissionError, match="banned"):await plain.request(provider_addr, "a2a://agent", "/card")+ # Only nodes host services, as sam-node's checkPeerLabels requires.+ with pytest.raises(BiscuitVerificationError, match="lacks expected role 'sam:role:node'"):+ await held.request(not_a_node_addr, "a2a://agent", "/card")nursery.cancel_scope.cancel()trio.run(with_timeout, 60, main)diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.mdindex 665b7307..12b310b6 100644--- a/site/content/docs/guides/native-sdks.md+++ b/site/content/docs/guides/native-sdks.md@@ -890,8 +890,8 @@ round: `join({ egressRequireLabels })` (`join(egress_require_labels=)`)names labels every peer the session calls must attest, all of them, as`egress.require_labels` does for a `sam-node`. It is stated once at `join`and held for the session, on every call and however the peer was named;-the agent's calls cannot waive or widen it. It is the program author's-floor, not the operator's: nothing outside the process sets it.+the agent's calls cannot waive or widen it. The floor belongs to the+program that calls `join`; no configuration outside the process sets it.`acceptA2A` (`accept_a2a`) fetched the mesh policy and started answering.Every caller must present a credential signed by a trusted control plane