Skip to content

Agent Mesh

sambox: agents consume the mesh, never the node

Antonio Ojea279b31a69293
diff --git a/api/names.go b/api/names.go
index 43f9b3a3..6fda3d3f 100644
--- a/api/names.go
+++ b/api/names.go
@@ -51,11 +51,16 @@ const (
// sandbox fails closed instead of resolving to somebody else's host.
MeshZone = "sam.alt"
- // LocalNodeHost is the reserved name for the agent's own gateway: the
- // sidecar API of the sam-node it is attached to. Connecting here is
- // equivalent to talking to the local sidecar over its Unix socket, so
- // /v1/*, /mcp and /sam/* behave exactly as documented for that API.
- LocalNodeHost = "node." + MeshZone
+ // MeshEntrypointHost is the reserved name an agent uses to reach the mesh
+ // services its gateway offers it: inference and tools, with the provider
+ // chosen by policy.
+ //
+ // It deliberately does not name the node. A sam-node's sidecar API is a
+ // local, operator-facing surface — it can register services, drive the raw
+ // egress proxy and read node internals — and an agent has no business
+ // reaching any of it. The gateway consumes the node; the agent consumes the
+ // mesh through the gateway, and the two must not be the same address.
+ MeshEntrypointHost = "mesh." + MeshZone
)
// meshZoneSuffix is the dotted form used for suffix matching.
@@ -77,9 +82,10 @@ func IsMeshHost(host string) bool {
return h == MeshZone || strings.HasSuffix(h, meshZoneSuffix)
}
-// IsLocalNodeHost reports whether host addresses the local sidecar.
-func IsLocalNodeHost(host string) bool {
- return NormalizeMeshHost(host) == LocalNodeHost
+// IsMeshEntrypointHost reports whether host addresses the gateway's own
+// agent-facing surface.
+func IsMeshEntrypointHost(host string) bool {
+ return NormalizeMeshHost(host) == MeshEntrypointHost
}
// ParseMeshHost translates a mesh hostname into its canonical service URI.
@@ -89,8 +95,9 @@ func IsLocalNodeHost(host string) bool {
//
// The service type is the label immediately left of the zone; everything to its
// left is the service name, which may itself contain dots (service names are
-// validated as DNS names, not as single labels). LocalNodeHost is not a service
-// and is rejected here; callers must test it with IsLocalNodeHost first.
+// validated as DNS names, not as single labels). MeshEntrypointHost is not a
+// service and is rejected here; callers must test it with IsMeshEntrypointHost
+// first.
//
// Names are not resolved to a provider: which peer serves the returned URI is a
// discovery decision, and deliberately not encoded in the name. If pinning to
@@ -110,8 +117,8 @@ func ParseMeshHost(host string) (serviceURI string, err error) {
if strings.ContainsAny(h, ":/") {
return "", fmt.Errorf("mesh host %q must not contain a port or a path", host)
}
- if h == LocalNodeHost {
- return "", fmt.Errorf("%q is the local node, not a mesh service", host)
+ if h == MeshEntrypointHost {
+ return "", fmt.Errorf("%q is the gateway entrypoint, not a mesh service", host)
}
rest, found := strings.CutSuffix(h, meshZoneSuffix)
if !found || rest == "" {
diff --git a/api/names_test.go b/api/names_test.go
index da9e51e2..b1912894 100644
--- a/api/names_test.go
+++ b/api/names_test.go
@@ -30,7 +30,7 @@ func TestParseMeshHost(t *testing.T) {
{"dotted service name", "my-service.local.mcp.sam.alt", "mcp://my-service.local", false},
{"underscore service name", "my_service.mcp.sam.alt", "mcp://my_service", false},
- {"local node is not a service", "node.sam.alt", "", true},
+ {"local node is not a service", "mesh.sam.alt", "", true},
{"unknown service type", "thing.storage.sam.alt", "", true},
{"missing service type", "calculator.sam.alt", "", true},
{"zone only", "sam.alt", "", true},
@@ -111,19 +111,20 @@ func TestMeshHostRejects(t *testing.T) {
}
}
-func TestIsMeshHostAndIsLocalNodeHost(t *testing.T) {
+func TestIsMeshHostAndIsMeshEntrypointHost(t *testing.T) {
tests := []struct {
host string
isMesh bool
- isLocal bool
+ isEntry bool
}{
- {"node.sam.alt", true, true},
- {"NODE.SAM.ALT.", true, true},
+ {"mesh.sam.alt", true, true},
+ {"MESH.SAM.ALT.", true, true},
{"calculator.mcp.sam.alt", true, false},
{"sam.alt", true, false},
+ {"node.sam.alt", true, false},
{"api.github.com", false, false},
{"evil-sam.alt", false, false},
- {"node.sam.alt.evil.com", false, false},
+ {"mesh.sam.alt.evil.com", false, false},
{"", false, false},
}
@@ -132,8 +133,8 @@ func TestIsMeshHostAndIsLocalNodeHost(t *testing.T) {
if got := IsMeshHost(tc.host); got != tc.isMesh {
t.Errorf("IsMeshHost(%q) = %v, want %v", tc.host, got, tc.isMesh)
}
- if got := IsLocalNodeHost(tc.host); got != tc.isLocal {
- t.Errorf("IsLocalNodeHost(%q) = %v, want %v", tc.host, got, tc.isLocal)
+ if got := IsMeshEntrypointHost(tc.host); got != tc.isEntry {
+ t.Errorf("IsMeshEntrypointHost(%q) = %v, want %v", tc.host, got, tc.isEntry)
}
})
}
diff --git a/internal/sambox/dial.go b/internal/sambox/dial.go
index 91d94c20..77fb4af3 100644
--- a/internal/sambox/dial.go
+++ b/internal/sambox/dial.go
@@ -36,9 +36,8 @@ type AgentDialer struct {
Router *Router
// SidecarSocket is the Unix socket of the sam-node this sandbox is attached
- // to. Flows to node.sam.alt are piped to it verbatim: sam-box parses
- // nothing, so /v1/*, /mcp and /sam/* behave exactly as they do over TCP,
- // including how they treat their own authentication headers.
+ // to. sam-box is the node's only consumer here: an agent never reaches the
+ // socket, only the curated surface built on top of it (entrypoint.go).
SidecarSocket string
// DialContext opens external destinations. Nil uses a plain net.Dialer;
@@ -61,8 +60,8 @@ func (d *AgentDialer) DialDestination(ctx context.Context, _ *Credentials, dst D
defer cancel()
switch route.Kind {
- case RouteLocalNode:
- return d.dial(ctx, "unix", d.SidecarSocket)
+ case RouteMeshEntrypoint:
+ return d.dialMeshEntrypoint()
case RouteExternal:
return d.dial(ctx, "tcp", dst.Address())
case RouteMeshService:
diff --git a/internal/sambox/dial_test.go b/internal/sambox/dial_test.go
index 7cf432ae..c3695a2f 100644
--- a/internal/sambox/dial_test.go
+++ b/internal/sambox/dial_test.go
@@ -17,47 +17,12 @@ package sambox
import (
"context"
"errors"
- "io"
"net"
- "os"
- "path/filepath"
"testing"
- "golang.org/x/net/proxy"
+ "github.com/google/sam/api"
)
-// startUnixEcho stands in for a sam-node sidecar socket.
-func startUnixEcho(t *testing.T) string {
- t.Helper()
-
- dir, err := os.MkdirTemp("", "sambox")
- if err != nil {
- t.Fatalf("MkdirTemp: %v", err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(dir) })
-
- path := filepath.Join(dir, "sidecar.sock")
- l, err := net.Listen("unix", path)
- if err != nil {
- t.Fatalf("listen: %v", err)
- }
- t.Cleanup(func() { _ = l.Close() })
-
- go func() {
- for {
- conn, err := l.Accept()
- if err != nil {
- return
- }
- go func() {
- defer func() { _ = conn.Close() }()
- _, _ = io.Copy(conn, conn)
- }()
- }
- }()
- return path
-}
-
// closedTCPAddr returns an address nothing is listening on.
func closedTCPAddr(t *testing.T) string {
t.Helper()
@@ -81,62 +46,8 @@ func mustEgressPolicy(t *testing.T, allow ...string) *EgressPolicy {
return p
}
-// TestSandboxReachesSidecarThroughBoundary is the primary path end to end: an
-// unmodified client speaks SOCKS5 to the boundary, asks for node.sam.alt, and
-// its bytes arrive at the sidecar socket untouched.
-func TestSandboxReachesSidecarThroughBoundary(t *testing.T) {
- sidecar := startUnixEcho(t)
-
- path := startSOCKS5(t, &SOCKS5Server{
- Dialer: &AgentDialer{
- Router: &Router{},
- SidecarSocket: sidecar,
- },
- })
-
- dialer, err := proxy.SOCKS5("unix", path, nil, proxy.Direct)
- if err != nil {
- t.Fatalf("proxy.SOCKS5: %v", err)
- }
- conn, err := dialer.Dial("tcp", "node.sam.alt:80")
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- defer func() { _ = conn.Close() }()
-
- if _, err := conn.Write([]byte("GET /v1/models")); err != nil {
- t.Fatalf("write: %v", err)
- }
- got := make([]byte, len("GET /v1/models"))
- if _, err := io.ReadFull(conn, got); err != nil {
- t.Fatalf("read: %v", err)
- }
- if string(got) != "GET /v1/models" {
- t.Errorf("sidecar received %q, want it verbatim", got)
- }
-}
-
-// TestLocalNodeIgnoresTheRequestedPort pins that node.sam.alt is a name for the
-// sidecar socket, not an address: whatever port a client happens to use, the
-// flow lands on the socket.
-func TestLocalNodeIgnoresTheRequestedPort(t *testing.T) {
- sidecar := startUnixEcho(t)
- d := &AgentDialer{Router: &Router{}, SidecarSocket: sidecar}
-
- for _, port := range []uint16{80, 443, 8080} {
- conn, err := d.DialDestination(context.Background(), nil, Destination{Name: "node.sam.alt", Port: port, IsName: true})
- if err != nil {
- t.Fatalf("port %d: %v", port, err)
- }
- _ = conn.Close()
- }
-}
-
func TestExternalDestinationRequiresPolicy(t *testing.T) {
- d := &AgentDialer{
- Router: &Router{Egress: mustEgressPolicy(t, "127.0.0.1")},
- SidecarSocket: startUnixEcho(t),
- }
+ d := &AgentDialer{Router: &Router{Egress: mustEgressPolicy(t, "127.0.0.1")}}
echo := startEcho(t)
host, port, err := net.SplitHostPort(echo)
@@ -190,17 +101,13 @@ func TestUnresolvableDestinationIsReportedAsUnreachable(t *testing.T) {
}
}
-func TestMissingSidecarSocketIsAnError(t *testing.T) {
- d := &AgentDialer{Router: &Router{}}
-
- if _, err := d.DialDestination(context.Background(), nil, Destination{Name: "node.sam.alt", Port: 80, IsName: true}); err == nil {
- t.Fatal("DialDestination with no sidecar socket succeeded, want an error")
- }
-}
-
func TestDialerRequiresARouter(t *testing.T) {
var d AgentDialer
- if _, err := d.DialDestination(context.Background(), nil, Destination{Name: "node.sam.alt", Port: 80, IsName: true}); err == nil {
+ if _, err := d.DialDestination(context.Background(), nil, Destination{
+ Name: api.MeshEntrypointHost,
+ Port: 80,
+ IsName: true,
+ }); err == nil {
t.Fatal("DialDestination with no router succeeded, want an error")
}
}
diff --git a/internal/sambox/entrypoint.go b/internal/sambox/entrypoint.go
new file mode 100644
index 00000000..f055f7a8
--- /dev/null
+++ b/internal/sambox/entrypoint.go
@@ -0,0 +1,92 @@
+// 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 (
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "strings"
+
+ "github.com/google/sam/api"
+)
+
+// The gateway consumes the node; the agent consumes the mesh through the
+// gateway. Those are different surfaces and this file is the boundary between
+// them.
+//
+// A sam-node's sidecar API is local and operator-facing: it can register
+// services under the node's identity, drive the raw /sam/<peer>/... egress
+// proxy at any peer and service the operator chooses, and read node internals.
+// Reaching its Unix socket is itself the credential — withAuth treats arriving
+// there as proof of authorization, on the grounds that it is the same bar as
+// reading the token file. Piping an agent's bytes to that socket would
+// therefore hand every sandbox the node's full local authority, so the
+// 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.
+//
+// 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.
+func agentMayReach(path string) bool {
+ switch path {
+ case "/v1/models", "/v1/chat/completions", "/v1/completions":
+ return true
+ }
+ return path == "/mcp" || strings.HasPrefix(path, "/mcp/")
+}
+
+// dialMeshEntrypoint returns a connection serving the agent-facing surface.
+func (d *AgentDialer) dialMeshEntrypoint() (net.Conn, error) {
+ if d.SidecarSocket == "" {
+ return nil, ErrHostUnreachable
+ }
+ return serveOnPipe(d.entrypointHandler()), nil
+}
+
+func (d *AgentDialer) entrypointHandler() http.Handler {
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) {
+ r.Out.URL.Scheme = "http"
+ r.Out.URL.Host = sidecarHost
+ r.Out.Host = sidecarHost
+
+ // Headers that assert an identity the agent does not have. The
+ // sidecar would honour them: X-Sam-Biscuit is the mesh datapath
+ // credential, and X-Sam-Authentication is the node's local gate.
+ // Authorization is left alone, because there it means the
+ // destination service's own credential and is the agent's to send.
+ r.Out.Header.Del(api.HeaderSamBiscuit)
+ r.Out.Header.Del(api.HeaderSamAuthentication)
+ },
+ Transport: d.sidecarTransport(),
+ }
+
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !agentMayReach(r.URL.Path) {
+ http.Error(w, "the mesh entrypoint serves /v1 and /mcp only", http.StatusForbidden)
+ return
+ }
+ proxy.ServeHTTP(w, r)
+ })
+}
diff --git a/internal/sambox/entrypoint_test.go b/internal/sambox/entrypoint_test.go
new file mode 100644
index 00000000..57cf5f05
--- /dev/null
+++ b/internal/sambox/entrypoint_test.go
@@ -0,0 +1,203 @@
+// 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"
+ "io"
+ "net/http"
+ "testing"
+
+ "github.com/google/sam/api"
+ "golang.org/x/net/proxy"
+)
+
+type sidecarCall struct {
+ path string
+ headers http.Header
+}
+
+// recordingSidecar answers anything and reports what it was asked for, so a
+// test can assert both what reached the node and what did not.
+func recordingSidecar(t *testing.T) (socket string, calls chan sidecarCall) {
+ t.Helper()
+ calls = make(chan sidecarCall, 8)
+ socket = startFakeSidecar(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case calls <- sidecarCall{path: r.URL.Path, headers: r.Header.Clone()}:
+ default:
+ t.Errorf("unexpected extra call to %s", r.URL.Path)
+ }
+ _, _ = io.WriteString(w, "ok")
+ }))
+ return socket, calls
+}
+
+func entrypointClient(t *testing.T, socket string) *http.Client {
+ t.Helper()
+ boundary := startSOCKS5(t, &SOCKS5Server{
+ Dialer: &AgentDialer{Router: &Router{}, SidecarSocket: socket},
+ })
+ dialer, err := proxy.SOCKS5("unix", boundary, nil, proxy.Direct)
+ if err != nil {
+ t.Fatalf("proxy.SOCKS5: %v", err)
+ }
+ contextDialer, ok := dialer.(proxy.ContextDialer)
+ if !ok {
+ t.Fatal("SOCKS5 dialer does not implement ContextDialer")
+ }
+ return &http.Client{Transport: &http.Transport{DialContext: contextDialer.DialContext}}
+}
+
+// TestAgentReachesInferenceAndTools covers what an agent is supposed to have:
+// the mesh's inference and tool endpoints, reached by name, over SOCKS5.
+func TestAgentReachesInferenceAndTools(t *testing.T) {
+ socket, calls := recordingSidecar(t)
+ client := entrypointClient(t, socket)
+
+ for _, path := range []string{"/v1/models", "/v1/chat/completions", "/v1/completions", "/mcp"} {
+ resp, err := client.Get("http://" + api.MeshEntrypointHost + path)
+ if err != nil {
+ t.Fatalf("GET %s: %v", path, err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET %s: status %s, want 200", path, resp.Status)
+ }
+ if got := (<-calls).path; got != path {
+ t.Errorf("node saw %q, want %q", got, path)
+ }
+ }
+}
+
+// TestAgentCannotReachTheNodeAPI is the separation this boundary exists for.
+// The node's sidecar is an operator surface: registering a service would let an
+// agent advertise itself into the mesh under the node's identity and choose the
+// URL the mesh then routes to, and the raw egress proxy would let it reach any
+// peer and service it names. Nothing here may reach the node at all.
+func TestAgentCannotReachTheNodeAPI(t *testing.T) {
+ socket, calls := recordingSidecar(t)
+ client := entrypointClient(t, socket)
+
+ forbidden := []string{
+ "/sam/service/register",
+ "/sam/service/unregister",
+ "/sam/service/discover",
+ "/sam/12D3KooWsomepeer/mcp/anything",
+ "/metrics",
+ "/healthz",
+ "/readyz",
+ "/",
+ "/v1/embeddings",
+ "/mcpsomething",
+ }
+
+ for _, path := range forbidden {
+ resp, err := client.Get("http://" + api.MeshEntrypointHost + path)
+ if err != nil {
+ t.Fatalf("GET %s: %v", path, err)
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden {
+ t.Errorf("GET %s: status %s, want 403", path, resp.Status)
+ }
+ }
+
+ select {
+ case call := <-calls:
+ t.Fatalf("the node was reached at %q; an agent must not reach it at all", call.path)
+ default:
+ }
+}
+
+// TestEntrypointStripsAssertedIdentityHeaders pins that an agent cannot claim
+// an identity by setting the headers the node honours.
+func TestEntrypointStripsAssertedIdentityHeaders(t *testing.T) {
+ socket, calls := recordingSidecar(t)
+ client := entrypointClient(t, socket)
+
+ req, err := http.NewRequest(http.MethodGet, "http://"+api.MeshEntrypointHost+"/v1/models", nil)
+ if err != nil {
+ t.Fatalf("NewRequest: %v", err)
+ }
+ req.Header.Set(api.HeaderSamBiscuit, "forged-mesh-credential")
+ req.Header.Set(api.HeaderSamAuthentication, "Bearer forged-node-token")
+ req.Header.Set("Authorization", "Bearer the-agents-own-backend-credential")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ _ = resp.Body.Close()
+
+ call := <-calls
+ if got := call.headers.Get(api.HeaderSamBiscuit); got != "" {
+ t.Errorf("%s reached the node as %q, want it stripped", api.HeaderSamBiscuit, got)
+ }
+ if got := call.headers.Get(api.HeaderSamAuthentication); got != "" {
+ t.Errorf("%s reached the node as %q, want it stripped", api.HeaderSamAuthentication, got)
+ }
+ // Authorization means the destination service's own credential, so it is
+ // the agent's to send and must survive.
+ if got := call.headers.Get("Authorization"); got != "Bearer the-agents-own-backend-credential" {
+ t.Errorf("Authorization = %q, want it forwarded untouched", got)
+ }
+}
+
+// TestEntrypointIgnoresTheRequestedPort pins that the entrypoint is a name for
+// a surface, not for an address.
+func TestEntrypointIgnoresTheRequestedPort(t *testing.T) {
+ socket, _ := recordingSidecar(t)
+ d := &AgentDialer{Router: &Router{}, SidecarSocket: socket}
+
+ for _, port := range []uint16{80, 443, 8080} {
+ conn, err := d.DialDestination(context.Background(), nil, Destination{
+ Name: api.MeshEntrypointHost,
+ Port: port,
+ IsName: true,
+ })
+ if err != nil {
+ t.Fatalf("port %d: %v", port, err)
+ }
+ _ = conn.Close()
+ }
+}
+
+func TestEntrypointRequiresASidecarSocket(t *testing.T) {
+ d := &AgentDialer{Router: &Router{}}
+ if _, err := d.DialDestination(context.Background(), nil, Destination{
+ Name: api.MeshEntrypointHost,
+ Port: 80,
+ IsName: true,
+ }); err == nil {
+ t.Fatal("DialDestination with no sidecar socket succeeded, want an error")
+ }
+}
+
+func TestAgentMayReach(t *testing.T) {
+ allowed := []string{"/v1/models", "/v1/chat/completions", "/v1/completions", "/mcp", "/mcp/session"}
+ for _, path := range allowed {
+ if !agentMayReach(path) {
+ t.Errorf("agentMayReach(%q) = false, want true", path)
+ }
+ }
+
+ denied := []string{"", "/", "/v1", "/v1/", "/v1/models/extra", "/mcpsomething", "/sam/service/register", "/metrics"}
+ for _, path := range denied {
+ if agentMayReach(path) {
+ t.Errorf("agentMayReach(%q) = true, want false", path)
+ }
+ }
+}
diff --git a/internal/sambox/mesh.go b/internal/sambox/mesh.go
index 23cb204c..ea8049ad 100644
--- a/internal/sambox/mesh.go
+++ b/internal/sambox/mesh.go
@@ -69,13 +69,25 @@ func (d *AgentDialer) dialMeshService(ctx context.Context, route Route) (net.Con
r.Out.Host = sidecarHost
r.Out.URL.Path = prefix + r.In.URL.Path
r.Out.URL.RawPath = ""
+
+ // Same reasoning as the entrypoint: an agent must not be able to
+ // assert an identity by setting the headers the sidecar honours.
+ r.Out.Header.Del(api.HeaderSamBiscuit)
+ r.Out.Header.Del(api.HeaderSamAuthentication)
},
Transport: transport,
}
+ return serveOnPipe(proxy), nil
+}
+
+// serveOnPipe runs h on one end of an in-memory connection and hands back the
+// other, so an HTTP handler can be given to the SOCKS5 layer as an ordinary
+// connection.
+func serveOnPipe(h http.Handler) net.Conn {
agentSide, boundarySide := net.Pipe()
server := &http.Server{
- Handler: proxy,
+ Handler: h,
// Mirrors the sidecar: bound header reads, but let bodies and responses
// stream, since inference completions and MCP sessions legitimately do.
ReadHeaderTimeout: 10 * time.Second,
@@ -84,14 +96,13 @@ func (d *AgentDialer) dialMeshService(ctx context.Context, route Route) (net.Con
go func() {
_ = server.Serve(newSingleConnListener(boundarySide))
}()
-
- return agentSide, nil
+ return agentSide
}
// discoverProvider asks the sidecar which peers serve the requested service.
// A well-formed name with no provider is unreachable rather than forbidden:
// unlike a malformed mesh name, it tells a sandbox nothing it could not already
-// learn by calling discovery itself through node.sam.alt.
+// learn from the tool catalog it is allowed to read.
func (d *AgentDialer) discoverProvider(ctx context.Context, svcType, svcName string) (string, error) {
endpoint := (&url.URL{
Scheme: "http",
diff --git a/internal/sambox/route.go b/internal/sambox/route.go
index 3e1caaac..452aa725 100644
--- a/internal/sambox/route.go
+++ b/internal/sambox/route.go
@@ -30,8 +30,10 @@ import (
type RouteKind int
const (
- // RouteLocalNode is the sam-node sidecar this sandbox is attached to.
- RouteLocalNode RouteKind = iota
+ // RouteMeshEntrypoint is the gateway's own agent-facing surface: the mesh
+ // services an agent may consume, with the provider chosen by policy. It is
+ // not the node's sidecar API, which an agent never reaches.
+ RouteMeshEntrypoint RouteKind = iota
// RouteMeshService is a service provided by some peer in the mesh. Which
// peer is a discovery decision, deliberately not encoded in the name.
@@ -43,8 +45,8 @@ const (
func (k RouteKind) String() string {
switch k {
- case RouteLocalNode:
- return "local-node"
+ case RouteMeshEntrypoint:
+ return "mesh-entrypoint"
case RouteMeshService:
return "mesh-service"
case RouteExternal:
@@ -137,8 +139,8 @@ type Router struct {
// sandbox, "not permitted" and "does not exist" must look the same, or the
// boundary becomes a discovery oracle for the mesh's contents.
func (r *Router) Route(dst Destination) (Route, error) {
- if api.IsLocalNodeHost(dst.Name) {
- return Route{Kind: RouteLocalNode, Destination: dst}, nil
+ if api.IsMeshEntrypointHost(dst.Name) {
+ return Route{Kind: RouteMeshEntrypoint, Destination: dst}, nil
}
if api.IsMeshHost(dst.Name) {
diff --git a/internal/sambox/route_test.go b/internal/sambox/route_test.go
index bd207353..c18a67dc 100644
--- a/internal/sambox/route_test.go
+++ b/internal/sambox/route_test.go
@@ -44,8 +44,8 @@ func TestRouteClassification(t *testing.T) {
wantURI string
wantDenied bool
}{
- {"local sidecar", "node.sam.alt", RouteLocalNode, "", false},
- {"local sidecar is case-insensitive", "NODE.SAM.ALT", RouteLocalNode, "", false},
+ {"mesh entrypoint", "mesh.sam.alt", RouteMeshEntrypoint, "", false},
+ {"mesh entrypoint is case-insensitive", "MESH.SAM.ALT", RouteMeshEntrypoint, "", false},
{"mesh inference service", "openrouter.inference.sam.alt", RouteMeshService, "inference://openrouter", false},
{"mesh mcp service", "code-reviewer.mcp.sam.alt", RouteMeshService, "mcp://code-reviewer", false},
{"allowlisted host", "api.github.com", RouteExternal, "", false},
diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.md
index 9a0e9977..94e80740 100644
--- a/site/content/docs/agent-architecture.md
+++ b/site/content/docs/agent-architecture.md
@@ -100,7 +100,7 @@ One socket, one protocol, one policy point. SOCKS5 is the waist.
│ sam-box (one per sandbox, NO libp2p host, NO enrollment) │
│ = SOCKS5 server = THE policy enforcement point │
│ │ │
-│ ├── node.sam.alt ── byte pipe ───────────┐ │
+│ ├── mesh.sam.alt ── /v1 + /mcp only ─────┐ │
│ ├── <svc>.<type>.sam.alt ── HTTP: discover, then ┤ │
│ │ /sam/<peer>/<type>/… │ │
│ └── anything else ── deny-by-default domain │ │
@@ -175,12 +175,12 @@ Sandbox names are a **projection of it**, not a second namespace:
```text
inference://openrouter <-> openrouter.inference.sam.alt
mcp://code-reviewer <-> code-reviewer.mcp.sam.alt
-(local sidecar) <-> node.sam.alt
+(the mesh, curated) <-> mesh.sam.alt
```
The mapping is declared once, in [`api/names.go`](https://github.com/google/sam/blob/main/api/names.go)
-(`MeshZone`, `LocalNodeHost`, `MeshHost`, `ParseMeshHost`), so the gateway and
-the node cannot drift. The rule that keeps it honest: **never introduce a
+(`MeshZone`, `MeshEntrypointHost`, `MeshHost`, `ParseMeshHost`), so the gateway
+and the node cannot drift. The rule that keeps it honest: **never introduce a
routing decision expressible in one form but not the other.**
`.alt` is the pseudo-TLD reserved by RFC 9476 for namespaces that are
@@ -275,15 +275,14 @@ SOCKS5 server; `internal/node` keeps everything mesh.
### 5.1 What the harness sees
```bash
-OPENAI_BASE_URL=http://node.sam.alt/v1 # inference, provider chosen by policy
-MCP_URL=http://node.sam.alt/mcp # tools: local catalog + remote services
+OPENAI_BASE_URL=http://mesh.sam.alt/v1 # inference, provider chosen by policy
+MCP_URL=http://mesh.sam.alt/mcp # tools: local catalog + remote services
```
No `HTTP_PROXY`. No CA bundle, unless a domain is explicitly configured for
-secret injection. No mesh concepts, and no sidecar token: reaching the sidecar
-socket is itself the credential (§5.2). `cmd/chaos-agent` already takes
-`--mcp-url` and `--inference-url`, so it needs no change beyond the values it is
-given.
+secret injection. No mesh concepts, and no token of any kind.
+`cmd/chaos-agent` already takes `--mcp-url` and `--inference-url`, so it needs
+no change beyond the values it is given.
A harness that wants one specific service instead of policy-chosen routing uses
its mesh name directly: `http://code-reviewer.mcp.sam.alt/`.
@@ -293,19 +292,25 @@ its mesh name directly: `http://code-reviewer.mcp.sam.alt/`.
Applied to the SOCKS5 request's `(host, port)` — `host` is the name
`tun2socks` preserved, never an IP — in order:
-1. **`node.sam.alt`** (`api.IsLocalNodeHost`) → **byte pipe** to the local
- `sam-node` sidecar Unix socket. `sam-box` parses nothing, so `/v1/*`, `/mcp`
- and `/sam/*` behave exactly as they do over TCP. No credential is injected:
- `withAuth` treats arriving on the socket as proof of authorization, on the
- grounds that it is the same bar as reading the token file.
-
- That has a consequence worth stating plainly. While the pipe is verbatim, an
- agent can reach *every* sidecar endpoint — including `/sam/service/register`
- with a `target_url` of its choosing, which is exactly what §11.1 requires
- `sam-box` to rewrite. Closing that gap means terminating HTTP on this path
- too, which is also what attaching the agent's identity to each flow (§10)
- will require. Until both land, this path assumes the sandbox is trusted not
- to register services on the node's behalf.
+1. **`mesh.sam.alt`** (`api.IsMeshEntrypointHost`) → the gateway's own
+ agent-facing surface, served in process: `/v1/models`,
+ `/v1/chat/completions`, `/v1/completions`, and `/mcp`. Nothing else. Any
+ other path is refused with 403 and never reaches the node.
+
+ **The agent never touches the node.** A `sam-node` sidecar is a local,
+ operator-facing API: it can register services under the node's identity, and
+ its `/sam/<peer>/<type>/<name>` proxy will carry a request to any peer and
+ service the caller names. Worse, arriving on its Unix socket *is* the
+ credential — `withAuth` treats reaching the socket as proof of authorization,
+ on the grounds that it is the same bar as reading the token file. So piping
+ an agent's bytes to that socket would hand every sandbox the node's full
+ local authority. `sam-box` is the node's consumer; the agent is the mesh's
+ consumer, through `sam-box`, and the two are different surfaces.
+
+ Discovery is deliberately absent from the list even though agents need it:
+ MCP already exposes `find_remote_tools` and `discover_remote_services` as
+ tools, so opening `/sam/service/discover` as well would widen the surface
+ without adding a capability.
2. **`<service>.<type>.sam.alt`** (`api.ParseMeshHost`) → `sam-box` terminates
HTTP and rewrites onto the sidecar's existing surface:
`GET /sam/service/discover?type=<type>&name=<service>` picks a provider, then
@@ -351,8 +356,9 @@ exactly once, at the top.
**Unit (`internal/…`, `api/`).** SOCKS5 request/reply codec; the name↔URI
projection (`api/names_test.go`, already landed); dispatch classification
-(`node.sam.alt` / mesh name / public / denied); wildcard matching in the
-allowlist; SNI-vs-authorized-name mismatch. Pure functions, microseconds.
+(`mesh.sam.alt` / mesh name / public / denied); the agent-facing path allowlist;
+wildcard matching in the egress allowlist; SNI-vs-authorized-name mismatch.
+Pure functions, microseconds.
**Integration (`tests/integration/`, budget 10s each).** The whole datapath, no
containers:
@@ -365,13 +371,12 @@ containers:
SOCKS5 on a second socket in `t.TempDir()`;
* the test drives a real SOCKS5 client (`golang.org/x/net/proxy`, already a
direct dependency) over that socket and asserts:
- 1. `node.sam.alt:80` → `/v1/chat/completions` reaches A's fake LLM across the mesh,
- 2. `node.sam.alt:80` → `/mcp` `call_remote_tool` reaches B's fake MCP,
+ 1. `mesh.sam.alt:80` → `/v1/chat/completions` reaches A's fake LLM across the mesh,
+ 2. `mesh.sam.alt:80` → `/mcp` `call_remote_tool` reaches B's fake MCP,
3. `<svc>.mcp.sam.alt:80` resolves through discovery to B and reaches it,
4. an allowlisted public name reaches a local `httptest` server,
5. a non-allowlisted name is refused with SOCKS5 `0x02`,
- 6. the sandbox's sidecar token never appears in what A, B or the public
- server receive.
+ 6. no path outside `/v1/*` and `/mcp` reaches node C at all.
**E2E (`tests/e2e/*.bats`).** Two CUJs, no more:
@@ -646,16 +651,60 @@ make this smaller than it looks.
API already exists**: `RegisterServiceRequest{service{type,name,description},
target_url}` on `/sam/service/register`.
-### 11.1 Declaring
+### 11.1 Declaring: autoregistration through the gateway
-Either the platform declares it at admission (§12), or the agent registers at
-runtime by POSTing to `http://node.sam.alt/sam/service/register` — which already
-works over the egress path, with no new API.
+The agent does **not** call the node. `/sam/service/register` is part of the
+operator surface an agent never reaches (§5.2), for two independent reasons: the
+request carries a `target_url`, so an agent could point the mesh at anything and
+turn its node into an open relay; and it carries a service *name*, so an agent
+could advertise itself as `code-reviewer` under the node's identity and take
+over somebody else's traffic.
-`sam-box` **rewrites `target_url`** to its own per-agent ingress endpoint before
-forwarding the registration. A sandboxed agent must never be able to point the
-mesh at a URL of its choosing: that would turn its node into an open relay and
-hand every agent an SSRF primitive against the host's network.
+Both are properties of *that* API, not of the capability. So the gateway offers
+the capability without the API:
+
+```http
+POST http://mesh.sam.alt/ingress
+{"type": "mcp", "name": "code-reviewer", "port": 8080}
+```
+
+`sam-box` serves this itself — it is never forwarded — and then registers with
+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 its
+ own per-agent ingress endpoint, so the field an agent could abuse is one it
+ never 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.
+
+### 11.1.1 Why this is also the better UX
+
+This is not only the safe shape, it is the one that matches how agents actually
+start:
+
+* **The platform knows *what* an agent may serve; only the agent knows *when*.**
+ A statically declared route advertises a service that is not listening yet, so
+ the mesh routes to it and fails. Splitting the declaration from the readiness
+ signal removes that window without a health-check protocol.
+* **The port is usually the agent's own business**, chosen at runtime by the
+ framework it happens to use.
+* **Lifetime is tied to the sandbox.** `sam-box` unregisters when the agent's
+ channel drops or the platform detaches it, so a suspended agent stops being
+ advertised without anyone reconciling anything.
+* **Resume is automatic.** On another host, the new `sam-box` re-registers the
+ same name against a different peer, and discovery re-points. That is exactly
+ the property §10 exists to provide, and it would be lost if routes lived in
+ static platform config.
+
+The bundle stays the authority (what may be served), and the agent supplies only
+liveness and a port. An agent that declares nothing serves nothing.
+
+Still to fix before this is built: whether an agent may re-register under a
+changed port (flapping needs a rate limit), and whether `sam-box` should probe
+the port before advertising rather than trusting the agent's claim.
### 11.2 The reverse channel