Skip to content

Agent Mesh

sam-box: become only the sandbox dataplane

Antonio Ojea4e08647ef824
diff --git a/.github/k8s/sam-box-canary-template.yaml b/.github/k8s/sam-box-canary-template.yaml
index 1e587e2d..e0dc0be4 100644
--- a/.github/k8s/sam-box-canary-template.yaml
+++ b/.github/k8s/sam-box-canary-template.yaml
@@ -11,10 +11,6 @@ data:
checks: []
rules: []
services: []
- secrets.yaml: |
- example.com:
- kind: Bearer
- value: real-upstream-secret-123
---
apiVersion: v1
kind: ServiceAccount
@@ -22,6 +18,12 @@ metadata:
name: sam-box-sa
namespace: sam-canary-${ENV_NAME}
---
+# Canary for the sandbox datapath: an agent holding no credential reaches an
+# allowlisted destination through the boundary, and nothing else.
+#
+# The node enrols and owns the mesh identity; sam-box consumes it over the API
+# socket and serves the sandbox; the agent speaks plain SOCKS5. All that is
+# shared between them is the socket, which is the point of the arrangement.
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -38,39 +40,25 @@ spec:
app: box-canary-${ENV_NAME}
spec:
serviceAccountName: sam-box-sa
- initContainers:
- - name: init-nano-init
- image: ghcr.io/google/sam-nano-init:${IMAGE_TAG}
- command: ["/nano-init", "copy", "/shared-bin/nano-init"]
- volumeMounts:
- - name: shared-bin
- mountPath: /shared-bin
containers:
- - name: agent
- image: alpine/curl:8.12.1
- command:
- - "/shared-bin/nano-init"
- - "run"
- - "/var/run/sam/sam-box.sock"
- - "sh"
- - "-c"
- - "while true; do curl -v -H 'Authorization: Bearer dummy-token' http://example.com/test; sleep 10; done"
- volumeMounts:
- - name: shared-bin
- mountPath: /shared-bin
- - name: sam-uds
- mountPath: /var/run/sam
- - name: sam-box
- image: ghcr.io/google/sam-box:${IMAGE_TAG}
+ - name: sam-node
+ image: ghcr.io/google/sam-node:${IMAGE_TAG}
args:
- "run"
- - "--uds-path=/var/run/sam/sam-box.sock"
- "--config=/etc/sam/sam-node.yaml"
- - "--secrets-file=/etc/sam/secrets.yaml"
- "--control-plane=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
- "--jwt-path=/var/run/secrets/tokens/sam-token"
- - "--allow-loopback"
- - "--log-level=debug"
+ # Socket only: with no TCP listener there is no API token to leak, and
+ # the socket's permissions are the credential.
+ - "--bind-addr="
+ - "--socket-path=/var/run/sam/node.sock"
+ resources:
+ requests:
+ cpu: 50m
+ memory: 64Mi
+ limits:
+ cpu: 200m
+ memory: 256Mi
volumeMounts:
- name: config-volume
mountPath: /etc/sam
@@ -79,9 +67,59 @@ spec:
readOnly: true
- name: sam-uds
mountPath: /var/run/sam
+ - name: sam-box
+ image: ghcr.io/google/sam-box:${IMAGE_TAG}
+ args:
+ - "run"
+ - "--socket=/var/run/sam/agent.sock"
+ - "--sidecar-socket=/var/run/sam/node.sock"
+ - "--egress-allow=example.com"
+ - "--log-level=debug"
+ resources:
+ requests:
+ cpu: 20m
+ memory: 32Mi
+ limits:
+ cpu: 100m
+ memory: 128Mi
+ volumeMounts:
+ - name: sam-uds
+ mountPath: /var/run/sam
+ # Stands in for the tun2socks a real sandbox runs: the boundary is reached
+ # over a socket, and an ordinary client needs a TCP address.
+ - name: socks-bridge
+ image: alpine/socat:1.8.0.0
+ args: ["TCP-LISTEN:1080,fork,reuseaddr", "UNIX-CONNECT:/var/run/sam/agent.sock"]
+ resources:
+ requests:
+ cpu: 10m
+ memory: 16Mi
+ limits:
+ cpu: 50m
+ memory: 64Mi
+ volumeMounts:
+ - name: sam-uds
+ mountPath: /var/run/sam
+ - name: agent
+ image: alpine/curl:8.12.1
+ command:
+ - "sh"
+ - "-c"
+ - |
+ while true; do
+ echo "allowlisted destination (expect 200): $(curl -s -o /dev/null -w '%{http_code}' --socks5-hostname 127.0.0.1:1080 http://example.com/)"
+ echo "the node's own API (expect 403): $(curl -s -o /dev/null -w '%{http_code}' --socks5-hostname 127.0.0.1:1080 http://mesh.sam.alt/sam/service/register)"
+ curl -s -o /dev/null --socks5-hostname 127.0.0.1:1080 http://blocked.example/ && echo "unlisted destination was NOT refused" || echo "unlisted destination refused (expected)"
+ sleep 30
+ done
+ resources:
+ requests:
+ cpu: 10m
+ memory: 16Mi
+ limits:
+ cpu: 50m
+ memory: 64Mi
volumes:
- - name: shared-bin
- emptyDir: {}
- name: sam-uds
emptyDir: {}
- name: config-volume
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.go
index 4bab191a..de04cb92 100644
--- a/cmd/sam-box/main.go
+++ b/cmd/sam-box/main.go
@@ -12,667 +12,105 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// Command sam-box is the sandbox dataplane: one per agent sandbox, serving the
+// boundary an agent's traffic leaves through.
+//
+// It holds no libp2p host, no enrollment and no mesh identity of its own. It
+// consumes a local sam-node over that node's API socket and offers the sandbox
+// a curated surface: mesh inference and tools addressed by name, plus whatever
+// egress policy allows. The node's own API stays on the node's side of the
+// boundary.
package main
import (
"context"
- "crypto/ed25519"
- "encoding/hex"
- "fmt"
- "net"
"os"
"os/signal"
- "strings"
"syscall"
- "time"
- "github.com/google/sam/api"
- "github.com/google/sam/internal/node"
- "github.com/google/sam/internal/sambox"
- "github.com/google/sam/internal/secrets"
golog "github.com/ipfs/go-log/v2"
- "github.com/multiformats/go-multiaddr"
- madns "github.com/multiformats/go-multiaddr-dns"
"github.com/spf13/cobra"
- "gopkg.in/yaml.v2"
-)
-
-func init() {
- if dnsServer := os.Getenv("SAM_TEST_DNS_SERVER"); dnsServer != "" {
- customResolver := &net.Resolver{
- PreferGo: true,
- Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
- d := net.Dialer{Timeout: 5 * time.Second}
- return d.DialContext(ctx, "udp", dnsServer)
- },
- }
- net.DefaultResolver = customResolver
- madns.DefaultResolver, _ = madns.NewResolver(madns.WithDefaultResolver(customResolver))
- }
-}
-var (
- controlPlaneAddr string
- jwtFlag string
- jwtPathFlag string
- bootstrapTokenFlag string
- bootstrapTokenPathFlag string
- clientIDFlag string
- clientSecretFlag string
- clientSecretPathFlag string
- controlPlanePublicKeyFlag string
- meshFlag string
- discoveryIntervalFlag string
- listenAddrs []string
- enableRelayFlag bool
- configFile string
- oidcIssuerFlag string
- deviceAuthURLFlag string
- audienceFlag string
- dataDirFlag string
- headlessFlag bool
- authModeFlag string
- offlineAccessFlag bool
- logLevelFlag string
- keyGracePeriodFlag time.Duration
- allowLoopbackFlag bool
- monitorBootstrapFlag time.Duration
- monitorCheckIntervalFlag time.Duration
- autoRelayMinIntervalFlag time.Duration
- autoRelayBootDelayFlag time.Duration
- autoRelayBackoffFlag time.Duration
- routerConnectTimeoutFlag time.Duration
-
- // sam-box specific flags
- udsPathFlag string
- secretsFileFlag string
- interceptorsDirFlag string
-
- // sandbox boundary flags
- sandboxSocketFlag string
- sidecarSocketFlag string
- egressAllowFlag []string
+ "github.com/google/sam/api"
+ "github.com/google/sam/internal/sambox"
)
-var logger = golog.Logger("sam-box-cli")
-
-// resolveSecretFlag folds a --<name>-path file variant into its value flag
-// and warns when the secret was passed on the command line, where it leaks
-// via /proc/<pid>/cmdline, shell history, and pod specs.
-func resolveSecretFlag(name, value, path string) string {
- if value != "" {
- logger.Warnf("--%s passes a secret on the command line; prefer --%s-path", name, name)
- }
- secret, err := secrets.Resolve(name, value, path)
- if err != nil {
- logger.Fatalf("%v", err)
- }
- return secret
-}
-
-// resolveDaemonSecret resolves a secret that lives for the daemon's whole
-// lifetime: file (recommended) or environment variable, never a flag value.
-func resolveDaemonSecret(name, path, envVar string) string {
- secret, err := secrets.FromPathOrEnv(name, path, envVar)
- if err != nil {
- logger.Fatalf("%v", err)
- }
- return secret
-}
+var logger = golog.Logger("sam-box")
func main() {
+ var (
+ sandboxSocket string
+ sidecarSocket string
+ egressAllow []string
+ logLevel string
+ )
+
rootCmd := &cobra.Command{
Use: "sam-box",
- Short: "Sovereign Agent Mesh Secure Gateway Node",
+ Short: "Sovereign Agent Mesh sandbox gateway",
}
runCmd := &cobra.Command{
Use: "run",
- Short: "Start the secure gateway node",
- Run: func(cmd *cobra.Command, args []string) {
- ctx := cmd.Context()
- golog.SetAllLoggers(golog.LevelInfo)
- if logLevelFlag != "" {
- lvl, err := golog.LevelFromString(logLevelFlag)
- if err == nil {
- golog.SetAllLoggers(lvl)
- }
- }
-
- // Suppress noisy DHT logs
- _ = golog.SetLogLevel("dht", "fatal")
- _ = golog.SetLogLevel("dht/RtRefreshManager", "fatal")
-
- bootstrapTokenFlag = resolveSecretFlag("bootstrap-token", bootstrapTokenFlag, bootstrapTokenPathFlag)
- clientSecretFlag = resolveDaemonSecret("client-secret", clientSecretPathFlag, "SAM_CLIENT_SECRET")
- if jwtFlag != "" {
- logger.Warn("--jwt passes a secret on the command line; prefer --jwt-path")
- }
-
- if udsPathFlag == "" {
- logger.Fatal("missing required flag: --uds-path")
- }
-
- store, err := node.NewStore(resolveDataDir())
- if err != nil {
- logger.Fatalf("Failed to open store: %v", err)
- }
- nodeConfig, err := node.LoadNodeConfig(configFile)
- if err != nil {
- logger.Fatalf("Failed to load node config: %v", err)
- }
- defer func() {
- if err := store.Close(); err != nil {
- logger.Errorf("closing store: %v", err)
- }
- }()
-
- var controlPlanePubKey ed25519.PublicKey
- var routerAddrs []multiaddr.Multiaddr
-
- storedPubKey, syncedAddrs, err := node.SyncMeshConfig(ctx, store)
- if err != nil {
- logger.Warnf("Failed to sync mesh config: %v", err)
- }
- if len(storedPubKey) > 0 {
- controlPlanePubKey = storedPubKey
- routerAddrs = syncedAddrs
- }
-
- if controlPlanePublicKeyFlag != "" {
- pubBytes, err := hex.DecodeString(strings.TrimSpace(controlPlanePublicKeyFlag))
- if err != nil {
- logger.Fatalf("Invalid control plane public key: %v", err)
- }
- controlPlanePubKey = pubBytes
- }
-
- var meshNode *node.SamNode
- var jwtStr string
-
- if jwtFlag != "" {
- jwtStr = jwtFlag
- } else if jwtPathFlag != "" {
- data, err := os.ReadFile(jwtPathFlag)
- if err != nil {
- logger.Fatalf("Failed to read JWT file: %v", err)
- }
- jwtStr = strings.TrimSpace(string(data))
- } else if oidcIssuerFlag != "" {
- logger.Info("Discovering OIDC endpoints...")
- dummyNode := &node.SamNode{}
- tokenURL, err := dummyNode.DiscoverTokenURL(ctx, oidcIssuerFlag)
- if err != nil {
- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
- }
- logger.Info("Fetching JWT via OIDC Client Credentials...")
- jwtStr, err = dummyNode.FetchJWT(ctx, tokenURL, clientIDFlag, clientSecretFlag)
- if err != nil {
- logger.Fatalf("Failed to fetch JWT: %v", err)
- }
- }
-
- if jwtStr == "" && bootstrapTokenFlag == "" {
- token, _ := store.LoadIdentity()
- if len(token) == 0 {
- displayControlPlane := controlPlaneAddr
- if displayControlPlane == "" {
- if h, err := store.LoadControlPlaneURL(); err == nil && h != "" {
- displayControlPlane = h
- }
- }
- logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")
- unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, "127.0.0.1:8080", "", "", "")
- if err != nil {
- logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)
- }
- defer func() {
- _ = unauthSrv.Close()
- }()
- <-ctx.Done()
- return
- }
- logger.Infoln("Using stored identity.")
-
- if len(controlPlanePubKey) == 0 {
- logger.Fatal("Control plane public key not found in store and not provided. Cannot verify peers.")
- }
- priv := node.GetOrGenerateKey(store)
- meshNode, err = node.NewSamNode(node.Options{
- PrivKey: priv,
- ControlPlanePubKey: controlPlanePubKey,
- RouterAddrs: routerAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: listenAddrs,
- EnableRelay: enableRelayFlag,
- NodeConfig: nodeConfig,
- KeyGracePeriod: keyGracePeriodFlag,
- AllowLoopback: allowLoopbackFlag,
- MonitorBootstrap: monitorBootstrapFlag,
- MonitorInterval: monitorCheckIntervalFlag,
- AutoRelayMinInterval: autoRelayMinIntervalFlag,
- AutoRelayBootDelay: autoRelayBootDelayFlag,
- AutoRelayBackoff: autoRelayBackoffFlag,
- RouterConnectTimeout: routerConnectTimeoutFlag,
- RequiredRole: api.RoleSamBox,
- })
- if err != nil {
- logger.Fatalf("Failed to initialize mesh node: %v", err)
- }
- if err := meshNode.Start(ctx); err != nil {
- logger.Fatalf("Failed to start mesh node: %v", err)
- }
- } else {
- // We have a new JWT (from flag or interactive login), need to enroll
- var initRouterAddrs []multiaddr.Multiaddr
- if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {
- ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)
- if err == nil {
- initRouterAddrs = []multiaddr.Multiaddr{ma}
- } else {
- host, port, err := net.SplitHostPort(controlPlaneAddr)
- if err == nil {
- ip := net.ParseIP(host)
- var maddr multiaddr.Multiaddr
- var parseErr error
- if ip != nil {
- maddr, parseErr = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
- } else {
- maddr, parseErr = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
- }
- if parseErr != nil {
- logger.Fatalf("Failed to parse multiaddr: %v", parseErr)
- }
- initRouterAddrs = []multiaddr.Multiaddr{maddr}
- } else {
- logger.Fatalf("Invalid control plane address: %v", err)
- }
- }
- }
-
- priv := node.GetOrGenerateKey(store)
- meshNode, err = node.NewSamNode(node.Options{
- PrivKey: priv,
- RouterAddrs: initRouterAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: listenAddrs,
- EnableRelay: enableRelayFlag,
- NodeConfig: nodeConfig,
- KeyGracePeriod: keyGracePeriodFlag,
- AllowLoopback: allowLoopbackFlag,
- MonitorBootstrap: monitorBootstrapFlag,
- MonitorInterval: monitorCheckIntervalFlag,
- AutoRelayMinInterval: autoRelayMinIntervalFlag,
- AutoRelayBootDelay: autoRelayBootDelayFlag,
- AutoRelayBackoff: autoRelayBackoffFlag,
- RouterConnectTimeout: routerConnectTimeoutFlag,
- RequiredRole: api.RoleSamBox,
- })
- if err != nil {
- logger.Fatalf("Failed to initialize node for enrollment: %v", err)
- }
- if err := meshNode.Start(ctx); err != nil {
- logger.Fatalf("Failed to start node for enrollment: %v", err)
- }
-
- if bootstrapTokenFlag != "" {
- err = meshNode.EnrollBootstrap(ctx, controlPlaneAddr, bootstrapTokenFlag)
- } else {
- err = meshNode.Enroll(ctx, controlPlaneAddr, jwtStr)
- }
- if err != nil {
- logger.Fatalf("Enrollment failed: %v", err)
- }
- if err := store.SaveControlPlaneURL(controlPlaneAddr); err != nil {
- logger.Warnf("Failed to save control plane URL: %v", err)
- }
- logger.Infoln("Successfully enrolled with control plane!")
-
- if len(controlPlanePubKey) == 0 {
- if syncPubKey, _, err := node.SyncMeshConfig(ctx, store); err != nil || len(syncPubKey) == 0 {
- logger.Fatal("Control plane public key not found in store after enrollment.")
- }
- }
- }
-
- // Load secrets config if provided
- secretStore := make(map[string]sambox.SecretConfig)
- if secretsFileFlag != "" {
- s, err := loadSecrets(secretsFileFlag)
- if err != nil {
- logger.Fatalf("Failed to load secrets config: %v", err)
- }
- secretStore = s
- logger.Infof("Loaded %d secrets from %s", len(secretStore), secretsFileFlag)
- }
-
- // Listen on UDS for Secure Outbound Gateway
- if err := os.Remove(udsPathFlag); err != nil && !os.IsNotExist(err) {
- logger.Fatalf("Failed to remove existing UDS file: %v", err)
- }
- listener, err := net.Listen("unix", udsPathFlag)
- if err != nil {
- logger.Fatalf("Failed to listen on UDS socket: %v", err)
- }
- if err := os.Chmod(udsPathFlag, 0600); err != nil {
- logger.Fatalf("Failed to set permissions on UDS socket: %v", err)
- }
- defer func() {
- _ = listener.Close()
- _ = os.Remove(udsPathFlag)
- }()
-
- logger.Infof("Secure Gateway listening on UDS %s", udsPathFlag)
- gateway, err := sambox.NewGateway(secretStore, nil, interceptorsDirFlag)
- if err != nil {
- logger.Fatalf("Failed to initialize gateway: %v", err)
- }
-
- serverErrChan := make(chan error, 1)
- go func() {
- if err := gateway.Serve(listener); err != nil {
- serverErrChan <- err
- }
- }()
-
- select {
- case <-ctx.Done():
- logger.Info("Shutting down Secure Outbound Gateway...")
- _ = listener.Close()
- case err := <-serverErrChan:
- logger.Fatalf("Secure Outbound Gateway server error: %v", err)
- }
- },
- }
-
- joinCmd := &cobra.Command{
- Use: "join",
- Short: "Join the mesh interactively",
- Run: func(cmd *cobra.Command, args []string) {
- ctx := cmd.Context()
- targetControlPlane := controlPlaneAddr
- if targetControlPlane == "" {
- logger.Fatal("join needs a control plane to enroll with: pass --control-plane <url> (e.g. https://bananas.sam-mesh.dev for the public testnet).")
- }
- if !strings.HasPrefix(targetControlPlane, "http://") && !strings.HasPrefix(targetControlPlane, "https://") {
- targetControlPlane = "https://" + targetControlPlane
- }
- targetControlPlane = strings.TrimSuffix(targetControlPlane, "/")
-
- store, err := node.NewStore(resolveDataDir())
- if err != nil {
- logger.Fatalf("Failed to open store: %v", err)
- }
- nodeConfig, err := node.LoadNodeConfig(configFile)
- if err != nil {
- logger.Fatalf("Failed to load node config: %v", err)
- }
- defer func() {
- if err := store.Close(); err != nil {
- logger.Errorf("closing store: %v", err)
- }
- }()
-
- dummyNode := &node.SamNode{Store: store}
- fmt.Printf("Discovering control plane info from %s...\n", targetControlPlane)
- controlPlaneInfo, err := node.FetchControlPlaneInfo(ctx, targetControlPlane)
- if err != nil {
- logger.Fatalf("Failed to discover control plane info: %v", err)
- }
-
- var jwtStr string
- if bootstrapTokenFlag == "" {
- fmt.Printf("OIDC Issuer discovered: %s\n", controlPlaneInfo.OidcIssuer)
- fmt.Printf("Client ID discovered: %s\n", controlPlaneInfo.ClientId)
-
- logger.Info("Discovering OIDC endpoints...")
- endpoints, err := dummyNode.DiscoverEndpointsWithDevice(ctx, controlPlaneInfo.OidcIssuer)
- if err != nil {
- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
- }
- deviceAuthURL := endpoints.DeviceAuthURL
- if deviceAuthURLFlag != "" {
- deviceAuthURL = deviceAuthURLFlag
- }
-
- mode, err := node.ParseAuthMode(authModeFlag)
- if err != nil {
- logger.Fatalf("Invalid --auth-mode: %v", err)
- }
-
- jwtStr, err = dummyNode.InteractiveLoginWithMode(ctx, endpoints.AuthURL, endpoints.TokenURL, deviceAuthURL, controlPlaneInfo.ClientId, controlPlaneInfo.Audience, offlineAccessFlag, headlessFlag, mode)
- if err != nil {
- logger.Fatalf("Failed to get token: %v", err)
- }
- }
-
- controlPlaneAddr = targetControlPlane
- var initRouterAddrs []multiaddr.Multiaddr
- if !strings.HasPrefix(controlPlaneAddr, "http://") && !strings.HasPrefix(controlPlaneAddr, "https://") {
- ma, err := multiaddr.NewMultiaddr(controlPlaneAddr)
- if err == nil {
- initRouterAddrs = []multiaddr.Multiaddr{ma}
- } else {
- host, port, err := net.SplitHostPort(controlPlaneAddr)
- if err == nil {
- ip := net.ParseIP(host)
- var maddr multiaddr.Multiaddr
- var parseErr error
- if ip != nil {
- maddr, parseErr = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
- } else {
- maddr, parseErr = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
- }
- if parseErr != nil {
- logger.Fatalf("Failed to parse multiaddr: %v", parseErr)
- }
- initRouterAddrs = []multiaddr.Multiaddr{maddr}
- } else {
- logger.Fatalf("Invalid control plane address: %v", err)
- }
- }
- }
-
- priv := node.GetOrGenerateKey(store)
- meshNode, err := node.NewSamNode(node.Options{
- PrivKey: priv,
- RouterAddrs: initRouterAddrs,
- Store: store,
- MeshID: meshFlag,
- DiscoveryInterval: discoveryIntervalFlag,
- ListenAddrs: []string{"/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/tcp/0"},
- EnableRelay: enableRelayFlag,
- NodeConfig: nodeConfig,
- KeyGracePeriod: keyGracePeriodFlag,
- AllowLoopback: allowLoopbackFlag,
- MonitorBootstrap: 2 * time.Minute,
- MonitorInterval: 1 * time.Minute,
- AutoRelayMinInterval: 30 * time.Second,
- AutoRelayBootDelay: 0 * time.Second,
- AutoRelayBackoff: 3 * time.Second,
- RouterConnectTimeout: routerConnectTimeoutFlag,
- RequiredRole: api.RoleSamBox,
- })
- if err != nil {
- logger.Fatalf("Failed to initialize node for enrollment: %v", err)
- }
- if err := meshNode.Start(ctx); err != nil {
- logger.Fatalf("Failed to start node for enrollment: %v", err)
- }
-
- if bootstrapTokenFlag != "" {
- err = meshNode.EnrollBootstrap(ctx, targetControlPlane, bootstrapTokenFlag)
- } else {
- err = meshNode.Enroll(ctx, targetControlPlane, jwtStr)
- }
- if err != nil {
- logger.Fatalf("Enrollment failed: %v", err)
- }
- if err := store.SaveControlPlaneURL(targetControlPlane); err != nil {
- logger.Warnf("Failed to save control plane URL: %v", err)
- }
- if bootstrapTokenFlag == "" {
- if err := store.SaveOIDCConfig(controlPlaneInfo.OidcIssuer, controlPlaneInfo.ClientId, controlPlaneInfo.Audience); err != nil {
- logger.Warnf("Failed to save OIDC config: %v", err)
- }
- }
-
- fmt.Println("Successfully joined the Sovereign Agent Mesh!")
- },
- }
-
- // 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) {
+ Long: "Serves SOCKS5 on a sandbox-facing Unix socket, so an unmodified agent reaches\n" +
+ "mesh inference and tools by name, and reaches nothing else unless egress policy\n" +
+ "allows it.",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
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")
+ if lvl, err := golog.LevelFromString(logLevel); err == nil {
+ golog.SetAllLoggers(lvl)
}
- egress, err := sambox.NewEgressPolicy(egressAllowFlag)
+ egress, err := sambox.NewEgressPolicy(egressAllow)
if err != nil {
- logger.Fatalf("Invalid egress policy: %v", err)
+ return err
}
- listener, err := sambox.ListenSandboxSocket(sandboxSocketFlag)
+ listener, err := sambox.ListenSandboxSocket(sandboxSocket)
if err != nil {
- logger.Fatalf("Failed to serve the sandbox boundary: %v", err)
+ return err
}
defer func() {
_ = listener.Close()
- _ = os.Remove(sandboxSocketFlag)
+ _ = os.Remove(sandboxSocket)
}()
server := &sambox.SOCKS5Server{
Dialer: &sambox.AgentDialer{
Router: &sambox.Router{Egress: egress},
- SidecarSocket: sidecarSocketFlag,
+ SidecarSocket: sidecarSocket,
},
}
- 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))
+ logger.Infof("Sandbox boundary listening on %s, node at %s", sandboxSocket, sidecarSocket)
+ logger.Infof("Agents reach the mesh at http://%s; %d egress destination(s) allowed", api.MeshEntrypointHost, len(egressAllow))
if err := server.Serve(cmd.Context(), listener); err != nil {
- logger.Fatalf("Sandbox boundary error: %v", err)
+ return err
}
logger.Info("Sandbox boundary stopped")
+ return nil
},
}
- // Register flags
- runCmd.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")
- runCmd.Flags().StringVar(&jwtPathFlag, "jwt-path", "", "Path to file containing JWT token")
- runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
- runCmd.Flags().StringVar(&bootstrapTokenPathFlag, "bootstrap-token-path", "", "Path to file containing the bootstrap token (recommended over --bootstrap-token)")
- runCmd.Flags().StringVar(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")
- runCmd.Flags().StringVar(&clientSecretPathFlag, "client-secret-path", "", "Path to file containing the OIDC client secret (or env SAM_CLIENT_SECRET)")
- runCmd.Flags().StringVar(&controlPlanePublicKeyFlag, "control-plane-public-key", "", "Control plane public key (32-byte Hex)")
- runCmd.Flags().StringVar(&meshFlag, "mesh", node.DefaultMeshName, "Mesh federation name")
- runCmd.Flags().StringVar(&discoveryIntervalFlag, "discovery-interval", node.DefaultDiscoveryInterval, "Polling interval for DHT discovery")
- runCmd.Flags().DurationVar(&monitorBootstrapFlag, "monitor-bootstrap", 2*time.Minute, "Initial wait before monitoring router connection")
- runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking router connection")
- runCmd.Flags().DurationVar(&autoRelayMinIntervalFlag, "autorelay-min-interval", 30*time.Second, "AutoRelay Min Interval")
- runCmd.Flags().DurationVar(&autoRelayBootDelayFlag, "autorelay-boot-delay", 0*time.Second, "AutoRelay Boot Delay")
- runCmd.Flags().DurationVar(&autoRelayBackoffFlag, "autorelay-backoff", 3*time.Second, "AutoRelay Backoff")
- runCmd.Flags().DurationVar(&routerConnectTimeoutFlag, "router-connect-timeout", node.DefaultRouterConnectTimeout, "Timeout for dialing each router address")
- runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")
- runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")
- runCmd.Flags().DurationVar(&keyGracePeriodFlag, "key-grace-period", 24*time.Hour, "Key grace period for old keys (e.g. 24h)")
- runCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")
-
- // sam-box specific flags
- runCmd.Flags().StringVarP(&udsPathFlag, "uds-path", "u", "", "Path to the Unix Domain Socket to listen on")
- 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")
- joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
- joinCmd.Flags().StringVar(&bootstrapTokenPathFlag, "bootstrap-token-path", "", "Path to file containing the bootstrap token (recommended over --bootstrap-token)")
-
- rootCmd.PersistentFlags().StringVar(&controlPlaneAddr, "control-plane", "", "Control plane URL")
- rootCmd.PersistentFlags().StringVar(&configFile, "config", node.DefaultConfigFile, "Path to sam-node.yaml configuration file")
- rootCmd.PersistentFlags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC Issuer URL")
- rootCmd.PersistentFlags().StringVar(&deviceAuthURLFlag, "device-auth-url", "", "OIDC Device Authorization URL")
- rootCmd.PersistentFlags().StringVar(&audienceFlag, "audience", api.DefaultAudience, "OIDC Audience")
- rootCmd.PersistentFlags().StringVar(&dataDirFlag, "data-dir", "", "Override directory for the agent store (defaults to OS user config dir)")
- rootCmd.PersistentFlags().BoolVar(&headlessFlag, "headless", false, "Force headless out-of-band (OOB) authentication flow")
- rootCmd.PersistentFlags().StringVar(&authModeFlag, "auth-mode", "auto", "Interactive enrollment auth mode: auto, device, oob, or browser")
+ runCmd.Flags().StringVar(&sandboxSocket, "socket", "", "Path to the sandbox-facing Unix socket to serve SOCKS5 on (required)")
+ runCmd.Flags().StringVar(&sidecarSocket, "sidecar-socket", "", "Path to the local sam-node API Unix socket (required)")
+ runCmd.Flags().StringSliceVar(&egressAllow, "egress-allow", nil, "Destinations outside the mesh an agent may reach, e.g. api.github.com or *.pypi.org (default: none)")
+ runCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")
+ for _, required := range []string{"socket", "sidecar-socket"} {
+ if err := runCmd.MarkFlagRequired(required); err != nil {
+ panic(err)
+ }
+ }
rootCmd.AddCommand(runCmd)
- rootCmd.AddCommand(joinCmd)
- rootCmd.AddCommand(sandboxCmd)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
-
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
- go func() {
- <-sigChan
- fmt.Println("\n[Signal] Received interrupt, shutting down...")
- cancel()
- signal.Stop(sigChan)
- }()
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
if err := rootCmd.ExecuteContext(ctx); err != nil {
- os.Exit(1)
- }
-}
-
-func resolveDataDir() string {
- var dir string
- if dataDirFlag != "" {
- dir = dataDirFlag
- } else {
- d, err := node.GetDefaultDataDir()
- if err != nil {
- logger.Fatalf("Failed to get default data directory: %v", err)
- }
- dir = d
- }
- if err := os.MkdirAll(dir, 0700); err != nil {
- logger.Fatalf("Failed to create data directory: %v", err)
- }
- return dir
-}
-
-func loadSecrets(path string) (map[string]sambox.SecretConfig, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return nil, err
- }
- var store map[string]sambox.SecretConfig
- if err := yaml.Unmarshal(data, &store); err != nil {
- return nil, err
+ logger.Fatalf("%v", err)
}
- return store, nil
}
diff --git a/scripts/launch-microvms.sh b/scripts/launch-microvms.sh
index 674055e0..d16b4b2e 100755
--- a/scripts/launch-microvms.sh
+++ b/scripts/launch-microvms.sh
@@ -12,16 +12,27 @@ fi
echo "=== Launching $COUNT MicroVMs ==="
for i in $(seq 1 $COUNT); do
VM_ID="vm-$i"
- UDS_PATH="/var/run/sam-box-$VM_ID.sock"
+ # Firecracker's vsock device multiplexes guest->host connections onto
+ # "<uds_path>_<port>", so the boundary has to listen on that exact name for
+ # the guest's connections to CID 2 port 1080 to arrive.
+ VSOCK_UDS="/var/run/sam-$VM_ID.vsock"
+ BOUNDARY_UDS="${VSOCK_UDS}_1080"
+ NODE_UDS="/var/run/sam-node-$VM_ID.sock"
API_SOCKET="/tmp/firecracker-$VM_ID.socket"
-
+
# Clean up old sockets
- rm -f $UDS_PATH $API_SOCKET
-
- # Start sam-box on the host, listening on a dedicated UDS for this VM
- # The sam-box acts as the gateway to the mesh.
- mkdir -p /tmp/sam-box-$VM_ID
- SAM_API_TOKEN="secret-token" sam-box run -u "$UDS_PATH" --data-dir "/tmp/sam-box-$VM_ID" --control-plane "https://bananas.sam-mesh.dev" --log-level debug > /var/log/sam-box-$VM_ID.log 2>&1 &
+ rm -f $VSOCK_UDS $BOUNDARY_UDS $NODE_UDS $API_SOCKET
+
+ # The node owns the mesh identity; sam-box holds none and simply consumes
+ # the node's API socket on the agent's behalf.
+ mkdir -p /tmp/sam-node-$VM_ID
+ sam-node run --data-dir "/tmp/sam-node-$VM_ID" \
+ --control-plane "https://bananas.sam-mesh.dev" \
+ --bind-addr "" --socket-path "$NODE_UDS" \
+ --log-level debug > /var/log/sam-node-$VM_ID.log 2>&1 &
+
+ sam-box run --socket "$BOUNDARY_UDS" --sidecar-socket "$NODE_UDS" \
+ --log-level debug > /var/log/sam-box-$VM_ID.log 2>&1 &
# Start Firecracker
firecracker --api-sock $API_SOCKET > /var/log/fc-$VM_ID.log 2>&1 &
@@ -49,15 +60,15 @@ for i in $(seq 1 $COUNT); do
}" > /dev/null
# Setup VM VSOCK
- # Guest CID 3 is typically the first available guest CID.
- # The host UDS will receive connections from the guest's socat.
+ # Guest CID 3 is typically the first available guest CID. Connections the
+ # guest makes to CID 2 surface on the host as "<uds_path>_<port>".
curl -s -X PUT --unix-socket $API_SOCKET \
http://localhost/vsock \
-H 'Content-Type: application/json' \
-d "{
\"vsock_id\": \"vsock0\",
\"guest_cid\": 3,
- \"uds_path\": \"$UDS_PATH\"
+ \"uds_path\": \"$VSOCK_UDS\"
}" > /dev/null
# Start VM
diff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.md
index dec1090e..1c79b5b9 100644
--- a/site/content/docs/user/secure-gateway.md
+++ b/site/content/docs/user/secure-gateway.md
@@ -1,182 +1,116 @@
---
-title: "Secure Outbound Gateway Guide"
-linkTitle: "Secure Outbound Gateway"
+title: "Sandbox Gateway Guide"
+linkTitle: "Sandbox Gateway"
weight: 30
---
-The Secure Outbound Gateway (`sam-box`) and the `nano-init` init-system allow operators to apply access control policies and secure credential injection for all outbound HTTP/HTTPS traffic originating from AI agent sandboxes.
+`sam-box` is the sandbox gateway: one per agent sandbox, serving the boundary an
+agent's traffic leaves through. An unmodified agent reaches mesh inference and
+tools by name, reaches allowlisted destinations on the internet, and reaches
+nothing else.
+
+For the reasoning behind the design, see
+[Agent Architecture]({{< relref "/docs/agent-architecture" >}}).
---
-## 1. Overview & Architecture
+## 1. What it is, and is not
-When running AI agents in isolated sandbox environments (such as gVisor, Kata Containers, or Docker with host network disabled), the agent's network namespace is entirely isolated. The Secure Outbound Gateway provides a transparent HTTP proxy model:
+`sam-box` holds **no libp2p host, no enrolment and no mesh identity**. It
+consumes a local `sam-node` over that node's API socket, and offers the sandbox
+a curated surface built on top of it.
```mermaid
sequenceDiagram
- participant Agent as AI Agent (Inside Sandbox)
- participant Init as nano-init (Sandbox PID 1)
- participant Box as sam-box (Host / Shared Vol)
- participant ControlPlane as sam-control-plane (Mesh)
- participant Upstream as External Service (e.g. OpenAI API)
-
- Agent->>Init: HTTP GET http://api.openai.com/v1/models (via HTTP_PROXY)
- Init->>Box: Forward raw bytes via Unix Domain Socket (UDS)
- Box->>Box: Parse & verify client's Biscuit token
- Box->>ControlPlane: Verify policy rights
- Box->>Box: Lookup & Inject real API Key (e.g. Bearer sk-...)
- Box->>Upstream: HTTPS GET https://api.openai.com/v1/models (Upgraded to SSL)
- Upstream-->>Box: Response
- Box-->>Init: Forward response
- Init-->>Agent: Return response
+ participant Agent as Agent (inside the sandbox)
+ participant Box as sam-box (sandbox boundary)
+ participant Node as sam-node (mesh member)
+ participant Mesh as The mesh / the internet
+
+ Agent->>Box: SOCKS5 CONNECT mesh.sam.alt:80
+ Box->>Box: Classify by name, apply policy
+ Box->>Node: /v1/chat/completions over the node's API socket
+ Node->>Mesh: Route to a provider, authorized by the node's Biscuit
+ Mesh-->>Agent: Response
```
-### Rationale
-* **Zero Trust Policy Enforcement**: Every request made by the agent sandbox is verified cryptographically using Biscuit tokens.
-* **Transparent Secret Injection**: Agent sandboxes never see the real API keys or credentials. The gateway injects them at the network boundary before the request goes to the public internet.
-* **Secure Upgrade**: Plain HTTP requests inside the sandbox are securely upgraded to HTTPS when forwarded to external targets.
+The split matters. A `sam-node`'s API can register services under the node's
+identity and proxy to any peer, and reaching its socket is itself the
+credential. So an agent never touches it: `sam-box` is the node's consumer, the
+agent is the mesh's consumer through `sam-box`.
---
-## 2. Setting Up the Gateway (`sam-box`)
-
-`sam-box` runs as a daemon on the host or inside a sidecar container, listening on a Unix Domain Socket (UDS). It operates as a first-class node in the Sovereign Agent Mesh.
+## 2. Running it
-### 1. Enrollment & Configuration
-Since `sam-box` is built on top of the `sam-node` architecture, it supports the exact same 4 enrollment flows (JWT, file-based JWT, OIDC Client Credentials, and pre-shared Bootstrap tokens).
-
-To join the mesh interactively:
-```bash
-sam-box join https://bananas.sam-mesh.dev
-```
-
-### 2. Running the Gateway
-Start the gateway using the `run` command:
```bash
sam-box run \
- --uds-path=/var/run/sam/sam-box.sock \
- --secrets-file=/etc/sam/secrets.yaml \
- --log-level=info
+ --socket=/var/run/sam/agent.sock \
+ --sidecar-socket=/var/run/sam/node.sock \
+ --egress-allow=api.github.com \
+ --egress-allow='*.pypi.org'
```
-#### Key Parameters:
-* `--uds-path` (or `-u`): The path where the gateway will expose its Unix Domain Socket (e.g. `/var/run/sam/sam-box.sock`).
-* `--secrets-file` (or `-s`): The YAML configuration file containing host-to-credential mappings for secret injection.
+| Flag | Meaning |
+|---|---|
+| `--socket` | The sandbox-facing socket. Created 0600: its permissions are the credential. |
+| `--sidecar-socket` | The local `sam-node`'s API socket (`sam-node run --socket-path`). |
+| `--egress-allow` | A destination outside the mesh the agent may reach. Repeatable. **Empty means nothing is reachable.** |
+
+Egress entries are matched on the name the agent asked for, never on a resolved
+address. A wildcard covers subdomains only: `*.pypi.org` matches
+`files.pypi.org` but not `pypi.org`, and never `evilpypi.org`.
---
-## 3. Configuring Secrets (`secrets.yaml`)
+## 3. What the agent sees
-The secrets file specifies the credential injection policies for outbound destinations:
+```bash
+OPENAI_BASE_URL=http://mesh.sam.alt/v1
+MCP_URL=http://mesh.sam.alt/mcp
+```
-```yaml
-# /etc/sam/secrets.yaml
-"api.openai.com":
- kind: Bearer
- value: "sk-proj-xxxxxxxxxxxx"
+No proxy variables, no CA bundle, no token: the agent holds no credential at
+all. `mesh.sam.alt` serves exactly four paths — `/v1/models`,
+`/v1/chat/completions`, `/v1/completions` and `/mcp`. Anything else is refused
+with 403 and never reaches the node.
-"api.anthropic.com":
- kind: CustomHeader
- header_name: "x-api-key"
- value: "sk-ant-xxxxxxxxxxxx"
+A specific service can be addressed by its own name instead of letting policy
+choose: `http://code-reviewer.mcp.sam.alt/`.
-"custom-auth-service.internal":
- kind: BasicAuth
- value: "dXNlcjpwYXNz" # base64(username:password)
-```
+Destinations that policy refuses fail the SOCKS5 handshake, which the sandbox's
+kernel turns into an ordinary connection refusal — so an agent sees "refused"
+rather than a hang.
---
-## 4. Running the Sandbox with `nano-init`
+## 4. Connecting a sandbox to the socket
-`nano-init` acts as PID 1 inside the agent's container. To enforce zero trust outbound security without port collisions or reliance on agent configuration:
+The sandbox has no network of its own. It runs `tun2socks` against a `tun`
+device and points it at the boundary socket, so every flow leaves as SOCKS5
+carrying the destination *name*:
-1. **Dynamic Loopback Binding**: `nano-init` binds to a dynamic loopback port (`127.0.0.1:0`) for the blind UDS forwarder. This prevents `EADDRINUSE` address collisions when the agent app attempts to host web servers on port 80 or 443.
-2. **Cooperative Proxy Configuration**: The allocated dynamic port is injected into the sandbox environment variables: `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `http_proxy`, `https_proxy`, and `all_proxy` set to `http://127.0.0.1:<assignedPort>`.
-3. **Transparent Interception via C Hook**: To secure uncooperative agents or tools that bypass environment proxy configurations, `nano-init` injects a dynamic library (`LD_PRELOAD=/opt/sam/libinterceptor.so`). This hooks the C `connect()` syscall, intercepting outgoing TCP requests targeting ports 80 and 443, and transparently rewrites both the target IP to loopback (`127.0.0.1` or `::1`) and the port to `SAM_PROXY_PORT` (the assigned proxy port).
+| sandbox | how it reaches the socket |
+|---|---|
+| Firecracker microVM | vsock; firecracker terminates it as `<uds_path>_<port>` on the host |
+| container with `network=none` | the socket is bind-mounted in |
-### Local Execution (Docker)
+For a quick test without a sandbox, bridge a TCP port to the socket and use any
+SOCKS5 client:
-To run the sandbox locally:
```bash
-# 1. Start sam-box on the host
-sam-box run --uds-path /tmp/sam-box.sock --secrets-file secrets.yaml
-
-# 2. Run the agent container wrapping it with nano-init
-docker run --network none \
- -v /tmp/sam-box.sock:/var/run/sam-box.sock \
- -e TOKEN="<agent-biscuit-token>" \
- my-agent-image \
- /usr/local/bin/nano-init run /var/run/sam-box.sock python3 agent.py
+socat TCP-LISTEN:1080,fork,reuseaddr UNIX-CONNECT:/var/run/sam/agent.sock &
+curl --socks5-hostname 127.0.0.1:1080 http://mesh.sam.alt/v1/models
```
---
-## 5. Kubernetes Deployment (Shared Volume Pod)
-
-In a Kubernetes environment, you run `sam-box` as a sidecar container, and copy `nano-init` into the agent's namespace using an `initContainer` and a shared `emptyDir` volume:
-
-```yaml
-apiVersion: apps/v1
-kind: Deployment
-metadata:
- name: agent-sandbox
-spec:
- replicas: 1
- template:
- spec:
- serviceAccountName: sam-node-sa
- initContainers:
- - name: init-nano-init
- image: ghcr.io/google/sam-nano-init:latest
- command: ["/nano-init", "copy", "/shared-bin/nano-init"]
- volumeMounts:
- - name: shared-bin
- mountPath: /shared-bin
- containers:
- - name: agent
- image: python:3.11-alpine
- command:
- - "/shared-bin/nano-init"
- - "run"
- - "/var/run/sam/sam-box.sock"
- - "python3"
- - "agent.py"
- volumeMounts:
- - name: shared-bin
- mountPath: /shared-bin
- - name: sam-uds
- mountPath: /var/run/sam
- - name: sam-box
- image: ghcr.io/google/sam-box:latest
- args:
- - "run"
- - "--uds-path=/var/run/sam/sam-box.sock"
- - "--config=/etc/sam/sam-node.yaml"
- - "--secrets-file=/etc/sam/secrets.yaml"
- - "--control-plane=http://sam-control-plane.sam.svc.cluster.local:8080"
- - "--jwt-path=/var/run/secrets/tokens/sam-token"
- volumeMounts:
- - name: config-volume
- mountPath: /etc/sam
- - name: sam-token
- mountPath: /var/run/secrets/tokens
- readOnly: true
- - name: sam-uds
- mountPath: /var/run/sam
- volumes:
- - name: shared-bin
- emptyDir: {}
- - name: sam-uds
- emptyDir: {}
- - name: config-volume
- configMap:
- name: sam-box-config
- - name: sam-token
- projected:
- sources:
- - serviceAccountToken:
- path: sam-token
- expirationSeconds: 3600
- audience: "sam-control-plane-audience"
-```
+## 5. Not yet implemented
+
+Deliberately absent, and tracked in the architecture document:
+
+* **Secret injection** for external destinations. The ephemeral CA and the
+ injection machinery exist, but are not wired into this datapath.
+* **Ingress**: an agent serving a mesh service of its own.
+* **Per-agent identity** on the wire. Today flows carry the node's identity;
+ the agent's own identity is the next piece of work.