Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: a caller's label requirement is met by any one pair, as in sam-node
Antonio Ojea5bb6c83e8ff7
diff --git a/sdk/README.md b/sdk/README.mdindex 9ef484b6..0ad47dae 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -422,7 +422,10 @@ holds against the control plane's records.multiaddr is dialed as given.- `/sam/mcp/1.0.0` client: `session.openMCP(peer, "mcp://<name>")` sendsthe `AuthFrame` naming the service, verifies the provider's credential- and the caller's required labels (`checkPeerLabels`), then runs the+ and the caller's required labels (`checkPeerLabels`: several pairs are+ met by any one of them, as `api.LabelCheck` joins them with `or`; the+ conjunction is the operator's egress floor, which only `sam-node` has),+ then runs theofficial MCP client over the varint-framed stream. JS: a `Transport` for`@modelcontextprotocol/sdk`; Python: a pair of memory streams pumped toand from the libp2p stream for `mcp.ClientSession`. `""` as the target isdiff --git a/sdk/js/src/conformance-join.ts b/sdk/js/src/conformance-join.tsindex e143b698..f5fd28a9 100644--- a/sdk/js/src/conformance-join.ts+++ b/sdk/js/src/conformance-join.ts@@ -22,10 +22,12 @@// run the auth handshake// {"cmd": "discover", "type": "mcp", "name": "calc"}// DHT lookup for a service's providers-// {"cmd": "tools", "addr": "<multiaddr>", "service": "mcp://calc"}-// list a provider's tools+// {"cmd": "tools", "addr": "<multiaddr>", "service": "mcp://calc",+// "required_labels": {"region": "eu"}} list a provider's tools; the labels,+// if given, must be on its credential// {"cmd": "call", "addr": "<multiaddr>", "service": "mcp://calc",-// "tool": "add", "args": {...}} call one tool+// "tool": "add", "args": {...}, "required_labels": {...}}+// call one tool// {"cmd": "accept", "name": "agent", "target": "<url>"}// accept A2A requests for this// member's agent; without target,@@ -61,6 +63,7 @@ interface Command {method?: string;body?: string;headers?: Record<string, string>;+ required_labels?: Record<string, string>;}function requireEnv(name: string): string {@@ -79,6 +82,10 @@ function failure(cmd: string | undefined, err: unknown): unknown {return { cmd, ok: false, error: err instanceof Error ? `${err.name}: ${err.message}` : String(err) };}+function requiredLabelsOf(command: Command): { requiredLabels?: Record<string, string> } {+ return command.required_labels !== undefined ? { requiredLabels: command.required_labels } : {};+}+async function handle(session: MeshSession, command: Command): Promise<unknown> {try {switch (command.cmd) {@@ -98,11 +105,14 @@ async function handle(session: MeshSession, command: Command): Promise<unknown>return { cmd: "discover", ok: true, providers: providers.map((p) => ({ peer_id: p.peerId, addrs: p.addrs })) };}case "tools": {- const tools = await session.listTools(command.addr ?? "", command.service ?? "", { signal: AbortSignal.timeout(15_000) });+ const tools = await session.listTools(command.addr ?? "", command.service ?? "", { signal: AbortSignal.timeout(15_000), ...requiredLabelsOf(command) });return { cmd: "tools", ok: true, tools: tools.map((t) => t.name) };}case "call": {- const result = await session.callTool(command.addr ?? "", command.service ?? "", command.tool ?? "", command.args ?? {}, { signal: AbortSignal.timeout(15_000) });+ const result = await session.callTool(command.addr ?? "", command.service ?? "", command.tool ?? "", command.args ?? {}, {+ signal: AbortSignal.timeout(15_000),+ ...requiredLabelsOf(command),+ });return { cmd: "call", ok: true, is_error: result.isError, text: result.text };}case "peers":@@ -160,8 +170,23 @@ async function main(): Promise<void> {const stateDir = requireEnv("SAM_SDK_STATE_DIR");const allowInsecure = process.env.SAM_INSECURE_CONTROL_PLANE === "1";const listenAddrs = (process.env.SAM_SDK_LISTEN_ADDRS ?? "").split(",").filter((a) => a !== "");+ // Labels this member declares at enrollment, "k=v,k2=v2"; the policy's+ // allowed_labels decide whether the control plane attests them.+ const labels = Object.fromEntries(+ (process.env.SAM_SDK_LABELS ?? "")+ .split(",")+ .filter((pair) => pair.includes("="))+ .map((pair) => pair.split("=", 2) as [string, string]),+ );- const mesh = await AgentMesh.enroll({ controlPlaneUrl, allowInsecure, stateDir, bootstrapTokenPath, pollIntervalMs: 200 });+ const mesh = await AgentMesh.enroll({+ controlPlaneUrl,+ allowInsecure,+ stateDir,+ bootstrapTokenPath,+ pollIntervalMs: 200,+ ...(Object.keys(labels).length > 0 ? { labels } : {}),+ });// The test drives every pull itself; only gossip events bring one forward.const session = await mesh.join({ listenAddrs, signal: AbortSignal.timeout(20_000), controlPlaneSyncIntervalMs: 0, controlPlaneSyncJitterMs: 0 });diff --git a/sdk/js/src/mcp.test.ts b/sdk/js/src/mcp.test.tsindex 18d36183..efad91bc 100644--- a/sdk/js/src/mcp.test.ts+++ b/sdk/js/src/mcp.test.ts@@ -168,6 +168,23 @@ test("required labels are checked on the provider's credential", async () => {assert.throws(() => requireLabels({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels: {} }, { team: "x" }), /team=x/);});+test("a requirement of several labels is met by any one of them, as sam-node's checkPeerLabels", () => {+ // The cases of internal/node/labels_gate_test.go, run through the SDK's predicate.+ const attesting = (labels: Record<string, string>) => ({ peerId: "p", expiration: new Date(), verifyingKey: cpKey, roles: [], labels });+ // exact match+ requireLabels(attesting({ region: "us-east-1" }), { region: "us-east-1" });+ // any-of requirement matches one key+ requireLabels(attesting({ region: "na-us", team: "platform" }), { region: "eu", team: "platform" });+ // no built-in hierarchy: coarser requirement fails a finer claim+ assert.throws(() => requireLabels(attesting({ region: "us-east-1" }), { region: "us" }), LabelsNotSatisfiedError);+ // disjoint labels fail+ assert.throws(() => requireLabels(attesting({ region: "na-us" }), { region: "eu" }), LabelsNotSatisfiedError);+ // unattested token fails closed, naming every pair the caller asked for+ assert.throws(() => requireLabels(attesting({}), { region: "eu", team: "platform" }), /region=eu, team=platform/);+ // an empty requirement is no requirement+ requireLabels(attesting({}), {});+});+test("a caller the provider cannot verify gets no session", async () => {const conn = await caller.dial(provider.getMultiaddrs()[0] as Parameters<typeof caller.dial>[0]);const forged = new wasm.KeyPair(wasm.SignatureAlgorithm.Ed25519);diff --git a/sdk/js/src/mcp.ts b/sdk/js/src/mcp.tsindex 2e46b17d..ae67c268 100644--- a/sdk/js/src/mcp.ts+++ b/sdk/js/src/mcp.ts@@ -102,24 +102,32 @@ export interface MCPSession {close(): Promise<void>;}-/** The provider's credential lacks a label the caller requires (checkPeerLabels). */+/** The provider's credential carries none of the labels the caller requires (checkPeerLabels). */export class LabelsNotSatisfiedError extends Error {- constructor(peerId: string, missing: string[]) {- super(`peer ${peerId} does not carry the required labels: ${missing.join(", ")}`);+ constructor(peerId: string, required: string[]) {+ super(`peer ${peerId} carries none of the required labels: ${required.join(", ")}`);this.name = "LabelsNotSatisfiedError";}}+/**+ * A caller's requirement is satisfied by any one pair, as sam-node's+ * api.LabelCheck (`check if label(k1, v1) or label(k2, v2)`): several pairs+ * mean "any of these will do". The operator's egress floor is the+ * conjunction, and sam-node's alone.+ */export function requireLabels(provider: VerifiedBiscuit, required: Record<string, string> | undefined): void {if (!required) {return;}- const missing = Object.entries(required)- .filter(([k, v]) => provider.labels[k] !== v)- .map(([k, v]) => `${k}=${v}`);- if (missing.length > 0) {- throw new LabelsNotSatisfiedError(provider.peerId, missing);+ const pairs = Object.entries(required);+ if (pairs.length === 0 || pairs.some(([k, v]) => provider.labels[k] === v)) {+ return;}+ throw new LabelsNotSatisfiedError(+ provider.peerId,+ pairs.map(([k, v]) => `${k}=${v}`),+ );}/**diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.pyindex cd69fabd..d206a923 100644--- a/sdk/python/src/agent_mesh/conformance_join.py+++ b/sdk/python/src/agent_mesh/conformance_join.py@@ -21,10 +21,12 @@ then takes JSON commands on stdin, one per line, until stdin closes:the auth handshake{"cmd": "discover", "type": "mcp", "name": "calc"}DHT lookup for a service's providers- {"cmd": "tools", "addr": "<multiaddr>", "service": "mcp://calc"}- list a provider's tools+ {"cmd": "tools", "addr": "<multiaddr>", "service": "mcp://calc",+ "required_labels": {"region": "eu"}} list a provider's tools; the labels,+ if given, must be on its credential{"cmd": "call", "addr": "<multiaddr>", "service": "mcp://calc",- "tool": "add", "args": {...}} call one tool+ "tool": "add", "args": {...}, "required_labels": {...}}+ call one tool{"cmd": "accept", "name": "agent", "target": "<url>"}accept A2A requests for thismember's agent; without target, a@@ -92,11 +94,13 @@ async def _handle(session: MeshSession, command: dict) -> dict:return {"cmd": cmd, "ok": True, "providers": [{"peer_id": p.peer_id, "addrs": p.addrs} for p in providers]}if cmd == "tools":with trio.fail_after(15):- tools = await session.list_tools(command["addr"], command.get("service", ""))+ tools = await session.list_tools(command["addr"], command.get("service", ""), required_labels=command.get("required_labels"))return {"cmd": cmd, "ok": True, "tools": [t.name for t in tools]}if cmd == "call":with trio.fail_after(15):- result = await session.call_tool(command["addr"], command.get("service", ""), command["tool"], command.get("args") or {})+ result = await session.call_tool(+ command["addr"], command.get("service", ""), command["tool"], command.get("args") or {}, required_labels=command.get("required_labels")+ )return {"cmd": cmd, "ok": True, "is_error": result.is_error, "text": result.text}if cmd == "peers":return {"cmd": cmd, "authenticated_peers": sorted(session.authenticated_peers)}@@ -154,12 +158,16 @@ async def main() -> None:state_dir = _require_env("SAM_SDK_STATE_DIR")allow_insecure = os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "1"listen = [a for a in os.environ.get("SAM_SDK_LISTEN_ADDRS", "").split(",") if a]+ # Labels this member declares at enrollment, "k=v,k2=v2"; the policy's+ # allowed_labels decide whether the control plane attests them.+ labels = dict(pair.split("=", 1) for pair in os.environ.get("SAM_SDK_LABELS", "").split(",") if "=" in pair)mesh = AgentMesh.enroll(control_plane_url,bootstrap_token_path=bootstrap_token_path,state_dir=state_dir,allow_insecure=allow_insecure,+ labels=labels or None,poll_interval=0.2,)# The test drives every pull itself; only gossip events bring one forward.diff --git a/sdk/python/src/agent_mesh/mcp_client.py b/sdk/python/src/agent_mesh/mcp_client.pyindex 8cebb624..005e07c5 100644--- a/sdk/python/src/agent_mesh/mcp_client.py+++ b/sdk/python/src/agent_mesh/mcp_client.py@@ -46,18 +46,22 @@ MCP_CLIENT_INFO = mcp_types.Implementation(name="agent-mesh-sdk", version="0.1.0class LabelsNotSatisfiedError(Exception):- """The provider's credential lacks a label the caller requires (checkPeerLabels)."""+ """The provider's credential carries none of the labels the caller requires (checkPeerLabels)."""- def __init__(self, peer_id: str, missing: Sequence[str]):- super().__init__(f"peer {peer_id} does not carry the required labels: {', '.join(missing)}")+ def __init__(self, peer_id: str, required: Sequence[str]):+ super().__init__(f"peer {peer_id} carries none of the required labels: {', '.join(required)}")def require_labels(provider: VerifiedBiscuit, required: Optional[Mapping[str, str]]) -> None:+ """A caller's requirement is satisfied by any one pair, as sam-node's+ api.LabelCheck (`check if label(k1, v1) or label(k2, v2)`): several pairs+ mean "any of these will do". The operator's egress floor is the+ conjunction, and sam-node's alone."""if not required:return- missing = [f"{k}={v}" for k, v in required.items() if provider.labels.get(k) != v]- if missing:- raise LabelsNotSatisfiedError(provider.peer_id, missing)+ if any(provider.labels.get(k) == v for k, v in required.items()):+ return+ raise LabelsNotSatisfiedError(provider.peer_id, [f"{k}={v}" for k, v in required.items()])@dataclassdiff --git a/sdk/python/tests/test_mcp.py b/sdk/python/tests/test_mcp.pyindex 7a96e49f..c8feb33c 100644--- a/sdk/python/tests/test_mcp.py+++ b/sdk/python/tests/test_mcp.py@@ -33,11 +33,11 @@ from mcp.shared.message import SessionMessagefrom agent_mesh._proto import sam_pb2 as pbfrom agent_mesh.auth import MCP_PROTOCOL, AuthRejectedError-from agent_mesh.biscuit import verify_peer_biscuit+from agent_mesh.biscuit import VerifiedBiscuit, verify_peer_biscuitfrom agent_mesh.controlplane import ROLE_NODEfrom agent_mesh.discovery import parse_service_target, service_keyfrom agent_mesh.identity import Identity-from agent_mesh.mcp_client import LabelsNotSatisfiedError, open_mcp_session, tool_call_result+from agent_mesh.mcp_client import LabelsNotSatisfiedError, open_mcp_session, require_labels, tool_call_resultfrom .test_session import CP, CP_KEY, libp2p_host@@ -192,6 +192,9 @@ def test_tools_over_the_mesh_stream():with pytest.raises(LabelsNotSatisfiedError):async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://calc"), [CP_KEY], required_labels={"region": "us"}):pass+ # Several pairs are met by any one of them; the provider attests region=eu only.+ async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://calc"), [CP_KEY], required_labels={"region": "eu", "team": "platform"}):+ pass# A provider whose credential the caller does not trust is rejected.with pytest.raises(AuthRejectedError):@@ -216,3 +219,30 @@ def test_tools_over_the_mesh_stream():await main()trio.run(with_timeout)+++def test_a_requirement_of_several_labels_is_met_by_any_one_of_them():+ """The cases of internal/node/labels_gate_test.go, run through the SDK's+ predicate: a caller naming several pairs means any of these will do, as+ sam-node's checkPeerLabels and api.LabelCheck read it."""+ from datetime import datetime, timezone++ def attesting(labels: dict) -> VerifiedBiscuit:+ return VerifiedBiscuit(peer_id="p", expiration=datetime.now(timezone.utc), verifying_key=CP_KEY, roles=[], labels=labels)++ # exact match+ require_labels(attesting({"region": "us-east-1"}), {"region": "us-east-1"})+ # any-of requirement matches one key+ require_labels(attesting({"region": "na-us", "team": "platform"}), {"region": "eu", "team": "platform"})+ # no built-in hierarchy: coarser requirement fails a finer claim+ with pytest.raises(LabelsNotSatisfiedError):+ require_labels(attesting({"region": "us-east-1"}), {"region": "us"})+ # disjoint labels fail+ with pytest.raises(LabelsNotSatisfiedError):+ require_labels(attesting({"region": "na-us"}), {"region": "eu"})+ # unattested token fails closed, naming every pair the caller asked for+ with pytest.raises(LabelsNotSatisfiedError, match="region=eu, team=platform"):+ require_labels(attesting({}), {"region": "eu", "team": "platform"})+ # an empty requirement is no requirement+ require_labels(attesting({}), {})+ require_labels(attesting({}), None)diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.mdindex c2f84e3c..9a8d37d8 100644--- a/site/content/docs/guides/native-sdks.md+++ b/site/content/docs/guides/native-sdks.md@@ -881,7 +881,8 @@ through every router that admitted the caller, and the router opens acircuit because it admitted the agent too. Either way the SDK verifies thepeer's credential before sending anything, and `requiredLabels`(`required_labels` in Python) refuses a peer whose control-plane-attested-labels do not carry the values you ask for.+labels carry none of the pairs you ask for; one matching pair is enough,+as with `X-Sam-Required-Labels` on a `sam-node`.`acceptA2A` (`accept_a2a`) fetched the mesh policy and started answering.Every caller must present a credential signed by a trusted control planediff --git a/tests/integration/sdk_mesh_test.go b/tests/integration/sdk_mesh_test.goindex 534f17d5..e441a77b 100644--- a/tests/integration/sdk_mesh_test.go+++ b/tests/integration/sdk_mesh_test.go@@ -30,6 +30,7 @@ import ("os""os/exec""path/filepath"+ "sort""strconv""strings""testing"@@ -72,6 +73,28 @@ type sdkMesh struct {mintToken func(map[string]interface{}) string}+// sdkMeshLabels is what every provider in the mesh attests, the node and the+// SDK members alike: the inputs of the "any-of requirement matches one key"+// case of internal/node/labels_gate_test.go, so the caller-side check can be+// run against a real credential from every implementation.+var sdkMeshLabels = map[string]string{"region": "na-us", "team": "platform"}++// sdkMeshLabelRequirements are the caller requirements the matrix runs against+// sdkMeshLabels: one pair of two matches, so a requirement is met by any of its+// pairs (api.LabelCheck joins them with `or`); none of the pairs matches, so+// it is refused; one pair that matches; the coarser value of a finer claim, so+// there is no hierarchy.+var sdkMeshLabelRequirements = []struct {+ name string+ required map[string]string+ allowed bool+}{+ {"any-of requirement matches one key", map[string]string{"region": "eu", "team": "platform"}, true},+ {"disjoint labels fail", map[string]string{"region": "eu", "team": "sre"}, false},+ {"exact match", map[string]string{"team": "platform"}, true},+ {"no built-in hierarchy", map[string]string{"region": "na"}, false},+}+const sdkMeshAdminToken = "test-admin-token"func startSDKMesh(t *testing.T) *sdkMesh {@@ -114,8 +137,9 @@ func startSDKMesh(t *testing.T) *sdkMesh {// The router enrolls through OIDC with group "routers" and the node with// user mock-user. Every member holds the node role, which may reach any- // service on any target; the SDK members get it from their bootstrap- // token and the node from its binding.+ // service on any target and declare the two labels the matrix uses; the+ // SDK members get it from their bootstrap token and the node from its+ // binding.policyFile := filepath.Join(t.TempDir(), "policy.yaml")policy := fmt.Sprintf(`roles:- name: %s@@ -124,6 +148,7 @@ func startSDKMesh(t *testing.T) *sdkMesh {- name: %sallowed_services: ["*"]allowed_targets: ["*"]+ allowed_labels: ["region=*", "team=*"]bindings:- role: %smembers: ["group:routers"]@@ -159,7 +184,7 @@ bindings:"--allow-loopback","--api-token-path", tokenPath(t, "node-token"),"--discovery-interval", "100ms",- "--config", writeNodeConfig(t, nodeHome, nil, svcDecl{Type: "mcp", Name: "calc", TargetURL: backend.URL}),+ "--config", writeNodeConfig(t, nodeHome, sdkMeshLabels, svcDecl{Type: "mcp", Name: "calc", TargetURL: backend.URL}),"--log-level", "debug",)return &sdkMesh{@@ -260,7 +285,11 @@ var sdkMemberLaunchers = []sdkRunner{// credential gets no answer. Then each SDK member discovers the sam-node's// service in the DHT, lists and calls its tools over /sam/mcp/1.0.0 through// the router, reads the node's own catalog, and is refused a service the-// node does not have. Then each SDK member accepts A2A requests for its+// node does not have. Every member and the sam-node attest the same labels,+// and the caller-side label requirement is run as one matrix from each SDK+// against the node and from the node against each SDK agent, so the three+// implementations agree on what a requirement of several pairs means. Then+// each SDK member accepts A2A requests for its// agent: the sam-node reaches it by peer ID through its egress proxy// (/sam/<peer>/a2a/agent/...), the other SDK member does the same over the// mesh, the agent is in no discovery table, the member speaks no@@ -384,6 +413,35 @@ func TestNativeSDKsMesh(t *testing.T) {})}+ // The caller-side label requirement means the same thing in every+ // implementation: a requirement of several pairs is met by any one of+ // them, none of them is a refusal, and a value is matched whole. The node+ // and every SDK member attest the same labels, so the matrix below runs+ // each requirement from each caller against a credential each provider+ // minted: SDK -> node over /sam/mcp/1.0.0, and node -> SDK through the+ // egress proxy's X-Sam-Required-Labels, which runs checkPeerLabels.+ t.Run("required-labels", func(t *testing.T) {+ for _, m := range members {+ if got := m.auth(t, samNode.p2pAddr).Labels; got["region"] != sdkMeshLabels["region"] || got["team"] != sdkMeshLabels["team"] {+ t.Fatalf("%s sees the node's labels as %v, want %v", m.name, got, sdkMeshLabels)+ }+ }+ for _, tc := range sdkMeshLabelRequirements {+ t.Run(tc.name, func(t *testing.T) {+ nodeRelayAddr := routerAddr + "/p2p-circuit/p2p/" + samNode.peerID.String()+ for _, m := range members {+ res := m.toolsRequiring(t, nodeRelayAddr, "mcp://"+serviceName, tc.required)+ if res.OK != tc.allowed {+ t.Errorf("%s requiring %v of the node: ok=%v (%s), want %v", m.name, tc.required, res.OK, res.Error, tc.allowed)+ }+ if !tc.allowed && res.OK == false && !strings.Contains(res.Error, "LabelsNotSatisfied") {+ t.Errorf("%s requiring %v of the node was refused for another reason: %s", m.name, tc.required, res.Error)+ }+ }+ })+ }+ })+// Every SDK member is an agent: it accepts A2A requests for a2a://agent,// answered in the runner's process, reachable by peer ID through the// router. It publishes nothing; the policy rules it evaluates are the@@ -413,6 +471,19 @@ func TestNativeSDKsMesh(t *testing.T) {t.Fatalf("sam-node egress to %s agent answered %s", m.name, body)}+ // The node's caller-side requirement against the member's+ // credential, the same matrix the members ran against the node's.+ for _, tc := range sdkMeshLabelRequirements {+ want := http.StatusForbidden+ if tc.allowed {+ want = http.StatusOK+ }+ status, body := egressGetRequiring(t, nodeAPI, "node-token", "/sam/"+m.report.PeerID+"/a2a/agent/card", tc.required)+ if status != want {+ t.Errorf("sam-node requiring %v of %s (%s): status %d %s, want %d", tc.required, m.name, tc.name, status, strings.TrimSpace(body), want)+ }+ }+// The agent is not in the discovery table: nothing was announced.if providers := m.discoverOnce(t, "a2a", "agent"); len(providers) != 0 {t.Fatalf("%s discovered %+v for a2a://agent, want nothing: an agent is not published", m.name, providers)@@ -604,6 +675,7 @@ func startSDKMember(t *testing.T, name string, cmd *exec.Cmd, root, baseURL, adm"SAM_BOOTSTRAP_TOKEN_PATH="+tokenPath,"SAM_SDK_STATE_DIR="+filepath.Join(t.TempDir(), "state"),"SAM_SDK_LISTEN_ADDRS=/ip4/127.0.0.1/tcp/0",+ "SAM_SDK_LABELS="+labelsEnv(sdkMeshLabels),)cmd.Dir = rootm := &sdkMember{name: name, cmd: cmd, stderr: &bytes.Buffer{}}@@ -807,20 +879,39 @@ func (m *sdkMember) discoverOnce(t *testing.T, serviceType, name string) []sdkPrfunc (m *sdkMember) tools(t *testing.T, addr, service string) []string {t.Helper()- var res struct {- OK bool `json:"ok"`- Error string `json:"error"`- Tools []string `json:"tools"`- }- if line := m.send(t, map[string]string{"cmd": "tools", "addr": addr, "service": service}); json.Unmarshal(line, &res) != nil {- t.Fatalf("%s member: tools answered %q", m.name, line)- }+ res := m.toolsRequiring(t, addr, service, nil)if !res.OK {t.Fatalf("%s member could not list tools of %q at %s: %s", m.name, service, addr, res.Error)}return res.Tools}+// sdkToolsResult answers a {"cmd":"tools"} command.+type sdkToolsResult struct {+ OK bool `json:"ok"`+ Error string `json:"error"`+ Tools []string `json:"tools"`+}++// toolsRequiring lists a provider's tools with a caller-side label requirement+// on the provider's credential, and reports a refusal instead of failing.+func (m *sdkMember) toolsRequiring(t *testing.T, addr, service string, required map[string]string) sdkToolsResult {+ t.Helper()+ command := map[string]any{"cmd": "tools", "addr": addr, "service": service}+ if required != nil {+ command["required_labels"] = required+ }+ line, _ := json.Marshal(command)+ if _, err := m.stdin.Write(append(line, '\n')); err != nil {+ t.Fatalf("%s member: write command: %v", m.name, err)+ }+ var res sdkToolsResult+ if answer := m.readLine(t, 20*time.Second); json.Unmarshal(answer, &res) != nil {+ t.Fatalf("%s member: tools answered %q", m.name, answer)+ }+ return res+}+// sdkCallResult answers a {"cmd":"call"} command.type sdkCallResult struct {OK bool `json:"ok"`@@ -1039,12 +1130,22 @@ func libp2pHTTPGet(t *testing.T, ctx context.Context, h host.Host, target peer.I// egressGet is a GET through sam-node's egress proxy with the node API token.func egressGet(t *testing.T, apiAddr, token, path string) (int, string) {+ t.Helper()+ return egressGetRequiring(t, apiAddr, token, path, nil)+}++// egressGetRequiring is egressGet with a caller-side label requirement on the+// destination, as X-Sam-Required-Labels carries it.+func egressGetRequiring(t *testing.T, apiAddr, token, path string, required map[string]string) (int, string) {t.Helper()req, err := http.NewRequest(http.MethodGet, "http://"+apiAddr+path, nil)if err != nil {t.Fatal(err)}req.Header.Set(api.HeaderSamAuthentication, "Bearer "+token)+ if required != nil {+ req.Header.Set(api.HeaderSamRequiredLabels, labelsEnv(required))+ }resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)if err != nil {t.Fatalf("GET %s through the sidecar: %v", path, err)@@ -1054,6 +1155,21 @@ func egressGet(t *testing.T, apiAddr, token, path string) (int, string) {return resp.StatusCode, string(body)}+// labelsEnv renders labels as "k=v,k2=v2", the form the runners' SAM_SDK_LABELS+// and sam-node's X-Sam-Required-Labels both take, keys sorted.+func labelsEnv(labels map[string]string) string {+ keys := make([]string, 0, len(labels))+ for k := range labels {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ pairs := make([]string, 0, len(keys))+ for _, k := range keys {+ pairs = append(pairs, k+"="+labels[k])+ }+ return strings.Join(pairs, ",")+}+// authHandshake runs the client side of /sam/auth/1.0.0 against target and// returns the credential target answers with.func authHandshake(t *testing.T, ctx context.Context, h host.Host, target peer.ID, biscuit []byte) []byte {