Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sambox: open the connection a route calls for
Antonio Ojea94f7f96ebfc8
diff --git a/internal/sambox/dial.go b/internal/sambox/dial.gonew file mode 100644index 00000000..0c995f6a--- /dev/null+++ b/internal/sambox/dial.go@@ -0,0 +1,111 @@+// 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"+ "errors"+ "fmt"+ "net"+ "syscall"+ "time"+)++// dialTimeout bounds opening a destination. The SOCKS5 layer deliberately drops+// its handshake deadline before dialling, so this is the only bound and it has+// to exist here.+const dialTimeout = 30 * time.Second++// AgentDialer opens whatever a Route calls for. It is the only place in the+// sandbox boundary that touches the network, which keeps the routing decision+// (route.go) and the protocol (socks5.go) free of I/O.+type AgentDialer struct {+ // Router classifies destinations. Required.+ 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.+ SidecarSocket string++ // 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)+}++// DialDestination implements Dialer.+func (d *AgentDialer) DialDestination(ctx context.Context, _ *Credentials, dst Destination) (net.Conn, error) {+ if d.Router == nil {+ return nil, errors.New("sambox: AgentDialer requires a Router")+ }++ route, err := d.Router.Route(dst)+ if err != nil {+ return nil, err+ }++ ctx, cancel := context.WithTimeout(ctx, dialTimeout)+ defer cancel()++ switch route.Kind {+ case RouteLocalNode:+ return d.dial(ctx, "unix", d.SidecarSocket)+ case 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)+ default:+ return nil, fmt.Errorf("sambox: unhandled route %v", route.Kind)+ }+}++func (d *AgentDialer) dial(ctx context.Context, network, address string) (net.Conn, error) {+ if address == "" {+ return nil, fmt.Errorf("sambox: no %s address configured", network)+ }++ dial := d.DialContext+ if dial == nil {+ dial = (&net.Dialer{}).DialContext+ }++ conn, err := dial(ctx, network, address)+ if err != nil {+ return nil, classifyDialError(err)+ }+ return conn, nil+}++// classifyDialError maps a dial failure onto the vocabulary the SOCKS5 layer+// can report, so an agent sees "refused" or "unreachable" rather than a+// generic failure it cannot act on.+func classifyDialError(err error) error {+ var dnsErr *net.DNSError+ switch {+ case errors.Is(err, syscall.ECONNREFUSED):+ return fmt.Errorf("%w: %v", ErrConnectionRefused, err)+ case errors.As(err, &dnsErr),+ errors.Is(err, syscall.EHOSTUNREACH),+ errors.Is(err, syscall.ENETUNREACH):+ return fmt.Errorf("%w: %v", ErrHostUnreachable, err)+ default:+ return err+ }+}diff --git a/internal/sambox/dial_test.go b/internal/sambox/dial_test.gonew file mode 100644index 00000000..7cf432ae--- /dev/null+++ b/internal/sambox/dial_test.go@@ -0,0 +1,215 @@+// 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"+ "errors"+ "io"+ "net"+ "os"+ "path/filepath"+ "testing"++ "golang.org/x/net/proxy"+)++// 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()+ l, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen: %v", err)+ }+ addr := l.Addr().String()+ if err := l.Close(); err != nil {+ t.Fatalf("close: %v", err)+ }+ return addr+}++func mustEgressPolicy(t *testing.T, allow ...string) *EgressPolicy {+ t.Helper()+ p, err := NewEgressPolicy(allow)+ if err != nil {+ t.Fatalf("NewEgressPolicy: %v", err)+ }+ 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),+ }++ echo := startEcho(t)+ host, port, err := net.SplitHostPort(echo)+ if err != nil {+ t.Fatalf("SplitHostPort: %v", err)+ }+ dst := Destination{Name: host, Port: atoiPort(t, port)}++ conn, err := d.DialDestination(context.Background(), nil, dst)+ if err != nil {+ t.Fatalf("allowlisted destination was refused: %v", err)+ }+ _ = conn.Close()++ denied := Destination{Name: "evil.example", Port: 443, IsName: true}+ if _, err := d.DialDestination(context.Background(), nil, denied); !errors.Is(err, ErrNotAllowed) {+ t.Errorf("DialDestination(%s) = %v, want ErrNotAllowed", denied, err)+ }+}++// TestRefusedDestinationIsReportedAsRefused pins the error mapping: an agent+// should be able to tell "nothing is listening" from "you may not go there".+func TestRefusedDestinationIsReportedAsRefused(t *testing.T) {+ closed := closedTCPAddr(t)+ host, port, err := net.SplitHostPort(closed)+ if err != nil {+ t.Fatalf("SplitHostPort: %v", err)+ }++ d := &AgentDialer{Router: &Router{Egress: mustEgressPolicy(t, host)}}++ _, err = d.DialDestination(context.Background(), nil, Destination{Name: host, Port: atoiPort(t, port)})+ if !errors.Is(err, ErrConnectionRefused) {+ t.Fatalf("DialDestination to a closed port = %v, want ErrConnectionRefused", err)+ }+ if code := replyCodeFor(err); code != replyConnectionRefused {+ t.Errorf("reply code = %#x, want %#x", code, replyConnectionRefused)+ }+}++func TestUnresolvableDestinationIsReportedAsUnreachable(t *testing.T) {+ d := &AgentDialer{Router: &Router{Egress: mustEgressPolicy(t, "*.invalid")}}++ _, err := d.DialDestination(context.Background(), nil, Destination{+ Name: "nothing.here.invalid",+ Port: 443,+ IsName: true,+ })+ if !errors.Is(err, ErrHostUnreachable) {+ t.Fatalf("DialDestination to an unresolvable name = %v, want ErrHostUnreachable", err)+ }+}++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 {+ t.Fatal("DialDestination with no router succeeded, want an error")+ }+}++func atoiPort(t *testing.T, port string) uint16 {+ t.Helper()+ addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort("127.0.0.1", port))+ if err != nil {+ t.Fatalf("ResolveTCPAddr: %v", err)+ }+ return uint16(addr.Port)+}