Skip to content

Agent Mesh

feat(sandbox): implement zero-trust outbound sandbox with dynamic ports and connect hook redirection

Antonio Ojea740ff0596313
diff --git a/.github/k8s/sam-box-canary-template.yaml b/.github/k8s/sam-box-canary-template.yaml
new file mode 100644
index 00000000..f0c5af04
--- /dev/null
+++ b/.github/k8s/sam-box-canary-template.yaml
@@ -0,0 +1,90 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: sam-canary-box-config-${ENV_NAME}
+ namespace: sam-canary-${ENV_NAME}
+data:
+ sam-node.yaml: |
+ version: "v1alpha1"
+ attenuation:
+ policies: []
+ checks: []
+ rules: []
+ services: []
+ secrets.yaml: |
+ example.com:
+ kind: Bearer
+ value: real-upstream-secret-123
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: box-canary-${ENV_NAME}
+ namespace: sam-canary-${ENV_NAME}
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: box-canary-${ENV_NAME}
+ template:
+ metadata:
+ labels:
+ app: box-canary-${ENV_NAME}
+ spec:
+ serviceAccountName: sam-node-sa
+ initContainers:
+ - name: init-nano-init
+ image: ghcr.io/google/sam-nano-init:${IMAGE_TAG}
+ command: ["cp", "/nano-init", "/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"
+ - "/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}
+ args:
+ - "run"
+ - "--uds-path=/var/run/sam/sam-box.sock"
+ - "--config=/etc/sam/sam-node.yaml"
+ - "--secrets-file=/etc/sam/secrets.yaml"
+ - "--hub=http://sam-control-plane-${ENV_NAME}.${NAMESPACE}.svc.cluster.local:8080"
+ - "--jwt-path=/var/run/secrets/tokens/sam-token"
+ - "--api-token=secret-token"
+ - "--allow-loopback"
+ - "--log-level=debug"
+ 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-canary-box-config-${ENV_NAME}
+ - name: sam-token
+ projected:
+ sources:
+ - serviceAccountToken:
+ path: sam-token
+ expirationSeconds: 3600
+ audience: "sam-hub-audience"
diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml
index 03be1842..7aa9afc2 100644
--- a/.github/workflows/deploy.yaml
+++ b/.github/workflows/deploy.yaml
@@ -103,6 +103,50 @@ jobs:
tags: ${{ steps.meta-node.outputs.tags }}
labels: ${{ steps.meta-node.outputs.labels }}
+ - name: Extract metadata for nano-init
+ id: meta-nano-init
+ uses: docker/metadata-action@v6
+ with:
+ images: ${{ env.REGISTRY }}/google/sam-nano-init
+ tags: |
+ type=ref,event=branch
+ type=ref,event=tag
+ type=raw,value=${{ github.sha }}
+ type=raw,value=latest,enable={{is_default_branch}}
+ type=raw,value=stable,enable=${{ startsWith(github.ref, 'refs/tags/v') }}
+
+ - name: Build and push nano-init image
+ uses: docker/build-push-action@v7
+ with:
+ context: .
+ file: Dockerfile.nano-init
+ platforms: ${{ github.ref_type == 'tag' && 'linux/amd64,linux/arm64' || 'linux/amd64' }}
+ push: true
+ tags: ${{ steps.meta-nano-init.outputs.tags }}
+ labels: ${{ steps.meta-nano-init.outputs.labels }}
+
+ - name: Extract metadata for sam-box
+ id: meta-sambox
+ uses: docker/metadata-action@v6
+ with:
+ images: ${{ env.REGISTRY }}/google/sam-box
+ tags: |
+ type=ref,event=branch
+ type=ref,event=tag
+ type=raw,value=${{ github.sha }}
+ type=raw,value=latest,enable={{is_default_branch}}
+ type=raw,value=stable,enable=${{ startsWith(github.ref, 'refs/tags/v') }}
+
+ - name: Build and push sam-box image
+ uses: docker/build-push-action@v7
+ with:
+ context: .
+ file: Dockerfile.sam-box
+ platforms: ${{ github.ref_type == 'tag' && 'linux/amd64,linux/arm64' || 'linux/amd64' }}
+ push: true
+ tags: ${{ steps.meta-sambox.outputs.tags }}
+ labels: ${{ steps.meta-sambox.outputs.labels }}
+
deploy:
name: Deploy to GKE
runs-on: ubuntu-latest
@@ -432,6 +476,7 @@ jobs:
envsubst < .github/k8s/sam-node-vllm-template.yaml | kubectl apply -f -
envsubst < .github/k8s/sam-node-everything-template.yaml | kubectl apply -f -
envsubst < .github/k8s/sam-node-cop-template.yaml | kubectl apply -f -
+ envsubst < .github/k8s/sam-box-canary-template.yaml | kubectl apply -f -
kubectl rollout status deployment/cop-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} --timeout=120s || {
echo "Cop Canary Deployment failed!"
@@ -439,6 +484,12 @@ jobs:
exit 1
}
+ kubectl rollout status deployment/box-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} --timeout=120s || {
+ echo "sam-box Canary Deployment failed!"
+ print_rollout_diagnostics "${CANARY_NAMESPACE}" "box-canary-${ENV_NAME}" "app=box-canary-${ENV_NAME}"
+ exit 1
+ }
+
kubectl rollout status deployment/sam-canary-${ENV_NAME} -n ${CANARY_NAMESPACE} --timeout=120s || {
echo "Canary Deployment failed!"
diff --git a/.goreleaser.yaml b/.goreleaser.yaml
index 8f8a27ed..ecff677a 100644
--- a/.goreleaser.yaml
+++ b/.goreleaser.yaml
@@ -57,6 +57,34 @@ builds:
- arm64
ldflags:
- -s -w
+ - id: sam-box
+ main: ./cmd/sam-box
+ binary: sam-box
+ env:
+ - CGO_ENABLED=0
+ goos:
+ - linux
+ - windows
+ - darwin
+ goarch:
+ - amd64
+ - arm64
+ ldflags:
+ - -s -w
+ - id: nano-init
+ main: ./cmd/nano-init
+ binary: nano-init
+ env:
+ - CGO_ENABLED=0
+ goos:
+ - linux
+ - windows
+ - darwin
+ goarch:
+ - amd64
+ - arm64
+ ldflags:
+ - -s -w
archives:
- format: tar.gz
name_template: >-
diff --git a/Dockerfile.nano-init b/Dockerfile.nano-init
new file mode 100644
index 00000000..b05d4ef7
--- /dev/null
+++ b/Dockerfile.nano-init
@@ -0,0 +1,15 @@
+# Stage 1: Build
+FROM golang:1.26.4 AS builder
+RUN apt-get update && apt-get install -y gcc libc-dev
+WORKDIR /app
+COPY go.mod go.sum ./
+RUN go mod download
+COPY . .
+RUN gcc -shared -fPIC -ldl -o libinterceptor.so cmd/nano-init/interceptor/interceptor.c
+RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o nano-init ./cmd/nano-init
+
+# Stage 2: Final
+FROM gcr.io/distroless/base:latest
+COPY --from=builder /app/nano-init /
+COPY --from=builder /app/libinterceptor.so /opt/sam/libinterceptor.so
+ENTRYPOINT ["/nano-init"]
diff --git a/Dockerfile.sam-box b/Dockerfile.sam-box
new file mode 100644
index 00000000..1ec8b38d
--- /dev/null
+++ b/Dockerfile.sam-box
@@ -0,0 +1,12 @@
+# Stage 1: Build
+FROM golang:1.26.4 AS builder
+WORKDIR /app
+COPY go.mod go.sum ./
+RUN go mod download
+COPY . .
+RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o sam-box ./cmd/sam-box
+
+# Stage 2: Final
+FROM gcr.io/distroless/static:latest
+COPY --from=builder /app/sam-box /
+ENTRYPOINT ["/sam-box"]
diff --git a/Makefile b/Makefile
index edb105aa..b0771e4d 100644
--- a/Makefile
+++ b/Makefile
@@ -20,11 +20,18 @@ ANDROID_CC_ARM64=$(ANDROID_NDK_TOOLCHAIN)/aarch64-linux-android30-clang
ANDROID_CC_X86_64=$(ANDROID_NDK_TOOLCHAIN)/x86_64-linux-android30-clang
-build:
+$(OUT_DIR)/libinterceptor.so: cmd/nano-init/interceptor/interceptor.c
+ mkdir -p "$(OUT_DIR)"
+ gcc -shared -fPIC -ldl -o "$(OUT_DIR)/libinterceptor.so" cmd/nano-init/interceptor/interceptor.c
+
+build: $(OUT_DIR)/libinterceptor.so
go build -v -o "$(OUT_DIR)/sam-node" ./cmd/sam-node
go build -v -o "$(OUT_DIR)/sam-control-plane" ./cmd/sam-control-plane
go build -v -o "$(OUT_DIR)/sam-router" ./cmd/sam-router
go build -v -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client
+ go build -v -o "$(OUT_DIR)/nano-init" ./cmd/nano-init
+ go build -v -o "$(OUT_DIR)/sam-box" ./cmd/sam-box
+
.PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-android-x86_64 mobile-ffi-ios mobile-ffi mobile-app-apk mobile-app-apk-emulator
mobile-ffi-host:
@@ -169,6 +176,12 @@ docker-build-mock-oidc:
docker-build-e2e-runtime:
docker build --load -t sam-e2e-runtime:local -f tests/e2e/docker/Dockerfile.sam-runtime .
-docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime
+docker-build-nano-init:
+ docker build --load -t sam-nano-init:local -f Dockerfile.nano-init .
+
+docker-build-sam-box:
+ docker build --load -t sam-box:local -f Dockerfile.sam-box .
+
+docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box
-.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build
+.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-mock-oidc docker-build-e2e-runtime docker-build-nano-init docker-build-sam-box docker-build
diff --git a/cmd/nano-init/README.md b/cmd/nano-init/README.md
new file mode 100644
index 00000000..a96b6c70
--- /dev/null
+++ b/cmd/nano-init/README.md
@@ -0,0 +1,34 @@
+# nano-init
+
+`nano-init` is a minimal init system designed to run as PID 1 in a container, while transparently proxying HTTP/HTTPS traffic to a Unix Domain Socket (UDS).
+
+## What it does
+
+1. **PID 1 Duties (Zombie Reaping):** It correctly handles `SIGCHLD` to reap any zombie child processes spawned during the container's lifecycle.
+2. **UDS to TCP Proxy:** It spins up a transparent TCP listener on a random localhost port and securely proxies all traffic over a given Unix Domain Socket.
+3. **Process Management:** It wraps your target application (e.g., an agent), automatically injecting the standard `HTTP_PROXY` and `HTTPS_PROXY` environment variables pointing to the dynamic TCP port it opened.
+4. **Signal Propagation:** It intercepts termination signals (`SIGINT`, `SIGTERM`, `SIGQUIT`) and gracefully propagates them to the child process group to orchestrate clean shutdowns.
+5. **Exit Code Passthrough:** When the target process exits, `nano-init` catches its exit code and exits with the same code.
+
+## Why it is needed
+
+Many applications and standard libraries lack native support for using a Unix Domain Socket as an HTTP/HTTPS proxy. By running `nano-init` as the entrypoint, the containerized application can simply use standard TCP-based `HTTP_PROXY` environment variables to securely route traffic out through the node's Unix Domain Socket, without needing any code modifications or complex network configurations.
+
+### Architecture & Rationale
+
+When deploying agent sandboxes, runtimes like gVisor, Kata Containers, or Docker with `network:none` are used to completely isolate the network namespace. In this isolated environment, we securely bind mount a Unix Domain Socket into the sandbox. `nano-init` then acts as the primary init process, forwarding all the agent's HTTP traffic to that bind-mounted socket.
+
+This approach is highly opinionated by design:
+* **Simplified Auth/Authz:** HTTP has a long, well-established list of mechanisms for authentication and authorization. Funneling traffic through an HTTP proxy simplifies how we assert identity and enforce access control for agents.
+* **Scalability vs L3/L4:** Supporting arbitrary L3 or L4 protocols directly is complex and difficult to scale securely. By enforcing HTTP proxying at the boundary, we avoid building a custom L3/L4 stack and instead leverage our existing network architecture to provide a highly scalable authentication and authorization framework.
+## Usage
+
+```bash
+./nano-init <uds-path> <cmd> [args...]
+```
+
+Example:
+
+```bash
+./nano-init /var/run/sam.sock ./my-agent --flag1 value
+```
diff --git a/cmd/nano-init/interceptor/interceptor.c b/cmd/nano-init/interceptor/interceptor.c
new file mode 100644
index 00000000..a264569a
--- /dev/null
+++ b/cmd/nano-init/interceptor/interceptor.c
@@ -0,0 +1,58 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dlfcn.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <errno.h>
+
+// Function pointer to the original connect syscall
+static int (*original_connect)(int sockfd, const struct sockaddr *addr, socklen_t addrlen) = NULL;
+
+int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
+ if (!original_connect) {
+ original_connect = dlsym(RTLD_NEXT, "connect");
+ if (!original_connect) {
+ fprintf(stderr, "[interceptor] Error: failed to locate original connect: %s\n", dlerror());
+ errno = EFAULT;
+ return -1;
+ }
+ }
+
+ struct sockaddr_storage modified_addr;
+ const struct sockaddr *final_addr = addr;
+
+ if (addr && (addr->sa_family == AF_INET || addr->sa_family == AF_INET6)) {
+ char *proxy_port_str = getenv("SAM_PROXY_PORT");
+ if (proxy_port_str) {
+ int proxy_port = atoi(proxy_port_str);
+ if (proxy_port > 0 && proxy_port < 65536) {
+ if (addr->sa_family == AF_INET && addrlen >= sizeof(struct sockaddr_in)) {
+ struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
+ uint16_t port = ntohs(addr4->sin_port);
+ if (port == 80 || port == 443) {
+ memcpy(&modified_addr, addr, sizeof(struct sockaddr_in));
+ struct sockaddr_in *m_addr4 = (struct sockaddr_in *)&modified_addr;
+ m_addr4->sin_port = htons(proxy_port);
+ m_addr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ final_addr = (const struct sockaddr *)&modified_addr;
+ }
+ } else if (addr->sa_family == AF_INET6 && addrlen >= sizeof(struct sockaddr_in6)) {
+ struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
+ uint16_t port = ntohs(addr6->sin6_port);
+ if (port == 80 || port == 443) {
+ memcpy(&modified_addr, addr, sizeof(struct sockaddr_in6));
+ struct sockaddr_in6 *m_addr6 = (struct sockaddr_in6 *)&modified_addr;
+ m_addr6->sin6_port = htons(proxy_port);
+ m_addr6->sin6_addr = in6addr_loopback;
+ final_addr = (const struct sockaddr *)&modified_addr;
+ }
+ }
+ }
+ }
+ }
+
+ return original_connect(sockfd, final_addr, addrlen);
+}
diff --git a/cmd/nano-init/main.go b/cmd/nano-init/main.go
new file mode 100644
index 00000000..4f4039a4
--- /dev/null
+++ b/cmd/nano-init/main.go
@@ -0,0 +1,430 @@
+// 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 main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "os/signal"
+ "runtime"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+func main() {
+ if len(os.Args) < 3 {
+ log.Fatalf("Usage: %s <uds-path> <cmd> [args...]", os.Args[0])
+ }
+ udsPath := os.Args[1]
+ cmdName := os.Args[2]
+ cmdArgs := os.Args[3:]
+
+ ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
+ defer cancel()
+
+ log.Printf("Bootstrapping CA certificate from UDS: %s", udsPath)
+ if err := bootstrapCA(ctx, udsPath); err != nil {
+ log.Fatalf("Bootstrap CA failed: %v", err)
+ }
+ log.Println("Bootstrap CA successfully written to /tmp/ephemeral_ca.pem")
+
+ // 1b. Bootstrap Interceptor
+ log.Println("Attempting to bootstrap socket interceptor from UDS gateway...")
+ var bootstrappedInterceptor string
+ if interceptor, err := bootstrapInterceptor(ctx, udsPath); err != nil {
+ log.Printf("Warning: failed to bootstrap socket interceptor: %v. Running without transparent interception.", err)
+ } else {
+ bootstrappedInterceptor = interceptor
+ log.Printf("Socket interceptor successfully written to %s", bootstrappedInterceptor)
+ }
+
+ // 2. DNS Spoofer
+ dnsPort := os.Getenv("SAM_DNS_PORT")
+ if dnsPort == "" {
+ dnsPort = "53"
+ }
+ dnsAddr := "127.0.0.1:" + dnsPort
+ if err := startDNSSpoofer(ctx, dnsAddr); err != nil {
+ log.Fatalf("Failed to start DNS spoofer: %v", err)
+ }
+ log.Printf("DNS spoofer listening on UDP %s", dnsAddr)
+
+ // Overwrite /etc/resolv.conf
+ if err := os.WriteFile("/etc/resolv.conf", []byte("nameserver 127.0.0.1\n"), 0644); err != nil {
+ log.Printf("Warning: failed to overwrite /etc/resolv.conf: %v", err)
+ } else {
+ log.Println("Overwrote /etc/resolv.conf to nameserver 127.0.0.1")
+ }
+
+ // 3. TCP Forwarding
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ log.Fatalf("Failed to bind random TCP port: %v", err)
+ }
+ defer func() { _ = listener.Close() }()
+ assignedProxyPort := listener.Addr().(*net.TCPAddr).Port
+ log.Printf("Blind UDS-forwarder listening on random port 127.0.0.1:%d", assignedProxyPort)
+
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ log.Printf("TCP Accept error: %v", err)
+ return
+ }
+ }
+ go handleConnection(conn, udsPath)
+ }
+ }()
+
+ // 4. Execution of the target process
+ cmd := exec.CommandContext(ctx, cmdName, cmdArgs...)
+ cmd.Cancel = func() error {
+ if cmd.Process == nil {
+ return nil
+ }
+ return syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
+ }
+ cmd.WaitDelay = 5 * time.Second
+
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ cmd.Stdin = os.Stdin
+
+ // Inject environment variables
+ interceptorPath := os.Getenv("SAM_INTERCEPTOR_PATH")
+ if interceptorPath == "" {
+ interceptorPath = bootstrappedInterceptor
+ }
+ cmd.Env = buildAgentEnv(assignedProxyPort, "/tmp/ephemeral_ca.pem", interceptorPath)
+
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+
+ if err := cmd.Start(); err != nil {
+ log.Fatalf("Failed to start agent: %v", err)
+ }
+
+ agentExitStatus := make(chan syscall.WaitStatus, 1)
+ setupPID1Duties(cmd.Process.Pid, agentExitStatus)
+
+ waitErr := cmd.Wait()
+ cancel()
+
+ var status syscall.WaitStatus
+ hasStatus := false
+
+ if waitErr != nil && errors.Is(waitErr, syscall.ECHILD) {
+ status = <-agentExitStatus
+ hasStatus = true
+ }
+
+ if hasStatus {
+ if status.Signaled() {
+ os.Exit(128 + int(status.Signal()))
+ }
+ os.Exit(status.ExitStatus())
+ }
+
+ if waitErr != nil {
+ if exitError, ok := waitErr.(*exec.ExitError); ok {
+ os.Exit(exitError.ExitCode())
+ }
+ os.Exit(1)
+ }
+ os.Exit(0)
+}
+
+func bootstrapCA(ctx context.Context, udsPath string) error {
+ client := &http.Client{
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return net.Dial("unix", udsPath)
+ },
+ },
+ }
+ req, err := http.NewRequestWithContext(ctx, "GET", "http://localhost/internal/bootstrap/ca.crt", nil)
+ if err != nil {
+ return err
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("unexpected status: %s", resp.Status)
+ }
+
+ caBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+
+ return os.WriteFile("/tmp/ephemeral_ca.pem", caBytes, 0644)
+}
+
+func bootstrapInterceptor(ctx context.Context, udsPath string) (string, error) {
+ client := &http.Client{
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return net.Dial("unix", udsPath)
+ },
+ },
+ Timeout: 5 * time.Second,
+ }
+
+ arch := runtime.GOARCH
+ libc := detectLibc()
+
+ urlStr := fmt.Sprintf("http://localhost/internal/bootstrap/libinterceptor.so?arch=%s&libc=%s", arch, libc)
+ req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)
+ if err != nil {
+ return "", err
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("server returned status: %s", resp.Status)
+ }
+
+ soBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", err
+ }
+
+ targetPath := "/tmp/libinterceptor.so"
+ if err := os.WriteFile(targetPath, soBytes, 0755); err != nil {
+ return "", err
+ }
+
+ return targetPath, nil
+}
+
+func detectLibc() string {
+ paths := []string{
+ "/lib/ld-musl-x86_64.so.1",
+ "/lib/ld-musl-aarch64.so.1",
+ "/lib/ld-musl-arm.so.1",
+ }
+ for _, p := range paths {
+ if _, err := os.Stat(p); err == nil {
+ return "musl"
+ }
+ }
+
+ // Also scan directories as fallback
+ if files, err := os.ReadDir("/lib"); err == nil {
+ for _, f := range files {
+ if strings.Contains(strings.ToLower(f.Name()), "musl") {
+ return "musl"
+ }
+ }
+ }
+ if files, err := os.ReadDir("/lib64"); err == nil {
+ for _, f := range files {
+ if strings.Contains(strings.ToLower(f.Name()), "musl") {
+ return "musl"
+ }
+ }
+ }
+
+ return "glibc"
+}
+
+func startDNSSpoofer(ctx context.Context, dnsAddr string) error {
+ addr, err := net.ResolveUDPAddr("udp", dnsAddr)
+ if err != nil {
+ return err
+ }
+ conn, err := net.ListenUDP("udp", addr)
+ if err != nil {
+ return err
+ }
+ go func() {
+ <-ctx.Done()
+ _ = conn.Close()
+ }()
+
+ go func() {
+ buf := make([]byte, 512)
+ for {
+ n, remoteAddr, err := conn.ReadFromUDP(buf)
+ if err != nil {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ log.Printf("DNS Server read error: %v", err)
+ return
+ }
+ }
+
+ packet := make([]byte, n)
+ copy(packet, buf[:n])
+
+ go func(p []byte, rAddr *net.UDPAddr) {
+ var msg dnsmessage.Message
+ if err := msg.Unpack(p); err != nil {
+ return
+ }
+
+ resp := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: msg.ID,
+ Response: true,
+ Authoritative: true,
+ },
+ Questions: msg.Questions,
+ }
+
+ if len(msg.Questions) > 0 {
+ q := msg.Questions[0]
+ switch q.Type {
+ case dnsmessage.TypeA:
+ resp.Answers = append(resp.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{Name: q.Name, Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.AResource{A: [4]byte{127, 0, 0, 1}},
+ })
+ case dnsmessage.TypeAAAA:
+ ip := net.ParseIP("127.0.0.1").To16()
+ var aaaa [16]byte
+ copy(aaaa[:], ip)
+ resp.Answers = append(resp.Answers, dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{Name: q.Name, Type: dnsmessage.TypeAAAA, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.AAAAResource{AAAA: aaaa},
+ })
+ }
+ }
+
+ packed, err := resp.Pack()
+ if err == nil {
+ _, _ = conn.WriteToUDP(packed, rAddr)
+ }
+ }(packet, remoteAddr)
+ }
+ }()
+
+ return nil
+}
+
+func handleConnection(client net.Conn, udsPath string) {
+ defer func() { _ = client.Close() }()
+
+ uds, err := net.DialTimeout("unix", udsPath, 5*time.Second)
+ if err != nil {
+ log.Printf("UDS Dial error: %v", err)
+ return
+ }
+ defer func() { _ = uds.Close() }()
+
+ cp := func(dst, src net.Conn, done chan<- struct{}) {
+ _, _ = io.Copy(dst, src)
+ if cw, ok := dst.(interface{ CloseWrite() error }); ok {
+ _ = cw.CloseWrite()
+ }
+ done <- struct{}{}
+ }
+
+ done := make(chan struct{}, 2)
+ go cp(uds, client, done)
+ go cp(client, uds, done)
+
+ <-done
+ <-done
+}
+
+func setupPID1Duties(agentPid int, exitChan chan<- syscall.WaitStatus) {
+ sigCh := make(chan os.Signal, 10)
+ signal.Notify(sigCh, syscall.SIGCHLD)
+
+ go func() {
+ for range sigCh {
+ for {
+ var status syscall.WaitStatus
+ pid, err := syscall.Wait4(-1, &status, syscall.WNOHANG, nil)
+ if pid <= 0 || err != nil {
+ break
+ }
+ if pid == agentPid {
+ select {
+ case exitChan <- status:
+ default:
+ }
+ }
+ }
+ }
+ }()
+}
+
+func buildAgentEnv(assignedPort int, caPath string, interceptorPath string) []string {
+ proxyURL := fmt.Sprintf("http://127.0.0.1:%d", assignedPort)
+
+ overrides := map[string]string{
+ "SSL_CERT_FILE": caPath,
+ "REQUESTS_CA_BUNDLE": caPath,
+ "NODE_EXTRA_CA_CERTS": caPath,
+ "HTTP_PROXY": proxyURL,
+ "HTTPS_PROXY": proxyURL,
+ "ALL_PROXY": proxyURL,
+ "http_proxy": proxyURL,
+ "https_proxy": proxyURL,
+ "all_proxy": proxyURL,
+ "SAM_PROXY_PORT": strconv.Itoa(assignedPort),
+ }
+
+ if interceptorPath != "" {
+ overrides["LD_PRELOAD"] = interceptorPath
+ }
+
+ var result []string
+ for _, env := range os.Environ() {
+ parts := strings.SplitN(env, "=", 2)
+ if len(parts) != 2 {
+ continue
+ }
+ key := parts[0]
+ if _, exists := overrides[key]; exists {
+ continue
+ }
+ result = append(result, env)
+ }
+
+ for k, v := range overrides {
+ result = append(result, fmt.Sprintf("%s=%s", k, v))
+ }
+
+ return result
+}
diff --git a/cmd/nano-init/main_test.go b/cmd/nano-init/main_test.go
new file mode 100644
index 00000000..9df901bb
--- /dev/null
+++ b/cmd/nano-init/main_test.go
@@ -0,0 +1,373 @@
+// 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 main
+
+import (
+ "context"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+func TestBootstrapCA(t *testing.T) {
+ tempDir := t.TempDir()
+ udsPath := filepath.Join(tempDir, "mock-sam-box.sock")
+
+ // Start a mock HTTP server on a Unix Domain Socket
+ listener, err := net.Listen("unix", udsPath)
+ if err != nil {
+ t.Fatalf("Failed to listen on UDS: %v", err)
+ }
+ defer func() { _ = listener.Close() }()
+
+ mockCACert := []byte("fake-ca-cert-data")
+
+ srv := &http.Server{
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "GET" && r.URL.Path == "/internal/bootstrap/ca.crt" {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(mockCACert)
+ } else {
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }),
+ }
+ go func() {
+ _ = srv.Serve(listener)
+ }()
+ defer func() { _ = srv.Close() }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ // Clean target file if it already exists
+ _ = os.Remove("/tmp/ephemeral_ca.pem")
+ defer func() { _ = os.Remove("/tmp/ephemeral_ca.pem") }()
+
+ if err := bootstrapCA(ctx, udsPath); err != nil {
+ t.Fatalf("bootstrapCA failed: %v", err)
+ }
+
+ data, err := os.ReadFile("/tmp/ephemeral_ca.pem")
+ if err != nil {
+ t.Fatalf("Failed to read bootstrap CA: %v", err)
+ }
+
+ if string(data) != string(mockCACert) {
+ t.Errorf("Expected cert data %q, got %q", string(mockCACert), string(data))
+ }
+}
+
+func TestDNSSpoofer(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ dnsAddr := "127.0.0.1:10053"
+ if err := startDNSSpoofer(ctx, dnsAddr); err != nil {
+ t.Fatalf("Failed to start DNS spoofer: %v", err)
+ }
+
+ // Create UDP connection to make queries
+ conn, err := net.Dial("udp", dnsAddr)
+ if err != nil {
+ t.Fatalf("Failed to dial DNS spoofer: %v", err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ // Query A record
+ msgA := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: 1234,
+ OpCode: 0,
+ RecursionDesired: true,
+ },
+ Questions: []dnsmessage.Question{
+ {
+ Name: dnsmessage.MustNewName("api.github.com."),
+ Type: dnsmessage.TypeA,
+ Class: dnsmessage.ClassINET,
+ },
+ },
+ }
+ packedA, _ := msgA.Pack()
+ _, _ = conn.Write(packedA)
+
+ buf := make([]byte, 512)
+ _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
+ n, err := conn.Read(buf)
+ if err != nil {
+ t.Fatalf("Failed to read DNS reply: %v", err)
+ }
+
+ var respA dnsmessage.Message
+ if err := respA.Unpack(buf[:n]); err != nil {
+ t.Fatalf("Failed to unpack DNS response: %v", err)
+ }
+
+ if len(respA.Answers) == 0 {
+ t.Fatalf("No answers in DNS A response")
+ }
+
+ answerA := respA.Answers[0]
+ if answerA.Header.Type != dnsmessage.TypeA {
+ t.Fatalf("Expected A record answer, got %v", answerA.Header.Type)
+ }
+
+ bodyVarA := answerA.Body
+ aRes, ok := bodyVarA.(*dnsmessage.AResource)
+ if !ok {
+ t.Fatalf("Expected AResource body type")
+ }
+
+ expectedA := [4]byte{127, 0, 0, 1}
+ if aRes.A != expectedA {
+ t.Errorf("Expected A record %v, got %v", expectedA, aRes.A)
+ }
+
+ // Query AAAA record
+ msgAAAA := dnsmessage.Message{
+ Header: dnsmessage.Header{
+ ID: 5678,
+ OpCode: 0,
+ RecursionDesired: true,
+ },
+ Questions: []dnsmessage.Question{
+ {
+ Name: dnsmessage.MustNewName("api.github.com."),
+ Type: dnsmessage.TypeAAAA,
+ Class: dnsmessage.ClassINET,
+ },
+ },
+ }
+ packedAAAA, _ := msgAAAA.Pack()
+ _, _ = conn.Write(packedAAAA)
+
+ _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
+ n, err = conn.Read(buf)
+ if err != nil {
+ t.Fatalf("Failed to read DNS reply: %v", err)
+ }
+
+ var respAAAA dnsmessage.Message
+ if err := respAAAA.Unpack(buf[:n]); err != nil {
+ t.Fatalf("Failed to unpack DNS response: %v", err)
+ }
+
+ if len(respAAAA.Answers) == 0 {
+ t.Fatalf("No answers in DNS AAAA response")
+ }
+
+ answerAAAA := respAAAA.Answers[0]
+ if answerAAAA.Header.Type != dnsmessage.TypeAAAA {
+ t.Fatalf("Expected AAAA record answer, got %v", answerAAAA.Header.Type)
+ }
+
+ bodyVarAAAA := answerAAAA.Body
+ aaaaRes, ok := bodyVarAAAA.(*dnsmessage.AAAAResource)
+ if !ok {
+ t.Fatalf("Expected AAAAResource body type")
+ }
+
+ expectedAAAA := net.ParseIP("127.0.0.1").To16()
+ var expectedAAAABytes [16]byte
+ copy(expectedAAAABytes[:], expectedAAAA)
+
+ if aaaaRes.AAAA != expectedAAAABytes {
+ t.Errorf("Expected AAAA record %v, got %v", expectedAAAABytes, aaaaRes.AAAA)
+ }
+}
+
+func TestTCPForwarder(t *testing.T) {
+ tempDir := t.TempDir()
+ udsPath := filepath.Join(tempDir, "mock-uds.sock")
+
+ // UDS Listener (representing gateway)
+ udsListener, err := net.Listen("unix", udsPath)
+ if err != nil {
+ t.Fatalf("Failed to listen on UDS: %v", err)
+ }
+ defer func() { _ = udsListener.Close() }()
+
+ mockGatewayMsg := []byte("hello from gateway")
+
+ go func() {
+ conn, err := udsListener.Accept()
+ if err != nil {
+ return
+ }
+ defer func() { _ = conn.Close() }()
+ _, _ = conn.Write(mockGatewayMsg)
+ }()
+
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("Failed to listen: %v", err)
+ }
+ defer func() { _ = listener.Close() }()
+
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ go handleConnection(conn, udsPath)
+ }
+ }()
+
+ // Dial forwarder
+ conn, err := net.Dial("tcp", listener.Addr().String())
+ if err != nil {
+ t.Fatalf("Failed to dial forwarder: %v", err)
+ }
+ defer func() { _ = conn.Close() }()
+
+ reply := make([]byte, len(mockGatewayMsg))
+ _, err = io.ReadFull(conn, reply)
+ if err != nil {
+ t.Fatalf("Failed to read from forwarder connection: %v", err)
+ }
+
+ if string(reply) != string(mockGatewayMsg) {
+ t.Errorf("Expected message %q, got %q", string(mockGatewayMsg), string(reply))
+ }
+}
+
+func TestBuildAgentEnv(t *testing.T) {
+ caPath := "/tmp/test_ca.pem"
+ interceptorPath := "/tmp/test_interceptor.so"
+
+ env := buildAgentEnv(1234, caPath, interceptorPath)
+
+ expected := map[string]string{
+ "SSL_CERT_FILE": caPath,
+ "REQUESTS_CA_BUNDLE": caPath,
+ "NODE_EXTRA_CA_CERTS": caPath,
+ "HTTP_PROXY": "http://127.0.0.1:1234",
+ "HTTPS_PROXY": "http://127.0.0.1:1234",
+ "ALL_PROXY": "http://127.0.0.1:1234",
+ "http_proxy": "http://127.0.0.1:1234",
+ "https_proxy": "http://127.0.0.1:1234",
+ "all_proxy": "http://127.0.0.1:1234",
+ "SAM_PROXY_PORT": "1234",
+ "LD_PRELOAD": interceptorPath,
+ }
+
+ envMap := make(map[string]string)
+ for _, kv := range env {
+ parts := strings.SplitN(kv, "=", 2)
+ if len(parts) == 2 {
+ envMap[parts[0]] = parts[1]
+ }
+ }
+
+ for k, expectedVal := range expected {
+ val, exists := envMap[k]
+ if !exists {
+ t.Errorf("Expected environment variable %s to be set", k)
+ continue
+ }
+ if val != expectedVal {
+ t.Errorf("Expected environment variable %s to be %q, got %q", k, expectedVal, val)
+ }
+ }
+}
+
+func TestBootstrapInterceptor(t *testing.T) {
+ tempDir := t.TempDir()
+ udsPath := filepath.Join(tempDir, "mock-sam-box-interceptor.sock")
+
+ listener, err := net.Listen("unix", udsPath)
+ if err != nil {
+ t.Fatalf("Failed to listen on UDS: %v", err)
+ }
+ defer func() { _ = listener.Close() }()
+
+ mockSO := []byte("fake-shared-library-so-data")
+ var receivedArch, receivedLibc string
+
+ srv := &http.Server{
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "GET" && r.URL.Path == "/internal/bootstrap/libinterceptor.so" {
+ receivedArch = r.URL.Query().Get("arch")
+ receivedLibc = r.URL.Query().Get("libc")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(mockSO)
+ } else {
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }),
+ }
+ go func() {
+ _ = srv.Serve(listener)
+ }()
+ defer func() { _ = srv.Close() }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ _ = os.Remove("/tmp/libinterceptor.so")
+ defer func() { _ = os.Remove("/tmp/libinterceptor.so") }()
+
+ soPath, err := bootstrapInterceptor(ctx, udsPath)
+ if err != nil {
+ t.Fatalf("bootstrapInterceptor failed: %v", err)
+ }
+
+ if soPath != "/tmp/libinterceptor.so" {
+ t.Errorf("Expected path '/tmp/libinterceptor.so', got %q", soPath)
+ }
+
+ data, err := os.ReadFile("/tmp/libinterceptor.so")
+ if err != nil {
+ t.Fatalf("Failed to read bootstrap SO: %v", err)
+ }
+
+ if string(data) != string(mockSO) {
+ t.Errorf("Expected SO data %q, got %q", string(mockSO), string(data))
+ }
+
+ if receivedArch == "" {
+ t.Errorf("Expected arch query parameter to be passed, but was empty")
+ }
+ if receivedLibc == "" {
+ t.Errorf("Expected libc query parameter to be passed, but was empty")
+ }
+
+ // Test fallback / error case (server returns 404)
+ errSrvListener, err := net.Listen("unix", filepath.Join(tempDir, "mock-error-sam-box.sock"))
+ if err == nil {
+ defer func() { _ = errSrvListener.Close() }()
+ errSrv := &http.Server{
+ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ }),
+ }
+ go func() { _ = errSrv.Serve(errSrvListener) }()
+ defer func() { _ = errSrv.Close() }()
+
+ _, err = bootstrapInterceptor(ctx, errSrvListener.Addr().String())
+ if err == nil {
+ t.Errorf("Expected bootstrapInterceptor to return error when server returns 404")
+ }
+ }
+}
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.go
new file mode 100644
index 00000000..59694462
--- /dev/null
+++ b/cmd/sam-box/main.go
@@ -0,0 +1,567 @@
+// 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 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"
+ 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 (
+ hubAddr string
+ jwtFlag string
+ jwtPathFlag string
+ bootstrapTokenFlag string
+ clientIDFlag string
+ clientSecretFlag string
+ hubPublicKeyFlag string
+ meshFlag string
+ discoveryIntervalFlag string
+ listenAddrs []string
+ enableRelayFlag bool
+ configFile string
+ oidcIssuerFlag string
+ deviceAuthURLFlag string
+ audienceFlag string
+ dataDirFlag string
+ headlessFlag bool
+ offlineAccessFlag bool
+ logLevelFlag string
+ keyGracePeriodFlag time.Duration
+ allowLoopbackFlag bool
+ monitorBootstrapFlag time.Duration
+ monitorCheckIntervalFlag time.Duration
+ autoRelayMinIntervalFlag time.Duration
+ autoRelayBootDelayFlag time.Duration
+ autoRelayBackoffFlag time.Duration
+ hubConnectTimeoutFlag time.Duration
+
+ // sam-box specific flags
+ udsPathFlag string
+ secretsFileFlag string
+ interceptorsDirFlag string
+)
+
+var logger = golog.Logger("sam-box-cli")
+
+func main() {
+ rootCmd := &cobra.Command{
+ Use: "sam-box",
+ Short: "Sovereign Agent Mesh Secure Gateway Node",
+ }
+
+ 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")
+
+ 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 hubPubKey ed25519.PublicKey
+ var hubAddrs []multiaddr.Multiaddr
+
+ storedPubKey, syncedAddrs, err := node.SyncHubConfig(ctx, store)
+ if err != nil {
+ logger.Warnf("Failed to sync hub config: %v", err)
+ }
+ if len(storedPubKey) > 0 {
+ hubPubKey = storedPubKey
+ hubAddrs = syncedAddrs
+ }
+
+ if hubPublicKeyFlag != "" {
+ pubBytes, err := hex.DecodeString(strings.TrimSpace(hubPublicKeyFlag))
+ if err != nil {
+ logger.Fatalf("Invalid hub public key: %v", err)
+ }
+ hubPubKey = 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 {
+ displayHub := hubAddr
+ if displayHub == "" {
+ if h, err := store.LoadHubURL(); err == nil && h != "" {
+ displayHub = h
+ } else {
+ displayHub = "https://bananas.sam-mesh.dev"
+ }
+ }
+ logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")
+ unauthSrv, err := node.StartUnauthSidecarServer(displayHub, "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(hubPubKey) == 0 {
+ logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")
+ }
+ priv := node.GetOrGenerateKey(store)
+ meshNode, err = node.NewSamNode(node.Options{
+ PrivKey: priv,
+ HubPubKey: hubPubKey,
+ HubAddrs: hubAddrs,
+ 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,
+ HubConnectTimeout: hubConnectTimeoutFlag,
+ })
+ 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 initHubAddrs []multiaddr.Multiaddr
+ if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
+ if err == nil {
+ initHubAddrs = []multiaddr.Multiaddr{ma}
+ } else {
+ host, port, err := net.SplitHostPort(hubAddr)
+ 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)
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
+ } else {
+ logger.Fatalf("Invalid hub address: %v", err)
+ }
+ }
+ }
+
+ priv := node.GetOrGenerateKey(store)
+ meshNode, err = node.NewSamNode(node.Options{
+ PrivKey: priv,
+ HubAddrs: initHubAddrs,
+ 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,
+ HubConnectTimeout: hubConnectTimeoutFlag,
+ })
+ 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, hubAddr, bootstrapTokenFlag)
+ } else {
+ err = meshNode.Enroll(ctx, hubAddr, jwtStr)
+ }
+ if err != nil {
+ logger.Fatalf("Enrollment failed: %v", err)
+ }
+ if err := store.SaveHubURL(hubAddr); err != nil {
+ logger.Warnf("Failed to save hub URL: %v", err)
+ }
+ logger.Infoln("Successfully enrolled with hub!")
+
+ if len(hubPubKey) == 0 {
+ if syncPubKey, _, err := node.SyncHubConfig(ctx, store); err != nil || len(syncPubKey) == 0 {
+ logger.Fatal("Hub 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)
+ }
+ oldUmask := syscall.Umask(0177)
+ listener, err := net.Listen("unix", udsPathFlag)
+ syscall.Umask(oldUmask)
+ 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()
+ targetHub := hubAddr
+ if targetHub == "" {
+ targetHub = "https://bananas.sam-mesh.dev"
+ }
+ if !strings.HasPrefix(targetHub, "http://") && !strings.HasPrefix(targetHub, "https://") {
+ targetHub = "https://" + targetHub
+ }
+ targetHub = strings.TrimSuffix(targetHub, "/")
+
+ 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 hub info from %s...\n", targetHub)
+ hubInfo, err := node.FetchHubInfo(ctx, targetHub)
+ if err != nil {
+ logger.Fatalf("Failed to discover hub info: %v", err)
+ }
+
+ var jwtStr string
+ if bootstrapTokenFlag == "" {
+ fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)
+ fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)
+
+ logger.Info("Discovering OIDC endpoints...")
+ tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)
+ if err != nil {
+ logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
+ }
+
+ jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)
+ if err != nil {
+ logger.Fatalf("Failed to get token: %v", err)
+ }
+ }
+
+ hubAddr = targetHub
+ var initHubAddrs []multiaddr.Multiaddr
+ if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
+ if err == nil {
+ initHubAddrs = []multiaddr.Multiaddr{ma}
+ } else {
+ host, port, err := net.SplitHostPort(hubAddr)
+ 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)
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
+ } else {
+ logger.Fatalf("Invalid hub address: %v", err)
+ }
+ }
+ }
+
+ priv := node.GetOrGenerateKey(store)
+ meshNode, err := node.NewSamNode(node.Options{
+ PrivKey: priv,
+ HubAddrs: initHubAddrs,
+ 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,
+ HubConnectTimeout: hubConnectTimeoutFlag,
+ })
+ 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, targetHub, bootstrapTokenFlag)
+ } else {
+ err = meshNode.Enroll(ctx, targetHub, jwtStr)
+ }
+ if err != nil {
+ logger.Fatalf("Enrollment failed: %v", err)
+ }
+ if err := store.SaveHubURL(targetHub); err != nil {
+ logger.Warnf("Failed to save hub URL: %v", err)
+ }
+ if bootstrapTokenFlag == "" {
+ if err := store.SaveOIDCConfig(hubInfo.OidcIssuer, hubInfo.ClientId, hubInfo.Audience); err != nil {
+ logger.Warnf("Failed to save OIDC config: %v", err)
+ }
+ }
+
+ fmt.Println("Successfully joined the Sovereign Agent Mesh!")
+ },
+ }
+
+ // 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(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")
+ runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", "", "OIDC Client Secret for M2M")
+ runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub 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 hub connection")
+ runCmd.Flags().DurationVar(&monitorCheckIntervalFlag, "monitor-interval", 1*time.Minute, "Interval for checking hub 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(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub 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")
+
+ joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")
+ joinCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub 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")
+
+ rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "", "Hub 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.AddCommand(runCmd)
+ rootCmd.AddCommand(joinCmd)
+
+ 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)
+ }()
+
+ 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
+ }
+ return store, nil
+}
diff --git a/internal/sambox/gateway.go b/internal/sambox/gateway.go
new file mode 100644
index 00000000..0e6ee3bc
--- /dev/null
+++ b/internal/sambox/gateway.go
@@ -0,0 +1,437 @@
+// 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 (
+ "bufio"
+ "bytes"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+)
+
+type SecretKind string
+
+const (
+ SecretKindBearer SecretKind = "Bearer"
+ SecretKindCustomHeader SecretKind = "CustomHeader"
+ SecretKindBasicAuth SecretKind = "BasicAuth"
+)
+
+type SecretConfig struct {
+ Kind SecretKind `yaml:"kind" json:"kind"`
+ HeaderName string `yaml:"header_name" json:"header_name"`
+ Value string `yaml:"value" json:"value"`
+}
+
+type CA struct {
+ CertBytes []byte
+ Certificate *x509.Certificate
+ PrivateKey *rsa.PrivateKey
+}
+
+func GenerateEphemeralCA() (*CA, error) {
+ priv, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ return nil, err
+ }
+
+ serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
+ serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
+ if err != nil {
+ return nil, err
+ }
+
+ template := &x509.Certificate{
+ SerialNumber: serialNumber,
+ Subject: pkix.Name{
+ Organization: []string{"Ephemeral SamBox CA"},
+ CommonName: "SamBox Ephemeral Root CA",
+ },
+ NotBefore: time.Now().Add(-1 * time.Hour),
+ NotAfter: time.Now().Add(365 * 24 * time.Hour),
+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+ BasicConstraintsValid: true,
+ IsCA: true,
+ }
+
+ derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
+ if err != nil {
+ return nil, err
+ }
+
+ certPEM := pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: derBytes,
+ })
+
+ cert, err := x509.ParseCertificate(derBytes)
+ if err != nil {
+ return nil, err
+ }
+
+ return &CA{
+ CertBytes: certPEM,
+ Certificate: cert,
+ PrivateKey: priv,
+ }, nil
+}
+
+type CertCache struct {
+ mu sync.RWMutex
+ certs map[string]*tls.Certificate
+}
+
+func NewCertCache() *CertCache {
+ return &CertCache{
+ certs: make(map[string]*tls.Certificate),
+ }
+}
+
+func (c *CertCache) GetCertificate(sni string, ca *CA) (*tls.Certificate, error) {
+ c.mu.RLock()
+ cert, exists := c.certs[sni]
+ c.mu.RUnlock()
+ if exists {
+ return cert, nil
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if cert, exists = c.certs[sni]; exists {
+ return cert, nil
+ }
+
+ newCert, err := GenerateLeafCert(sni, ca)
+ if err != nil {
+ return nil, err
+ }
+ c.certs[sni] = newCert
+ return newCert, nil
+}
+
+func GenerateLeafCert(sni string, ca *CA) (*tls.Certificate, error) {
+ priv, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ return nil, err
+ }
+
+ serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
+ serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
+ if err != nil {
+ return nil, err
+ }
+
+ template := &x509.Certificate{
+ SerialNumber: serialNumber,
+ Subject: pkix.Name{
+ CommonName: sni,
+ },
+ DNSNames: []string{sni},
+ NotBefore: time.Now().Add(-1 * time.Hour),
+ NotAfter: time.Now().Add(24 * time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
+ ExtKeyUsage: []x509.ExtKeyUsage{
+ x509.ExtKeyUsageServerAuth,
+ },
+ }
+
+ derBytes, err := x509.CreateCertificate(rand.Reader, template, ca.Certificate, &priv.PublicKey, ca.PrivateKey)
+ if err != nil {
+ return nil, err
+ }
+
+ certPEM := pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: derBytes,
+ })
+
+ privDer := x509.MarshalPKCS1PrivateKey(priv)
+ keyPEM := pem.EncodeToMemory(&pem.Block{
+ Type: "RSA PRIVATE KEY",
+ Bytes: privDer,
+ })
+
+ tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
+ if err != nil {
+ return nil, err
+ }
+
+ return &tlsCert, nil
+}
+
+type Gateway struct {
+ CA *CA
+ CertCache *CertCache
+ SecretStore map[string]SecretConfig
+ Transport http.RoundTripper
+ InterceptorsDir string
+}
+
+func NewGateway(secretStore map[string]SecretConfig, transport http.RoundTripper, interceptorsDir string) (*Gateway, error) {
+ ca, err := GenerateEphemeralCA()
+ if err != nil {
+ return nil, err
+ }
+ return &Gateway{
+ CA: ca,
+ CertCache: NewCertCache(),
+ SecretStore: secretStore,
+ Transport: transport,
+ InterceptorsDir: interceptorsDir,
+ }, nil
+}
+
+func (g *Gateway) Serve(listener net.Listener) error {
+ tlsListener := &channelListener{
+ conns: make(chan net.Conn, 100),
+ closed: make(chan struct{}),
+ }
+ defer func() { _ = tlsListener.Close() }()
+
+ director := func(req *http.Request) {
+ req.URL.Scheme = "https"
+ req.URL.Host = req.Host
+ req.Header.Set("Authorization", "Bearer mock-token")
+ }
+
+ proxy := &httputil.ReverseProxy{
+ Director: director,
+ Transport: g.Transport,
+ }
+
+ server := &http.Server{
+ Handler: proxy,
+ }
+
+ serverErrChan := make(chan error, 1)
+ go func() {
+ if err := server.Serve(tlsListener); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ serverErrChan <- err
+ }
+ }()
+
+ for {
+ rawConn, err := listener.Accept()
+ if err != nil {
+ select {
+ case <-tlsListener.closed:
+ return nil
+ default:
+ return err
+ }
+ }
+
+ go g.handleConnection(rawConn, tlsListener)
+ }
+}
+
+func (g *Gateway) handleConnection(rawConn net.Conn, tlsListener *channelListener) {
+ br := bufio.NewReader(rawConn)
+ peekBytes, err := br.Peek(5)
+ if err != nil {
+ _ = rawConn.Close()
+ return
+ }
+
+ conn := &bufferedConn{
+ Conn: rawConn,
+ r: br,
+ }
+
+ if len(peekBytes) > 0 && peekBytes[0] == 0x16 {
+ tlsConfig := &tls.Config{
+ GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ sni := info.ServerName
+ if sni == "" {
+ return nil, fmt.Errorf("missing SNI")
+ }
+ return g.CertCache.GetCertificate(sni, g.CA)
+ },
+ }
+ tlsConn := tls.Server(conn, tlsConfig)
+ if err := tlsConn.Handshake(); err != nil {
+ _ = tlsConn.Close()
+ return
+ }
+
+ select {
+ case tlsListener.conns <- tlsConn:
+ case <-tlsListener.closed:
+ _ = tlsConn.Close()
+ }
+ } else {
+ g.handleHTTPConnection(conn, tlsListener)
+ }
+}
+
+func (g *Gateway) handleHTTPConnection(conn net.Conn, tlsListener *channelListener) {
+ req, err := http.ReadRequest(bufio.NewReader(conn))
+ if err != nil {
+ _ = conn.Close()
+ return
+ }
+
+ if req.Method == "CONNECT" {
+ _, err := conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
+ if err != nil {
+ _ = conn.Close()
+ return
+ }
+ g.upgradeToTLS(conn, req.Host, tlsListener)
+ return
+ }
+
+ defer func() { _ = conn.Close() }()
+
+ if req.Method == "GET" && req.URL.Path == "/internal/bootstrap/ca.crt" {
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: int64(len(g.CA.CertBytes)),
+ Body: io.NopCloser(bytes.NewReader(g.CA.CertBytes)),
+ Header: make(http.Header),
+ }
+ resp.Header.Set("Content-Type", "application/x-x509-ca-cert")
+ _ = resp.Write(conn)
+ } else if req.Method == "GET" && req.URL.Path == "/internal/bootstrap/libinterceptor.so" {
+ if g.InterceptorsDir == "" {
+ write404(conn)
+ return
+ }
+ arch := req.URL.Query().Get("arch")
+ libc := req.URL.Query().Get("libc")
+
+ var filename string
+ if arch != "" && libc != "" {
+ filename = fmt.Sprintf("libinterceptor-%s-%s.so", arch, libc)
+ } else {
+ filename = "libinterceptor.so"
+ }
+
+ filePath := filepath.Join(g.InterceptorsDir, filename)
+ fileData, err := os.ReadFile(filePath)
+ if err != nil && filename != "libinterceptor.so" {
+ filePath = filepath.Join(g.InterceptorsDir, "libinterceptor.so")
+ fileData, err = os.ReadFile(filePath)
+ }
+
+ if err != nil {
+ write404(conn)
+ return
+ }
+
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ ContentLength: int64(len(fileData)),
+ Body: io.NopCloser(bytes.NewReader(fileData)),
+ Header: make(http.Header),
+ }
+ resp.Header.Set("Content-Type", "application/octet-stream")
+ _ = resp.Write(conn)
+ } else {
+ write404(conn)
+ }
+}
+
+func write404(conn net.Conn) {
+ resp := &http.Response{
+ StatusCode: http.StatusNotFound,
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Body: io.NopCloser(strings.NewReader("Not Found")),
+ Header: make(http.Header),
+ }
+ _ = resp.Write(conn)
+}
+
+func (g *Gateway) upgradeToTLS(rawConn net.Conn, sni string, tlsListener *channelListener) {
+ host, _, err := net.SplitHostPort(sni)
+ if err != nil {
+ host = sni
+ }
+
+ tlsConfig := &tls.Config{
+ GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ return g.CertCache.GetCertificate(host, g.CA)
+ },
+ }
+
+ tlsConn := tls.Server(rawConn, tlsConfig)
+ if err := tlsConn.Handshake(); err != nil {
+ _ = tlsConn.Close()
+ return
+ }
+
+ select {
+ case tlsListener.conns <- tlsConn:
+ case <-tlsListener.closed:
+ _ = tlsConn.Close()
+ }
+}
+
+type bufferedConn struct {
+ net.Conn
+ r io.Reader
+}
+
+func (c *bufferedConn) Read(b []byte) (int, error) {
+ return c.r.Read(b)
+}
+
+type channelListener struct {
+ conns chan net.Conn
+ closed chan struct{}
+}
+
+func (l *channelListener) Accept() (net.Conn, error) {
+ select {
+ case conn := <-l.conns:
+ return conn, nil
+ case <-l.closed:
+ return nil, io.EOF
+ }
+}
+
+func (l *channelListener) Close() error {
+ select {
+ case <-l.closed:
+ default:
+ close(l.closed)
+ }
+ return nil
+}
+
+func (l *channelListener) Addr() net.Addr {
+ return &net.UnixAddr{Name: "internal-tls-multiplexer", Net: "unix"}
+}
diff --git a/internal/sambox/gateway_test.go b/internal/sambox/gateway_test.go
new file mode 100644
index 00000000..d384f10e
--- /dev/null
+++ b/internal/sambox/gateway_test.go
@@ -0,0 +1,183 @@
+// 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"
+ "crypto/tls"
+ "crypto/x509"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestGenerateEphemeralCA(t *testing.T) {
+ ca, err := GenerateEphemeralCA()
+ if err != nil {
+ t.Fatalf("GenerateEphemeralCA failed: %v", err)
+ }
+
+ if len(ca.CertBytes) == 0 {
+ t.Fatal("Empty CertBytes")
+ }
+
+ if ca.Certificate == nil {
+ t.Fatal("Certificate is nil")
+ }
+
+ if ca.PrivateKey == nil {
+ t.Fatal("PrivateKey is nil")
+ }
+
+ // Validate self-signed
+ roots := x509.NewCertPool()
+ roots.AddCert(ca.Certificate)
+ opts := x509.VerifyOptions{
+ Roots: roots,
+ }
+ if _, err := ca.Certificate.Verify(opts); err != nil {
+ t.Fatalf("Certificate self-verification failed: %v", err)
+ }
+}
+
+func TestCertCache(t *testing.T) {
+ ca, _ := GenerateEphemeralCA()
+ cache := NewCertCache()
+
+ cert1, err := cache.GetCertificate("example.com", ca)
+ if err != nil {
+ t.Fatalf("Failed to get cert: %v", err)
+ }
+
+ cert2, err := cache.GetCertificate("example.com", ca)
+ if err != nil {
+ t.Fatalf("Failed to get cert second time: %v", err)
+ }
+
+ if cert1 != cert2 {
+ t.Errorf("CertCache did not cache the certificate")
+ }
+
+ cert3, err := cache.GetCertificate("another.com", ca)
+ if err != nil {
+ t.Fatalf("Failed to get cert for different domain: %v", err)
+ }
+
+ if cert1 == cert3 {
+ t.Errorf("CertCache returned same certificate for different domains")
+ }
+}
+
+func TestGatewayPlaintextAndTerminatingProxy(t *testing.T) {
+ // 1. Upstream Mock Server
+ upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ auth := r.Header.Get("Authorization")
+ if auth != "Bearer mock-token" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("mock upstream response"))
+ }))
+ defer upstream.Close()
+
+ // Redirect proxy calls to upstream mock server
+ transport := &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return net.Dial(network, upstream.Listener.Addr().String())
+ },
+ TLSClientConfig: &tls.Config{
+ InsecureSkipVerify: true,
+ },
+ }
+
+ // 2. Gateway setup
+ gateway, err := NewGateway(nil, transport, "")
+ if err != nil {
+ t.Fatalf("NewGateway failed: %v", err)
+ }
+
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("Failed to listen: %v", err)
+ }
+ defer func() { _ = listener.Close() }()
+
+ go func() {
+ _ = gateway.Serve(listener)
+ }()
+
+ addr := listener.Addr().String()
+
+ // 3. Test Plaintext HTTP bootstrap download
+ resp, err := http.Get("http://" + addr + "/internal/bootstrap/ca.crt")
+ if err != nil {
+ t.Fatalf("Failed to download CA cert: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("Expected 200, got %d", resp.StatusCode)
+ }
+
+ certBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatalf("Failed to read CA cert response body: %v", err)
+ }
+
+ // Verify downloaded cert matches gateway cert
+ roots := x509.NewCertPool()
+ if !roots.AppendCertsFromPEM(certBytes) {
+ t.Fatalf("Failed to parse downloaded certificate as PEM")
+ }
+
+ // 4. Test TLS Terminating Proxy
+ tlsConfig := &tls.Config{
+ RootCAs: roots,
+ }
+
+ // Create custom client that dials the gateway but expects "example.com" domain
+ client := &http.Client{
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
+ return net.Dial(network, addr)
+ },
+ TLSClientConfig: tlsConfig,
+ },
+ Timeout: 5 * time.Second,
+ }
+
+ resp2, err := client.Get("https://example.com/some-path")
+ if err != nil {
+ t.Fatalf("Terminating TLS proxy request failed: %v", err)
+ }
+ defer func() { _ = resp2.Body.Close() }()
+
+ if resp2.StatusCode != http.StatusOK {
+ t.Fatalf("Expected 200 from upstream, got %d", resp2.StatusCode)
+ }
+
+ body2, err := io.ReadAll(resp2.Body)
+ if err != nil {
+ t.Fatalf("Failed to read response body: %v", err)
+ }
+
+ if string(body2) != "mock upstream response" {
+ t.Errorf("Expected 'mock upstream response', got %q", string(body2))
+ }
+}
diff --git a/site/content/docs/user/secure-gateway.md b/site/content/docs/user/secure-gateway.md
new file mode 100644
index 00000000..21ce6c1c
--- /dev/null
+++ b/site/content/docs/user/secure-gateway.md
@@ -0,0 +1,181 @@
+---
+title: "Secure Outbound Gateway Guide"
+linkTitle: "Secure Outbound 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.
+
+---
+
+## 1. Overview & Architecture
+
+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:
+
+```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 Hub 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->>Hub: 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
+```
+
+### 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.
+
+---
+
+## 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.
+
+### 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
+```
+
+#### 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.
+
+---
+
+## 3. Configuring Secrets (`secrets.yaml`)
+
+The secrets file specifies the credential injection policies for outbound destinations:
+
+```yaml
+# /etc/sam/secrets.yaml
+"api.openai.com":
+ kind: Bearer
+ value: "sk-proj-xxxxxxxxxxxx"
+
+"api.anthropic.com":
+ kind: CustomHeader
+ header_name: "x-api-key"
+ value: "sk-ant-xxxxxxxxxxxx"
+
+"custom-auth-service.internal":
+ kind: BasicAuth
+ value: "dXNlcjpwYXNz" # base64(username:password)
+```
+
+---
+
+## 4. Running the Sandbox with `nano-init`
+
+`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:
+
+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).
+
+### Local Execution (Docker)
+
+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 /var/run/sam-box.sock python3 agent.py
+```
+
+---
+
+## 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: ["cp", "/nano-init", "/shared-bin/nano-init"]
+ volumeMounts:
+ - name: shared-bin
+ mountPath: /shared-bin
+ containers:
+ - name: agent
+ image: python:3.11-alpine
+ command:
+ - "/shared-bin/nano-init"
+ - "/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"
+ - "--hub=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-hub-audience"
+```
diff --git a/tests/e2e/fixtures/router.yaml b/tests/e2e/fixtures/router.yaml
index d11bca9a..af267739 100644
--- a/tests/e2e/fixtures/router.yaml
+++ b/tests/e2e/fixtures/router.yaml
@@ -59,6 +59,8 @@ spec:
- "--allow-loopback"
- "--lease-renew-interval=5s"
- "--log-level=debug"
+ - "--dht-provider-addr-ttl=5s"
+ - "--dht-max-record-age=5s"
volumeMounts:
- name: router-data
mountPath: /data
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 2e01709f..1ce3a28b 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -72,8 +72,6 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
mesh_cleanup_env() {
mesh_cleanup_test_resources
}
-
-
mesh_gen_hex32() {
hexdump -vn 32 -e '1/1 "%02x"' /dev/urandom
@@ -363,6 +361,8 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
--bind-addr "0.0.0.0:8080" \
--api-token "secret-token" \
--mesh "${MESH_PREFIX}" \
+ --dht-provider-addr-ttl 5s \
+ --dht-max-record-age 5s \
"${config_args[@]}" >/dev/null
MESH_CONTAINERS+=("${name}")
diff --git a/tests/integration/sambox_test.go b/tests/integration/sambox_test.go
new file mode 100644
index 00000000..53e9bfca
--- /dev/null
+++ b/tests/integration/sambox_test.go
@@ -0,0 +1,132 @@
+// 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 integration_test
+
+import (
+ "context"
+ "crypto/tls"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/google/sam/internal/sambox"
+)
+
+func TestSamBoxNanoInitIntegration(t *testing.T) {
+ // Build binaries (specifically we want to verify nano-init builds and runs)
+ nanoInitBin := buildBinary(t, "./cmd/nano-init")
+
+ // 1. Setup mock upstream "internet" server representing api.github.com
+ var mockServerReceivedAuth string
+ mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mockServerReceivedAuth = r.Header.Get("Authorization")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("mock-github-response-content"))
+ }))
+ defer mockServer.Close()
+
+ mockServerURL, err := url.Parse(mockServer.URL)
+ if err != nil {
+ t.Fatalf("Failed to parse mock server URL: %v", err)
+ }
+
+ // 2. Start sam-box in-process on a temporary UDS path
+ tempDir := t.TempDir()
+ udsPath := filepath.Join(tempDir, "sam-box-test.sock")
+
+ udsListener, err := net.Listen("unix", udsPath)
+ if err != nil {
+ t.Fatalf("Failed to listen on UDS socket: %v", err)
+ }
+ defer func() { _ = udsListener.Close() }()
+
+ gatewayTransport := &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ host = addr
+ }
+ if host == "api.github.com" {
+ return net.Dial(network, mockServerURL.Host)
+ }
+ return net.Dial(network, addr)
+ },
+ TLSClientConfig: &tls.Config{
+ InsecureSkipVerify: true,
+ },
+ }
+
+ gateway, err := sambox.NewGateway(nil, gatewayTransport, "")
+ if err != nil {
+ t.Fatalf("Failed to initialize gateway: %v", err)
+ }
+
+ go func() {
+ _ = gateway.Serve(udsListener)
+ }()
+
+ // 3. Start nano-init routines as a separate process (the target process will be a simple script/agent)
+ // We'll configure unprivileged ports for the test
+ dnsPort := "10053"
+
+ // Resolve the dynamic C interceptor path
+ interceptorPath, err := filepath.Abs("../../bin/libinterceptor.so")
+ if err != nil {
+ t.Fatalf("Failed to resolve interceptor path: %v", err)
+ }
+
+ // Run nano-init wrapper pointing to UDS, spawning curl
+ nanoInitCtx, nanoInitCancel := context.WithCancel(context.Background())
+ defer nanoInitCancel()
+
+ // Clean up /tmp/ephemeral_ca.pem before running
+ _ = os.Remove("/tmp/ephemeral_ca.pem")
+ defer func() { _ = os.Remove("/tmp/ephemeral_ca.pem") }()
+
+ nanoInitCmd := exec.CommandContext(nanoInitCtx, nanoInitBin, udsPath,
+ "curl", "--cacert", "/tmp/ephemeral_ca.pem", "-s", "https://api.github.com/",
+ )
+ nanoInitCmd.Env = append(os.Environ(),
+ "SAM_DNS_PORT="+dnsPort,
+ "SAM_INTERCEPTOR_PATH="+interceptorPath,
+ )
+
+ out, err := nanoInitCmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("nano-init failed: %v\nOutput:\n%s", err, out)
+ }
+
+ outStr := string(out)
+ t.Logf("Agent Output:\n%s", outStr)
+
+ // 4. Assert that the request reached the mock server and received correct response
+ expectedAgentOutput := "mock-github-response-content"
+ if !containsString(outStr, expectedAgentOutput) {
+ t.Errorf("Expected agent to output %q, got output:\n%s", expectedAgentOutput, outStr)
+ }
+
+ if mockServerReceivedAuth != "Bearer mock-token" {
+ t.Errorf("Mock server did not receive the expected token: %q", mockServerReceivedAuth)
+ }
+}
+
+func containsString(s, substr string) bool {
+ return len(s) >= len(substr) && (s == substr || len(s) > len(substr) && (s[:len(substr)] == substr || containsString(s[1:], substr)))
+}