Skip to content

Agent Mesh

node: serve the local API on a Unix socket

Antonio Ojea2b99660c75cc
diff --git a/agents/skills/sam-mesh/SKILL.md b/agents/skills/sam-mesh/SKILL.md
index 0f00b062..10e9b677 100644
--- a/agents/skills/sam-mesh/SKILL.md
+++ b/agents/skills/sam-mesh/SKILL.md
@@ -43,6 +43,20 @@ approve it before running anything.
`~/.gemini/config/mcp_config.json`.
5. Tell the user to restart the agent session, since MCP tools load at startup.
+MCP clients need that HTTP endpoint, but the node serves the same API on a Unix
+socket too, printed by step 2 and by default `~/.config/sam-mesh/sam.sock`. For
+shell commands prefer the socket: only the user who owns it can connect, so it
+needs no token at all and no secret ends up in a command line or in the
+transcript.
+
+```bash
+curl --unix-socket ~/.config/sam-mesh/sam.sock http://localhost/healthz
+```
+
+The host in the URL is a placeholder that curl ignores once it dials a socket.
+If the socket is missing, the node was started with `--socket-path ""`, and the
+TCP endpoint with the token header is the way in.
+
If setup is stuck in a half-configured state, ask the user before starting over:
stop the node, run `sam-node reset --all --yes` for a clean slate, then go back
to step 2. That deletes the node's identity and its PeerID, and enrolling again
@@ -139,6 +153,15 @@ as its `api_key`. Send a separate `Authorization` header only when the
destination model service needs its own credential: it passes through to that
service untouched.
+Over the Unix socket no token is needed, which keeps it out of shell history:
+
+```bash
+curl --unix-socket ~/.config/sam-mesh/sam.sock \
+ http://localhost/v1/chat/completions \
+ -H 'Content-Type: application/json' \
+ -d '{"model": "<model>", "messages": [{"role": "user", "content": "..."}]}'
+```
+
Ask the user before sending private or sensitive content to a mesh model, and
say which provider will receive it.
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.go
index 9b251093..6675a98c 100644
--- a/cmd/sam-box/main.go
+++ b/cmd/sam-box/main.go
@@ -218,7 +218,7 @@ func main() {
}
}
logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")
- unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, "127.0.0.1:8080", "", "")
+ unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, "127.0.0.1:8080", "", "", "")
if err != nil {
logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)
}
diff --git a/cmd/sam-node/daemonize.go b/cmd/sam-node/daemonize.go
index db5f762c..6871f92b 100644
--- a/cmd/sam-node/daemonize.go
+++ b/cmd/sam-node/daemonize.go
@@ -16,6 +16,7 @@ package main
import (
"bufio"
+ "context"
"crypto/rand"
"encoding/hex"
"errors"
@@ -44,11 +45,11 @@ const (
// daemonizeRun re-executes this binary as a detached background node and
// returns once its local API answers, so a single non-blocking command is
// enough to bring the mesh up.
-func daemonizeRun() error {
+func daemonizeRun(socketPath string) error {
dataDir := resolveDataDir()
- probe := localProbeAddr(bindAddrFlag)
+ probe := probeTarget{addr: localProbeAddr(bindAddrFlag), socketPath: socketPath}
- if probeReady(probe, time.Second) {
+ if probe.ready(time.Second) {
fmt.Printf("sam-node is already running and listening on %s\n", probe)
return nil
}
@@ -159,10 +160,10 @@ func ensureDaemonToken(dataDir string) ([]string, string, error) {
// waitForDaemon blocks until the background node answers, it exits, or the
// startup budget runs out.
-func waitForDaemon(probe string, exited <-chan error) error {
+func waitForDaemon(probe probeTarget, exited <-chan error) error {
deadline := time.After(daemonReadyTimeout)
for {
- if probeReady(probe, daemonPollInterval) {
+ if probe.ready(daemonPollInterval) {
return nil
}
select {
@@ -175,6 +176,29 @@ func waitForDaemon(probe string, exited <-chan error) error {
}
}
+// probeTarget is where a freshly started node is expected to answer. A node
+// can serve on a TCP address, on a Unix socket, or on both, so either endpoint
+// answering means it is up.
+type probeTarget struct {
+ addr string
+ socketPath string
+}
+
+func (p probeTarget) String() string {
+ if p.addr == "" {
+ return p.socketPath
+ }
+ return p.addr
+}
+
+// ready reports whether the node's local API is answering.
+func (p probeTarget) ready(timeout time.Duration) bool {
+ if p.addr != "" && probeReady(p.addr, timeout) {
+ return true
+ }
+ return p.socketPath != "" && socketProbeReady(p.socketPath, timeout)
+}
+
// probeReady reports whether the node's local API is answering on addr.
func probeReady(addr string, timeout time.Duration) bool {
if tlsCertFlag != "" {
@@ -194,6 +218,25 @@ func probeReady(addr string, timeout time.Duration) bool {
return resp.StatusCode == http.StatusOK
}
+// socketProbeReady reports whether the node's local API is answering on its
+// Unix socket. The host in the URL is ignored once the dialer targets a socket.
+func socketProbeReady(path string, timeout time.Duration) bool {
+ client := &http.Client{
+ Timeout: timeout,
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{Timeout: timeout}).DialContext(ctx, "unix", path)
+ },
+ },
+ }
+ resp, err := client.Get("http://localhost/healthz")
+ if err != nil {
+ return false
+ }
+ _ = resp.Body.Close()
+ return resp.StatusCode == http.StatusOK
+}
+
// localProbeAddr turns a listen address into one that can be dialed from this
// machine, since a wildcard bind is not itself a destination.
func localProbeAddr(bindAddr string) string {
@@ -330,14 +373,24 @@ func tailFile(path string, maxBytes int64, maxLines int) string {
return strings.Join(lines, "\n")
}
-func printDaemonSummary(pid int, probe, tokenPath, logPath string) {
+func printDaemonSummary(pid int, probe probeTarget, tokenPath, logPath string) {
fmt.Printf("sam-node is running in the background.\n")
fmt.Printf(" PID %d\n", pid)
- fmt.Printf(" Endpoint http://%s/mcp\n", probe)
+ if probe.addr != "" {
+ fmt.Printf(" Endpoint http://%s/mcp\n", probe.addr)
+ }
+ if probe.socketPath != "" {
+ fmt.Printf(" Socket %s\n", probe.socketPath)
+ }
if tokenPath != "" {
fmt.Printf(" Token %s\n", tokenPath)
}
fmt.Printf(" Logs %s\n", logPath)
fmt.Printf(" Stop kill %d\n", pid)
- fmt.Printf("\nAuthenticate to it with the header \"X-Sam-Authentication: Bearer <token>\".\n")
+ if probe.socketPath != "" {
+ fmt.Printf("\nCall it over the socket without a token, e.g.\n curl --unix-socket %s http://localhost/healthz\n", probe.socketPath)
+ }
+ if probe.addr != "" {
+ fmt.Printf("\nOver TCP, authenticate with the header \"X-Sam-Authentication: Bearer <token>\".\n")
+ }
}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index f2d325c9..43474d1e 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -23,6 +23,7 @@ import (
"net"
"os"
"os/signal"
+ "path/filepath"
"strings"
"syscall"
"time"
@@ -61,6 +62,7 @@ var (
clientSecretFlag string
controlPlanePublicKeyFlag string
bindAddrFlag string
+ socketPathFlag string
meshFlag string
discoveryIntervalFlag string
listenAddrs []string
@@ -222,7 +224,7 @@ func main() {
Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
if daemonizeFlag {
- if err := daemonizeRun(); err != nil {
+ if err := daemonizeRun(resolveSocketPath(cmd)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
@@ -368,7 +370,7 @@ func main() {
if len(token) == 0 {
displayControlPlane := defaultControlPlane(store, controlPlaneAddr)
logger.Infof("No identity found. Starting unauthenticated sidecar for enrollment over MCP...")
- unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddrFlag, tlsCertFlag, tlsKeyFlag)
+ unauthSrv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddrFlag, resolveSocketPath(cmd), tlsCertFlag, tlsKeyFlag)
if err != nil {
logger.Fatalf("Failed to start unauthenticated sidecar: %v", err)
}
@@ -578,7 +580,7 @@ func main() {
meshNode.Host.SetStreamHandler(api.AuthProtocolID, meshNode.HandleAuthHandshake)
// Start Sidecar API Server (multiplexed with MCP)
- sidecarSrv, err := node.StartSidecarServer(meshNode, bindAddrFlag, apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag)
+ sidecarSrv, err := node.StartSidecarServer(meshNode, bindAddrFlag, resolveSocketPath(cmd), apiTokenFlag, tlsCertFlag, tlsKeyFlag, tlsCAFlag)
if err != nil {
logger.Fatalf("Failed to start sidecar server: %v", err)
}
@@ -797,7 +799,8 @@ func main() {
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(&bindAddrFlag, "bind-addr", "127.0.0.1:8080", "Local TCP address for the HTTP server (MCP and Sidecar API)")
+ runCmd.Flags().StringVar(&bindAddrFlag, "bind-addr", "127.0.0.1:8080", "Local TCP address for the HTTP server (MCP and Sidecar API); pass an empty value to serve only on the Unix socket")
+ runCmd.Flags().StringVar(&socketPathFlag, "socket-path", "", "Unix socket serving the same API, where the socket's owner-only permissions replace the API token (defaults to <data-dir>/"+node.DefaultSocketName+"; pass an empty value to disable)")
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")
@@ -876,3 +879,12 @@ func resolveDataDir() string {
}
return dir
}
+
+// resolveSocketPath places the local API socket in the data directory unless
+// the operator names another path, or asks for no socket with --socket-path "".
+func resolveSocketPath(cmd *cobra.Command) string {
+ if cmd.Flags().Changed("socket-path") {
+ return socketPathFlag
+ }
+ return filepath.Join(resolveDataDir(), node.DefaultSocketName)
+}
diff --git a/internal/node/node.go b/internal/node/node.go
index f25da3fc..5340c39c 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -144,6 +144,7 @@ type SamNode struct {
rateLimiter *PeerRateLimiter
services *ServiceRegistry
BoundHTTPAddr string
+ BoundSocketPath string
AllowLoopback bool
authSuccess chan struct{}
@@ -1548,8 +1549,13 @@ func (n *SamNode) FindProvidersByType(ctx context.Context, serviceType api.Servi
// localProxyURL builds the loopback URL clients use to reach a remote service.
func (n *SamNode) localProxyURL(peerID peer.ID, typeStr, serviceName string) string {
+ host := n.BoundHTTPAddr
+ if host == "" {
+ // Socket-only node: any host works once the caller dials the socket.
+ host = "localhost"
+ }
return fmt.Sprintf("http://%s/sam/%s/%s/%s",
- n.BoundHTTPAddr, peerID.String(), typeStr, serviceName)
+ host, peerID.String(), typeStr, serviceName)
}
// DiscoverRemoteServices dispatches to the named or type-only path
diff --git a/internal/node/options.go b/internal/node/options.go
index 6e39d7d7..0aa435da 100644
--- a/internal/node/options.go
+++ b/internal/node/options.go
@@ -29,6 +29,8 @@ const (
DefaultDiscoveryInterval = "30s"
DefaultConfigFile = "sam-node.yaml"
DefaultRouterConnectTimeout = 5 * time.Second
+ // DefaultSocketName is the local API socket the node creates in its data directory.
+ DefaultSocketName = "sam.sock"
)
// Options holds all configuration options for a SamNode.
diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go
index 7c362f45..ca67e5b4 100644
--- a/internal/node/sidecar.go
+++ b/internal/node/sidecar.go
@@ -26,6 +26,7 @@ import (
"net/http"
"net/http/httputil"
"os"
+ "path/filepath"
"strconv"
"strings"
"time"
@@ -38,7 +39,10 @@ import (
"google.golang.org/protobuf/encoding/protojson"
)
-func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile string) (*http.Server, error) {
+// StartSidecarServer serves the node's local API on a TCP address, on a Unix
+// socket, or on both. An empty addr disables the TCP listener; an empty
+// socketPath disables the socket.
+func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFile, caFile string) (*http.Server, error) {
mux := http.NewServeMux()
// Public endpoints
@@ -84,21 +88,82 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile st
// (MCP sessions, inference completions), so no ReadTimeout/WriteTimeout.
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
+ ConnContext: markLocalSocketConn,
}
+ if addr == "" && socketPath == "" {
+ return nil, fmt.Errorf("no local API listener configured: set --bind-addr, --socket-path, or both")
+ }
+ if (certFile != "") != (keyFile != "") {
+ return nil, fmt.Errorf("both --tls-cert and --tls-key must be provided to enable TLS")
+ }
+
+ var socketListener net.Listener
+ if socketPath != "" {
+ l, err := bindLocalSocket(socketPath, addr == "")
+ if err != nil {
+ return nil, err
+ }
+ if l != nil {
+ socketListener = l
+ node.BoundSocketPath = socketPath
+ }
+ }
+
+ if addr != "" {
+ if err := serveTCP(server, node, addr, token, certFile, keyFile, caFile); err != nil {
+ if socketListener != nil {
+ _ = socketListener.Close()
+ }
+ return nil, err
+ }
+ }
+
+ serveSocket(server, socketListener, socketPath)
+
+ return server, nil
+}
+
+// bindLocalSocket binds the local API socket. Unless it is the only way into
+// the node, a path the OS rejects only downgrades to a warning: the socket is a
+// convenience on top of a working TCP listener and must never keep the node
+// from starting. A nil listener with a nil error means exactly that.
+func bindLocalSocket(socketPath string, required bool) (net.Listener, error) {
+ listener, err := listenLocalSocket(socketPath)
+ if err == nil {
+ return listener, nil
+ }
+ if required {
+ return nil, err
+ }
+ logger.Warnf("Local API socket disabled: %v", err)
+ return nil, nil
+}
+
+func serveSocket(server *http.Server, listener net.Listener, socketPath string) {
+ if listener == nil {
+ return
+ }
+ logger.Infof("Serving the local API on Unix socket %s", socketPath)
+ go func() {
+ if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
+ logger.Errorf("Sidecar API socket server error: %v", err)
+ }
+ }()
+}
+
+// serveTCP starts the sidecar's TCP listener, which — unlike the Unix socket —
+// is reachable by any local process and therefore always demands a token or
+// mutual TLS.
+func serveTCP(server *http.Server, node *SamNode, addr, token, certFile, keyFile, caFile string) error {
listener, err := net.Listen("tcp", addr)
if err != nil {
- return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
+ return fmt.Errorf("failed to listen on %s: %w", addr, err)
}
actualAddr := listener.Addr().String()
node.BoundHTTPAddr = actualAddr
- if (certFile != "") != (keyFile != "") {
- _ = listener.Close()
- return nil, fmt.Errorf("both --tls-cert and --tls-key must be provided to enable TLS")
- }
-
if certFile != "" && keyFile != "" {
tlsConfig := &tls.Config{}
isMTLS := false
@@ -106,7 +171,7 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile st
caCert, err := os.ReadFile(caFile)
if err != nil {
_ = listener.Close()
- return nil, fmt.Errorf("failed to read CA cert: %w", err)
+ return fmt.Errorf("failed to read CA cert: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
@@ -117,7 +182,7 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile st
if !isMTLS && token == "" {
_ = listener.Close()
- return nil, fmt.Errorf("token is mandatory when not using mTLS")
+ return fmt.Errorf("token is mandatory when not using mTLS")
}
server.TLSConfig = tlsConfig
@@ -127,22 +192,80 @@ func StartSidecarServer(node *SamNode, addr, token, certFile, keyFile, caFile st
logger.Errorf("Sidecar API server error: %v", err)
}
}()
- } else {
- if token == "" {
- _ = listener.Close()
- return nil, fmt.Errorf("token is mandatory when not using mTLS")
+ return nil
+ }
+
+ if token == "" {
+ _ = listener.Close()
+ return fmt.Errorf("token is mandatory when not using mTLS")
+ }
+ logger.Infof("Starting MCP server on TCP address %s", actualAddr)
+ go func() {
+ if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
+ logger.Errorf("Sidecar API server error: %v", err)
}
- logger.Infof("Starting MCP server on TCP address %s", actualAddr)
- go func() {
- if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
- logger.Errorf("Sidecar API server error: %v", err)
- }
- }()
+ }()
+ return nil
+}
+
+// listenLocalSocket binds the local API to a Unix socket whose permissions are
+// the credential: only the user who owns it can reach the mesh through it. A
+// socket left behind by a crashed node is replaced, one a live node is still
+// answering on is not.
+func listenLocalSocket(path string) (net.Listener, error) {
+ // The kernel's sun_path is a fixed-size buffer, and overflowing it only
+ // yields "invalid argument" from bind(2).
+ if len(path) >= 104 {
+ return nil, fmt.Errorf("socket path %q is too long (%d bytes, the kernel allows 103)", path, len(path))
}
- return server, nil
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ return nil, fmt.Errorf("creating the socket directory: %w", err)
+ }
+
+ if info, err := os.Stat(path); err == nil {
+ if info.Mode()&os.ModeSocket == 0 {
+ return nil, fmt.Errorf("%s already exists and is not a socket", path)
+ }
+ if conn, err := net.DialTimeout("unix", path, time.Second); err == nil {
+ _ = conn.Close()
+ return nil, fmt.Errorf("another node is already listening on %s", path)
+ }
+ if err := os.Remove(path); err != nil {
+ return nil, fmt.Errorf("removing the stale socket %s: %w", path, err)
+ }
+ }
+
+ listener, err := net.Listen("unix", path)
+ if err != nil {
+ return nil, fmt.Errorf("listening on %s: %w", path, err)
+ }
+ if err := os.Chmod(path, 0600); err != nil {
+ _ = listener.Close()
+ return nil, fmt.Errorf("restricting access to %s: %w", path, err)
+ }
+ return listener, nil
}
-func StartUnauthSidecarServer(controlPlaneURL, addr, certFile, keyFile string) (*http.Server, error) {
+type localSocketContextKey struct{}
+
+// markLocalSocketConn tags connections accepted on the Unix socket so the auth
+// gate can tell them apart from anything arriving over TCP.
+func markLocalSocketConn(ctx context.Context, c net.Conn) context.Context {
+ if addr := c.LocalAddr(); addr != nil && addr.Network() == "unix" {
+ return context.WithValue(ctx, localSocketContextKey{}, true)
+ }
+ return ctx
+}
+
+// fromLocalSocket reports whether the request arrived over the node's Unix socket.
+func fromLocalSocket(r *http.Request) bool {
+ authorized, _ := r.Context().Value(localSocketContextKey{}).(bool)
+ return authorized
+}
+
+// StartUnauthSidecarServer serves the enrollment-only API of a node that has no
+// identity yet, on a TCP address, on a Unix socket, or on both.
+func StartUnauthSidecarServer(controlPlaneURL, addr, socketPath, certFile, keyFile string) (*http.Server, error) {
mux := http.NewServeMux()
// Public endpoints
@@ -160,33 +283,51 @@ func StartUnauthSidecarServer(controlPlaneURL, addr, certFile, keyFile string) (
IdleTimeout: 120 * time.Second,
}
- listener, err := net.Listen("tcp", addr)
- if err != nil {
- return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
+ if addr == "" && socketPath == "" {
+ return nil, fmt.Errorf("no local API listener configured: set --bind-addr, --socket-path, or both")
}
-
- actualAddr := listener.Addr().String()
-
if (certFile != "") != (keyFile != "") {
- _ = listener.Close()
return nil, fmt.Errorf("both --tls-cert and --tls-key must be provided to enable TLS")
}
- if certFile != "" && keyFile != "" {
- logger.Infof("Starting Unauthenticated MCP server on TCP address %s (with TLS Sidecar)", actualAddr)
- go func() {
- if err := server.ServeTLS(listener, certFile, keyFile); err != nil && err != http.ErrServerClosed {
- logger.Errorf("Unauth Sidecar API server error: %v", err)
- }
- }()
- } else {
- logger.Infof("Starting Unauthenticated MCP server on TCP address %s", actualAddr)
- go func() {
- if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
- logger.Errorf("Unauth Sidecar API server error: %v", err)
+ var socketListener net.Listener
+ if socketPath != "" {
+ l, err := bindLocalSocket(socketPath, addr == "")
+ if err != nil {
+ return nil, err
+ }
+ socketListener = l
+ }
+
+ if addr != "" {
+ listener, err := net.Listen("tcp", addr)
+ if err != nil {
+ if socketListener != nil {
+ _ = socketListener.Close()
}
- }()
+ return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
+ }
+
+ actualAddr := listener.Addr().String()
+ if certFile != "" && keyFile != "" {
+ logger.Infof("Starting Unauthenticated MCP server on TCP address %s (with TLS Sidecar)", actualAddr)
+ go func() {
+ if err := server.ServeTLS(listener, certFile, keyFile); err != nil && err != http.ErrServerClosed {
+ logger.Errorf("Unauth Sidecar API server error: %v", err)
+ }
+ }()
+ } else {
+ logger.Infof("Starting Unauthenticated MCP server on TCP address %s", actualAddr)
+ go func() {
+ if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
+ logger.Errorf("Unauth Sidecar API server error: %v", err)
+ }
+ }()
+ }
}
+
+ serveSocket(server, socketListener, socketPath)
+
return server, nil
}
@@ -226,6 +367,13 @@ func withMeshConnection(node *SamNode, next http.Handler) http.Handler {
func withAuth(token string, allowAuthorizationFallback bool, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debugf("[SidecarAuth] Incoming request: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
+ if fromLocalSocket(r) {
+ // Reaching the socket at all already proves the caller is the user
+ // who owns it, which is the same bar as reading the token file.
+ r.Header.Del(api.HeaderSamAuthentication)
+ next.ServeHTTP(w, r)
+ return
+ }
if token == "" {
// If token is empty, we assume mTLS is handling authentication.
// StartSidecarServer enforces that token is present if mTLS is not used.
diff --git a/internal/node/sidecar_test.go b/internal/node/sidecar_test.go
index 3ad787c7..6118519e 100644
--- a/internal/node/sidecar_test.go
+++ b/internal/node/sidecar_test.go
@@ -18,8 +18,11 @@ import (
"bytes"
"context"
"encoding/json"
+ "net"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -34,6 +37,204 @@ import (
"google.golang.org/protobuf/encoding/protojson"
)
+// socketClient talks HTTP over a Unix socket; the host in the URL is ignored.
+func socketClient(path string) *http.Client {
+ return &http.Client{
+ Timeout: 2 * time.Second,
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", path)
+ },
+ },
+ }
+}
+
+func waitForSocket(t *testing.T, path string) *http.Client {
+ t.Helper()
+ client := socketClient(path)
+ for i := 0; i < 50; i++ {
+ resp, err := client.Get("http://localhost/healthz")
+ if err == nil {
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ return client
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatalf("sidecar socket %s never answered", path)
+ return nil
+}
+
+// TestSidecarSocketAuthorizesWithoutToken pins the socket's trust model: the
+// file's owner-only permissions are the credential, while the TCP listener on
+// the very same server keeps demanding the token.
+func TestSidecarSocketAuthorizesWithoutToken(t *testing.T) {
+ node := &SamNode{
+ BiscuitTimeout: 500 * time.Millisecond,
+ services: NewServiceRegistry(&fakeDHT{}),
+ }
+ socketPath := filepath.Join(t.TempDir(), "sam.sock")
+
+ srv, err := StartSidecarServer(node, "127.0.0.1:0", socketPath, "test-token", "", "", "")
+ if err != nil {
+ t.Fatalf("failed to start sidecar server: %v", err)
+ }
+ defer func() { _ = srv.Close() }()
+
+ client := waitForSocket(t, socketPath)
+
+ info, err := os.Stat(socketPath)
+ if err != nil {
+ t.Fatalf("failed to stat socket: %v", err)
+ }
+ if perm := info.Mode().Perm(); perm != 0600 {
+ t.Errorf("socket permissions are %#o, want 0600", perm)
+ }
+ if node.BoundSocketPath != socketPath {
+ t.Errorf("BoundSocketPath = %q, want %q", node.BoundSocketPath, socketPath)
+ }
+
+ // 503 means the request cleared the auth gate and was only stopped by the
+ // node not being connected to a mesh.
+ resp, err := client.Get("http://localhost/sam/service/discover?type=mcp&name=test")
+ if err != nil {
+ t.Fatalf("socket request failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Errorf("untokened socket request: got status %d, want %d", resp.StatusCode, http.StatusServiceUnavailable)
+ }
+
+ tcpClient := &http.Client{Timeout: 2 * time.Second}
+ tcpResp, err := tcpClient.Get("http://" + node.BoundHTTPAddr + "/sam/service/discover?type=mcp&name=test")
+ if err != nil {
+ t.Fatalf("tcp request failed: %v", err)
+ }
+ defer func() { _ = tcpResp.Body.Close() }()
+ if tcpResp.StatusCode != http.StatusUnauthorized {
+ t.Errorf("untokened TCP request: got status %d, want %d", tcpResp.StatusCode, http.StatusUnauthorized)
+ }
+}
+
+// TestSidecarSocketOnly covers a node with no TCP listener at all, where no API
+// token exists to demand.
+func TestSidecarSocketOnly(t *testing.T) {
+ node := &SamNode{
+ BiscuitTimeout: 500 * time.Millisecond,
+ services: NewServiceRegistry(&fakeDHT{}),
+ }
+ socketPath := filepath.Join(t.TempDir(), "sam.sock")
+
+ srv, err := StartSidecarServer(node, "", socketPath, "", "", "", "")
+ if err != nil {
+ t.Fatalf("failed to start socket-only sidecar server: %v", err)
+ }
+ defer func() { _ = srv.Close() }()
+
+ waitForSocket(t, socketPath)
+
+ if node.BoundHTTPAddr != "" {
+ t.Errorf("BoundHTTPAddr = %q, want empty with no TCP listener", node.BoundHTTPAddr)
+ }
+}
+
+func TestStartSidecarServerRequiresAListener(t *testing.T) {
+ node := &SamNode{services: NewServiceRegistry(&fakeDHT{})}
+ if _, err := StartSidecarServer(node, "", "", "token", "", "", ""); err == nil {
+ t.Fatal("expected an error when neither a TCP address nor a socket is configured")
+ }
+}
+
+// TestSidecarSocketFailureKeepsTCPServing pins that the socket stays optional:
+// an unusable path degrades to a warning as long as TCP is still serving, but
+// is fatal for a node that has no other way in.
+func TestSidecarSocketFailureKeepsTCPServing(t *testing.T) {
+ unusable := filepath.Join(t.TempDir(), "missing-parent")
+ if err := os.WriteFile(unusable, []byte("not a directory"), 0600); err != nil {
+ t.Fatalf("failed to write the blocking file: %v", err)
+ }
+ socketPath := filepath.Join(unusable, "sam.sock")
+
+ node := &SamNode{
+ BiscuitTimeout: 500 * time.Millisecond,
+ services: NewServiceRegistry(&fakeDHT{}),
+ }
+ srv, err := StartSidecarServer(node, "127.0.0.1:0", socketPath, "test-token", "", "", "")
+ if err != nil {
+ t.Fatalf("a bad socket path must not stop a TCP-serving node: %v", err)
+ }
+ defer func() { _ = srv.Close() }()
+ if node.BoundHTTPAddr == "" {
+ t.Error("expected the TCP listener to be bound")
+ }
+ if node.BoundSocketPath != "" {
+ t.Errorf("BoundSocketPath = %q, want empty after a failed socket", node.BoundSocketPath)
+ }
+
+ socketOnly := &SamNode{services: NewServiceRegistry(&fakeDHT{})}
+ if _, err := StartSidecarServer(socketOnly, "", socketPath, "", "", "", ""); err == nil {
+ t.Error("expected an error when the socket is the only configured listener")
+ }
+}
+
+func TestListenLocalSocket(t *testing.T) {
+ t.Run("replaces a socket left behind by a crashed node", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sam.sock")
+ stale, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatalf("failed to create the stale socket: %v", err)
+ }
+ // Closing without unlinking is what a crash leaves behind.
+ if unixListener, ok := stale.(*net.UnixListener); ok {
+ unixListener.SetUnlinkOnClose(false)
+ }
+ _ = stale.Close()
+
+ listener, err := listenLocalSocket(path)
+ if err != nil {
+ t.Fatalf("listenLocalSocket on a stale socket: %v", err)
+ }
+ _ = listener.Close()
+ })
+
+ t.Run("refuses a socket a live node is using", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sam.sock")
+ live, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatalf("failed to create the live socket: %v", err)
+ }
+ defer func() { _ = live.Close() }()
+ go func() {
+ for {
+ conn, err := live.Accept()
+ if err != nil {
+ return
+ }
+ _ = conn.Close()
+ }
+ }()
+
+ if _, err := listenLocalSocket(path); err == nil {
+ t.Fatal("expected an error when another node is listening on the socket")
+ }
+ })
+
+ t.Run("refuses to remove a file that is not a socket", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sam.sock")
+ if err := os.WriteFile(path, []byte("precious"), 0600); err != nil {
+ t.Fatalf("failed to write the file: %v", err)
+ }
+
+ if _, err := listenLocalSocket(path); err == nil {
+ t.Fatal("expected an error for an existing non-socket file")
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Errorf("the existing file must be left alone: %v", err)
+ }
+ })
+}
+
func TestWithAuth(t *testing.T) {
token := "test-token"
handler := withAuth(token, true, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -170,7 +371,7 @@ func TestSidecarServerAuthEnforcement(t *testing.T) {
token := "test-token"
// Start sidecar on an ephemeral port
- sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", token, "", "", "")
+ sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", "", token, "", "", "")
if err != nil {
t.Fatalf("Failed to start sidecar server: %v", err)
}
@@ -254,7 +455,7 @@ func TestSidecarAuthorizationFallbackScope(t *testing.T) {
}
token := "test-token"
- sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", token, "", "", "")
+ sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", "", token, "", "", "")
if err != nil {
t.Fatalf("Failed to start sidecar server: %v", err)
}
@@ -657,7 +858,7 @@ func TestStartSidecarServer_TokenMandatory(t *testing.T) {
node := &SamNode{BiscuitTimeout: 500 * time.Millisecond}
// Test case: No token, no TLS
- _, err := StartSidecarServer(node, "127.0.0.1:0", "", "", "", "")
+ _, err := StartSidecarServer(node, "127.0.0.1:0", "", "", "", "", "")
if err == nil {
t.Fatal("Expected StartSidecarServer to fail without token and TLS, but it succeeded")
}
@@ -666,7 +867,7 @@ func TestStartSidecarServer_TokenMandatory(t *testing.T) {
}
// Test case: Token provided, should not fail immediately
- sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", "some-token", "", "", "")
+ sidecarSrv, err := StartSidecarServer(node, "127.0.0.1:0", "", "some-token", "", "", "")
if err == nil {
defer func() { _ = sidecarSrv.Close() }()
} else {
diff --git a/mobile/sam-node-ffi/ffi/ffi.go b/mobile/sam-node-ffi/ffi/ffi.go
index a04346e9..482f2ad7 100644
--- a/mobile/sam-node-ffi/ffi/ffi.go
+++ b/mobile/sam-node-ffi/ffi/ffi.go
@@ -114,7 +114,7 @@ func StartNode(configJSON string) error {
if bindAddr == "" {
bindAddr = "127.0.0.1:8080"
}
- srv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddr, "", "")
+ srv, err := node.StartUnauthSidecarServer(displayControlPlane, bindAddr, "", "", "")
if err != nil {
_ = store.Close()
activeStore = nil
@@ -193,7 +193,7 @@ func StartNode(configJSON string) error {
if bindAddr == "" {
bindAddr = "127.0.0.1:8080"
}
- sidecarSrv, err = node.StartSidecarServer(samNode, bindAddr, config.ApiToken, "", "", "")
+ sidecarSrv, err = node.StartSidecarServer(samNode, bindAddr, "", config.ApiToken, "", "", "")
if err != nil {
_ = stopNodeInternal()
return fmt.Errorf("failed to start sidecar server: %w", err)
diff --git a/site/content/docs/integrations/antigravity.md b/site/content/docs/integrations/antigravity.md
index 25c43b30..011b4b96 100644
--- a/site/content/docs/integrations/antigravity.md
+++ b/site/content/docs/integrations/antigravity.md
@@ -29,6 +29,7 @@ sam-node run --daemonize
sam-node is running in the background.
PID 48213
Endpoint http://127.0.0.1:8080/mcp
+ Socket /home/you/.config/sam-mesh/sam.sock
Token /home/you/.config/sam-mesh/api-token
Logs /home/you/.config/sam-mesh/sam-node.log
Stop kill 48213
@@ -36,6 +37,12 @@ sam-node is running in the background.
The command is idempotent: re-run it any time to make sure a node is up. Enrollment still needs a one-time login, so if the node has no identity yet the command tells you to run `sam-node join --headless <control-plane-url>` first, which prints a URL and a code to complete in your browser.
+Antigravity's MCP client needs the HTTP endpoint, but the socket serves the same API for anything the agent runs in a shell — including mesh inference — without a token to pass around:
+
+```bash
+curl --unix-socket ~/.config/sam-mesh/sam.sock http://localhost/v1/models
+```
+
### Alternative: a dedicated terminal
On the very first run, `--join` needs an interactive terminal to complete the browser/device-code login; after that, the identity is stored and `--join` is a no-op, so the node can be started detached/hidden freely.
diff --git a/site/content/docs/user/agent-usage.md b/site/content/docs/user/agent-usage.md
index e166debf..11ab0c4c 100644
--- a/site/content/docs/user/agent-usage.md
+++ b/site/content/docs/user/agent-usage.md
@@ -76,8 +76,9 @@ SAM_API_TOKEN="my-agent-super-token-123" sam-node run --bind-addr "127.0.0.1:808
```
### Key CLI Parameters
-* `--bind-addr`: The local TCP address where the node's local HTTP server runs (default: `127.0.0.1:8080`).
-* API token (`SAM_API_TOKEN` env or `--api-token-path` file): a security token required by any local AI agent attempting to connect to your node.
+* `--bind-addr`: The local TCP address where the node's local HTTP server runs (default: `127.0.0.1:8080`). Pass an empty value to serve only on the Unix socket.
+* `--socket-path`: Unix socket serving the same API (default: `<data-dir>/sam.sock`). Pass an empty value to disable it.
+* API token (`SAM_API_TOKEN` env or `--api-token-path` file): a security token required by any local AI agent attempting to connect to your node over TCP.
* `--data-dir`: Custom path to store configurations and Biscuit tokens (defaults to `~/.config/sam-mesh` or env `SAM_DATA_DIR`).
---
@@ -90,6 +91,28 @@ Your AI agent connects to the node's local MCP server. The local server translat
The local MCP endpoint is served via **HTTP Server-Sent Events (SSE)** at:
`http://127.0.0.1:8080/mcp`
+The node serves the very same API on a Unix socket, `<data-dir>/sam.sock`
+(usually `~/.config/sam-mesh/sam.sock`). Reaching that socket already proves
+the caller is the user who owns it — the same bar as reading the token file —
+so requests over it need no token, exactly like `docker.sock`:
+
+```bash
+curl --unix-socket ~/.config/sam-mesh/sam.sock \
+ http://localhost/v1/chat/completions \
+ -H 'Content-Type: application/json' \
+ -d '{"model": "mistralai/mistral-7b-instruct", "messages": [{"role": "user", "content": "Write a haiku about a decentralized mesh network."}]}'
+```
+
+(`http://localhost` is a placeholder host that clients ignore once they dial a
+socket.) The socket is created with `0600` permissions inside the `0700` data
+directory, and removed when the node stops.
+
+Most MCP clients speak only stdio or HTTP, so the TCP listener stays on by
+default and the socket is an addition rather than a replacement. Use
+`--socket-path ""` to run without it, or `--bind-addr ""` to drop the TCP port
+and serve the API exclusively over the socket, which leaves the node with no
+listening port and no shared secret to manage.
+
### Authentication
When configuring your agent client, you must pass the API token in a SAM-specific
header — not the standard `Authorization` header: