Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sam-box: serve the sandbox boundary from the command line
Antonio Ojeab6ce1cd7cea9
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.goindex d87e811b..4bab191a 100644--- a/cmd/sam-box/main.go+++ b/cmd/sam-box/main.go@@ -87,6 +87,11 @@ var (udsPathFlag stringsecretsFileFlag stringinterceptorsDirFlag string++ // sandbox boundary flags+ sandboxSocketFlag string+ sidecarSocketFlag string+ egressAllowFlag []string)var logger = golog.Logger("sam-box-cli")@@ -520,6 +525,61 @@ func main() {},}+ // sandboxCmd is the shape sam-box is moving to: no libp2p host, no+ // enrollment, no identity of its own. It is a client of the local+ // sam-node's socket and a server to the sandbox, and nothing else.+ sandboxCmd := &cobra.Command{+ Use: "sandbox",+ Short: "Serve the sandbox boundary for an agent",+ Long: "Serves SOCKS5 on a sandbox-facing Unix socket, so an unmodified agent\n" ++ "reaches mesh inference and tools by name, and reaches nothing else\n" ++ "unless egress policy allows it.",+ Run: func(cmd *cobra.Command, args []string) {+ golog.SetAllLoggers(golog.LevelInfo)+ if logLevelFlag != "" {+ if lvl, err := golog.LevelFromString(logLevelFlag); err == nil {+ golog.SetAllLoggers(lvl)+ }+ }++ if sandboxSocketFlag == "" {+ logger.Fatal("missing required flag: --socket")+ }+ if sidecarSocketFlag == "" {+ logger.Fatal("missing required flag: --sidecar-socket")+ }++ egress, err := sambox.NewEgressPolicy(egressAllowFlag)+ if err != nil {+ logger.Fatalf("Invalid egress policy: %v", err)+ }++ listener, err := sambox.ListenSandboxSocket(sandboxSocketFlag)+ if err != nil {+ logger.Fatalf("Failed to serve the sandbox boundary: %v", err)+ }+ defer func() {+ _ = listener.Close()+ _ = os.Remove(sandboxSocketFlag)+ }()++ server := &sambox.SOCKS5Server{+ Dialer: &sambox.AgentDialer{+ Router: &sambox.Router{Egress: egress},+ SidecarSocket: sidecarSocketFlag,+ },+ }++ logger.Infof("Sandbox boundary listening on %s, node at %s", sandboxSocketFlag, sidecarSocketFlag)+ logger.Infof("Agents reach the mesh at http://%s; %d egress destination(s) allowed", api.MeshEntrypointHost, len(egressAllowFlag))++ if err := server.Serve(cmd.Context(), listener); err != nil {+ logger.Fatalf("Sandbox boundary error: %v", err)+ }+ logger.Info("Sandbox boundary stopped")+ },+ }+// Register flagsrunCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")runCmd.Flags().StringVar(&jwtFlag, "jwt", "", "Pre-fetched JWT token")@@ -547,6 +607,11 @@ func main() {runCmd.Flags().StringVarP(&secretsFileFlag, "secrets-file", "s", "", "Path to the YAML file containing secrets configuration")runCmd.Flags().StringVar(&interceptorsDirFlag, "interceptors-dir", "", "Path to the directory containing precompiled libinterceptor.so binaries")+ sandboxCmd.Flags().StringVar(&sandboxSocketFlag, "socket", "", "Path to the sandbox-facing Unix socket to serve SOCKS5 on")+ sandboxCmd.Flags().StringVar(&sidecarSocketFlag, "sidecar-socket", "", "Path to the local sam-node API Unix socket")+ sandboxCmd.Flags().StringSliceVar(&egressAllowFlag, "egress-allow", nil, "Destinations outside the mesh an agent may reach, e.g. api.github.com or *.pypi.org (default: none)")+ sandboxCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")+joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")joinCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")@@ -564,6 +629,7 @@ func main() {rootCmd.AddCommand(runCmd)rootCmd.AddCommand(joinCmd)+ rootCmd.AddCommand(sandboxCmd)ctx, cancel := context.WithCancel(context.Background())defer cancel()diff --git a/internal/sambox/listen.go b/internal/sambox/listen.gonew file mode 100644index 00000000..60fd765a--- /dev/null+++ b/internal/sambox/listen.go@@ -0,0 +1,69 @@+// 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 (+ "fmt"+ "net"+ "os"+ "path/filepath"+ "time"+)++// maxUnixPathLen is the kernel's sun_path budget. Overflowing it only yields+// "invalid argument" from bind(2), which is not a useful thing to hand an+// operator.+const maxUnixPathLen = 104++// ListenSandboxSocket binds the sandbox-facing socket. A socket left behind by+// a crashed gateway is replaced; one a live gateway is still answering on is+// not.+//+// The socket is created 0600. For a microVM that is exactly right, since+// firecracker connects to it as the same user. For a container whose sandbox+// runs as a different uid, the platform has to align ownership when it creates+// the sandbox — which is where per-agent sockets will be created once admission+// exists, and the only place that knows which uid to use.+func ListenSandboxSocket(path string) (net.Listener, error) {+ if len(path) >= maxUnixPathLen {+ return nil, fmt.Errorf("socket path %q is too long (%d bytes, the kernel allows %d)", path, len(path), maxUnixPathLen-1)+ }+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {+ return nil, fmt.Errorf("creating the socket directory: %w", err)+ }++ if info, err := os.Stat(path); err == nil {+ if info.Mode()&os.ModeSocket == 0 {+ return nil, fmt.Errorf("%s already exists and is not a socket", path)+ }+ if conn, err := net.DialTimeout("unix", path, time.Second); err == nil {+ _ = conn.Close()+ return nil, fmt.Errorf("another gateway is already listening on %s", path)+ }+ if err := os.Remove(path); err != nil {+ return nil, fmt.Errorf("removing the stale socket %s: %w", path, err)+ }+ }++ listener, err := net.Listen("unix", path)+ if err != nil {+ return nil, fmt.Errorf("listening on %s: %w", path, err)+ }+ if err := os.Chmod(path, 0600); err != nil {+ _ = listener.Close()+ return nil, fmt.Errorf("restricting access to %s: %w", path, err)+ }+ return listener, nil+}diff --git a/internal/sambox/listen_test.go b/internal/sambox/listen_test.gonew file mode 100644index 00000000..809e32be--- /dev/null+++ b/internal/sambox/listen_test.go@@ -0,0 +1,126 @@+// 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"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func tempSocketPath(t *testing.T, name string) string {+ t.Helper()+ dir, err := os.MkdirTemp("", "sambox")+ if err != nil {+ t.Fatalf("MkdirTemp: %v", err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(dir) })+ return filepath.Join(dir, name)+}++func TestListenSandboxSocketIsPrivate(t *testing.T) {+ path := tempSocketPath(t, "agent.sock")++ l, err := ListenSandboxSocket(path)+ if err != nil {+ t.Fatalf("ListenSandboxSocket: %v", err)+ }+ defer func() { _ = l.Close() }()++ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("Stat: %v", err)+ }+ if perm := info.Mode().Perm(); perm != 0600 {+ t.Errorf("socket mode = %o, want 600", perm)+ }+}++// TestListenSandboxSocketReplacesAStaleSocket covers the restart case: a+// gateway that crashed leaves the file behind, and refusing to start would turn+// one crash into a permanent outage.+func TestListenSandboxSocketReplacesAStaleSocket(t *testing.T) {+ path := tempSocketPath(t, "agent.sock")++ first, err := ListenSandboxSocket(path)+ if err != nil {+ t.Fatalf("first listen: %v", err)+ }+ if err := first.Close(); err != nil {+ t.Fatalf("close: %v", err)+ }+ // Closing a Unix listener removes the file, so put it back to model the+ // crash that never got to clean up.+ stale, err := net.Listen("unix", path)+ if err != nil {+ t.Fatalf("recreate socket: %v", err)+ }+ stale.(*net.UnixListener).SetUnlinkOnClose(false)+ if err := stale.Close(); err != nil {+ t.Fatalf("close stale: %v", err)+ }++ second, err := ListenSandboxSocket(path)+ if err != nil {+ t.Fatalf("ListenSandboxSocket over a stale socket: %v", err)+ }+ _ = second.Close()+}++// TestListenSandboxSocketRefusesALiveGateway is the other half: replacing a+// socket somebody is still answering on would silently steal their agents.+func TestListenSandboxSocketRefusesALiveGateway(t *testing.T) {+ path := tempSocketPath(t, "agent.sock")++ live, err := ListenSandboxSocket(path)+ if err != nil {+ t.Fatalf("first listen: %v", err)+ }+ defer func() { _ = live.Close() }()+ go func() {+ for {+ conn, err := live.Accept()+ if err != nil {+ return+ }+ _ = conn.Close()+ }+ }()++ if _, err := ListenSandboxSocket(path); err == nil {+ t.Fatal("ListenSandboxSocket replaced a live gateway, want an error")+ }+}++func TestListenSandboxSocketRejectsBadPaths(t *testing.T) {+ t.Run("not a socket", func(t *testing.T) {+ path := tempSocketPath(t, "agent.sock")+ if err := os.WriteFile(path, []byte("not a socket"), 0600); err != nil {+ t.Fatalf("WriteFile: %v", err)+ }+ if _, err := ListenSandboxSocket(path); err == nil {+ t.Fatal("ListenSandboxSocket accepted a regular file, want an error")+ }+ })++ t.Run("too long for the kernel", func(t *testing.T) {+ path := tempSocketPath(t, strings.Repeat("a", 120)+".sock")+ if _, err := ListenSandboxSocket(path); err == nil {+ t.Fatal("ListenSandboxSocket accepted an over-long path, want an error")+ }+ })+}