Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: hold the egress floor when the caller requires nothing
Antonio Ojea881915bb13d9
diff --git a/internal/node/mcp.go b/internal/node/mcp.goindex 522ed749..414e64a4 100644--- a/internal/node/mcp.go+++ b/internal/node/mcp.go@@ -240,10 +240,10 @@ func (s *agentMCPServers) forAgent(agentID string) *mcp.Server {return server}-// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.// CallMCPTool opens a stream to a remote peer, performs the handshake, and calls a tool.// requiredLabels, when non-empty, fail-closed verifies the peer's control-plane-attested-// labels (see checkPeerLabels) before the tool is invoked; nil means no requirement.+// labels (see checkPeerLabels) before the tool is invoked; nil means no caller+// requirement, though the operator's egress floor, if configured, is still enforced.func (n *SamNode) CallMCPTool(ctx context.Context, targetPeer peer.ID, toolName string, params any, requiredLabels map[string]string) (*mcp.CallToolResult, error) {var res *mcp.CallToolResultvar err error@@ -378,7 +378,10 @@ func (n *SamNode) ConnectMCPSession(ctx context.Context, targetPeer peer.ID, tarreturn nil, nil, fmt.Errorf("%w by %s: %s", ErrAuthRejected, targetPeer, resp.Error)}- if len(requiredLabels) > 0 {+ // The gate runs when the caller requires labels or when the operator's+ // egress floor does: a caller that requires nothing is still held to the+ // floor (checkPeerLabels ANDs both).+ if len(requiredLabels) > 0 || len(n.egressFloor()) > 0 {if err := n.checkPeerLabels(resp.Biscuit, targetPeer, requiredLabels); err != nil {cleanup()return nil, nil, errdiff --git a/internal/node/mcp_handlers_test.go b/internal/node/mcp_handlers_test.goindex 4caa6195..345b624a 100644--- a/internal/node/mcp_handlers_test.go+++ b/internal/node/mcp_handlers_test.go@@ -744,6 +744,70 @@ func TestCallMCPTool_LabelEnforcement(t *testing.T) {}}+// The operator's egress floor gates MCP egress even when the caller supplies no+// required_labels: silence must not waive the floor (see #385).+func TestCallMCPTool_EgressFloorEnforcement(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()++ nodeA, cleanupA := startBareNode(t, ctx)+ defer cleanupA()+ nodeB, cleanupB := startBareNode(t, ctx)+ defer cleanupB()++ if err := nodeA.Host.Connect(ctx, peer.AddrInfo{ID: nodeB.Host.ID(), Addrs: nodeB.Host.Addrs()}); err != nil {+ t.Fatalf("connect: %v", err)+ }++ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("gen root key: %v", err)+ }++ // nodeA authenticates to nodeB as an unrestricted caller.+ if err := buildAndSaveBiscuit(nodeA, rootPriv); err != nil {+ t.Fatalf("buildAndSaveBiscuit: %v", err)+ }+ nodeB.keysMu.Lock()+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeB.keysMu.Unlock()++ // nodeB attests region=eu-de and nothing else.+ nodeBIdentity, err := identity.MintBootstrapBiscuitToken(rootPriv, nodeB.Host.ID(), api.RoleNode, time.Now().Add(time.Hour), nil, map[string]string{"region": "eu-de"})+ if err != nil {+ t.Fatalf("mint nodeB identity: %v", err)+ }+ nodeB.SetIdentityCache(nodeBIdentity)+ nodeA.keysMu.Lock()+ nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeA.keysMu.Unlock()++ hostedSrv := httptest.NewServer(newFakeMCPHandler(t, []*mcp.Tool{+ {Name: "review_pr", Description: "Run a code review", InputSchema: map[string]any{"type": "object"}},+ }))+ defer hostedSrv.Close()++ if err := nodeB.RegisterService(ctx, &api.RegisterServiceRequest{+ Service: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "code-reviewer"},+ Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: hostedSrv.URL},+ }); err != nil {+ t.Fatalf("RegisterService: %v", err)+ }+ defer func() { _ = nodeB.UnregisterService(ctx, "code-reviewer") }()++ // Floor satisfied by nodeB's attestation; the caller requires nothing.+ nodeA.nodeConfig = &NodeConfigComplete{EgressRequireLabels: map[string]string{"region": "eu-de"}}+ if _, err := nodeA.CallMCPTool(ctx, nodeB.Host.ID(), "mcp://code-reviewer/review_pr", map[string]any{}, nil); err != nil {+ t.Fatalf("CallMCPTool inside the floor should succeed: %v", err)+ }++ // Floor nodeB does not attest; the caller staying silent must not waive it.+ nodeA.nodeConfig = &NodeConfigComplete{EgressRequireLabels: map[string]string{"jurisdiction": "eu"}}+ if _, err := nodeA.CallMCPTool(ctx, nodeB.Host.ID(), "mcp://code-reviewer/review_pr", map[string]any{}, nil); err == nil {+ t.Fatal("CallMCPTool outside the floor with no caller requirement must fail")+ }+}+func TestNewMCPHandler_RegistersFindRemoteTools(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.goindex a00eb112..dee7b216 100644--- a/internal/node/openai_facade.go+++ b/internal/node/openai_facade.go@@ -410,8 +410,10 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)} else {// Labels ranked this provider; the label gate is the enforcement// point: the provider's biscuit must attest the requirement before- // the request body leaves this node.- if len(requiredLabels) > 0 {+ // the request body leaves this node. The gate also runs when only+ // the operator's floor requires it — a caller that asked for+ // nothing is still held to the floor (VerifyPeerLabels ANDs both).+ if len(requiredLabels) > 0 || len(f.floor()) > 0 {if f.verifyPeerLabels == nil {recordFacadeRejection(reasonLabelUnattested)writeOpenAIError(w, http.StatusServiceUnavailable, "label_unattested",@@ -421,9 +423,16 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)// No backoff on failure: the verdict is requirement-scoped,// the provider stays eligible for unconstrained requests.if err := f.verifyPeerLabels(r.Context(), p.peerID, requiredLabels); err != nil {- recordFacadeRejection(reasonLabelUnattested)- logger.Warnf("[OpenAIFacade] provider peer=%q service=%q failed label attestation for %v: %v; trying next",- p.peerID, p.service, requiredLabels, err)+ // With no caller requirement the only thing that can have+ // failed is the floor; attribute it so the operator can+ // tell their floor apart from a caller's requirement.+ if len(requiredLabels) == 0 {+ recordFacadeRejection(reasonEgressFloorMismatch)+ } else {+ recordFacadeRejection(reasonLabelUnattested)+ }+ logger.Warnf("[OpenAIFacade] provider peer=%q service=%q failed label attestation for %v (egress floor %v): %v; trying next",+ p.peerID, p.service, requiredLabels, f.floor(), err)continue}}diff --git a/internal/node/openai_facade_test.go b/internal/node/openai_facade_test.goindex 956c4caf..7fd8e3fb 100644--- a/internal/node/openai_facade_test.go+++ b/internal/node/openai_facade_test.go@@ -896,3 +896,85 @@ func TestRankProvidersEnforcesEgressFloor(t *testing.T) {}})}++// Ranking is a hint; the gate on the forward path is the enforcement. Gossip is+// unauthenticated, so an unlabelled remote survives ranking and the biscuit+// gate is the only check left before the body leaves the node — it must run+// even when the caller required nothing, or the floor is waived by silence.+func TestFacade_Completions_FloorGatesSilentCaller(t *testing.T) {+ newFloorFacade := func() *openAIFacade {+ f := newTestFacade()+ f.egressFloor = func() map[string]string { return map[string]string{"jurisdiction": "eu"} }+ f.viewProviders = func(string) []modelProvider {+ return []modelProvider{{peerID: "peerX", service: "srv"}}+ }+ return f+ }+ silentRequest := func() *http.Request {+ // No X-Sam-Required-Labels header: the caller requires nothing.+ return httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))+ }++ t.Run("an unattested floor blocks the forward", func(t *testing.T) {+ f := newFloorFacade()+ var gateRequired map[string]string+ gateCalled := false+ f.verifyPeerLabels = func(_ context.Context, _ string, required map[string]string) error {+ gateCalled = true+ gateRequired = required+ return fmt.Errorf("floor not attested")+ }+ forwarded := false+ f.forward = http.HandlerFunc(func(http.ResponseWriter, *http.Request) { forwarded = true })++ rec := httptest.NewRecorder()+ f.handleCompletions(rec, silentRequest())++ if !gateCalled {+ t.Fatal("the gate must run for a caller that required nothing")+ }+ if gateRequired != nil {+ t.Errorf("the caller required nothing, so the gate must see required=nil, got %v", gateRequired)+ }+ if forwarded {+ t.Error("the body must not leave the node when the floor is unattested")+ }+ if rec.Code != http.StatusServiceUnavailable {+ t.Errorf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)+ }+ })++ t.Run("an attested floor forwards", func(t *testing.T) {+ f := newFloorFacade()+ f.verifyPeerLabels = func(context.Context, string, map[string]string) error { return nil }+ forwarded := false+ f.forward = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ forwarded = true+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"ok":true}`))+ })++ rec := httptest.NewRecorder()+ f.handleCompletions(rec, silentRequest())++ if rec.Code != http.StatusOK || !forwarded {+ t.Errorf("an attested floor must not block: status = %d, forwarded = %v", rec.Code, forwarded)+ }+ })++ t.Run("a floor with no gate seam fails closed", func(t *testing.T) {+ f := newFloorFacade() // verifyPeerLabels stays nil+ forwarded := false+ f.forward = http.HandlerFunc(func(http.ResponseWriter, *http.Request) { forwarded = true })++ rec := httptest.NewRecorder()+ f.handleCompletions(rec, silentRequest())++ if forwarded {+ t.Error("no gate available must mean no egress, not ungated egress")+ }+ if rec.Code != http.StatusServiceUnavailable {+ t.Errorf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)+ }+ })+}diff --git a/internal/node/proxy_test.go b/internal/node/proxy_test.goindex 1bc33ef2..afa3c267 100644--- a/internal/node/proxy_test.go+++ b/internal/node/proxy_test.go@@ -31,6 +31,7 @@ import ("time""github.com/google/sam/api"+ "github.com/google/sam/internal/identity""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer")@@ -844,3 +845,100 @@ func TestDatapathHeadersAndRoutingTable(t *testing.T) {})}}++// The operator's egress floor holds at the /sam/ chokepoint itself, so an agent+// that skips the facade and dials /sam/<peer>/... raw is still gated: the+// provider's biscuit must attest every pair of the floor before anything is+// forwarded, whatever the caller did or did not ask for (see #385).+func TestEgressProxyEnforcesFloor(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ nodeA, cleanupA := startBareNode(t, ctx) // provider+ defer cleanupA()+ nodeB, cleanupB := startBareNode(t, ctx) // egress side, holds the floor+ defer cleanupB()++ rootPub, rootPriv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("gen root key: %v", err)+ }++ // nodeB authenticates to nodeA as an unrestricted caller.+ if err := buildAndSaveBiscuit(nodeB, rootPriv); err != nil {+ t.Fatalf("buildAndSaveBiscuit: %v", err)+ }+ nodeA.keysMu.Lock()+ nodeA.trustedKeys = append(nodeA.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeA.keysMu.Unlock()++ // nodeA attests jurisdiction=eu and nothing else.+ nodeAIdentity, err := identity.MintBootstrapBiscuitToken(rootPriv, nodeA.Host.ID(), api.RoleNode, time.Now().Add(time.Hour), nil, map[string]string{"jurisdiction": "eu"})+ if err != nil {+ t.Fatalf("mint nodeA identity: %v", err)+ }+ nodeA.SetIdentityCache(nodeAIdentity)+ nodeB.keysMu.Lock()+ nodeB.trustedKeys = append(nodeB.trustedKeys, TrustedKey{Key: rootPub, ReceivedAt: time.Now()})+ nodeB.keysMu.Unlock()++ if err := nodeB.Host.Connect(ctx, peer.AddrInfo{ID: nodeA.Host.ID(), Addrs: nodeA.Host.Addrs()}); err != nil {+ t.Fatal(err)+ }++ const expectedBody = `{"status":"floored"}`+ dummyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(expectedBody))+ }))+ defer dummyServer.Close()++ serviceInfo := &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_MCP, Name: "dummy-tool"}+ targetURL, _ := url.Parse(dummyServer.URL)+ nodeA.services.insertService(&testService{+ info: serviceInfo,+ handler: httputil.NewSingleHostReverseProxy(targetURL),+ })++ proxyServer := httptest.NewServer(createEgressProxy(nodeB))+ defer proxyServer.Close()+ // The caller stays silent: no X-Sam-Required-Labels anywhere.+ rawURL := fmt.Sprintf("%s/sam/%s/mcp/dummy-tool/api/v1/test", proxyServer.URL, nodeA.Host.ID())++ get := func() *http.Response {+ t.Helper()+ resp, err := http.Get(rawURL)+ if err != nil {+ t.Fatal(err)+ }+ return resp+ }++ // nodeA attests the whole floor: egress proceeds.+ nodeB.nodeConfig = &NodeConfigComplete{EgressRequireLabels: map[string]string{"jurisdiction": "eu"}}+ var resp *http.Response+ for i := 0; i < 3; i++ {+ resp = get()+ if resp.StatusCode == http.StatusOK {+ break+ }+ _ = resp.Body.Close()+ time.Sleep(time.Second)+ }+ body, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err != nil {+ t.Fatal(err)+ }+ if resp.StatusCode != http.StatusOK || string(body) != expectedBody {+ t.Fatalf("egress inside the floor must pass: status %d, body %q", resp.StatusCode, body)+ }++ // One pair short of the floor: refused at the chokepoint, nothing forwarded.+ nodeB.nodeConfig = &NodeConfigComplete{EgressRequireLabels: map[string]string{"jurisdiction": "eu", "compliance": "gdpr"}}+ resp = get()+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusForbidden {+ t.Fatalf("egress outside the floor must be 403 at the chokepoint, got %d", resp.StatusCode)+ }+}diff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex c2429858..2a0e2e3b 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -711,6 +711,29 @@ func createEgressProxy(node *SamNode) http.Handler {return}+ // The operator's egress floor (egress.require_labels) holds at this+ // chokepoint whatever the surface, so an agent that skips the facade+ // and dials /sam/<peer>/... raw is gated the same way. required is nil:+ // any caller requirement was already enforced by the surface that+ // parsed it; the floor is what a silent caller cannot waive.+ if floor := node.egressFloor(); len(floor) > 0 {+ route, ok := parseEgressRoute(r.URL.Path)+ if !ok {+ http.Error(w, "Forbidden: egress floor in force and request names no peer", http.StatusForbidden)+ return+ }+ pid, err := peer.Decode(route.peerID)+ if err != nil {+ http.Error(w, "Bad Request: invalid peer ID", http.StatusBadRequest)+ return+ }+ if err := node.VerifyPeerLabels(r.Context(), pid, nil); err != nil {+ logger.Warnf("[Egress] floor gate refused egress to %s: %v", route.peerID, err)+ http.Error(w, "Forbidden: provider does not attest the egress floor", http.StatusForbidden)+ return+ }+ }+r.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuitBytes))// Forwarded, not stripped: the agent claim is what lets the peer at the