Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: an agent serves only itself, over A2A, contracted statically
Antonio Ojeaae97f2abffed
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex 66ad0d7c..9b3d4ccc 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -51,6 +51,7 @@ func main() {logLevel stringagentIngressSocket string+ ingressListen string)rootCmd := &cobra.Command{@@ -78,12 +79,12 @@ func main() {if err := verifyBundleCredential(cmd.Context(), bundlePath, issuer, audience, insecure); err != nil {return err}- ingress, err := resolveIngress(bundlePath, sidecarSocket, agentIngressSocket)+ ingress, err := resolveIngress(bundlePath, ingressListen, agentIngressSocket)if err != nil {return err}if ingress != nil {- defer ingress.Close(context.WithoutCancel(cmd.Context()))+ defer ingress.Close()}listener, err := sambox.ListenSandboxSocket(sandboxSocket)@@ -107,7 +108,6 @@ func main() {Router: &sambox.Router{Egress: egress},SidecarSocket: sidecarSocket,AgentID: agentID,- Ingress: ingress,},}@@ -136,6 +136,7 @@ func main() {runCmd.Flags().BoolVar(&insecure, "insecure-unverified-bundle", false, "Trust the bundle's declared identity without a credential to back it, letting whoever can write the file decide which agent this sandbox is")runCmd.Flags().StringVar(&metricsAddr, "metrics-addr", "", "Serve unauthenticated Prometheus metrics on this address, e.g. 127.0.0.1:9600; off by default")runCmd.Flags().StringVar(&agentIngressSocket, "agent-ingress-socket", "", "Path to the sandbox's reverse channel, served by nano-init --ingress-socket; required to reach an agent that serves the mesh, because an isolated sandbox cannot be dialled")+ runCmd.Flags().StringVar(&ingressListen, "ingress-listen", "127.0.0.1:7080", "Stable address the gateway's mesh-facing ingress listens on; the node's configuration declares services with this address as their backend")runCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")for _, required := range []string{"socket", "sidecar-socket"} {if err := runCmd.MarkFlagRequired(required); err != nil {@@ -222,7 +223,7 @@ func verifyBundleCredential(ctx context.Context, bundlePath, issuer, audience st// resolveIngress prepares what the agent is permitted to serve. Nil means// nothing, which is the case for a sandbox that only calls out.-func resolveIngress(bundlePath, sidecarSocket, agentIngressSocket string) (*sambox.IngressManager, error) {+func resolveIngress(bundlePath, ingressListen, agentIngressSocket string) (*sambox.IngressManager, error) {if bundlePath == "" {return nil, nil}@@ -230,7 +231,7 @@ func resolveIngress(bundlePath, sidecarSocket, agentIngressSocket string) (*sambif err != nil {return nil, err}- if len(bundle.Ingress) == 0 {+ if bundle.Serves == nil {return nil, nil}if agentIngressSocket == "" {@@ -238,15 +239,23 @@ func resolveIngress(bundlePath, sidecarSocket, agentIngressSocket string) (*samb// only address left is one in this process's network namespace, which// is the pod's: the node's API and every sidecar are on that loopback,// and the port would be the agent's to choose.- return nil, fmt.Errorf("agent %s may serve %d mesh service(s), but --agent-ingress-socket is not set. "++ return nil, fmt.Errorf("agent %s serves a2a://%s, but --agent-ingress-socket is not set. "+"Point it at the path nano-init --ingress-socket serves; without it there is no way into the "+"sandbox, and delivering to this process's own network namespace would reach the gateway's "+- "neighbours instead of the agent", bundle.Agent.ID, len(bundle.Ingress))- }- logger.Infof("Agent %s may serve %d mesh service(s) once it announces them", bundle.Agent.ID, len(bundle.Ingress))- return &sambox.IngressManager{- SidecarSocket: sidecarSocket,- Allowed: bundle.Ingress,- AgentSocket: agentIngressSocket,- }, nil+ "neighbours instead of the agent", bundle.Agent.ID, bundle.Serves.Name)+ }+ manager := &sambox.IngressManager{+ ListenAddr: ingressListen,+ Serves: *bundle.Serves,+ AgentSocket: agentIngressSocket,+ }+ // The routes are the bundle's contract and exist from startup; the node's+ // config declares services backed by this address, and its backend probe+ // fails until the agent actually binds its contracted port.+ addr, err := manager.Start()+ if err != nil {+ return nil, fmt.Errorf("serving ingress on %s: %w", ingressListen, err)+ }+ logger.Infof("Agent %s serves a2a://%s; ingress at http://%s", bundle.Agent.ID, bundle.Serves.Name, addr)+ return manager, nil}diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.goindex fae5af62..5990098c 100644--- a/internal/node/a2a_service.go+++ b/internal/node/a2a_service.go@@ -56,6 +56,36 @@ func (s *A2AService) Init(ctx context.Context) error {return nil}+// Probe asks the backend for its agent card, which is the protocol's own+// definition of ready: an A2A agent is up exactly when it serves its card.+// Gating advertisement on it lets a service be declared before its agent is+// (a sandbox that has not bound its port yet probes as down and stays out of+// discovery). Deliberately not cached, like the MCP probe.+func (s *A2AService) Probe(ctx context.Context) error {+ target, ok := s.backend.(*api.RegisterServiceRequest_TargetUrl)+ if !ok {+ return fmt.Errorf("a2a service %q has no URL backend to probe", s.info.GetName())+ }+ cardURL := strings.TrimSuffix(target.TargetUrl, "/") + "/.well-known/agent-card.json"+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, cardURL, nil)+ if err != nil {+ return err+ }+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return fmt.Errorf("fetch agent card of %q: %w", s.info.GetName(), err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("agent card of %q: %s", s.info.GetName(), resp.Status)+ }+ var card map[string]any+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&card); err != nil {+ return fmt.Errorf("agent card of %q is not JSON: %w", s.info.GetName(), err)+ }+ return nil+}+// a2aEgressGate runs the caller-side A2A checks on a raw egress request:// the fail-closed labels gate. On refusal it writes the HTTP error itself// and returns ok=false.diff --git a/internal/node/a2a_service_test.go b/internal/node/a2a_service_test.goindex d13e3db9..45466e40 100644--- a/internal/node/a2a_service_test.go+++ b/internal/node/a2a_service_test.go@@ -65,6 +65,57 @@ func TestNewServiceFromRequestA2A(t *testing.T) {}}+// TestA2AServiceProbe pins advertisement gating on the agent card: an a2a+// service may be declared before its agent is up (a sandbox that has not+// bound its port), and must probe as down until the card is served.+func TestA2AServiceProbe(t *testing.T) {+ newSvc := func(target string) *A2AService {+ return &A2AService{baseService: baseService{+ info: &api.ServiceInfo{Type: api.ServiceType_SERVICE_TYPE_A2A, Name: "agent"},+ backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: target},+ }}+ }++ t.Run("card served means ready", func(t *testing.T) {+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/.well-known/agent-card.json" {+ http.NotFound(w, r)+ return+ }+ _, _ = w.Write([]byte(`{"name":"agent","version":"1.0.0"}`))+ }))+ defer backend.Close()+ if err := newSvc(backend.URL).Probe(context.Background()); err != nil {+ t.Fatalf("Probe with a served card: %v", err)+ }+ })++ t.Run("no card means not ready", func(t *testing.T) {+ backend := httptest.NewServer(http.NotFoundHandler())+ defer backend.Close()+ if err := newSvc(backend.URL).Probe(context.Background()); err == nil {+ t.Fatal("Probe must fail while the card is not served")+ }+ })++ t.Run("dead backend means not ready", func(t *testing.T) {+ // A declared sandbox service whose agent never bound its port.+ if err := newSvc("http://127.0.0.1:1").Probe(context.Background()); err == nil {+ t.Fatal("Probe must fail when nothing listens")+ }+ })++ t.Run("non-json card means not ready", func(t *testing.T) {+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte("<html>login page</html>"))+ }))+ defer backend.Close()+ if err := newSvc(backend.URL).Probe(context.Background()); err == nil {+ t.Fatal("Probe must fail on a non-JSON card")+ }+ })+}+func TestA2AEgressHookNonA2APassthrough(t *testing.T) {rec := httptest.NewRecorder()req := httptest.NewRequest("GET", "/sam/12D3KooWpeer/mcp/svc/foo", nil)diff --git a/internal/sambox/bundle.go b/internal/sambox/bundle.goindex 9faa2b82..502637c6 100644--- a/internal/sambox/bundle.go+++ b/internal/sambox/bundle.go@@ -39,11 +39,14 @@ type AgentBundle struct {Agent AgentIdentity `yaml:"agent"`Egress BundleEgress `yaml:"egress"`- // Ingress is what this agent is permitted to serve, not what it is- // currently serving. The agent says when it is ready, and on which port,- // through the gateway's ingress endpoint; the platform decides only which- // names it may claim.- Ingress []BundleIngress `yaml:"ingress"`+ // Serves is the one mesh service this agent provides: itself, as an A2A+ // agent. The name is the platform's grant and the port is its contract+ // with the agent (like $PORT on a serverless runtime); the agent binds it+ // when ready, and everything else about serving -- capabilities, skills,+ // negotiation -- lives on the agent's own card, inside the A2A protocol.+ // Tools (mcp://) and models (inference://) are operator workloads declared+ // in a node's configuration, never agent ingress.+ Serves *BundleServes `yaml:"serves,omitempty"`// egress is the compiled form of Egress.Allow, built during loading so a// malformed allowlist fails at startup rather than on an agent's first@@ -51,10 +54,11 @@ type AgentBundle struct {egress *EgressPolicy}-// BundleIngress is one mesh service the agent may advertise.-type BundleIngress struct {+// BundleServes contracts the agent's own a2a service: its mesh name and the+// sandbox port it must bind.+type BundleServes struct {Name string `yaml:"name"`- Type string `yaml:"type"`+ Port int `yaml:"port"`}// AgentIdentity names the principal the gateway asserts for this sandbox.@@ -106,12 +110,12 @@ func LoadAgentBundle(path string) (*AgentBundle, error) {}bundle.egress = policy- for i, ingress := range bundle.Ingress {- if _, err := api.ParseServiceType(ingress.Type); err != nil {- return nil, fmt.Errorf("agent bundle %s: ingress %d: %w", path, i, err)+ if bundle.Serves != nil {+ if err := api.ValidateServiceFormat("a2a://" + bundle.Serves.Name); err != nil {+ return nil, fmt.Errorf("agent bundle %s: serves: %w", path, err)}- if err := api.ValidateServiceFormat(ingress.Type + "://" + ingress.Name); err != nil {- return nil, fmt.Errorf("agent bundle %s: ingress %d: %w", path, i, err)+ if bundle.Serves.Port < 1 || bundle.Serves.Port > 65535 {+ return nil, fmt.Errorf("agent bundle %s: serves: port %d is not a port", path, bundle.Serves.Port)}}diff --git a/internal/sambox/dial.go b/internal/sambox/dial.goindex e5516572..62188fe3 100644--- a/internal/sambox/dial.go+++ b/internal/sambox/dial.go@@ -46,11 +46,6 @@ type AgentDialer struct {// unidentified, and mesh policy sees only the node it came through.AgentID string- // Ingress serves what the agent is permitted to advertise. Nil means the- // agent may serve nothing, which is the case for a sandbox that only calls- // out.- Ingress *IngressManager-// DialContext opens external destinations. Nil uses a plain net.Dialer;// tests and future egress interception replace it.DialContext func(ctx context.Context, network, address string) (net.Conn, error)diff --git a/internal/sambox/entrypoint.go b/internal/sambox/entrypoint.goindex 655a806c..fef3a73f 100644--- a/internal/sambox/entrypoint.go+++ b/internal/sambox/entrypoint.go@@ -43,11 +43,9 @@ import (// Discovery is not on the list even though agents need it: it is already// available through MCP as find_remote_tools and discover_remote_services, so// exposing /sam/service/discover as well would widen the surface without adding-// a capability. Registration is not on the list at all — an agent that could-// register would advertise itself into the mesh under the node's identity, and-// choose the target_url the mesh then routes to. What an agent may serve is-// declared by the platform in its bundle, and announced through the gateway's-// own /ingress endpoint, which never reaches the node.+// a capability. Serving is not on the list at all — what an agent serves is+// declared by the platform in its bundle and by the operator in the node's+// configuration, and the agent's only part is binding its contracted port.func agentMayReach(path string) bool {switch path {case "/v1/models", "/v1/chat/completions", "/v1/completions":@@ -56,9 +54,6 @@ func agentMayReach(path string) bool {return path == "/mcp" || strings.HasPrefix(path, "/mcp/")}-// ingressPath is served by the gateway itself rather than proxied.-const ingressPath = "/ingress"-// dialMeshEntrypoint returns a connection serving the agent-facing surface.func (d *AgentDialer) dialMeshEntrypoint() (net.Conn, error) {if d.SidecarSocket == "" {@@ -78,22 +73,9 @@ func (d *AgentDialer) entrypointHandler() http.Handler {Transport: d.sidecarTransport(),}- var ingress http.Handler- if d.Ingress != nil {- ingress = d.Ingress.Handler()- }-return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path == ingressPath {- if ingress == nil {- http.Error(w, "this agent was granted nothing to serve", http.StatusForbidden)- return- }- ingress.ServeHTTP(w, r)- return- }if !agentMayReach(r.URL.Path) {- http.Error(w, "the mesh entrypoint serves /v1, /mcp and /ingress only", http.StatusForbidden)+ http.Error(w, "the mesh entrypoint serves /v1 and /mcp only", http.StatusForbidden)return}proxy.ServeHTTP(w, r)diff --git a/internal/sambox/ingress.go b/internal/sambox/ingress.goindex 045b2ee3..46f9c86e 100644--- a/internal/sambox/ingress.go+++ b/internal/sambox/ingress.go@@ -16,9 +16,7 @@ package samboximport ("bufio"- "bytes""context"- "encoding/json""fmt""io""log"@@ -30,40 +28,35 @@ import ("strings""sync""time"-- "google.golang.org/protobuf/encoding/protojson"-- "github.com/google/sam/api")-// An agent that serves is still not allowed to talk to the node. Registering a-// service means naming a target_url the mesh will route to and a name it will-// route under, and an agent holding either would be able to point the mesh at-// anything and to advertise itself as somebody else's service. So the gateway-// offers the capability without the API: the agent says it is ready, and the-// gateway does the registering.+// An agent that serves never says so to anyone. The node's exposed services+// are declared in the node's own configuration, where the operator names this+// gateway's ingress address as the backend; the bundle contracts which names+// the agent serves and on which sandbox port (like $PORT on a serverless+// runtime). Nothing at runtime can add a name to the mesh, and there is no+// agent-facing surface at all: the agent just binds its contracted port.//-// Two things make that safe. The target_url is never the agent's to give: it is-// always this gateway's own ingress address. And the name must be one the-// platform already granted in the bundle, so claiming a name nobody granted is-// not expressible rather than merely refused.-//-// Splitting it this way is also what makes the timing work. The platform knows-// what an agent may serve; only the agent knows when it is listening. A route-// declared up front advertises a service that is not up yet, and the mesh-// routes to it and fails.--// maxIngressBody bounds the declaration an agent posts.-const maxIngressBody = 4 << 10--// IngressManager registers what an agent serves, and forwards what arrives.+// Readiness is implicit. Until the agent listens, forwarding fails at the+// sandbox's reverse channel, so the node's backend probe fails and the name+// is withheld from discovery; when the agent binds the port everything+// converges, and when the sandbox goes away the probe fails again. Dynamic+// agent behaviour beyond that -- capabilities, negotiation, reconfiguration --+// belongs to the protocol served over the name (A2A, MCP), not to the mesh.++// IngressManager forwards what the mesh delivers to the ports the platform+// contracted the agent to serve.type IngressManager struct {- // SidecarSocket is the node's API socket, where registrations are made.- SidecarSocket string+ // ListenAddr is where this gateway's ingress listens, e.g.+ // "127.0.0.1:7080". It must be stable: the node's configuration names it+ // as the declared services' backend. Empty picks an ephemeral port,+ // which only tests can meaningfully consume via Addr.+ ListenAddr string- // Allowed is what the bundle permits this agent to serve. Empty means the- // agent may serve nothing.- Allowed []BundleIngress+ // Serves is the bundle's contract: the agent's a2a service name and the+ // sandbox port it binds. An agent serves at most itself; tools and models+ // are operator workloads, not agent ingress.+ Serves BundleServes// AgentSocket is the sandbox's reverse channel: a Unix socket nano-init// listens on from inside the sandbox. It is how an isolated agent is@@ -86,95 +79,28 @@ type IngressManager struct {routes map[string]int // service name -> port inside the sandbox}-// ingressDeclaration is what an agent posts to say it is ready.-type ingressDeclaration struct {- Name string `json:"name"`- Type string `json:"type"`- Port int `json:"port"`-}--// Handler serves the gateway's own ingress endpoint. It is never forwarded to-// the node.-func (m *IngressManager) Handler() http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodPost {- http.Error(w, "POST a declaration to announce a service", http.StatusMethodNotAllowed)- return- }-- var decl ingressDeclaration- if err := json.NewDecoder(io.LimitReader(r.Body, maxIngressBody)).Decode(&decl); err != nil {- http.Error(w, "expected {\"name\":..., \"type\":..., \"port\":...}", http.StatusBadRequest)- return- }-- if err := m.Announce(r.Context(), decl); err != nil {- // The agent is told what it did wrong, which is always something it- // declared, never anything about the node behind the gateway.- http.Error(w, err.Error(), http.StatusForbidden)- return- }- w.WriteHeader(http.StatusNoContent)- })-}--// Announce validates a declaration, starts routing to the agent, and registers-// the service with the node.-func (m *IngressManager) Announce(ctx context.Context, decl ingressDeclaration) error {- if decl.Port < 1 || decl.Port > 65535 {- return fmt.Errorf("port %d is not a port", decl.Port)- }- if !m.permits(decl) {- return fmt.Errorf("this agent was not granted %s://%s", decl.Type, decl.Name)- }+// Start validates that the sandbox can be reached, builds the routes the+// bundle contracts, and serves the ingress. It returns the bound address,+// which is what the node's configuration must name as the services' backend.+func (m *IngressManager) Start() (string, error) {if err := m.reachable(); err != nil {- return err- }-- addr, err := m.ensureListening()- if err != nil {- return fmt.Errorf("serving ingress: %w", err)- }-- m.mu.Lock()- m.routes[decl.Name] = decl.Port- m.mu.Unlock()-- // The agent named a service; the gateway names where the mesh reaches it.- target := "http://" + addr + "/" + decl.Name- if err := m.register(ctx, decl, target); err != nil {- m.mu.Lock()- delete(m.routes, decl.Name)- m.mu.Unlock()- return fmt.Errorf("registering %s://%s: %w", decl.Type, decl.Name, err)- }- log.Printf("sambox: serving %s://%s from the sandbox's port %d", decl.Type, decl.Name, decl.Port)- return nil-}--func (m *IngressManager) permits(decl ingressDeclaration) bool {- for _, allowed := range m.Allowed {- if allowed.Name == decl.Name && allowed.Type == decl.Type {- return true- }+ return "", err}- return false-}-// ensureListening starts the ingress listener on first use, so an agent that-// serves nothing costs nothing.-func (m *IngressManager) ensureListening() (string, error) {m.mu.Lock()defer m.mu.Unlock()if m.listener != nil {return m.listener.Addr().String(), nil}- if m.routes == nil {- m.routes = make(map[string]int)- }+ m.routes = map[string]int{m.Serves.Name: m.Serves.Port}+ log.Printf("sambox: serving a2a://%s from the sandbox's port %d", m.Serves.Name, m.Serves.Port)- listener, err := net.Listen("tcp", "127.0.0.1:0")+ addr := m.ListenAddr+ if addr == "" {+ addr = "127.0.0.1:0"+ }+ listener, err := net.Listen("tcp", addr)if err != nil {return "", err}@@ -300,87 +226,18 @@ func dialSandbox(ctx context.Context, socket, port string) (net.Conn, error) {return conn, nil}-// register tells the node to advertise the service, with a target only the-// gateway could have chosen.-func (m *IngressManager) register(ctx context.Context, decl ingressDeclaration, target string) error {- serviceType, err := api.ParseServiceType(decl.Type)- if err != nil {- return err- }-- body, err := protojson.Marshal(&api.RegisterServiceRequest{- Service: &api.ServiceInfo{- Type: serviceType,- Name: decl.Name,- Description: "served by an agent behind this gateway",- },- Backend: &api.RegisterServiceRequest_TargetUrl{TargetUrl: target},- })- if err != nil {- return err- }-- req, err := http.NewRequestWithContext(ctx, http.MethodPost,- "http://"+sidecarHost+"/sam/service/register", bytes.NewReader(body))- if err != nil {- return err- }- req.Header.Set("Content-Type", "application/json")-- resp, err := (&http.Client{Transport: sidecarTransport(m.SidecarSocket)}).Do(req)- if err != nil {- return err- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode != http.StatusOK {- detail, _ := io.ReadAll(io.LimitReader(resp.Body, maxIngressBody))- return fmt.Errorf("the node refused it: %s: %s", resp.Status, bytes.TrimSpace(detail))- }- return nil-}--// Close stops serving and withdraws everything this gateway advertised, so a-// detached sandbox stops being routed to instead of lingering in discovery.-func (m *IngressManager) Close(ctx context.Context) {+// Close stops serving, so a detached sandbox stops being routed to: the+// node's backend probe starts failing and withholds the name from discovery.+func (m *IngressManager) Close() {m.mu.Lock()listener := m.listenerm.listener = nil- routes := m.routesm.routes = nilm.mu.Unlock()if listener != nil {_ = listener.Close()}- for name := range routes {- if err := m.unregister(ctx, name); err != nil {- log.Printf("sambox: withdrawing %s: %v", name, err)- }- }-}--func (m *IngressManager) unregister(ctx context.Context, name string) error {- body, err := json.Marshal(map[string]string{"name": name})- if err != nil {- return err- }- req, err := http.NewRequestWithContext(ctx, http.MethodPost,- "http://"+sidecarHost+"/sam/service/unregister", bytes.NewReader(body))- if err != nil {- return err- }- req.Header.Set("Content-Type", "application/json")-- resp, err := (&http.Client{Transport: sidecarTransport(m.SidecarSocket)}).Do(req)- if err != nil {- return err- }- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("the node returned %s", resp.Status)- }- return nil}// splitServicePath separates the leading service name from the rest of the path.diff --git a/internal/sambox/ingress_test.go b/internal/sambox/ingress_test.goindex 9103d21b..674b8eb6 100644--- a/internal/sambox/ingress_test.go+++ b/internal/sambox/ingress_test.go@@ -15,216 +15,19 @@package samboximport (- "context"- "encoding/json"- "fmt""io"- "net""net/http""net/http/httptest""path/filepath"- "strconv""strings""testing"-- "google.golang.org/protobuf/encoding/protojson"-- "github.com/google/sam/api")-// registrationRecorder stands in for the node, capturing what the gateway asks-// it to advertise.-func registrationRecorder(t *testing.T, registrations chan<- *api.RegisterServiceRequest) string {- t.Helper()- return startFakeSidecar(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.URL.Path {- case "/sam/service/register":- body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))- if err != nil {- t.Errorf("reading registration: %v", err)- return- }- var req api.RegisterServiceRequest- if err := protojson.Unmarshal(body, &req); err != nil {- t.Errorf("unmarshalling registration: %v", err)- http.Error(w, "bad request", http.StatusBadRequest)- return- }- registrations <- &req- case "/sam/service/unregister":- // Accepted; the withdrawal path is covered by its own test.- default:- http.Error(w, "unexpected", http.StatusNotFound)- }- }))-}--func announce(t *testing.T, handler http.Handler, body string) *httptest.ResponseRecorder {- t.Helper()- req := httptest.NewRequest(http.MethodPost, ingressPath, strings.NewReader(body))- rec := httptest.NewRecorder()- handler.ServeHTTP(rec, req)- return rec-}--// TestIngressRegistersWhatTheAgentAnnounces covers the shape of the capability:-// the agent supplies liveness and a port, and the gateway supplies everything-// that would be dangerous for the agent to choose.-func TestIngressRegistersWhatTheAgentAnnounces(t *testing.T) {- registrations := make(chan *api.RegisterServiceRequest, 1)- socket := registrationRecorder(t, registrations)-- manager := &IngressManager{- SidecarSocket: socket,- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- // Registration never dials it, but a manager with no way into the- // sandbox now refuses to register at all.- AgentSocket: filepath.Join(t.TempDir(), "ingress.sock"),- }- t.Cleanup(func() { manager.Close(context.Background()) })-- rec := announce(t, manager.Handler(), `{"name":"code-reviewer","type":"mcp","port":8080}`)- if rec.Code != http.StatusNoContent {- t.Fatalf("status = %d, want 204: %s", rec.Code, rec.Body)- }-- got := <-registrations- if got.GetService().GetName() != "code-reviewer" {- t.Errorf("registered name = %q", got.GetService().GetName())- }- if got.GetService().GetType() != api.ServiceType_SERVICE_TYPE_MCP {- t.Errorf("registered type = %v", got.GetService().GetType())- }- // The target is the gateway's own address, never anything the agent said.- if target := got.GetTargetUrl(); !strings.HasPrefix(target, "http://127.0.0.1:") ||- !strings.HasSuffix(target, "/code-reviewer") {- t.Errorf("target_url = %q, want this gateway's own ingress address", target)- }-}--// TestIngressRefusesNamesTheAgentWasNotGranted is the property that keeps an-// agent from advertising itself as somebody else's service.-func TestIngressRefusesNamesTheAgentWasNotGranted(t *testing.T) {- registrations := make(chan *api.RegisterServiceRequest, 1)- socket := registrationRecorder(t, registrations)-- manager := &IngressManager{- SidecarSocket: socket,- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- // Registration never dials it, but a manager with no way into the- // sandbox now refuses to register at all.- AgentSocket: filepath.Join(t.TempDir(), "ingress.sock"),- }- t.Cleanup(func() { manager.Close(context.Background()) })-- tests := []struct {- name string- body string- }{- {"a name it was not granted", `{"name":"payments","type":"mcp","port":8080}`},- {"the right name with the wrong type", `{"name":"code-reviewer","type":"inference","port":8080}`},- {"a port that is not a port", `{"name":"code-reviewer","type":"mcp","port":0}`},- {"a port out of range", `{"name":"code-reviewer","type":"mcp","port":70000}`},- {"a negative port", `{"name":"code-reviewer","type":"mcp","port":-1}`},- {"nothing at all", `{}`},- {"not json", `port 8080`},- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- rec := announce(t, manager.Handler(), tc.body)- if rec.Code == http.StatusNoContent {- t.Fatalf("the gateway accepted %s", tc.body)- }- select {- case reg := <-registrations:- t.Fatalf("it registered %v anyway", reg)- default:- }- })- }-}--// TestIngressWithNoWayInRefusesRatherThanDiallingItsOwnNamespace is a-// vulnerability regression.-//-// There used to be a fallback: with no reverse channel, deliver to-// 127.0.0.1:<port>. That address is in the gateway's network namespace, which-// in a pod is the pod's -- sam-node's API, the other sidecars, every other-// boundary. The port comes from the agent. So an agent could announce a-// service whose backend was the node that vouches for it, and the mesh would-// route to it.-//-// Nothing is registered without a way into the sandbox, so there is no address-// for the mesh to reach and nothing for the agent to aim.-func TestIngressWithNoWayInRefusesRatherThanDiallingItsOwnNamespace(t *testing.T) {- // Stands in for whatever else shares the gateway's namespace: the node's- // API, a metrics endpoint, another agent's boundary.- neighbour := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- t.Error("the gateway dialled a neighbour in its own network namespace")- w.WriteHeader(http.StatusOK)- }))- defer neighbour.Close()-- _, portStr, err := net.SplitHostPort(strings.TrimPrefix(neighbour.URL, "http://"))- if err != nil {- t.Fatalf("SplitHostPort: %v", err)- }- port, err := strconv.Atoi(portStr)- if err != nil {- t.Fatalf("Atoi: %v", err)- }-- registrations := make(chan *api.RegisterServiceRequest, 1)- manager := &IngressManager{- SidecarSocket: registrationRecorder(t, registrations),- // Granted the name, so only the missing channel can refuse it.- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- }- t.Cleanup(func() { manager.Close(context.Background()) })-- body := fmt.Sprintf(`{"name":"code-reviewer","type":"mcp","port":%d}`, port)- rec := announce(t, manager.Handler(), body)- if rec.Code == http.StatusNoContent {- t.Fatalf("the agent announced a service aimed at the gateway's own namespace and was accepted")- }-- select {- case got := <-registrations:- t.Fatalf("registered %q despite having no way into the sandbox", got.GetService().GetName())- default:- }-}--func TestIngressRefusesEverythingWhenNothingWasGranted(t *testing.T) {- registrations := make(chan *api.RegisterServiceRequest, 1)- manager := &IngressManager{SidecarSocket: registrationRecorder(t, registrations)}- t.Cleanup(func() { manager.Close(context.Background()) })-- if rec := announce(t, manager.Handler(), `{"name":"anything","type":"mcp","port":8080}`); rec.Code == http.StatusNoContent {- t.Fatal("an agent granted no ingress was allowed to serve")- }-}--func TestIngressRejectsNonPost(t *testing.T) {- manager := &IngressManager{}- t.Cleanup(func() { manager.Close(context.Background()) })-- req := httptest.NewRequest(http.MethodGet, ingressPath, nil)- rec := httptest.NewRecorder()- manager.Handler().ServeHTTP(rec, req)- if rec.Code != http.StatusMethodNotAllowed {- t.Errorf("status = %d, want 405", rec.Code)- }-}--// TestIngressForwardsIntoTheSandbox covers the other direction: what the node-// delivers reaches the agent, with the service name the gateway added stripped-// back off so the agent sees the path it published.+// TestIngressForwardsIntoTheSandbox: what the node delivers reaches the agent+// on its bundle-contracted port, with the service name the operator's config+// added stripped back off so the agent sees the path it serves. The agent did+// nothing to make this happen but listen.func TestIngressForwardsIntoTheSandbox(t *testing.T) {- registrations := make(chan *api.RegisterServiceRequest, 1)- socket := registrationRecorder(t, registrations)-paths := make(chan string, 1)agent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {paths <- r.URL.Path@@ -233,20 +36,19 @@ func TestIngressForwardsIntoTheSandbox(t *testing.T) {defer agent.Close()manager := &IngressManager{- SidecarSocket: socket,- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- // The sandbox here is an ordinary server, so the port the agent- // announces is reached at the test server's address.+ Serves: BundleServes{Name: "code-reviewer", Port: 8080},+ // The sandbox here is an ordinary server, so the contracted port is+ // reached at the test server's address.AgentAddr: func(int) string { return strings.TrimPrefix(agent.URL, "http://") },}- t.Cleanup(func() { manager.Close(context.Background()) })+ t.Cleanup(manager.Close)- if rec := announce(t, manager.Handler(), `{"name":"code-reviewer","type":"mcp","port":8080}`); rec.Code != http.StatusNoContent {- t.Fatalf("announce: %d %s", rec.Code, rec.Body)+ addr, err := manager.Start()+ if err != nil {+ t.Fatalf("Start: %v", err)}- target := (<-registrations).GetTargetUrl()- resp, err := http.Get(target + "/review")+ resp, err := http.Get("http://" + addr + "/code-reviewer/review")if err != nil {t.Fatalf("Get: %v", err)}@@ -261,60 +63,68 @@ func TestIngressForwardsIntoTheSandbox(t *testing.T) {}}-func TestIngressRefusesToRouteAnUnknownService(t *testing.T) {+// TestIngressRefusesToRouteAnUngrantedName is the property that keeps an+// agent from serving under somebody else's name: only the names the bundle+// contracts have routes, and nothing at runtime can add one.+func TestIngressRefusesToRouteAnUngrantedName(t *testing.T) {manager := &IngressManager{- SidecarSocket: registrationRecorder(t, make(chan *api.RegisterServiceRequest, 1)),- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},+ Serves: BundleServes{Name: "code-reviewer", Port: 8080},+ AgentSocket: filepath.Join(t.TempDir(), "ingress.sock"),}- t.Cleanup(func() { manager.Close(context.Background()) })+ t.Cleanup(manager.Close)- addr, err := manager.ensureListening()+ addr, err := manager.Start()if err != nil {- t.Fatalf("ensureListening: %v", err)+ t.Fatalf("Start: %v", err)}- resp, err := http.Get("http://" + addr + "/never-announced/anything")+ resp, err := http.Get("http://" + addr + "/never-granted/anything")if err != nil {t.Fatalf("Get: %v", err)}defer func() { _ = resp.Body.Close() }()if resp.StatusCode == http.StatusOK {- t.Error("the gateway routed a service nobody announced")+ t.Error("the gateway routed a name the bundle never granted")}}-// TestIngressWithdrawsOnClose: a detached sandbox must stop being routed to,-// rather than lingering in discovery until something times out.-func TestIngressWithdrawsOnClose(t *testing.T) {- registrations := make(chan *api.RegisterServiceRequest, 1)- withdrawals := make(chan string, 1)+// TestIngressWithNoWayInRefusesRatherThanDiallingItsOwnNamespace is a+// vulnerability regression.+//+// There used to be a fallback: with no reverse channel, deliver to+// 127.0.0.1:<port>. That address is in the gateway's network namespace, which+// in a pod is the pod's -- sam-node's API, the other sidecars, every other+// boundary. So a bundle-contracted port would be delivered to the gateway's+// neighbours rather than the agent. Without a way into the sandbox the+// gateway must not serve at all.+func TestIngressWithNoWayInRefusesRatherThanDiallingItsOwnNamespace(t *testing.T) {+ manager := &IngressManager{+ Serves: BundleServes{Name: "code-reviewer", Port: 8080},+ }+ t.Cleanup(manager.Close)- socket := startFakeSidecar(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.URL.Path {- case "/sam/service/register":- registrations <- nil- case "/sam/service/unregister":- var body map[string]string- _ = json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body)- withdrawals <- body["name"]- }- }))+ if _, err := manager.Start(); err == nil {+ t.Fatal("the gateway agreed to serve a sandbox it has no way into")+ }+}+// TestIngressStopsAnsweringOnClose: a detached sandbox must stop being routed+// to. With the service declared on the node, that means the ingress goes away+// and the node's backend probe withholds the name from discovery.+func TestIngressStopsAnsweringOnClose(t *testing.T) {manager := &IngressManager{- SidecarSocket: socket,- Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- // Registration never dials it, but a manager with no way into the- // sandbox now refuses to register at all.+ Serves: BundleServes{Name: "code-reviewer", Port: 8080},AgentSocket: filepath.Join(t.TempDir(), "ingress.sock"),}- if rec := announce(t, manager.Handler(), `{"name":"code-reviewer","type":"mcp","port":8080}`); rec.Code != http.StatusNoContent {- t.Fatalf("announce: %d", rec.Code)+ addr, err := manager.Start()+ if err != nil {+ t.Fatalf("Start: %v", err)}- <-registrations- manager.Close(context.Background())- if got := <-withdrawals; got != "code-reviewer" {- t.Errorf("withdrew %q, want code-reviewer", got)+ manager.Close()++ if _, err := http.Get("http://" + addr + "/code-reviewer/review"); err == nil {+ t.Error("the ingress still answers after Close")}}diff --git a/tests/integration/agent_ingress_test.go b/tests/integration/agent_ingress_test.goindex bd5be0f5..26422587 100644--- a/tests/integration/agent_ingress_test.go+++ b/tests/integration/agent_ingress_test.go@@ -16,29 +16,39 @@ package integration_testimport ("context"+ "iter""net/http""net/http/httptest""os""path/filepath""strings""testing"+ "time"+ "github.com/a2aproject/a2a-go/v2/a2a"+ "github.com/a2aproject/a2a-go/v2/a2aclient"+ "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"+ "github.com/a2aproject/a2a-go/v2/a2asrv""github.com/google/sam/api""github.com/google/sam/internal/sambox")-// TestAgentIngressCUJ has an agent serve a mesh service and another node call-// it, which is the direction the boundary was not built for at first.+// TestAgentIngressCUJ has a sandboxed agent serve the mesh, which is the+// direction the boundary was not built for at first.//-// The agent announces that it is ready and on which port. It never registers-// anything: it cannot name the URL the mesh routes to, and it cannot claim a-// name the platform did not grant it in its bundle.+// An agent serves exactly one thing: itself, over A2A. The bundle contracts+// the name and the sandbox port; the node's configuration declares the+// a2a:// service with the gateway's ingress as its backend; capabilities live+// on the agent's own card. The agent here is a stock a2a-go server that never+// learns the mesh exists, and the consumer is a stock a2a-go client that+// bootstraps from the card the mesh regenerates.func TestAgentIngressCUJ(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")_, hubAddr := startMockRouter(t)homeA := t.TempDir()homeB := t.TempDir()+ apiToken := "test-token"sockDir, err := os.MkdirTemp("", "ingress")if err != nil {@@ -48,17 +58,64 @@ func TestAgentIngressCUJ(t *testing.T) {nodeSocket := filepath.Join(sockDir, "node.sock")agentSocket := filepath.Join(sockDir, "agent.sock")+ // The agent: a stock A2A server inside its sandbox, bound to its+ // contracted port. Its card names an address only it can dial, which the+ // mesh must replace on the consumer side.+ echo := a2asrv.AgentExecutorFunc(func(ctx context.Context, ec *a2asrv.ExecutorContext) iter.Seq2[a2a.Event, error] {+ return func(yield func(a2a.Event, error) bool) {+ yield(a2a.NewMessageForTask(a2a.MessageRoleAgent, ec, a2a.NewTextPart("echo from the sandbox")), nil)+ }+ })+ agentCard := &a2a.AgentCard{+ Name: "code-reviewer",+ Description: "sandboxed a2a agent",+ Version: "1.0.0",+ SupportedInterfaces: []*a2a.AgentInterface{+ {URL: "http://127.0.0.1:8080", ProtocolBinding: a2a.TransportProtocolJSONRPC, ProtocolVersion: "1.0"},+ },+ }+ agentMux := http.NewServeMux()+ agentMux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(agentCard))+ agentMux.Handle("/", a2asrv.NewJSONRPCHandler(a2asrv.NewHandler(echo)))+ agent := httptest.NewServer(agentMux)+ defer agent.Close()+ agentHost := strings.TrimPrefix(agent.URL, "http://")++ // The gateway: routes the bundle-contracted name to the contracted port,+ // from startup. Nothing announces anything.+ ingress := &sambox.IngressManager{+ Serves: sambox.BundleServes{Name: "code-reviewer", Port: 8080},+ AgentAddr: func(int) string { return agentHost },+ }+ t.Cleanup(ingress.Close)+ ingressAddr, err := ingress.Start()+ if err != nil {+ t.Fatalf("ingress.Start: %v", err)+ }++ // Node B declares the sandbox's a2a service up front, backed by the+ // gateway. Advertisement is gated on the card probe passing through it.+ cfgPath := filepath.Join(homeB, "node-config.yaml")+ cfg := "version: \"v1alpha1\"\nservices:\n" ++ " - type: \"a2a\"\n name: \"code-reviewer\"\n" ++ " description: \"served by an agent behind the gateway\"\n" ++ " target_url: \"http://" + ingressAddr + "/code-reviewer\"\n"+ if err := os.WriteFile(cfgPath, []byte(cfg), 0o600); err != nil {+ t.Fatalf("writing node config: %v", err)+ }+_ = startBackgroundNode(t, nodeBin, hubAddr, homeA,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms",)- // Node B hosts the agent, and is the one that will advertise its service.+ // Node B hosts the agent, and is the one that advertises its service._ = startBackgroundNode(t, nodeBin, hubAddr, homeB,"--listen", "/ip4/127.0.0.1/udp/0/quic-v1","--listen", "/ip4/127.0.0.1/tcp/0","--discovery-interval", "100ms","--socket-path", nodeSocket,+ "--config", cfgPath,)apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))@@ -71,22 +128,10 @@ func TestAgentIngressCUJ(t *testing.T) {connectPeer(t, apiAddrA, addrB)waitForDHTPeers(t, apiAddrB)- // The agent's own server, inside its sandbox.- agent := httptest.NewServer(newBoundaryMCPHandler(t))- defer agent.Close()- agentHost := strings.TrimPrefix(agent.URL, "http://")-- ingress := &sambox.IngressManager{- SidecarSocket: nodeSocket,- Allowed: []sambox.BundleIngress{{Name: "code-reviewer", Type: "mcp"}},- AgentAddr: func(int) string { return agentHost },- }- t.Cleanup(func() { ingress.Close(context.Background()) })-- startBoundaryServing(t, agentSocket, nodeSocket, "reviewer-7.prod.acme.example", ingress)+ startBoundaryServing(t, agentSocket, nodeSocket, "reviewer-7.prod.acme.example")client := boundaryClient(t, agentSocket)- t.Run("a name the platform did not grant is refused", func(t *testing.T) {+ t.Run("the agent has no serving surface at all", func(t *testing.T) {resp, err := client.Post("http://"+api.MeshEntrypointHost+"/ingress","application/json", strings.NewReader(`{"name":"payments","type":"mcp","port":9000}`))if err != nil {@@ -98,32 +143,60 @@ func TestAgentIngressCUJ(t *testing.T) {}})- t.Run("the agent announces and the mesh can reach it", func(t *testing.T) {- resp, err := client.Post("http://"+api.MeshEntrypointHost+"/ingress",- "application/json", strings.NewReader(`{"name":"code-reviewer","type":"mcp","port":8080}`))- if err != nil {- t.Fatalf("Post: %v", err)+ t.Run("a stock a2a client reaches the agent through the mesh", func(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ // Bootstrap from the card the mesh regenerates at the consumer's+ // edge: the agent's own 127.0.0.1 URL must have been replaced.+ meshBase := "http://" + apiAddrA + "/sam/" + peerB + "/a2a/code-reviewer"+ resolver := agentcard.NewResolver(meshHTTPClient(apiToken, nil))+ var card *a2a.AgentCard+ deadline := time.Now().Add(30 * time.Second)+ for {+ card, err = resolver.Resolve(ctx, meshBase)+ if err == nil {+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("timeout resolving the agent card through the mesh: %v", err)+ }+ time.Sleep(200 * time.Millisecond)}- defer func() { _ = resp.Body.Close() }()- if resp.StatusCode != http.StatusNoContent {- t.Fatalf("status = %s, want 204", resp.Status)+ if len(card.SupportedInterfaces) != 1 || card.SupportedInterfaces[0].URL != meshBase {+ t.Errorf("card interfaces not regenerated for the mesh: %+v", card.SupportedInterfaces)}- // Node A calls the agent's tool across the mesh, knowing only the- // service name the agent published.- got := callMCP(t, apiAddrA, "call_remote_tool", map[string]any{- "peer_id": peerB,- "tool_name": "mcp://code-reviewer/add",- "arguments": map[string]any{},- })- if !strings.Contains(got, "fake-result:add") {- t.Errorf("remote call returned %q, want the agent's own answer", got)+ a2aClient, err := a2aclient.NewFromCard(ctx, card,+ a2aclient.WithJSONRPCTransport(meshHTTPClient(apiToken, nil)))+ if err != nil {+ t.Fatalf("stock client rejected the regenerated card: %v", err)+ }+ req := &a2a.SendMessageRequest{Message: a2a.NewMessage(a2a.MessageRoleUser, a2a.NewTextPart("hi"))}+ var result a2a.SendMessageResult+ deadline = time.Now().Add(30 * time.Second)+ for {+ result, err = a2aClient.SendMessage(ctx, req)+ if err == nil {+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("message/send through the sandbox failed: %v", err)+ }+ time.Sleep(200 * time.Millisecond)+ }+ reply, ok := result.(*a2a.Message)+ if !ok {+ t.Fatalf("send result = %T, want *a2a.Message", result)+ }+ if len(reply.Parts) == 0 || reply.Parts[0].Text() != "echo from the sandbox" {+ t.Fatalf("unexpected reply: %+v", reply)}})}// startBoundaryServing runs a boundary for an agent that also serves.-func startBoundaryServing(t *testing.T, agentSocket, nodeSocket, agentID string, ingress *sambox.IngressManager) {+func startBoundaryServing(t *testing.T, agentSocket, nodeSocket, agentID string) {t.Helper()egress, err := sambox.NewEgressPolicy(nil)@@ -140,7 +213,6 @@ func startBoundaryServing(t *testing.T, agentSocket, nodeSocket, agentID string,Router: &sambox.Router{Egress: egress},SidecarSocket: nodeSocket,AgentID: agentID,- Ingress: ingress,},}