Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: let an agent serve the mesh without touching the node
Antonio Ojea705e01a61bea
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex 05d06277..c62e5736 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -75,6 +75,13 @@ func main() {if err := verifyBundleCredential(cmd.Context(), bundlePath, issuer, audience, insecure); err != nil {return err}+ ingress, err := resolveIngress(bundlePath, sidecarSocket)+ if err != nil {+ return err+ }+ if ingress != nil {+ defer ingress.Close(context.WithoutCancel(cmd.Context()))+ }listener, err := sambox.ListenSandboxSocket(sandboxSocket)if err != nil {@@ -90,6 +97,7 @@ func main() {Router: &sambox.Router{Egress: egress},SidecarSocket: sidecarSocket,AgentID: agentID,+ Ingress: ingress,},}@@ -199,3 +207,23 @@ func verifyBundleCredential(ctx context.Context, bundlePath, issuer, audience stlogger.Infof("Credential verified: %s is %s", bundle.Agent.ID, bundle.Agent.ExternalID)return nil}++// 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 string) (*sambox.IngressManager, error) {+ if bundlePath == "" {+ return nil, nil+ }+ bundle, err := sambox.LoadAgentBundle(bundlePath)+ if err != nil {+ return nil, err+ }+ if len(bundle.Ingress) == 0 {+ return nil, nil+ }+ 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,+ }, nil+}diff --git a/internal/sambox/bundle.go b/internal/sambox/bundle.goindex ea5253bc..9faa2b82 100644--- a/internal/sambox/bundle.go+++ b/internal/sambox/bundle.go@@ -39,12 +39,24 @@ 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"`+// 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// request.egress *EgressPolicy}+// BundleIngress is one mesh service the agent may advertise.+type BundleIngress struct {+ Name string `yaml:"name"`+ Type string `yaml:"type"`+}+// AgentIdentity names the principal the gateway asserts for this sandbox.type AgentIdentity struct {// ID is the canonical mesh identifier, without the "agent:" prefix.@@ -94,6 +106,15 @@ 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 err := api.ValidateServiceFormat(ingress.Type + "://" + ingress.Name); err != nil {+ return nil, fmt.Errorf("agent bundle %s: ingress %d: %w", path, i, err)+ }+ }+return &bundle, nil}diff --git a/internal/sambox/dial.go b/internal/sambox/dial.goindex feaadaab..161cbce5 100644--- a/internal/sambox/dial.go+++ b/internal/sambox/dial.go@@ -45,6 +45,11 @@ 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 93699a00..655a806c 100644--- a/internal/sambox/entrypoint.go+++ b/internal/sambox/entrypoint.go@@ -37,17 +37,17 @@ import (// entrypoint terminates HTTP and forwards only what an agent is supposed to// have.-// agentMayReach is the entire surface an agent gets. Inference and tools, and-// nothing else.+// agentMayReach is the entire surface an agent gets on the node. Inference and+// tools, and nothing else.//// 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. Ingress is declared by the-// platform through the connector interface, which is the only party that knows-// what an agent is supposed to serve.+// 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.func agentMayReach(path string) bool {switch path {case "/v1/models", "/v1/chat/completions", "/v1/completions":@@ -56,6 +56,9 @@ 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 == "" {@@ -75,9 +78,22 @@ 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 and /mcp only", http.StatusForbidden)+ http.Error(w, "the mesh entrypoint serves /v1, /mcp and /ingress only", http.StatusForbidden)return}proxy.ServeHTTP(w, r)diff --git a/internal/sambox/ingress.go b/internal/sambox/ingress.gonew file mode 100644index 00000000..124e07d2--- /dev/null+++ b/internal/sambox/ingress.go@@ -0,0 +1,304 @@+// 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 sambox++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net"+ "net/http"+ "net/http/httputil"+ "net/url"+ "strconv"+ "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.+//+// 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.+type IngressManager struct {+ // SidecarSocket is the node's API socket, where registrations are made.+ SidecarSocket string++ // Allowed is what the bundle permits this agent to serve. Empty means the+ // agent may serve nothing.+ Allowed []BundleIngress++ // AgentAddr resolves where the agent listens inside its sandbox. It exists+ // because reaching in is topology-dependent: a sandbox sharing a network+ // namespace with the gateway is reachable on loopback, while an isolated+ // one needs a reverse channel that does not exist yet.+ AgentAddr func(port int) string++ mu sync.Mutex+ listener net.Listener+ 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)+ }++ 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 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)+ }++ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ return "", err+ }+ m.listener = listener++ server := &http.Server{Handler: m.forwarder(), ReadHeaderTimeout: 10 * time.Second}+ go func() {+ _ = server.Serve(listener)+ }()+ return listener.Addr().String(), nil+}++// forwarder carries what the node delivers into the sandbox, stripping the+// service name the gateway added so the agent sees the path it published.+func (m *IngressManager) forwarder() http.Handler {+ proxy := &httputil.ReverseProxy{+ Rewrite: func(r *httputil.ProxyRequest) {+ name, rest := splitServicePath(r.In.URL.Path)++ m.mu.Lock()+ port, known := m.routes[name]+ m.mu.Unlock()+ if !known {+ // Nothing to route to; the proxy reports a failure rather than+ // dialling something arbitrary.+ r.Out.URL = &url.URL{Scheme: "http", Host: "ingress.invalid"}+ return+ }++ r.Out.URL.Scheme = "http"+ r.Out.URL.Host = m.agentAddr(port)+ r.Out.Host = r.Out.URL.Host+ r.Out.URL.Path = rest+ r.Out.URL.RawPath = ""+ },+ }+ return proxy+}++func (m *IngressManager) agentAddr(port int) string {+ if m.AgentAddr != nil {+ return m.AgentAddr(port)+ }+ return net.JoinHostPort("127.0.0.1", strconv.Itoa(port))+}++// 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) {+ m.mu.Lock()+ listener := m.listener+ m.listener = nil+ routes := m.routes+ m.routes = nil+ m.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.+func splitServicePath(path string) (name, rest string) {+ trimmed := path+ if len(trimmed) > 0 && trimmed[0] == '/' {+ trimmed = trimmed[1:]+ }+ for i := 0; i < len(trimmed); i++ {+ if trimmed[i] == '/' {+ return trimmed[:i], trimmed[i:]+ }+ }+ return trimmed, "/"+}diff --git a/internal/sambox/ingress_test.go b/internal/sambox/ingress_test.gonew file mode 100644index 00000000..f9f15660--- /dev/null+++ b/internal/sambox/ingress_test.go@@ -0,0 +1,278 @@+// 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 sambox++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "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"}},+ }+ 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"}},+ }+ 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:+ }+ })+ }+}++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.+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+ _, _ = io.WriteString(w, "served by the agent")+ }))+ 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.+ AgentAddr: func(int) string { return strings.TrimPrefix(agent.URL, "http://") },+ }+ t.Cleanup(func() { manager.Close(context.Background()) })++ 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)+ }+ target := (<-registrations).GetTargetUrl()++ resp, err := http.Get(target + "/review")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()++ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if string(body) != "served by the agent" {+ t.Errorf("body = %q", body)+ }+ if got := <-paths; got != "/review" {+ t.Errorf("the agent saw %q, want the service name stripped", got)+ }+}++func TestIngressRefusesToRouteAnUnknownService(t *testing.T) {+ manager := &IngressManager{+ SidecarSocket: registrationRecorder(t, make(chan *api.RegisterServiceRequest, 1)),+ Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},+ }+ t.Cleanup(func() { manager.Close(context.Background()) })++ addr, err := manager.ensureListening()+ if err != nil {+ t.Fatalf("ensureListening: %v", err)+ }++ resp, err := http.Get("http://" + addr + "/never-announced/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")+ }+}++// 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)++ 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"]+ }+ }))++ manager := &IngressManager{+ SidecarSocket: socket,+ Allowed: []BundleIngress{{Name: "code-reviewer", Type: "mcp"}},+ }+ if rec := announce(t, manager.Handler(), `{"name":"code-reviewer","type":"mcp","port":8080}`); rec.Code != http.StatusNoContent {+ t.Fatalf("announce: %d", rec.Code)+ }+ <-registrations++ manager.Close(context.Background())+ if got := <-withdrawals; got != "code-reviewer" {+ t.Errorf("withdrew %q, want code-reviewer", got)+ }+}++func TestSplitServicePath(t *testing.T) {+ tests := []struct {+ path string+ wantName string+ wantRest string+ }{+ {"/code-reviewer/review", "code-reviewer", "/review"},+ {"/code-reviewer", "code-reviewer", "/"},+ {"/code-reviewer/", "code-reviewer", "/"},+ {"/code-reviewer/a/b", "code-reviewer", "/a/b"},+ {"/", "", "/"},+ }++ for _, tc := range tests {+ t.Run(tc.path, func(t *testing.T) {+ name, rest := splitServicePath(tc.path)+ if name != tc.wantName || rest != tc.wantRest {+ t.Errorf("splitServicePath(%q) = %q, %q; want %q, %q", tc.path, name, rest, tc.wantName, tc.wantRest)+ }+ })+ }+}diff --git a/internal/sambox/mesh.go b/internal/sambox/mesh.goindex 5252af8d..bf82d7e3 100644--- a/internal/sambox/mesh.go+++ b/internal/sambox/mesh.go@@ -139,7 +139,12 @@ func (d *AgentDialer) discoverProvider(ctx context.Context, svcType, svcName str}func (d *AgentDialer) sidecarTransport() http.RoundTripper {- socket := d.SidecarSocket+ return sidecarTransport(d.SidecarSocket)+}++// sidecarTransport dials the node's API socket whatever host a URL names, since+// the host in these URLs is a placeholder and never resolved.+func sidecarTransport(socket string) http.RoundTripper {return &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {return (&net.Dialer{}).DialContext(ctx, "unix", socket)diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 1ba9dcb3..558a78f3 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -754,11 +754,20 @@ the node on the agent's behalf. Two things make that safe:* **`target_url` is not the agent's to give.** `sam-box` always substitutes itsown per-agent ingress endpoint, so the field an agent could abuse is one itnever supplies.-* **The name must be one the agent already had.** Either the bundle enumerated- it (§12.1 `ingress`), or it falls inside the agent's own namespace — derived- from its identifier, which is authority-anchored and collision-free by- construction (§10.8). Squatting a name the platform did not grant is therefore- not expressible, rather than merely rejected.+* **The name must be one the agent already had.** The bundle enumerates what it+ may serve (§12.1 `ingress`), and a name outside that list is not expressible+ rather than merely rejected.++The bundle declares `{name, type}` only. The port is the agent's to choose at+runtime, because that is what it actually knows.++**Implemented**, with one gap: reaching back into the sandbox currently means+dialling an address, which works when the gateway shares a network namespace+with the agent — the Kubernetes sidecar case, and what `TestAgentIngressCUJ`+covers end to end. A microVM or a `network=none` container cannot be reached+that way and needs the reverse channel below, which is not built. The seam is+`IngressManager.AgentAddr`, so that channel slots in without changing the+registration path.### 11.1.1 Why this is also the better UX@@ -852,7 +861,7 @@ egress:secrets:"api.github.com": {kind: bearer, value_from: /etc/sam/secrets/github}ingress:- - {name: code-reviewer, type: mcp, port: 8080}+ - {name: code-reviewer, type: mcp}```### 12.2 Operationsdiff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.mdindex 092351a3..ba723094 100644--- a/site/content/docs/user/secure-gateway.md+++ b/site/content/docs/user/secure-gateway.md@@ -118,13 +118,40 @@ curl --socks5-hostname 127.0.0.1:1080 http://mesh.sam.alt/v1/models----## 5. Not yet implemented+## 5. Serving a mesh service++An agent can serve, not only call. Its bundle says what it is allowed to serve;+the agent itself says when it is ready and on which port:++```yaml+ingress:+ - {name: code-reviewer, type: mcp}+```++```bash+curl -X POST http://mesh.sam.alt/ingress \+ -d '{"name":"code-reviewer","type":"mcp","port":8080}'+```++The gateway then registers the service with the node. The agent never does: it+cannot name the URL the mesh routes to, and it cannot claim a name its bundle+does not list. When the gateway stops, the service is withdrawn, so a suspended+agent stops being advertised without anyone reconciling anything.++Reaching back into the sandbox currently means dialling the port the agent+announced, which works when the gateway shares a network namespace with it —+the Kubernetes sidecar arrangement. An isolated sandbox needs the reverse+channel described in the architecture document, which is not built yet.++---++## 6. Not yet implementedDeliberately absent, and tracked in the architecture document:* **Secret injection** for external destinations. The ephemeral CA and theinjection machinery exist, but are not wired into this datapath.-* **Ingress**: an agent serving a mesh service of its own.+* **The ingress reverse channel**, for sandboxes the gateway cannot dial.* **Credential rotation.** A bundle's credential is verified when the gatewaystarts. Platforms rotate projected tokens, and re-verifying on rotation isthe connector interface's `Refresh` operation, which is not built yet.diff --git a/tests/integration/agent_ingress_test.go b/tests/integration/agent_ingress_test.gonew file mode 100644index 00000000..9d590587--- /dev/null+++ b/tests/integration/agent_ingress_test.go@@ -0,0 +1,159 @@+// 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 (+ "context"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "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.+//+// 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.+func TestAgentIngressCUJ(t *testing.T) {+ nodeBin := buildBinary(t, "./cmd/sam-node")+ _, hubAddr := startMockRouter(t)++ homeA := t.TempDir()+ homeB := t.TempDir()++ sockDir, err := os.MkdirTemp("", "ingress")+ if err != nil {+ t.Fatalf("MkdirTemp: %v", err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(sockDir) })+ nodeSocket := filepath.Join(sockDir, "node.sock")+ agentSocket := filepath.Join(sockDir, "agent.sock")++ _ = 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.+ _ = 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,+ )++ apiAddrA := waitForMCPAddr(t, filepath.Join(homeA, "node.log"))+ apiAddrB := waitForMCPAddr(t, filepath.Join(homeB, "node.log"))+ waitForAPI(t, apiAddrA)+ waitForAPI(t, apiAddrB)++ addrB := waitForPeerInfoInLog(t, filepath.Join(homeB, "node.log"))+ peerB := extractPeerID(addrB)+ callMCP(t, apiAddrA, "connect_peer", map[string]any{"peer_addr": 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)+ client := boundaryClient(t, agentSocket)++ t.Run("a name the platform did not grant is refused", 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 {+ t.Fatalf("Post: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusForbidden {+ t.Errorf("status = %s, want 403", resp.Status)+ }+ })++ 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)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusNoContent {+ t.Fatalf("status = %s, want 204", resp.Status)+ }++ // 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)+ }+ })+}++// startBoundaryServing runs a boundary for an agent that also serves.+func startBoundaryServing(t *testing.T, agentSocket, nodeSocket, agentID string, ingress *sambox.IngressManager) {+ t.Helper()++ egress, err := sambox.NewEgressPolicy(nil)+ if err != nil {+ t.Fatalf("NewEgressPolicy: %v", err)+ }+ listener, err := sambox.ListenSandboxSocket(agentSocket)+ if err != nil {+ t.Fatalf("ListenSandboxSocket: %v", err)+ }++ server := &sambox.SOCKS5Server{+ Dialer: &sambox.AgentDialer{+ Router: &sambox.Router{Egress: egress},+ SidecarSocket: nodeSocket,+ AgentID: agentID,+ Ingress: ingress,+ },+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ go func() {+ defer close(done)+ if err := server.Serve(ctx, listener); err != nil {+ t.Errorf("boundary: %v", err)+ }+ }()+ t.Cleanup(func() {+ cancel()+ <-done+ })+}