Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fix(node): stamp verified X-Peer-Id on mesh service ingress
Antonio Ojeac11d9e58dd74
diff --git a/api/network.go b/api/network.goindex 7fabf454..53afa43a 100644--- a/api/network.go+++ b/api/network.go@@ -87,6 +87,13 @@ const (// are forwarded to backend services.HeaderSamBiscuit = "X-Sam-Biscuit"+ // HeaderPeerID carries the authenticated libp2p peer ID of the caller.+ // The mesh ingress handler stamps it after authorization succeeds,+ // overwriting any inbound value, so backend services get verified caller+ // attribution without parsing biscuits. The inference facade sets it the+ // same way for locally served requests.+ HeaderPeerID = "X-Peer-Id"+// HeaderSamAgent names the agent a request is made on behalf of, as a// canonical agent identifier (see api/agent.go). It is set by the sandbox// gateway on the node's local API socket, and honoured by the node onlydiff --git a/internal/node/inference_service.go b/internal/node/inference_service.goindex 4f4a9acf..3d27ae0d 100644--- a/internal/node/inference_service.go+++ b/internal/node/inference_service.go@@ -177,7 +177,7 @@ func getPeerID(r *http.Request) string {}// Only trust X-Peer-Id if request comes from local loopback / trusted localhost sourceif host == "127.0.0.1" || host == "::1" || host == "localhost" {- if peerHeader := r.Header.Get("X-Peer-Id"); peerHeader != "" {+ if peerHeader := r.Header.Get(api.HeaderPeerID); peerHeader != "" {return peerHeader}}diff --git a/internal/node/node.go b/internal/node/node.goindex c2d6402d..bf1834ad 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -1937,6 +1937,9 @@ func (n *SamNode) StartIngressServer(ctx context.Context) error {// The agent is for policy, not for the backend, which has no way to// judge it.r.Header.Del(api.HeaderSamAgent)+ // Set, not Add: an inbound value is a spoof attempt, only the+ // transport-verified identity may reach the backend.+ r.Header.Set(api.HeaderPeerID, remotePeer.String())svc, ok := n.services.Get(serviceName)if !ok {diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.goindex fee4c635..a55c31a4 100644--- a/internal/node/openai_facade.go+++ b/internal/node/openai_facade.go@@ -445,7 +445,7 @@ func (f *openAIFacade) serveLocal(w http.ResponseWriter, r *http.Request, servic}// Attribute locally served tokens to this node in usage metrics.if id := f.localPeerID(); id != "" {- r.Header.Set("X-Peer-Id", id)+ r.Header.Set(api.HeaderPeerID, id)}svc.Handler().ServeHTTP(w, r)returndiff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.goindex c42c8eb3..1bc33ef2 100644--- a/internal/node/proxy_test.go+++ b/internal/node/proxy_test.go@@ -748,13 +748,26 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {},wantReceivedHeaders: map[string]string{"Authorization": "Bearer upstream-token",- api.HeaderSamAuthentication: "", // Must be stripped, local-only- api.HeaderSamBiscuit: "", // Must be stripped- api.HeaderSamNoTrailingSlash: "", // Must be stripped+ api.HeaderSamAuthentication: "", // Must be stripped, local-only+ api.HeaderSamBiscuit: "", // Must be stripped+ api.HeaderSamNoTrailingSlash: "", // Must be stripped+ api.HeaderPeerID: nodeB.Host.ID().String(), // Verified caller stamped by ingress"X-Test-Request": "yes",},wantReceivedPathSuffix: "/api/v1/test",},+ {+ name: "Inbound X-Peer-Id is overwritten with the verified caller",+ pathSuffix: "/api/v1/test",+ requestHeaders: map[string]string{+ api.HeaderSamAuthentication: "Bearer local-token",+ api.HeaderPeerID: "spoofed-peer-id",+ },+ wantReceivedHeaders: map[string]string{+ api.HeaderPeerID: nodeB.Host.ID().String(),+ },+ wantReceivedPathSuffix: "/api/v1/test",+ },{name: "Local gate header stripped, no Authorization to pass through",pathSuffix: "/api/v1/test",diff --git a/tests/integration/datapath_test.go b/tests/integration/datapath_test.goindex 68105bcd..57911a22 100644--- a/tests/integration/datapath_test.go+++ b/tests/integration/datapath_test.go@@ -23,6 +23,7 @@ import ("os""path/filepath""strings"+ "sync""testing""time"@@ -194,13 +195,26 @@ func TestIntegrationHTTPDatapath(t *testing.T) {addrA := waitForPeerInfoInLog(t, filepath.Join(homeA, "node.log"))peerIDA := getPeerIDFromAddr(addrA)+ addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))+ peerIDB := getPeerIDFromAddr(addrB)// Connect Node B to Node AcallMCP(t, actualApiAddrB, "connect_peer", map[string]any{"peer_addr": addrA})- // Start a dummy HTTP server on Node A's host (simulating local service)+ // Start a dummy HTTP server on Node A's host (simulating local service).+ // It captures the headers it receives so we can assert what actually+ // crosses the mesh: verified caller identity in, biscuit stripped.expectedBody := `{"status":"success"}`+ var (+ hdrMu sync.Mutex+ gotPeerID string+ gotBiscuit string+ )dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hdrMu.Lock()+ gotPeerID = r.Header.Get(api.HeaderPeerID)+ gotBiscuit = r.Header.Get(api.HeaderSamBiscuit)+ hdrMu.Unlock()w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusOK)_, _ = w.Write([]byte(expectedBody))@@ -246,6 +260,8 @@ func TestIntegrationHTTPDatapath(t *testing.T) {for i := 0; i < 3; i++ {req, _ := http.NewRequest("GET", url, nil)req.Header.Set(api.HeaderSamAuthentication, "Bearer "+apiToken)+ // Spoof attempt: the backend must see the verified peer id, not this.+ req.Header.Set(api.HeaderPeerID, "spoofed-peer")req.Close = true // Force close the connection so the libp2p stream terminates and flushed accounting logshttpResp, err = client.Do(req)if err == nil && httpResp.StatusCode == http.StatusOK {@@ -273,6 +289,15 @@ func TestIntegrationHTTPDatapath(t *testing.T) {t.Fatalf("Expected body %s, got %s", expectedBody, string(bodyBytes))}+ hdrMu.Lock()+ if gotPeerID != peerIDB.String() {+ t.Errorf("backend %s: got %q, want verified caller %q (spoofed inbound value must be overwritten)", api.HeaderPeerID, gotPeerID, peerIDB)+ }+ if gotBiscuit != "" {+ t.Errorf("%s leaked to backend: %q", api.HeaderSamBiscuit, gotBiscuit)+ }+ hdrMu.Unlock()+// Verify Audit Traceability and Stream Accounting logs were emittedassertLogInFile(t, filepath.Join(homeA, "node.log"), "Audit Traceability")assertLogInFile(t, filepath.Join(homeA, "node.log"), "Stream Accounting")