Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: reach a named mesh service through the sidecar
Antonio Ojea731c25bc9b52
diff --git a/internal/sambox/dial.go b/internal/sambox/dial.goindex 0c995f6a..91d94c20 100644--- a/internal/sambox/dial.go+++ b/internal/sambox/dial.go@@ -66,11 +66,7 @@ func (d *AgentDialer) DialDestination(ctx context.Context, _ *Credentials, dst Dcase RouteExternal:return d.dial(ctx, "tcp", dst.Address())case RouteMeshService:- // Reaching a named service means discovering a provider and rewriting- // onto the sidecar's /sam/<peer>/<type>/<name> path, which is an- // HTTP-level operation rather than a byte pipe. Until that lands, an- // agent reaches the mesh through node.sam.alt.- return nil, fmt.Errorf("mesh service routing is not wired yet: %s", route.ServiceURI)+ return d.dialMeshService(ctx, route)default:return nil, fmt.Errorf("sambox: unhandled route %v", route.Kind)}diff --git a/internal/sambox/mesh.go b/internal/sambox/mesh.gonew file mode 100644index 00000000..23cb204c--- /dev/null+++ b/internal/sambox/mesh.go@@ -0,0 +1,173 @@+// 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"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httputil"+ "net/url"+ "sync"+ "time"++ "github.com/google/sam/api"+)++// Reaching a named mesh service is the one destination that is not a byte pipe.+// The agent speaks HTTP to "openrouter.inference.sam.alt", while the sidecar+// routes by path, so somebody has to discover a provider and rewrite the+// request onto /sam/<peer>/<type>/<name>. That happens here, on an in-process+// HTTP server whose other end is handed back to the SOCKS5 layer as an ordinary+// connection.++const (+ // maxDiscoverBody bounds the discovery response. It is small and local, but+ // it is still parsed input and gets a limit like any other.+ maxDiscoverBody = 1 << 20++ // sidecarHost is a placeholder authority: the transport dials the Unix+ // socket, so the host in the URL is never resolved.+ sidecarHost = "sam-node"+)++// dialMeshService resolves the service to a provider and returns a connection+// that carries the agent's HTTP through to it.+func (d *AgentDialer) dialMeshService(ctx context.Context, route Route) (net.Conn, error) {+ if d.SidecarSocket == "" {+ return nil, fmt.Errorf("sambox: no sidecar socket configured")+ }++ svcType, svcName := api.ParseServiceTarget(route.ServiceURI)+ peerID, err := d.discoverProvider(ctx, svcType, svcName)+ if err != nil {+ return nil, err+ }++ transport := d.sidecarTransport()+ prefix := "/sam/" + peerID + "/" + svcType + "/" + svcName++ proxy := &httputil.ReverseProxy{+ Rewrite: func(r *httputil.ProxyRequest) {+ r.Out.URL.Scheme = "http"+ r.Out.URL.Host = sidecarHost+ r.Out.Host = sidecarHost+ r.Out.URL.Path = prefix + r.In.URL.Path+ r.Out.URL.RawPath = ""+ },+ Transport: transport,+ }++ agentSide, boundarySide := net.Pipe()+ server := &http.Server{+ Handler: proxy,+ // Mirrors the sidecar: bound header reads, but let bodies and responses+ // stream, since inference completions and MCP sessions legitimately do.+ ReadHeaderTimeout: 10 * time.Second,+ IdleTimeout: 120 * time.Second,+ }+ go func() {+ _ = server.Serve(newSingleConnListener(boundarySide))+ }()++ return agentSide, nil+}++// 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.+func (d *AgentDialer) discoverProvider(ctx context.Context, svcType, svcName string) (string, error) {+ endpoint := (&url.URL{+ Scheme: "http",+ Host: sidecarHost,+ Path: "/sam/service/discover",+ RawQuery: url.Values{"type": {svcType}, "name": {svcName}}.Encode(),+ }).String()++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return "", err+ }++ // No credential: reaching the sidecar's Unix socket is itself the proof of+ // authorization, which is why sam-box holds no sidecar token.+ resp, err := (&http.Client{Transport: d.sidecarTransport()}).Do(req)+ if err != nil {+ return "", fmt.Errorf("%w: discovery failed: %v", ErrHostUnreachable, err)+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("%w: discovery returned %s", ErrHostUnreachable, resp.Status)+ }++ var providers []*api.DiscoveredProvider+ if err := json.NewDecoder(io.LimitReader(resp.Body, maxDiscoverBody)).Decode(&providers); err != nil {+ return "", fmt.Errorf("%w: malformed discovery response: %v", ErrHostUnreachable, err)+ }+ for _, p := range providers {+ if p.GetPeerId() != "" {+ // The sidecar already scores and orders providers; taking the first+ // keeps that decision in one place.+ return p.GetPeerId(), nil+ }+ }+ return "", fmt.Errorf("%w: no provider for %s://%s", ErrHostUnreachable, svcType, svcName)+}++func (d *AgentDialer) sidecarTransport() http.RoundTripper {+ socket := d.SidecarSocket+ return &http.Transport{+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {+ return (&net.Dialer{}).DialContext(ctx, "unix", socket)+ },+ }+}++// singleConnListener hands one already-established connection to an+// http.Server and then blocks, so the server lives exactly as long as the+// agent's connection does.+type singleConnListener struct {+ conn net.Conn++ accept sync.Once+ closing sync.Once+ closed chan struct{}+}++func newSingleConnListener(conn net.Conn) *singleConnListener {+ return &singleConnListener{conn: conn, closed: make(chan struct{})}+}++func (l *singleConnListener) Accept() (net.Conn, error) {+ var conn net.Conn+ l.accept.Do(func() { conn = l.conn })+ if conn != nil {+ return conn, nil+ }+ <-l.closed+ return nil, net.ErrClosed+}++func (l *singleConnListener) Close() error {+ l.closing.Do(func() { close(l.closed) })+ return nil+}++func (l *singleConnListener) Addr() net.Addr { return l.conn.LocalAddr() }diff --git a/internal/sambox/mesh_test.go b/internal/sambox/mesh_test.gonew file mode 100644index 00000000..2bd68656--- /dev/null+++ b/internal/sambox/mesh_test.go@@ -0,0 +1,191 @@+// 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"+ "errors"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/google/sam/api"+)++// startFakeSidecar serves the two endpoints sam-box uses on a Unix socket:+// service discovery, and the egress proxy path it rewrites onto.+func startFakeSidecar(t *testing.T, h http.Handler) 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)+ }++ srv := httptest.NewUnstartedServer(h)+ _ = srv.Listener.Close()+ srv.Listener = l+ srv.Start()+ t.Cleanup(srv.Close)++ return path+}++func discoverHandler(t *testing.T, peerID string, seen *chan string) http.Handler {+ t.Helper()+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/sam/service/discover":+ providers := []*api.DiscoveredProvider{}+ if peerID != "" {+ providers = append(providers, &api.DiscoveredProvider{+ PeerId: peerID,+ SrvName: r.URL.Query().Get("name"),+ })+ }+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(providers); err != nil {+ t.Errorf("encode providers: %v", err)+ }+ default:+ if seen != nil {+ select {+ case *seen <- r.URL.Path:+ default:+ }+ }+ _, _ = io.WriteString(w, "reached")+ }+ })+}++// clientOver speaks HTTP over an already-established connection, the way an+// agent's HTTP client speaks over the connection SOCKS5 handed it.+func clientOver(conn net.Conn) *http.Client {+ return &http.Client{+ Transport: &http.Transport{+ DialContext: func(context.Context, string, string) (net.Conn, error) { return conn, nil },+ },+ }+}++// TestMeshServiceRequestIsRewrittenOntoTheSidecarPath is the point of this+// path: a name resolves to a provider, and the agent's request comes out on+// /sam/<peer>/<type>/<name>/<path> without the agent knowing any of it.+func TestMeshServiceRequestIsRewrittenOntoTheSidecarPath(t *testing.T) {+ seen := make(chan string, 1)+ socket := startFakeSidecar(t, discoverHandler(t, "12D3KooWtestpeer", &seen))++ d := &AgentDialer{Router: &Router{}, SidecarSocket: socket}+ conn, err := d.DialDestination(context.Background(), nil, Destination{+ Name: "openrouter.inference.sam.alt",+ Port: 80,+ IsName: true,+ })+ if err != nil {+ t.Fatalf("DialDestination: %v", err)+ }+ defer func() { _ = conn.Close() }()++ resp, err := clientOver(conn).Get("http://openrouter.inference.sam.alt/v1/models")+ if err != nil {+ t.Fatalf("Get: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("status = %s, want 200", resp.Status)+ }++ got := <-seen+ if want := "/sam/12D3KooWtestpeer/inference/openrouter/v1/models"; got != want {+ t.Errorf("sidecar saw %q, want %q", got, want)+ }+}++func TestMeshServiceWithNoProviderIsUnreachable(t *testing.T) {+ socket := startFakeSidecar(t, discoverHandler(t, "", nil))++ d := &AgentDialer{Router: &Router{}, SidecarSocket: socket}+ _, err := d.DialDestination(context.Background(), nil, Destination{+ Name: "missing.mcp.sam.alt",+ Port: 80,+ IsName: true,+ })+ if !errors.Is(err, ErrHostUnreachable) {+ t.Fatalf("DialDestination = %v, want ErrHostUnreachable", err)+ }+ if code := replyCodeFor(err); code != replyHostUnreachable {+ t.Errorf("reply code = %#x, want %#x", code, replyHostUnreachable)+ }+}++// TestMalformedMeshNameIsDeniedNotReportedMissing keeps the two failures+// distinct: a name that cannot be a service is a policy denial, so the boundary+// does not confirm what does or does not exist in the mesh.+func TestMalformedMeshNameIsDeniedNotReportedMissing(t *testing.T) {+ socket := startFakeSidecar(t, discoverHandler(t, "12D3KooWtestpeer", nil))++ d := &AgentDialer{Router: &Router{}, SidecarSocket: socket}+ _, err := d.DialDestination(context.Background(), nil, Destination{+ Name: "whatever.sam.alt",+ Port: 80,+ IsName: true,+ })+ if !errors.Is(err, ErrNotAllowed) {+ t.Fatalf("DialDestination = %v, want ErrNotAllowed", err)+ }+}++func TestMeshServiceRequiresASidecarSocket(t *testing.T) {+ d := &AgentDialer{Router: &Router{}}+ _, err := d.DialDestination(context.Background(), nil, Destination{+ Name: "openrouter.inference.sam.alt",+ Port: 80,+ IsName: true,+ })+ if err == nil {+ t.Fatal("DialDestination with no sidecar socket succeeded, want an error")+ }+}++func TestUnreachableSidecarIsReportedAsUnreachable(t *testing.T) {+ dir, err := os.MkdirTemp("", "sambox")+ if err != nil {+ t.Fatalf("MkdirTemp: %v", err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(dir) })++ d := &AgentDialer{Router: &Router{}, SidecarSocket: filepath.Join(dir, "absent.sock")}+ _, err = d.DialDestination(context.Background(), nil, Destination{+ Name: "openrouter.inference.sam.alt",+ Port: 80,+ IsName: true,+ })+ if !errors.Is(err, ErrHostUnreachable) {+ t.Fatalf("DialDestination = %v, want ErrHostUnreachable", err)+ }+}diff --git a/site/content/docs/agent-architecture.md b/site/content/docs/agent-architecture.mdindex 7e7399f5..9a0e9977 100644--- a/site/content/docs/agent-architecture.md+++ b/site/content/docs/agent-architecture.md@@ -277,12 +277,13 @@ SOCKS5 server; `internal/node` keeps everything mesh.```bashOPENAI_BASE_URL=http://node.sam.alt/v1 # inference, provider chosen by policyMCP_URL=http://node.sam.alt/mcp # tools: local catalog + remote services-SAM_API_TOKEN=<per-sandbox token> # X-Sam-Authentication for the two above```No `HTTP_PROXY`. No CA bundle, unless a domain is explicitly configured for-secret injection. No mesh concepts. `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 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.A harness that wants one specific service instead of policy-chosen routing usesits mesh name directly: `http://code-reviewer.mcp.sam.alt/`.@@ -293,10 +294,18 @@ 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: `/v1/*`, `/mcp` and- `/sam/*` behave exactly as they do over TCP today, including- `X-Sam-Authentication` and the `Authorization` passthrough rules. `sam-box`- injects the sandbox's token only if the request carries none.+ `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.2. **`<service>.<type>.sam.alt`** (`api.ParseMeshHost`) → `sam-box` terminatesHTTP and rewrites onto the sidecar's existing surface:`GET /sam/service/discover?type=<type>&name=<service>` picks a provider, then