Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
Enforce Zero Trust architecture by protecting MCP and SAM node endpoints with API token
Antonio Ojea591ec75baedf
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.goindex c2e23cf4..7bbb6415 100644--- a/cmd/sam-node/node.go+++ b/cmd/sam-node/node.go@@ -55,6 +55,7 @@ import ("github.com/libp2p/go-libp2p/p2p/discovery/util""github.com/libp2p/go-libp2p/p2p/host/autorelay""github.com/libp2p/go-libp2p/p2p/net/connmgr"+ "github.com/libp2p/go-libp2p/p2p/net/swarm"libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls""github.com/libp2p/go-msgio""github.com/multiformats/go-multiaddr"@@ -286,6 +287,7 @@ func NewSamNode(ctx context.Context, cfg SamNodeConfig) (*SamNode, error) {libp2p.EnableRelay(),libp2p.EnableHolePunching(),libp2p.ConnectionManager(cm),+ libp2p.SwarmOpts(swarm.WithDialTimeout(15 * time.Second)),libp2p.AddrsFactory(func(addrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {if cfg.AllowLoopback {return addrsdiff --git a/cmd/sam-node/sidecar.go b/cmd/sam-node/sidecar.goindex 9d08169c..88059596 100644--- a/cmd/sam-node/sidecar.go+++ b/cmd/sam-node/sidecar.go@@ -43,22 +43,22 @@ func startSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile stmux.HandleFunc("/readyz", handleReadyz)// Protected endpoints- mux.Handle("/sam/service/register", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mux.Handle("/sam/service/register", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleRegisterService(node, w, r)}))))- mux.Handle("/sam/service/unregister", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mux.Handle("/sam/service/unregister", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleUnregisterService(node, w, r)}))))- mux.Handle("/sam/service/discover", withMeshConnection(node, withAuth(token, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mux.Handle("/sam/service/discover", withAuth(token, withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {handleDiscoverService(node, w, r)}))))// Mount Egress Proxy- mux.Handle("/sam/", withMeshConnection(node, withAuth(token, createEgressProxy(node))))+ mux.Handle("/sam/", withAuth(token, withMeshConnection(node, createEgressProxy(node))))// Mount MCP handlermcpHandler := NewMCPHandler(node)- mux.Handle("/", withMeshConnection(node, mcpHandler))+ mux.Handle("/", withAuth(token, withMeshConnection(node, mcpHandler)))server := &http.Server{Handler: mux,diff --git a/cmd/sam-node/sidecar_test.go b/cmd/sam-node/sidecar_test.goindex 574d5854..b84c87ff 100644--- a/cmd/sam-node/sidecar_test.go+++ b/cmd/sam-node/sidecar_test.go@@ -96,21 +96,84 @@ func TestWithAuth(t *testing.T) {})}-func TestPublicEndpoints(t *testing.T) {- mux := http.NewServeMux()- mux.HandleFunc("/healthz", handleHealthz)- mux.HandleFunc("/readyz", handleReadyz)+func TestSidecarServerAuthEnforcement(t *testing.T) {+ node := &SamNode{+ BiscuitTimeout: 500 * time.Millisecond,+ services: NewServiceRegistry(&fakeDHT{}),+ }+ // We use a dummy token+ token := "test-token"- endpoints := []string{"/healthz", "/readyz"}+ // Start sidecar on an ephemeral port+ err := startSidecarServer(node, "127.0.0.1:0", token, "", "", "")+ if err != nil {+ t.Fatalf("Failed to start sidecar server: %v", err)+ }++ baseURL := "http://" + node.BoundHTTPAddr+ client := &http.Client{Timeout: 2 * time.Second}+ ready := false+ for i := 0; i < 50; i++ {+ time.Sleep(10 * time.Millisecond)+ resp, err := client.Get(baseURL + "/healthz")+ if err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ ready = true+ break+ }+ }+ }+ if !ready {+ t.Fatalf("Sidecar server failed to become ready")+ }- for _, ep := range endpoints {- req := httptest.NewRequest("GET", ep, nil)- rr := httptest.NewRecorder()- mux.ServeHTTP(rr, req)+ tests := []struct {+ name string+ method string+ path string+ expectedStatus int+ needsToken bool+ }{+ {"healthz is public", "GET", "/healthz", http.StatusOK, false},+ {"readyz is public", "GET", "/readyz", http.StatusOK, false},+ {"register is protected", "POST", "/sam/service/register", http.StatusUnauthorized, false},+ {"unregister is protected", "POST", "/sam/service/unregister", http.StatusUnauthorized, false},+ {"discover is protected", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusUnauthorized, false},+ {"egress proxy is protected", "GET", "/sam/", http.StatusUnauthorized, false},+ {"mcp root is protected", "GET", "/mcp", http.StatusUnauthorized, false},++ {"register with token (bad req)", "POST", "/sam/service/register", http.StatusServiceUnavailable, true},+ {"unregister with token (bad req)", "POST", "/sam/service/unregister", http.StatusServiceUnavailable, true},+ // /sam/service/discover without mesh connection will return 503 instead of 400 since node is not connected,+ // but as long as it gets past auth, that's what we want to verify.+ {"discover with token", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusServiceUnavailable, true},+ {"egress proxy with token", "GET", "/sam/", http.StatusServiceUnavailable, true},+ {"mcp root with token", "GET", "/mcp", http.StatusServiceUnavailable, true},+ }- if rr.Code != http.StatusOK {- t.Errorf("expected status OK for %s, got %d", ep, rr.Code)- }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req, err := http.NewRequest(tt.method, baseURL+tt.path, nil)+ if err != nil {+ t.Fatalf("Failed to create request: %v", err)+ }+ if tt.needsToken {+ req.Header.Set("Authorization", "Bearer "+token)+ }++ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("Request failed: %v", err)+ }+ defer func() {+ _ = resp.Body.Close()+ }()++ if resp.StatusCode != tt.expectedStatus {+ t.Errorf("expected status %d for %s, got %d", tt.expectedStatus, tt.path, resp.StatusCode)+ }+ })}}diff --git a/cmd/sam-node/stdio_bridge.go_patch b/cmd/sam-node/stdio_bridge.go_patchnew file mode 100644index 00000000..77fd32d9--- /dev/null+++ b/cmd/sam-node/stdio_bridge.go_patch@@ -0,0 +1 @@+func (b *StdioBridge) Start() {diff --git a/tests/e2e/docker/Dockerfile.sam-runtime b/tests/e2e/docker/Dockerfile.sam-runtimeindex 2a4551b8..9236c827 100644--- a/tests/e2e/docker/Dockerfile.sam-runtime+++ b/tests/e2e/docker/Dockerfile.sam-runtime@@ -25,5 +25,11 @@ RUN addgroup -S sam && adduser -S -G sam samCOPY --from=build /src/bin/ /usr/local/bin/+USER root+RUN mv /usr/local/bin/mcp-client /usr/local/bin/mcp-client-real && \+ echo '#!/bin/sh' > /usr/local/bin/mcp-client && \+ echo 'exec /usr/local/bin/mcp-client-real -token "secret-token" "$@"' >> /usr/local/bin/mcp-client && \+ chmod +x /usr/local/bin/mcp-client+USER samWORKDIR /home/samdiff --git a/tests/e2e/docs_snippets.bats b/tests/e2e/docs_snippets.batsindex 405a9995..11ed7f2e 100644--- a/tests/e2e/docs_snippets.bats+++ b/tests/e2e/docs_snippets.bats@@ -35,6 +35,7 @@ teardown() {-v "$(pwd)/site/content/docs/snippets:/snippets" \-e PYTHONPATH=/sam-mcp-python/src \-e SAM_MCP_URL="http://sam-node-1:8080/mcp" \+ -e SAM_API_TOKEN="secret-token" \python:3.12 \bash -c 'pip install mcp httpx && python3 /snippets/agent_demo.py'diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bashindex 1d75976e..6947afeb 100644--- a/tests/e2e/lib/container_mesh.bash+++ b/tests/e2e/lib/container_mesh.bash@@ -115,7 +115,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; thenlocal timeout_s="${2:-20}"local ifor ((i=0; i<timeout_s; i++)); do- if docker run --rm --network "${MESH_NETWORK}" python:3.12 curl -s -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"ping","id":1}' --max-time 5 -D - http://sam-node-${idx}:8080/mcp | grep -q "200 OK"; then+ if docker run --rm --network "${MESH_NETWORK}" python:3.12 curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer secret-token" -d '{"jsonrpc":"2.0","method":"ping","id":1}' --max-time 5 -D - http://sam-node-${idx}:8080/mcp | grep -q "200 OK"; thenreturn 0fisleep 1diff --git a/tests/e2e/python_sdk_test.bats b/tests/e2e/python_sdk_test.batsindex 36085352..1db098f7 100644--- a/tests/e2e/python_sdk_test.bats+++ b/tests/e2e/python_sdk_test.bats@@ -33,6 +33,7 @@ teardown() {--network "${MESH_NETWORK}" \-v "$(pwd)/sam-mcp-python:/sam-mcp-python" \-e PYTHONPATH=/sam-mcp-python/src \+ -e SAM_API_TOKEN=secret-token \python:3.12 \bash -c 'pip install mcp httpx && python3 /sam-mcp-python/test_client.py'echo "Python SDK output: $output"diff --git a/tests/integration/auth_test.go b/tests/integration/auth_test.gonew file mode 100644index 00000000..54a12782--- /dev/null+++ b/tests/integration/auth_test.go@@ -0,0 +1,128 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package integration_test++import (+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"+)++func TestNodeAuthEnforcementIntegration(t *testing.T) {+ nodeBin := buildBinary(t, "./cmd/sam-node")+ _, mockHubURL := startMockLibp2pHub(t)++ home := t.TempDir()+ logFile, err := os.Create(filepath.Join(home, "node.log"))+ if err != nil {+ t.Fatal(err)+ }+ defer func() {+ _ = logFile.Close()+ }()++ // getFreePort is already defined in minimal_helpers_test.go+ port := getFreePort(t)+ nodeURL := fmt.Sprintf("http://127.0.0.1:%d", port)+ apiToken := "secret-integration-token"++ cmd := exec.Command(nodeBin, "run",+ "--hub", mockHubURL,+ "--data-dir", home,+ "--api-token", apiToken,+ "--jwt", "fake-jwt",+ "--bind-addr", fmt.Sprintf("127.0.0.1:%d", port),+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ )+ cmd.Stdout = logFile+ cmd.Stderr = logFile++ if err := cmd.Start(); err != nil {+ t.Fatalf("failed to start node: %v", err)+ }+ defer func() { _ = cmd.Process.Kill() }()++ // Wait for node to be ready+ client := &http.Client{Timeout: 2 * time.Second}+ ready := false+ for i := 0; i < 50; i++ {+ time.Sleep(100 * time.Millisecond)+ resp, err := client.Get(nodeURL + "/healthz")+ if err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ ready = true+ break+ }+ }+ }++ if !ready {+ b, _ := os.ReadFile(filepath.Join(home, "node.log"))+ t.Fatalf("Node did not become ready in time. Log:\n%s", string(b))+ }++ // Verify authentication on endpoints+ tests := []struct {+ name string+ method string+ path string+ expectedStatus int+ needsToken bool+ }{+ {"healthz is public", "GET", "/healthz", http.StatusOK, false},+ {"readyz is public", "GET", "/readyz", http.StatusOK, false},+ {"register is protected", "POST", "/sam/service/register", http.StatusUnauthorized, false},+ {"unregister is protected", "POST", "/sam/service/unregister", http.StatusUnauthorized, false},+ {"discover is protected", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusUnauthorized, false},+ {"egress proxy is protected", "GET", "/sam/", http.StatusUnauthorized, false},+ {"mcp root is protected", "GET", "/mcp", http.StatusUnauthorized, false},++ {"register with token (bad req)", "POST", "/sam/service/register", http.StatusBadRequest, true},+ {"unregister with token (bad req)", "POST", "/sam/service/unregister", http.StatusBadRequest, true},+ // /sam/service/discover expects node to be connected.+ {"discover with token", "GET", "/sam/service/discover?type=mcp&name=test", http.StatusOK, true},+ {"mcp root with token", "GET", "/mcp", http.StatusBadRequest, true},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req, err := http.NewRequest(tt.method, nodeURL+tt.path, nil)+ if err != nil {+ t.Fatalf("Failed to create request: %v", err)+ }+ if tt.needsToken {+ req.Header.Set("Authorization", "Bearer "+apiToken)+ }++ resp, err := client.Do(req)+ if err != nil {+ t.Fatalf("Request failed: %v", err)+ }+ defer func() {+ _ = resp.Body.Close()+ }()++ if resp.StatusCode != tt.expectedStatus {+ t.Errorf("expected status %d for %s, got %d", tt.expectedStatus, tt.path, resp.StatusCode)+ }+ })+ }+}diff --git a/tests/integration/catalog_test.go b/tests/integration/catalog_test.goindex da4e37d4..30344fb1 100644--- a/tests/integration/catalog_test.go+++ b/tests/integration/catalog_test.go@@ -3,6 +3,7 @@ package integration_testimport ("context""encoding/json"+ "net/http""os""os/exec""path/filepath"@@ -75,7 +76,19 @@ func callMCP(t *testing.T, mcpAddr string, toolName string, params map[string]anVersion: "0.1.0",}, nil)- session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)+ // Custom RoundTripper to inject Authorization header for tests+ transport := http.DefaultTransport+ clientTransport := &mcp.StreamableClientTransport{+ Endpoint: "http://" + mcpAddr + "/mcp",+ HTTPClient: &http.Client{+ Transport: &authRoundTripper{+ token: "test-token", // Token used across all integration tests+ rt: transport,+ },+ },+ }++ session, err := client.Connect(ctx, clientTransport, nil)if err != nil {t.Fatalf("Failed to connect: %v", err)}@@ -101,6 +114,17 @@ func callMCP(t *testing.T, mcpAddr string, toolName string, params map[string]anreturn ""}+type authRoundTripper struct {+ token string+ rt http.RoundTripper+}++func (a *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {+ clone := req.Clone(req.Context())+ clone.Header.Set("Authorization", "Bearer "+a.token)+ return a.rt.RoundTrip(clone)+}+func waitForPeerInfoInLog(t *testing.T, logPath string) string {t.Helper()deadline := time.Now().Add(5 * time.Second)@@ -172,7 +196,12 @@ func TestCatalogRoutingAndFailover(t *testing.T) {for time.Now().Before(deadline) {client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.1.0"}, nil)- session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddrA + "/mcp"}, nil)+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{+ Endpoint: "http://" + mcpAddrA + "/mcp",+ HTTPClient: &http.Client{+ Transport: &authRoundTripper{token: "test-token", rt: http.DefaultTransport},+ },+ }, nil)if err != nil {t.Logf("Poll: failed to connect: %v", err)time.Sleep(500 * time.Millisecond)diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.goindex 26b22e44..0ffb24c9 100644--- a/tests/integration/datapath_test.go+++ b/tests/integration/datapath_test.go@@ -36,7 +36,7 @@ func TestIntegrationStdioDatapath(t *testing.T) {homeA := t.TempDir()homeB := t.TempDir()- apiToken := "secret-token"+ apiToken := "test-token"// Start Node At.Log("Starting Node A...")@@ -161,7 +161,7 @@ func TestIntegrationHTTPDatapath(t *testing.T) {homeA := t.TempDir()homeB := t.TempDir()- apiToken := "secret-token"+ apiToken := "test-token"// Start Node At.Log("Starting Node A...")diff --git a/tests/integration/mcp_local_tools_test.go b/tests/integration/mcp_local_tools_test.goindex 3da9c2be..fcde6ccd 100644--- a/tests/integration/mcp_local_tools_test.go+++ b/tests/integration/mcp_local_tools_test.go@@ -67,7 +67,7 @@ roles: {}fetchPeerID(t, httpPortHub)hubURL := fmt.Sprintf("http://127.0.0.1:%d", httpPortHub)- apiToken := "secret-token"+ apiToken := "test-token"homeA := t.TempDir()homeB := t.TempDir()diff --git a/tests/integration/pubsub_test.go b/tests/integration/pubsub_test.goindex 28d507fc..5f8373b1 100644--- a/tests/integration/pubsub_test.go+++ b/tests/integration/pubsub_test.go@@ -22,8 +22,6 @@ import ("strings""testing""time"-- "github.com/modelcontextprotocol/go-sdk/mcp")func TestPubSubTools(t *testing.T) {@@ -46,7 +44,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 1env1 := append(os.Environ(), "HOME="+tmpHome1, "XDG_CONFIG_HOME="+filepath.Join(tmpHome1, ".config"))- cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")+ cmd1 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5003/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5004", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")cmd1.Env = env1logFile1, err := os.Create(filepath.Join(tmpHome1, "node1.log"))if err != nil {@@ -61,7 +59,7 @@ func TestPubSubTools(t *testing.T) {// Start Node 2env2 := append(os.Environ(), "HOME="+tmpHome2, "XDG_CONFIG_HOME="+filepath.Join(tmpHome2, ".config"))- cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "dummy-token", "--allow-loopback")+ cmd2 := exec.CommandContext(ctx, nodeBin, "run", "--trust-hub-rbac", "--hub", hubAddr, "--bind-addr", "127.0.0.1:0", "--listen", "/ip4/127.0.0.1/udp/5005/quic-v1", "--listen", "/ip4/127.0.0.1/tcp/5006", "--jwt", "dummy-token", "--log-level", "debug", "--discovery-interval", "100ms", "--api-token", "test-token", "--allow-loopback")cmd2.Env = env2logFile2, err := os.Create(filepath.Join(tmpHome2, "node2.log"))if err != nil {@@ -100,35 +98,7 @@ func TestPubSubTools(t *testing.T) {// Helper to call MCP toolcallTool := func(mcpAddr string, toolName string, params map[string]any) string {- client := mcp.NewClient(&mcp.Implementation{- Name: "test-client",- Version: "0.1.0",- }, nil)-- session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: "http://" + mcpAddr + "/mcp"}, nil)- if err != nil {- t.Fatalf("Failed to connect: %v", err)- }- defer func() {- if err := session.Close(); err != nil {- t.Logf("failed to close session: %v", err)- }- }()-- result, err := session.CallTool(context.Background(), &mcp.CallToolParams{- Name: toolName,- Arguments: params,- })- if err != nil {- t.Fatalf("CallTool failed: %v", err)- }-- for _, content := range result.Content {- if textContent, ok := content.(*mcp.TextContent); ok {- return textContent.Text- }- }- return ""+ return callMCP(t, mcpAddr, toolName, params)}waitForPeerInfoInLog := func(t *testing.T, logPath string) string {diff --git a/tests/integration/service_discovery_test.go b/tests/integration/service_discovery_test.goindex d5fa9337..5cc1cbb1 100644--- a/tests/integration/service_discovery_test.go+++ b/tests/integration/service_discovery_test.go@@ -38,7 +38,7 @@ func TestServiceDiscovery(t *testing.T) {homeA := t.TempDir()homeB := t.TempDir()- apiToken := "secret-token"+ apiToken := "test-token"// Start Node At.Log("Starting Node A...")@@ -142,7 +142,7 @@ func TestServiceDiscoveryStreaming(t *testing.T) {homeA := t.TempDir()homeB := t.TempDir()- apiToken := "secret-token"+ apiToken := "test-token"// Start Node At.Log("Starting Node A...")