Skip to content

Agent Mesh

node: gate raw a2a egress with labels and rewrite agent cards for mesh use

Tomas Tormo3e9c515b6178
diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.go
index 5bf8af53..f5429b5a 100644
--- a/internal/node/a2a_service.go
+++ b/internal/node/a2a_service.go
@@ -15,10 +15,17 @@
package node
import (
+ "bytes"
"context"
+ "encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
"github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/peer"
)
// A2AService proxies Agent2Agent (A2A) JSON-RPC/REST traffic to a local
@@ -41,3 +48,109 @@ func (s *A2AService) Init(ctx context.Context) error {
}
return nil
}
+
+// a2aCardBaseURL is the context key carrying the caller-facing mesh base URL
+// of an agent-card fetch, set by a2aEgressHook and consumed by the rewrite.
+type a2aCardBaseURL struct{}
+
+// a2aEgressHook runs the caller-side A2A checks on a raw egress request:
+// the fail-closed labels gate and tagging agent-card fetches for rewrite.
+// On refusal it writes the HTTP error itself and returns ok=false.
+func a2aEgressHook(node *SamNode, w http.ResponseWriter, r *http.Request) (*http.Request, bool) {
+ parts := strings.SplitN(r.URL.Path, "/", 6)
+ if len(parts) < 5 || parts[3] != api.ServiceTypeStringA2A {
+ return r, true
+ }
+ if labelsHeader := r.Header.Get(api.HeaderSamRequiredLabels); labelsHeader != "" {
+ r.Header.Del(api.HeaderSamRequiredLabels)
+ required, err := parseRequiredLabels(labelsHeader)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("Invalid %s header: %v", api.HeaderSamRequiredLabels, err), http.StatusBadRequest)
+ return r, false
+ }
+ pid, err := peer.Decode(parts[2])
+ if err != nil {
+ http.Error(w, "Invalid peer ID", http.StatusBadRequest)
+ return r, false
+ }
+ if err := node.VerifyPeerLabels(r.Context(), pid, required); err != nil {
+ logger.Warnf("[A2A] label gate refused egress to %s: %v", parts[2], err)
+ http.Error(w, "Required labels not attested by provider", http.StatusForbidden)
+ return r, false
+ }
+ }
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/.well-known/agent-card.json") {
+ base := fmt.Sprintf("http://%s/sam/%s/%s/%s", r.Host, parts[2], parts[3], parts[4])
+ r = r.WithContext(context.WithValue(r.Context(), a2aCardBaseURL{}, base))
+ }
+ return r, true
+}
+
+// rewriteA2AAgentCard makes a proxied agent card usable by stock A2A clients:
+// interface URLs point back at the mesh path, transports the mesh cannot
+// carry are dropped, and streaming is advertised off until verified.
+func rewriteA2AAgentCard(resp *http.Response) error {
+ base, ok := resp.Request.Context().Value(a2aCardBaseURL{}).(string)
+ if !ok || resp.StatusCode != http.StatusOK {
+ return nil
+ }
+ if resp.Header.Get("Content-Encoding") != "" {
+ logger.Warnf("[A2A] agent card response is content-encoded; skipping rewrite")
+ return nil
+ }
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return err
+ }
+ var card map[string]any
+ if err := json.Unmarshal(body, &card); err != nil {
+ return fmt.Errorf("agent card is not valid JSON: %w", err)
+ }
+ if _, ok := card["url"]; ok {
+ card["url"] = base
+ }
+ if pt, ok := card["preferredTransport"].(string); ok && !a2aTransportOverHTTP(pt) {
+ card["preferredTransport"] = "JSONRPC"
+ }
+ for _, key := range []string{"additionalInterfaces", "supportedInterfaces"} {
+ ifaces, ok := card[key].([]any)
+ if !ok {
+ continue
+ }
+ kept := make([]any, 0, len(ifaces))
+ for _, entry := range ifaces {
+ iface, ok := entry.(map[string]any)
+ if !ok {
+ continue
+ }
+ transport, _ := iface["transport"].(string)
+ if transport == "" {
+ transport, _ = iface["protocolBinding"].(string)
+ }
+ if !a2aTransportOverHTTP(transport) {
+ continue
+ }
+ iface["url"] = base
+ kept = append(kept, iface)
+ }
+ card[key] = kept
+ }
+ if caps, ok := card["capabilities"].(map[string]any); ok {
+ caps["streaming"] = false
+ }
+ out, err := json.Marshal(card)
+ if err != nil {
+ return err
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(out))
+ resp.ContentLength = int64(len(out))
+ resp.Header.Set("Content-Length", strconv.Itoa(len(out)))
+ return nil
+}
+
+// a2aTransportOverHTTP reports whether an A2A transport can traverse the
+// mesh's HTTP-over-libp2p path; gRPC needs its own end-to-end connection.
+func a2aTransportOverHTTP(transport string) bool {
+ return transport == "JSONRPC" || transport == "HTTP+JSON"
+}
diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.go
index 0a0611f6..2418b3d9 100644
--- a/internal/node/a2a_service_test.go
+++ b/internal/node/a2a_service_test.go
@@ -16,6 +16,11 @@ package node
import (
"context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"github.com/google/sam/api"
@@ -57,3 +62,113 @@ func TestNewServiceFromRequestA2A(t *testing.T) {
t.Fatalf("factory returned %T, want *A2AService", svc)
}
}
+
+func TestA2AEgressHookNonA2APassthrough(t *testing.T) {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/mcp/svc/foo", nil)
+ req.Header.Set(api.HeaderSamRequiredLabels, "region=eu")
+ _, ok := a2aEgressHook(nil, rec, req)
+ if !ok {
+ t.Fatal("non-a2a path must pass through")
+ }
+ if req.Header.Get(api.HeaderSamRequiredLabels) == "" {
+ t.Fatal("labels header on non-a2a path must be left untouched")
+ }
+}
+
+func TestA2AEgressHookMalformedLabels(t *testing.T) {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/sam/12D3KooWpeer/a2a/agent/", nil)
+ req.Header.Set(api.HeaderSamRequiredLabels, "not-a-label")
+ _, ok := a2aEgressHook(nil, rec, req)
+ if ok {
+ t.Fatal("malformed labels must be refused")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", rec.Code)
+ }
+}
+
+func TestA2AEgressHookTagsCardFetch(t *testing.T) {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)
+ req.Host = "127.0.0.1:8080"
+ r2, ok := a2aEgressHook(nil, rec, req)
+ if !ok {
+ t.Fatal("card fetch must pass through")
+ }
+ base, _ := r2.Context().Value(a2aCardBaseURL{}).(string)
+ want := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"
+ if base != want {
+ t.Fatalf("card base = %q, want %q", base, want)
+ }
+}
+
+func TestRewriteA2AAgentCard(t *testing.T) {
+ card := `{
+ "name": "T",
+ "url": "http://localhost:9999",
+ "preferredTransport": "GRPC",
+ "additionalInterfaces": [
+ {"url": "http://localhost:9999", "transport": "JSONRPC"},
+ {"url": "localhost:50051", "transport": "GRPC"}
+ ],
+ "supportedInterfaces": [
+ {"url": "http://localhost:9999", "protocolBinding": "JSONRPC"},
+ {"url": "localhost:50051", "protocolBinding": "GRPC"}
+ ],
+ "capabilities": {"streaming": true}
+ }`
+ base := "http://127.0.0.1:8080/sam/12D3KooWpeer/a2a/agent"
+ req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/a2a/agent/.well-known/agent-card.json", nil)
+ req = req.WithContext(context.WithValue(req.Context(), a2aCardBaseURL{}, base))
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{},
+ Body: io.NopCloser(strings.NewReader(card)),
+ Request: req,
+ }
+ if err := rewriteA2AAgentCard(resp); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ var got map[string]any
+ if err := json.Unmarshal(body, &got); err != nil {
+ t.Fatalf("rewritten card is not JSON: %v", err)
+ }
+ if got["url"] != base {
+ t.Errorf("url = %v, want %s", got["url"], base)
+ }
+ if got["preferredTransport"] != "JSONRPC" {
+ t.Errorf("preferredTransport = %v, want JSONRPC", got["preferredTransport"])
+ }
+ for _, key := range []string{"additionalInterfaces", "supportedInterfaces"} {
+ ifaces, _ := got[key].([]any)
+ if len(ifaces) != 1 {
+ t.Fatalf("%s: want 1 HTTP interface after dropping gRPC, got %v", key, got[key])
+ }
+ if u := ifaces[0].(map[string]any)["url"]; u != base {
+ t.Errorf("%s url = %v, want %s", key, u, base)
+ }
+ }
+ if s := got["capabilities"].(map[string]any)["streaming"]; s != false {
+ t.Errorf("streaming = %v, want false", s)
+ }
+}
+
+func TestRewriteA2AAgentCardNoopWithoutTag(t *testing.T) {
+ orig := `{"name":"T","url":"http://localhost:9999"}`
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{},
+ Body: io.NopCloser(strings.NewReader(orig)),
+ Request: httptest.NewRequest("GET", "/anything", nil),
+ }
+ if err := rewriteA2AAgentCard(resp); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ if string(body) != orig {
+ t.Fatalf("untagged response was modified: %s", body)
+ }
+}
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index c9d264bb..811dab74 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -692,7 +692,8 @@ func createEgressProxy(node *SamNode) http.Handler {
req.URL.RawPath = ""
logger.Debugf("[Proxy] Rewriting URL to libp2p://%s%s", req.URL.Host, req.URL.Path)
},
- Transport: transport,
+ Transport: transport,
+ ModifyResponse: rewriteA2AAgentCard,
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -708,6 +709,11 @@ func createEgressProxy(node *SamNode) http.Handler {
return
}
+ r, ok := a2aEgressHook(node, w, r)
+ if !ok {
+ return
+ }
+
r.Header.Set(api.HeaderSamBiscuit, base64.StdEncoding.EncodeToString(biscuitBytes))
// Forwarded, not stripped: the agent claim is what lets the peer at the