Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
nano-init: use a vsock library, and test the path it serves
Antonio Ojea15c9a7ba3fdc
diff --git a/cmd/nano-init/go.mod b/cmd/nano-init/go.modindex 6e77a65c..406c8feb 100644--- a/cmd/nano-init/go.mod+++ b/cmd/nano-init/go.mod@@ -3,6 +3,7 @@ module github.com/google/sam/cmd/nano-initgo 1.26.5require (+ github.com/mdlayher/vsock v1.3.0github.com/vishvananda/netlink v1.3.1github.com/xjasonlyu/tun2socks/v2 v2.7.0golang.org/x/net v0.58.0@@ -21,12 +22,14 @@ require (github.com/google/uuid v1.6.0 // indirectgithub.com/gorilla/schema v1.4.1 // indirectgithub.com/gorilla/websocket v1.5.3 // indirect+ github.com/mdlayher/socket v0.6.0 // indirectgithub.com/vishvananda/netns v0.0.5 // indirectgo.uber.org/atomic v1.11.0 // indirectgo.uber.org/multierr v1.11.0 // indirectgo.uber.org/zap v1.28.0 // indirectgolang.org/x/crypto v0.55.0 // indirectgolang.org/x/exp v0.0.0-20260611194520-c48552f49976 // indirect+ golang.org/x/sync v0.21.0 // indirectgolang.org/x/time v0.15.0 // indirectgolang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirectgolang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 // indirectdiff --git a/cmd/nano-init/go.sum b/cmd/nano-init/go.sumindex c5b18ad4..4014fa43 100644--- a/cmd/nano-init/go.sum+++ b/cmd/nano-init/go.sum@@ -15,6 +15,8 @@ github.com/go-gost/relay v0.6.1 h1:7SqnHFbY8x/DzvjpK03a5zcVH9+TbJAcnW/RT6s1ecc=github.com/go-gost/relay v0.6.1/go.mod h1:Dku0f5sfjOClrZFiDmQUrYYJ4uof7rnkCUBfsl0PSAI=github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=@@ -23,6 +25,10 @@ github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=github.com/gorilla/schema v1.4.1/go.mod h1:Dg5SSm5PV60mhF2NFaTV1xuYYj8tV8NOPRo4FggUMnM=github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/mdlayher/socket v0.6.0 h1:ScZPaAGyO1icQnbFrhPM8mnXyMu9qukC1K4ZoM2IQKU=+github.com/mdlayher/socket v0.6.0/go.mod h1:q7vozUAnxSqnjHc12Fik5yUKIzfZ8ITCfMkhOtE9z18=+github.com/mdlayher/vsock v1.3.0 h1:bqQfZ1OznI03y6YiXp2sze05RVdzLn/zsfjnjd4+ivI=+github.com/mdlayher/vsock v1.3.0/go.mod h1:WsuksavOvwCnV5UqGHUkvAvCy+Dqy81y4goKQTzxxNY=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=@@ -49,6 +55,8 @@ golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZCgolang.org/x/exp v0.0.0-20260611194520-c48552f49976/go.mod h1:vnf4pv9iKZXY58sQE1L86zmNWJ4159e1RkcWiLCkeEY=golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=diff --git a/cmd/nano-init/vsock.go b/cmd/nano-init/vsock.goindex 804cb087..b2947ac8 100644--- a/cmd/nano-init/vsock.go+++ b/cmd/nano-init/vsock.go@@ -22,7 +22,7 @@ import ("strconv""strings"- "golang.org/x/sys/unix"+ "github.com/mdlayher/vsock")// A sandbox reaches its boundary one of two ways, and the difference is the@@ -31,19 +31,35 @@ import (// A container gets the socket bind-mounted in, so it dials a path. A microVM// has no shared filesystem and no network device, so it dials vsock, and// Firecracker delivers that to a Unix socket on the host named-// "<uds_path>_<port>". Both arrive at the same sam-box, which is why one-// binary serves both and neither sandbox contains anything that knows which-// kind it is beyond this string.+// "<uds_path>_<port>". Both arrive at the same sam-box, which is why one binary+// serves both and nothing else in the sandbox knows which kind it is.+//+// The vsock socket work is a library rather than forty lines of syscalls here.+// It was forty lines of syscalls, and they were wrong: net.FileConn refuses an+// AF_VSOCK descriptor outright, and the replacement leaned on os.File's poller+// registration for deadlines, which degrades silently to no deadlines at all if+// registration fails. Both are the kind of mistake that surfaces as a hung flow+// under load rather than an error at startup. This module already carries a+// TCP stack, so a thousand lines of well-exercised socket handling is not the+// dependency worth economising on.const vsockScheme = "vsock://"// dialBoundary opens a connection to the boundary named by spec, which is// either "vsock://<cid>:<port>" or a Unix socket path.func dialBoundary(ctx context.Context, spec string) (net.Conn, error) {- if strings.HasPrefix(spec, vsockScheme) {- return dialVsock(ctx, strings.TrimPrefix(spec, vsockScheme))+ if !strings.HasPrefix(spec, vsockScheme) {+ return (&net.Dialer{Timeout: boundaryDialTimeout}).DialContext(ctx, "unix", spec)+ }++ cid, port, err := parseVsock(strings.TrimPrefix(spec, vsockScheme))+ if err != nil {+ return nil, err}- return (&net.Dialer{Timeout: boundaryDialTimeout}).DialContext(ctx, "unix", spec)+ // There is no context-aware Dial, and none is needed: the peer is the+ // hypervisor on the other side of a virtual bus, so this either succeeds+ // or fails immediately rather than waiting on anything that could hang.+ return vsock.Dial(cid, port, nil)}// checkBoundary reports whether the boundary named by spec could plausibly be@@ -54,9 +70,8 @@ func checkBoundary(spec string) error {if _, _, err := parseVsock(strings.TrimPrefix(spec, vsockScheme)); err != nil {return err}- // Whether the host is listening cannot be known until a connection is- // attempted, and attempting one here would consume a flow the agent- // has not asked for yet.+ // Whether the host is listening cannot be known without connecting,+ // and connecting here would consume a flow the agent has not asked for.return nil}if _, err := os.Stat(spec); err != nil {@@ -81,36 +96,3 @@ func parseVsock(hostPort string) (cid, port uint32, err error) {}return uint32(parsedCID), uint32(parsedPort), nil}--// dialVsock opens an AF_VSOCK connection.-//-// This is done by hand rather than with a library because it is one socket, one-// connect, and a library would be a dependency carried into every sandbox for-// forty lines.-func dialVsock(ctx context.Context, hostPort string) (net.Conn, error) {- cid, port, err := parseVsock(hostPort)- if err != nil {- return nil, err- }-- fd, err := unix.Socket(unix.AF_VSOCK, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)- if err != nil {- return nil, fmt.Errorf("vsock socket: %w", err)- }-- if err := unix.Connect(fd, &unix.SockaddrVM{CID: cid, Port: port}); err != nil {- _ = unix.Close(fd)- return nil, fmt.Errorf("vsock connect %d:%d: %w", cid, port, err)- }-- // net.FileConn dups the descriptor and hands it to the runtime poller, so- // the original has to be closed or every flow leaks one.- file := os.NewFile(uintptr(fd), "vsock")- defer func() { _ = file.Close() }()-- conn, err := net.FileConn(file)- if err != nil {- return nil, fmt.Errorf("vsock conn: %w", err)- }- return conn, nil-}diff --git a/cmd/nano-init/vsock_test.go b/cmd/nano-init/vsock_test.gonew file mode 100644index 00000000..a8535b69--- /dev/null+++ b/cmd/nano-init/vsock_test.go@@ -0,0 +1,186 @@+// 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"+ "io"+ "net"+ "testing"+ "time"++ "golang.org/x/sys/unix"+)++// The vsock path is the microVM's only way out, and it is the one part of this+// program that cannot be exercised by the container sandbox. Left untested it+// would be discovered on a cloud VM in the middle of a scale run, which is an+// expensive place to find out that a socket option is wrong.+//+// Linux can loop vsock back to the host, so none of this needs a VM: the guest+// side of a real Firecracker connection makes the same calls against the same+// kernel code.++// vsockLoopback is VMADDR_CID_LOCAL, the CID that means "this machine".+const vsockLoopback = 1++func TestDialBoundaryOverVsock(t *testing.T) {+ listener, port := listenVsock(t)+ defer func() { _ = unix.Close(listener) }()++ accepted := make(chan []byte, 1)+ go func() {+ fd, _, err := unix.Accept(listener)+ if err != nil {+ accepted <- nil+ return+ }+ defer func() { _ = unix.Close(fd) }()++ buf := make([]byte, 5)+ if _, err := unix.Read(fd, buf); err != nil {+ accepted <- nil+ return+ }+ _, _ = unix.Write(fd, []byte("PONG"))+ accepted <- buf+ }()++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ conn, err := dialBoundary(ctx, vsockSpec(port))+ if err != nil {+ t.Fatalf("dialBoundary over vsock: %v", err)+ }+ defer func() { _ = conn.Close() }()++ if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {+ t.Fatalf("SetDeadline: %v", err)+ }+ if _, err := conn.Write([]byte("HELLO")); err != nil {+ t.Fatalf("write: %v", err)+ }++ reply := make([]byte, 4)+ if _, err := io.ReadFull(conn, reply); err != nil {+ t.Fatalf("read: %v", err)+ }+ if string(reply) != "PONG" {+ t.Errorf("reply = %q, want PONG", reply)+ }++ if got := <-accepted; string(got) != "HELLO" {+ t.Errorf("boundary received %q, want HELLO", got)+ }+}++func TestVsockConnectionIsAUsableNetConn(t *testing.T) {+ // The connection is handed to gVisor as an ordinary net.Conn and spliced+ // against sandbox traffic, so deadlines and Close have to work. A raw+ // descriptor wrapped carelessly satisfies the interface and then blocks+ // forever on a read that should have timed out.+ listener, port := listenVsock(t)+ defer func() { _ = unix.Close(listener) }()++ go func() {+ fd, _, err := unix.Accept(listener)+ if err != nil {+ return+ }+ // Accept and then say nothing, so the read below has to time out.+ time.Sleep(3 * time.Second)+ _ = unix.Close(fd)+ }()++ conn, err := dialBoundary(context.Background(), vsockSpec(port))+ if err != nil {+ t.Fatalf("dialBoundary: %v", err)+ }+ defer func() { _ = conn.Close() }()++ if err := conn.SetReadDeadline(time.Now().Add(200 * time.Millisecond)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ _, err = conn.Read(make([]byte, 1))+ if err == nil {+ t.Fatal("a read with an expired deadline returned no error")+ }+ var timeout net.Error+ if !errors.As(err, &timeout) || !timeout.Timeout() {+ t.Errorf("read error = %v, want a timeout", err)+ }+}++func TestDialBoundaryReportsAnAbsentVsocklistener(t *testing.T) {+ // A microVM whose host is not listening must fail loudly. Hanging would+ // look to the agent like a slow mesh rather than an absent one.+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ // Port 1 is not something this test ever binds.+ if _, err := dialBoundary(ctx, "vsock://1:1"); err == nil {+ t.Error("dialling a vsock port nobody listens on returned no error")+ }+}++// listenVsock binds a loopback vsock listener and returns it with its port.+func listenVsock(t *testing.T) (fd, port int) {+ t.Helper()++ fd, err := unix.Socket(unix.AF_VSOCK, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)+ if err != nil {+ t.Skipf("no AF_VSOCK on this kernel: %v", err)+ }++ // Port 0 asks the kernel to choose, so concurrent runs cannot collide.+ if err := unix.Bind(fd, &unix.SockaddrVM{CID: unix.VMADDR_CID_ANY, Port: 0}); err != nil {+ _ = unix.Close(fd)+ t.Skipf("cannot bind vsock (is vsock_loopback loaded?): %v", err)+ }+ if err := unix.Listen(fd, 1); err != nil {+ _ = unix.Close(fd)+ t.Skipf("cannot listen on vsock: %v", err)+ }++ sa, err := unix.Getsockname(fd)+ if err != nil {+ _ = unix.Close(fd)+ t.Fatalf("Getsockname: %v", err)+ }+ vm, ok := sa.(*unix.SockaddrVM)+ if !ok {+ _ = unix.Close(fd)+ t.Fatalf("Getsockname returned %T, want *unix.SockaddrVM", sa)+ }+ return fd, int(vm.Port)+}++func vsockSpec(port int) string {+ return "vsock://" + itoa(vsockLoopback) + ":" + itoa(port)+}++func itoa(v int) string {+ if v == 0 {+ return "0"+ }+ var digits []byte+ for v > 0 {+ digits = append([]byte{byte('0' + v%10)}, digits...)+ v /= 10+ }+ return string(digits)+}