carlos / platform Public

devbox on macOS (#488) Task 3: launchd socket activation, LOCAL_PEERCRED

internal/launchd: Listeners(name) calls launch_activate_socket(3) and
free(3) in libSystem with no cgo, in x/sys/unix's form: a
//go:cgo_import_dynamic per symbol, per-arch assembly trampolines, and
syscall.syscall reached by linkname (the syscall package marks it for
that). ESRCH is ErrNotManaged, ENOENT is ErrNoSocket; each fd is wrapped
with net.FileListener and the original closed. Elsewhere it returns
errors.ErrUnsupported.

internal/devbox: PeerUID on darwin reads LOCAL_PEERCRED (struct xucred)
and refuses a version other than XUCRED_VERSION (0). peer_other.go is now
!linux && !darwin. Uid 0 is not special.

internal/edge: DevboxConfig.Listener is served on instead of binding.
CheckDevboxListener holds it to ListenAddr exactly (same IP and port,
TCP) and refuses every interface; the refusal is a *DevboxListenerError
the CLI words. ServeDevbox closes a given listener whatever happens.

carlos devbox serve: with CARLOS_DEVBOX_LAUNCHD_SOCKET set it takes that
socket, refuses zero or several, and checks it against
CARLOS_DEVBOX_LISTEN before making anything. Strings DBX-C66..C71.

Linux tests pass; darwin vet and test compilation pass for
internal/devbox, internal/launchd and the root package. (internal/edge's
darwin test build fails on main already: readerConn lives in a
linux-only test file.)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f73c96f4fda05db53e0cd14db1e4908b1832e016 parent 2f14384
14 files changed, +663 −9
  • devbox_cli.go +82 −2
  • devbox_cli_test.go +107 −0
  • internal/devbox/peer_darwin.go +48 −0
  • internal/devbox/peer_darwin_test.go +54 −0
  • internal/devbox/peer_other.go +4 −3
  • internal/edge/devbox.go +69 −4
  • internal/edge/devbox_test.go +103 −0
  • internal/launchd/activate_darwin.go +82 −0
  • internal/launchd/activate_darwin_amd64.s +15 −0
  • internal/launchd/activate_darwin_arm64.s +15 −0
  • internal/launchd/activate_darwin_test.go +34 −0
  • internal/launchd/activate_other.go +14 −0
  • internal/launchd/activate_other_test.go +15 −0
  • internal/launchd/launchd.go +21 −0
diff --git a/devbox_cli.go b/devbox_cli.go
index cfb4c9db9..f8b1971cc 100644
--- a/devbox_cli.go
+++ b/devbox_cli.go
@@ -36,6 +36,7 @@ import (
"github.com/carlosframework/platform/internal/devbox"
"github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/launchd"
"github.com/carlosframework/platform/internal/registry"
)
@@ -87,6 +88,25 @@ func devboxEnvDuplicate(key, file string, first, second int) string {
return fmt.Sprintf("%s is set twice in %s, on lines %d and %d. keep one", key, file, first, second) // DBX-C65
}
+// The launchd socket's rows.
+const (
+ devboxLaunchdNotManaged = "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but launchd did not start this process, so there is no socket to take. start the service with launchctl, or unset CARLOS_DEVBOX_LAUNCHD_SOCKET to run it by hand" // DBX-C66
+ devboxLaunchdUnsupported = "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but only macOS hands over sockets this way. unset it, and the service binds CARLOS_DEVBOX_LISTEN itself" // DBX-C69
+)
+
+func devboxLaunchdNoSocket(name string) string {
+ return fmt.Sprintf("launchd has no socket called %s for this service. the Sockets entry in the plist and CARLOS_DEVBOX_LAUNCHD_SOCKET must use the same name", name) // DBX-C67
+}
+func devboxLaunchdTooMany(count int, name string) string {
+ return fmt.Sprintf("launchd handed over %d sockets called %s, and the service serves on exactly one. set SockFamily to IPv4 in the plist", count, name) // DBX-C68
+}
+func devboxLaunchdEveryInterface(addr string) string {
+ return fmt.Sprintf("launchd's socket listens on every interface, %s. set SockNodeName in the plist to the tailnet address in CARLOS_DEVBOX_LISTEN", addr) // DBX-C70
+}
+func devboxLaunchdWrongAddr(addr, want string) string {
+ return fmt.Sprintf("launchd's socket listens on %s, but CARLOS_DEVBOX_LISTEN is %s. make SockNodeName and SockServiceName in the plist match it", addr, want) // DBX-C71
+}
+
// The rows with placeholders, one format each.
func devboxPrinted(url string) string { return url } // DBX-C11
func devboxRemoved(url string) string { return fmt.Sprintf("removed %s", url) } // DBX-C12
@@ -598,6 +618,24 @@ func runDevboxServe(args []string) error {
}) {
return fmt.Errorf("devbox serve: CARLOS_DEVBOX_DOMAIN %s is not in CARLOS_WILDCARD_DOMAINS", domain)
}
+ // On macOS launchd binds port 443 and hands the socket over; the plist
+ // names its Sockets entry here. It is held to CARLOS_DEVBOX_LISTEN
+ // before anything else starts.
+ var given net.Listener
+ if name := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_LAUNCHD_SOCKET")); name != "" {
+ ln, err := devboxLaunchdListener(name, launchd.Listeners)
+ if err != nil {
+ return err
+ }
+ if err := edge.CheckDevboxListener(ln, listen); err != nil {
+ ln.Close()
+ return devboxListenerRefusal(err)
+ }
+ // ServeDevbox closes it once it has it; this is for a failure on
+ // the way there.
+ defer ln.Close()
+ given = ln
+ }
// The unit's StateDirectory makes it; this is for a run outside one.
if err := os.MkdirAll(dataDir, 0o700); err != nil {
return fmt.Errorf("devbox serve: %w", err)
@@ -620,11 +658,53 @@ func runDevboxServe(args []string) error {
SpoolCap: devboxSpoolCap,
LookupUser: lookupUsername,
}
- cfg := edge.DevboxConfig{Registry: reg, ListenAddr: listen, CertDir: filepath.Join(dataDir, "certs"), SpoolRoot: spool}
+ cfg := edge.DevboxConfig{Registry: reg, ListenAddr: listen, Listener: given, CertDir: filepath.Join(dataDir, "certs"), SpoolRoot: spool}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
- return serveDevboxParts(ctx, devboxSocketPath(), r, func(ctx context.Context) error { return edge.ServeDevbox(ctx, cfg) })
+ return serveDevboxParts(ctx, devboxSocketPath(), r, func(ctx context.Context) error {
+ return devboxListenerRefusal(edge.ServeDevbox(ctx, cfg))
+ })
+}
+
+// devboxLaunchdListener takes the one listening socket launchd opened for
+// the plist's Sockets entry called name, refusing in the deck's words what
+// it cannot serve on. take is launchd.Listeners (a test replaces it).
+func devboxLaunchdListener(name string, take func(string) ([]net.Listener, error)) (net.Listener, error) {
+ lns, err := take(name)
+ switch {
+ case errors.Is(err, errors.ErrUnsupported):
+ return nil, errors.New(devboxLaunchdUnsupported)
+ case errors.Is(err, launchd.ErrNotManaged):
+ return nil, errors.New(devboxLaunchdNotManaged)
+ case errors.Is(err, launchd.ErrNoSocket):
+ return nil, errors.New(devboxLaunchdNoSocket(name))
+ case err != nil:
+ return nil, fmt.Errorf("devbox serve: %w", err)
+ }
+ switch len(lns) {
+ case 0:
+ return nil, errors.New(devboxLaunchdNoSocket(name))
+ case 1:
+ return lns[0], nil
+ }
+ for _, ln := range lns {
+ ln.Close()
+ }
+ return nil, errors.New(devboxLaunchdTooMany(len(lns), name))
+}
+
+// devboxListenerRefusal words the edge's refusal of launchd's socket for a
+// person; any other error is returned as it is.
+func devboxListenerRefusal(err error) error {
+ var le *edge.DevboxListenerError
+ if !errors.As(err, &le) {
+ return err
+ }
+ if le.Unspecified {
+ return errors.New(devboxLaunchdEveryInterface(le.Addr))
+ }
+ return errors.New(devboxLaunchdWrongAddr(le.Addr, le.Want))
}
// lookupUsername is the account name for uid, or "" when this machine has
diff --git a/devbox_cli_test.go b/devbox_cli_test.go
index a45d8348a..057c51441 100644
--- a/devbox_cli_test.go
+++ b/devbox_cli_test.go
@@ -22,10 +22,13 @@ import (
"runtime"
"strings"
"sync"
+ "syscall"
"testing"
"time"
"github.com/carlosframework/platform/internal/devbox"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/launchd"
"github.com/carlosframework/platform/internal/registry"
)
@@ -641,3 +644,107 @@ func TestDevboxDefaultSocketPath(t *testing.T) {
t.Errorf("override = %q", got)
}
}
+
+// ---- serve on launchd's socket (macOS plan #488 Task 3) ---------------------
+
+// closeCounter is a listener that counts its Close calls.
+type closeCounter struct {
+ net.Listener
+ closed int
+}
+
+func (c *closeCounter) Close() error { c.closed++; return nil }
+
+func TestDevboxServeLaunchdRefusals(t *testing.T) {
+ refused := func(err error) func(string) ([]net.Listener, error) {
+ return func(string) ([]net.Listener, error) { return nil, err }
+ }
+ for _, c := range []struct {
+ name string
+ take func(string) ([]net.Listener, error)
+ want string
+ }{
+ {"not macOS", refused(errors.ErrUnsupported),
+ "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but only macOS hands over sockets this way. unset it, and the service binds CARLOS_DEVBOX_LISTEN itself"},
+ {"not started by launchd", refused(fmt.Errorf("%w (%w)", launchd.ErrNotManaged, syscall.ESRCH)),
+ "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but launchd did not start this process, so there is no socket to take. start the service with launchctl, or unset CARLOS_DEVBOX_LAUNCHD_SOCKET to run it by hand"},
+ {"no such socket", refused(fmt.Errorf("%w: x", launchd.ErrNoSocket)),
+ "launchd has no socket called Listeners for this service. the Sockets entry in the plist and CARLOS_DEVBOX_LAUNCHD_SOCKET must use the same name"},
+ {"none handed over", refused(nil),
+ "launchd has no socket called Listeners for this service. the Sockets entry in the plist and CARLOS_DEVBOX_LAUNCHD_SOCKET must use the same name"},
+ } {
+ ln, err := devboxLaunchdListener("Listeners", c.take)
+ if ln != nil || err == nil || err.Error() != c.want {
+ t.Errorf("%s: = %v, %v, want %q", c.name, ln, err, c.want)
+ }
+ }
+
+ // Two sockets (an IPv4 and an IPv6 one): refused, and both closed.
+ a, b := &closeCounter{}, &closeCounter{}
+ ln, err := devboxLaunchdListener("Listeners", func(string) ([]net.Listener, error) { return []net.Listener{a, b}, nil })
+ want := "launchd handed over 2 sockets called Listeners, and the service serves on exactly one. set SockFamily to IPv4 in the plist"
+ if ln != nil || err == nil || err.Error() != want {
+ t.Errorf("two sockets: = %v, %v, want %q", ln, err, want)
+ }
+ if a.closed != 1 || b.closed != 1 {
+ t.Errorf("two sockets: closed %d and %d times, want once each", a.closed, b.closed)
+ }
+
+ // One socket is the listener.
+ one := &closeCounter{}
+ ln, err = devboxLaunchdListener("Listeners", func(name string) ([]net.Listener, error) {
+ if name != "Listeners" {
+ t.Errorf("asked launchd for %q", name)
+ }
+ return []net.Listener{one}, nil
+ })
+ if err != nil || ln != one || one.closed != 0 {
+ t.Errorf("one socket: = %v, %v (closed %d)", ln, err, one.closed)
+ }
+
+ // The real thing, on Linux.
+ if _, err := devboxLaunchdListener("Listeners", launchd.Listeners); err == nil || !strings.HasPrefix(err.Error(), "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but only macOS") {
+ t.Errorf("launchd.Listeners on linux: %v", err)
+ }
+}
+
+func TestDevboxServeListenerRefusals(t *testing.T) {
+ for _, c := range []struct {
+ err error
+ want string
+ }{
+ {&edge.DevboxListenerError{Addr: "0.0.0.0:443", Want: "100.64.0.10:443", Unspecified: true},
+ "launchd's socket listens on every interface, 0.0.0.0:443. set SockNodeName in the plist to the tailnet address in CARLOS_DEVBOX_LISTEN"},
+ {fmt.Errorf("wrapped: %w", &edge.DevboxListenerError{Addr: "100.64.0.11:443", Want: "100.64.0.10:443"}),
+ "launchd's socket listens on 100.64.0.11:443, but CARLOS_DEVBOX_LISTEN is 100.64.0.10:443. make SockNodeName and SockServiceName in the plist match it"},
+ } {
+ if got := devboxListenerRefusal(c.err); got == nil || got.Error() != c.want {
+ t.Errorf("%v: = %v, want %q", c.err, got, c.want)
+ }
+ }
+ other := errors.New("edge broke")
+ if got := devboxListenerRefusal(other); got != other {
+ t.Errorf("another error = %v, want it unchanged", got)
+ }
+ if devboxListenerRefusal(nil) != nil {
+ t.Error("nil became an error")
+ }
+}
+
+// serve with CARLOS_DEVBOX_LAUNCHD_SOCKET set on Linux stops with the deck's
+// words, before it makes anything.
+func TestDevboxServeLaunchdSocketOnLinux(t *testing.T) {
+ data := filepath.Join(t.TempDir(), "data")
+ t.Setenv("CARLOS_DEVBOX_LISTEN", "127.0.0.1:8443")
+ t.Setenv("CARLOS_DEVBOX_DOMAIN", "devbox.example.com")
+ t.Setenv("CARLOS_WILDCARD_DOMAINS", "devbox.example.com")
+ t.Setenv("CARLOS_DATA_DIR", data)
+ t.Setenv("CARLOS_DEVBOX_LAUNCHD_SOCKET", "Listeners")
+ err := runDevboxServe(nil)
+ if err == nil || !strings.HasPrefix(err.Error(), "CARLOS_DEVBOX_LAUNCHD_SOCKET is set, but only macOS") {
+ t.Fatalf("serve = %v", err)
+ }
+ if _, err := os.Stat(data); err == nil {
+ t.Fatal("serve made the data dir before refusing")
+ }
+}
diff --git a/internal/devbox/peer_darwin.go b/internal/devbox/peer_darwin.go
new file mode 100644
index 000000000..b6be12f36
--- /dev/null
+++ b/internal/devbox/peer_darwin.go
@@ -0,0 +1,48 @@
+//go:build darwin
+
+package devbox
+
+import (
+ "errors"
+ "fmt"
+ "net"
+
+ "golang.org/x/sys/unix"
+)
+
+// xucredVersion is XUCRED_VERSION from <sys/ucred.h>, the only layout of
+// struct xucred the kernel writes. x/sys/unix does not export it.
+const xucredVersion = 0
+
+// PeerUID returns the uid of the process at the other end of a Unix socket,
+// as the kernel recorded it at connect time (LOCAL_PEERCRED, macOS's
+// SO_PEERCRED). Any other kind of connection, or credentials in a layout
+// this code does not know, is an error: no uid, no identity. Uid 0 is a uid
+// like any other.
+func PeerUID(c net.Conn) (uint32, error) {
+ uc, ok := c.(*net.UnixConn)
+ if !ok {
+ return 0, errors.New("devbox: not a unix connection")
+ }
+ raw, err := uc.SyscallConn()
+ if err != nil {
+ return 0, err
+ }
+ var cred *unix.Xucred
+ var cerr error
+ if err := raw.Control(func(fd uintptr) {
+ cred, cerr = unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
+ }); err != nil {
+ return 0, err
+ }
+ if cerr != nil {
+ return 0, cerr
+ }
+ if cred == nil {
+ return 0, errors.New("devbox: no peer credentials")
+ }
+ if cred.Version != xucredVersion {
+ return 0, fmt.Errorf("devbox: peer credentials in xucred version %d, want %d", cred.Version, xucredVersion)
+ }
+ return cred.Uid, nil
+}
diff --git a/internal/devbox/peer_darwin_test.go b/internal/devbox/peer_darwin_test.go
new file mode 100644
index 000000000..7e0b3f412
--- /dev/null
+++ b/internal/devbox/peer_darwin_test.go
@@ -0,0 +1,54 @@
+//go:build darwin
+
+package devbox
+
+import (
+ "net"
+ "os"
+ "testing"
+
+ "golang.org/x/sys/unix"
+)
+
+// A Unix socket pair made by this process: LOCAL_PEERCRED attributes the
+// other end to this process's uid. A TCP connection has no peer uid.
+func TestPeerUIDDarwin(t *testing.T) {
+ fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conns := make([]net.Conn, 2)
+ for i, fd := range fds {
+ f := os.NewFile(uintptr(fd), "pair")
+ c, err := net.FileConn(f) // dups fd
+ f.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Close() })
+ conns[i] = c
+ }
+ for _, c := range conns {
+ uid, err := PeerUID(c)
+ if err != nil {
+ t.Fatalf("PeerUID = %v", err)
+ }
+ if uid != uint32(os.Getuid()) {
+ t.Fatalf("PeerUID = %d, want %d", uid, os.Getuid())
+ }
+ }
+
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ c, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ if _, err := PeerUID(c); err == nil {
+ t.Fatal("PeerUID on a TCP connection = nil error, want a refusal")
+ }
+}
diff --git a/internal/devbox/peer_other.go b/internal/devbox/peer_other.go
index 5f36c4f9f..5698a0f40 100644
--- a/internal/devbox/peer_other.go
+++ b/internal/devbox/peer_other.go
@@ -1,4 +1,4 @@
-//go:build !linux
+//go:build !linux && !darwin
package devbox
@@ -7,8 +7,9 @@ import (
"net"
)
-// PeerUID is Linux only: elsewhere there is no SO_PEERCRED, so no caller has
-// an identity and the registrar refuses every request.
+// PeerUID is Linux and macOS only: elsewhere there is no SO_PEERCRED or
+// LOCAL_PEERCRED, so no caller has an identity and the registrar refuses
+// every request.
func PeerUID(c net.Conn) (uint32, error) {
return 0, errors.ErrUnsupported
}
diff --git a/internal/edge/devbox.go b/internal/edge/devbox.go
index 4d1605e9c..b85c7c1c4 100644
--- a/internal/edge/devbox.go
+++ b/internal/edge/devbox.go
@@ -40,6 +40,57 @@ type DevboxConfig struct {
ListenAddr string // host:port; host must be a specific IP
CertDir string // autocert.DirCache for the wildcard + ACME account key
SpoolRoot string // passed to WithLocalStatic
+ // Listener, when set, is served on instead of binding ListenAddr: on
+ // macOS launchd binds port 443 and hands the socket over (#488). It
+ // must be on ListenAddr exactly (CheckDevboxListener). ServeDevbox
+ // owns it from the call on and closes it before returning.
+ Listener net.Listener
+}
+
+// DevboxListenerError is a listener handed to ServeDevbox that is not on
+// ListenAddr: Addr is where it listens and Want is ListenAddr. Unspecified
+// says it listens on every interface (0.0.0.0 or ::), which is never
+// served. The caller words it for a person.
+type DevboxListenerError struct {
+ Addr, Want string
+ Unspecified bool
+}
+
+func (e *DevboxListenerError) Error() string {
+ if e.Unspecified {
+ return fmt.Sprintf("edge: devbox: the given listener is on %s, which is every interface; want %s", e.Addr, e.Want)
+ }
+ return fmt.Sprintf("edge: devbox: the given listener is on %s, not on the listen address %s", e.Addr, e.Want)
+}
+
+// CheckDevboxListener refuses, with a *DevboxListenerError, a listener that
+// is not a TCP listener on exactly listenAddr (the same IP and port), or
+// that listens on every interface. A listenAddr ServeDevbox would refuse
+// is refused first, with that error.
+func CheckDevboxListener(ln net.Listener, listenAddr string) error {
+ if err := checkDevboxListenAddr(listenAddr); err != nil {
+ return err
+ }
+ addr := ln.Addr()
+ refused := &DevboxListenerError{Addr: addr.String(), Want: listenAddr}
+ tcp, ok := addr.(*net.TCPAddr)
+ if !ok {
+ return refused
+ }
+ got, ok := netip.AddrFromSlice(tcp.IP)
+ if !ok {
+ return refused
+ }
+ got = got.Unmap()
+ if got.IsUnspecified() {
+ refused.Unspecified = true
+ return refused
+ }
+ want, err := netip.ParseAddrPort(listenAddr)
+ if err != nil || want.Addr().Unmap() != got || int(want.Port()) != tcp.Port {
+ return refused
+ }
+ return nil
}
// ServeDevbox serves the registry's routes over HTTPS on cfg.ListenAddr with
@@ -69,12 +120,23 @@ type devboxSeams struct {
}
func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error {
+ // A given listener is ours to close whatever happens. Once the server
+ // has it, Shutdown or Close closes it first, and this Close is a no-op.
+ if cfg.Listener != nil {
+ defer cfg.Listener.Close()
+ }
// The address first, before anything is built: a devbox is reachable
// only on its tailnet address, and an empty or wildcard host would put
- // every route on the office LAN too.
+ // every route on the office LAN too. A given listener is held to the
+ // same address.
if err := checkDevboxListenAddr(cfg.ListenAddr); err != nil {
return err
}
+ if cfg.Listener != nil {
+ if err := CheckDevboxListener(cfg.Listener, cfg.ListenAddr); err != nil {
+ return err
+ }
+ }
if cfg.Registry == nil {
return errors.New("edge: devbox: no registry")
}
@@ -122,9 +184,12 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error
// behind. The address is never empty here, so listen's default never
// applies; it is the address again rather than ":https", which would be
// every interface.
- ln, err := listen("https", cfg.ListenAddr, cfg.ListenAddr)
- if err != nil {
- return err
+ ln := cfg.Listener
+ if ln == nil {
+ ln, err = listen("https", cfg.ListenAddr, cfg.ListenAddr)
+ if err != nil {
+ return err
+ }
}
if seams.bound != nil {
seams.bound(ln.Addr())
diff --git a/internal/edge/devbox_test.go b/internal/edge/devbox_test.go
index 9f26e8695..d4836891c 100644
--- a/internal/edge/devbox_test.go
+++ b/internal/edge/devbox_test.go
@@ -251,6 +251,14 @@ type devboxRun struct {
// run loop loads it and orders nothing), adds a service route
// slow.<parent> to heldAddr when it is set, and serves on 127.0.0.1:0.
func startDevbox(t *testing.T, heldAddr string, drainTimeout time.Duration) *devboxRun {
+ t.Helper()
+ return startDevboxOn(t, heldAddr, drainTimeout, nil)
+}
+
+// startDevboxOn is startDevbox serving on ln, a listener handed in as
+// launchd hands one over, when ln is not nil; ListenAddr is then ln's
+// address.
+func startDevboxOn(t *testing.T, heldAddr string, drainTimeout time.Duration, ln net.Listener) *devboxRun {
t.Helper()
certDir := t.TempDir()
cert, key := selfSignedWildcard(t, devboxParent, time.Now().Add(60*24*time.Hour))
@@ -274,6 +282,9 @@ func startDevbox(t *testing.T, heldAddr string, drainTimeout time.Duration) *dev
boundAddr := make(chan string, 1)
done := make(chan error, 1)
cfg := DevboxConfig{Registry: reg, ListenAddr: "127.0.0.1:0", CertDir: certDir, SpoolRoot: t.TempDir()}
+ if ln != nil {
+ cfg.ListenAddr, cfg.Listener = ln.Addr().String(), ln
+ }
seams := devboxSeams{
bound: func(a net.Addr) { boundAddr <- a.String() },
errorLog: log.New(errLog, "", 0),
@@ -486,3 +497,95 @@ func TestDevboxBindFailureIsAnError(t *testing.T) {
t.Fatalf("ServeDevbox on a held port = %v (ctx %v), want an immediate bind error", err, ctx.Err())
}
}
+
+// A listener handed in (launchd's, on macOS) is served on as it is: the
+// devbox does not bind ListenAddr itself, which would fail here because the
+// listener holds that very address. Cancelling closes it.
+func TestDevboxUsesGivenListener(t *testing.T) {
+ ca, requests := countingCA(t)
+ devboxEnv(t, ca.URL)
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { ln.Close() })
+ run := startDevboxOn(t, "", 0, ln)
+ if run.addr != ln.Addr().String() {
+ t.Fatalf("served on %s, want the given listener's %s", run.addr, ln.Addr())
+ }
+ run.cancel()
+ select {
+ case err := <-run.done:
+ if err != nil {
+ t.Fatalf("ServeDevbox after cancel = %v", err)
+ }
+ case <-time.After(15 * time.Second):
+ t.Fatal("ServeDevbox did not return")
+ }
+ if _, err := ln.Accept(); err == nil {
+ t.Fatal("the given listener is still open after ServeDevbox returned")
+ }
+ if n := requests.Load(); n != 0 {
+ t.Fatalf("the CA saw %d request(s), want 0", n)
+ }
+}
+
+// fakeListener is a listener on any address, without binding it: binding
+// every interface in a test would put a port on the LAN.
+type fakeListener struct {
+ addr net.Addr
+ closed atomic.Bool
+}
+
+func (f *fakeListener) Accept() (net.Conn, error) { return nil, net.ErrClosed }
+func (f *fakeListener) Close() error { f.closed.Store(true); return nil }
+func (f *fakeListener) Addr() net.Addr { return f.addr }
+
+// A listener on any address but ListenAddr is refused before anything is
+// served or ordered, with a DevboxListenerError naming both addresses, and
+// closed. One on every interface is refused the same way, and says so.
+func TestDevboxRefusesListenerOnOtherAddr(t *testing.T) {
+ ca, requests := countingCA(t)
+ devboxEnv(t, ca.URL)
+ tcp := func(ip string, port int) net.Addr { return &net.TCPAddr{IP: net.ParseIP(ip), Port: port} }
+ for _, c := range []struct {
+ name string
+ ln net.Addr
+ listen string
+ unspecified bool
+ }{
+ {"other port", tcp("127.0.0.1", 8443), "127.0.0.1:443", false},
+ {"other ip", tcp("127.0.0.2", 443), "127.0.0.1:443", false},
+ {"ipv6 for ipv4", tcp("::1", 443), "127.0.0.1:443", false},
+ {"every interface", tcp("0.0.0.0", 443), "100.64.0.10:443", true},
+ {"every interface, ipv6", tcp("::", 443), "100.64.0.10:443", true},
+ {"not tcp", &net.UnixAddr{Name: "/tmp/x.sock", Net: "unix"}, "100.64.0.10:443", false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ ln := &fakeListener{addr: c.ln}
+ cfg := DevboxConfig{Registry: openReg(t), ListenAddr: c.listen, Listener: ln, CertDir: t.TempDir(), SpoolRoot: t.TempDir()}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ err := ServeDevbox(ctx, cfg)
+ var le *DevboxListenerError
+ if !errors.As(err, &le) || ctx.Err() != nil {
+ t.Fatalf("ServeDevbox = %v (ctx %v), want an immediate DevboxListenerError", err, ctx.Err())
+ }
+ if le.Addr != c.ln.String() || le.Want != c.listen || le.Unspecified != c.unspecified {
+ t.Fatalf("error = %+v, want Addr %s, Want %s, Unspecified %v", *le, c.ln, c.listen, c.unspecified)
+ }
+ if err := CheckDevboxListener(ln, c.listen); !errors.As(err, &le) {
+ t.Fatalf("CheckDevboxListener = %v, want the same refusal", err)
+ }
+ if !ln.closed.Load() {
+ t.Fatal("the refused listener was not closed")
+ }
+ })
+ }
+ if err := CheckDevboxListener(&fakeListener{addr: tcp("100.64.0.10", 443)}, "100.64.0.10:443"); err != nil {
+ t.Fatalf("CheckDevboxListener on the right address = %v", err)
+ }
+ if n := requests.Load(); n != 0 {
+ t.Fatalf("the CA saw %d request(s), want 0", n)
+ }
+}
diff --git a/internal/launchd/activate_darwin.go b/internal/launchd/activate_darwin.go
new file mode 100644
index 000000000..33c3d4bde
--- /dev/null
+++ b/internal/launchd/activate_darwin.go
@@ -0,0 +1,82 @@
+//go:build darwin
+
+package launchd
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// Listeners returns the listening sockets launchd opened for the plist's
+// Sockets entry called name. It may be called once per name: launchd
+// answers a second call with EALREADY. Each listener is a dup of launchd's
+// descriptor, which is closed, as is the array launchd allocated for them.
+func Listeners(name string) ([]net.Listener, error) {
+ cname, err := syscall.BytePtrFromString(name)
+ if err != nil {
+ return nil, fmt.Errorf("launchd: socket name %q: %w", name, err)
+ }
+ // int launch_activate_socket(const char *name, int **fds, size_t *cnt);
+ // It returns 0 or an errno value; it does not set errno.
+ var fds *int32
+ var cnt uintptr
+ r1, _, _ := syscall_syscall(libc_launch_activate_socket_trampoline_addr,
+ uintptr(unsafe.Pointer(cname)), uintptr(unsafe.Pointer(&fds)), uintptr(unsafe.Pointer(&cnt)))
+ if code := syscall.Errno(int32(r1)); code != 0 {
+ switch code {
+ case syscall.ESRCH:
+ return nil, fmt.Errorf("%w (%w)", ErrNotManaged, code)
+ case syscall.ENOENT:
+ return nil, fmt.Errorf("%w: %q (%w)", ErrNoSocket, name, code)
+ }
+ return nil, fmt.Errorf("launchd: launch_activate_socket %q: %w", name, code)
+ }
+ if fds == nil {
+ return nil, nil
+ }
+ raw := make([]int32, cnt)
+ copy(raw, unsafe.Slice(fds, cnt))
+ syscall_syscall(libc_free_trampoline_addr, uintptr(unsafe.Pointer(fds)), 0, 0)
+
+ var out []net.Listener
+ var errs []error
+ for _, fd := range raw {
+ f := os.NewFile(uintptr(fd), "launchd:"+name)
+ ln, err := net.FileListener(f) // dups the descriptor
+ f.Close()
+ if err != nil {
+ errs = append(errs, err)
+ continue
+ }
+ out = append(out, ln)
+ }
+ if len(errs) > 0 {
+ for _, ln := range out {
+ ln.Close()
+ }
+ return nil, fmt.Errorf("launchd: socket %q: %w", name, errors.Join(errs...))
+ }
+ return out, nil
+}
+
+// syscall_syscall is the syscall package's libc call (syscall.syscall),
+// which enters and leaves the scheduler's syscall state around fn. The
+// syscall package marks it for linkname use by x/sys/unix, which reaches it
+// exactly this way (unix/syscall_darwin_libSystem.go).
+func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+//go:linkname syscall_syscall syscall.syscall
+
+// The trampolines are in activate_darwin_$GOARCH.s; each jumps to the libc
+// symbol its directive below imports.
+var (
+ libc_launch_activate_socket_trampoline_addr uintptr
+ libc_free_trampoline_addr uintptr
+)
+
+//go:cgo_import_dynamic launchd_libc_launch_activate_socket launch_activate_socket "/usr/lib/libSystem.B.dylib"
+//go:cgo_import_dynamic launchd_libc_free free "/usr/lib/libSystem.B.dylib"
diff --git a/internal/launchd/activate_darwin_amd64.s b/internal/launchd/activate_darwin_amd64.s
new file mode 100644
index 000000000..fc98fc817
--- /dev/null
+++ b/internal/launchd/activate_darwin_amd64.s
@@ -0,0 +1,15 @@
+// The libc trampolines for activate_darwin.go, in x/sys/unix's form
+// (unix/zsyscall_darwin_*.s): a jump to the dynamically imported symbol,
+// and a read-only word holding the trampoline's address for Go to call.
+
+#include "textflag.h"
+
+TEXT libc_launch_activate_socket_trampoline<>(SB),NOSPLIT,$0-0
+ JMP launchd_libc_launch_activate_socket(SB)
+GLOBL ·libc_launch_activate_socket_trampoline_addr(SB), RODATA, $8
+DATA ·libc_launch_activate_socket_trampoline_addr(SB)/8, $libc_launch_activate_socket_trampoline<>(SB)
+
+TEXT libc_free_trampoline<>(SB),NOSPLIT,$0-0
+ JMP launchd_libc_free(SB)
+GLOBL ·libc_free_trampoline_addr(SB), RODATA, $8
+DATA ·libc_free_trampoline_addr(SB)/8, $libc_free_trampoline<>(SB)
diff --git a/internal/launchd/activate_darwin_arm64.s b/internal/launchd/activate_darwin_arm64.s
new file mode 100644
index 000000000..fc98fc817
--- /dev/null
+++ b/internal/launchd/activate_darwin_arm64.s
@@ -0,0 +1,15 @@
+// The libc trampolines for activate_darwin.go, in x/sys/unix's form
+// (unix/zsyscall_darwin_*.s): a jump to the dynamically imported symbol,
+// and a read-only word holding the trampoline's address for Go to call.
+
+#include "textflag.h"
+
+TEXT libc_launch_activate_socket_trampoline<>(SB),NOSPLIT,$0-0
+ JMP launchd_libc_launch_activate_socket(SB)
+GLOBL ·libc_launch_activate_socket_trampoline_addr(SB), RODATA, $8
+DATA ·libc_launch_activate_socket_trampoline_addr(SB)/8, $libc_launch_activate_socket_trampoline<>(SB)
+
+TEXT libc_free_trampoline<>(SB),NOSPLIT,$0-0
+ JMP launchd_libc_free(SB)
+GLOBL ·libc_free_trampoline_addr(SB), RODATA, $8
+DATA ·libc_free_trampoline_addr(SB)/8, $libc_free_trampoline<>(SB)
diff --git a/internal/launchd/activate_darwin_test.go b/internal/launchd/activate_darwin_test.go
new file mode 100644
index 000000000..c078611f7
--- /dev/null
+++ b/internal/launchd/activate_darwin_test.go
@@ -0,0 +1,34 @@
+//go:build darwin
+
+package launchd
+
+import (
+ "errors"
+ "testing"
+ "time"
+)
+
+// go test is not a launchd job, so there is no socket to take: Listeners
+// says so at once, and does not wait on launchd.
+func TestLaunchdListenersOutsideLaunchd(t *testing.T) {
+ done := make(chan error, 1)
+ go func() {
+ lns, err := Listeners("Listeners")
+ for _, ln := range lns {
+ ln.Close()
+ }
+ if err == nil {
+ err = errors.New("no error")
+ }
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if !errors.Is(err, ErrNotManaged) && !errors.Is(err, ErrNoSocket) {
+ t.Fatalf("Listeners outside launchd = %v, want ErrNotManaged (or ErrNoSocket)", err)
+ }
+ t.Logf("Listeners outside launchd: %v", err)
+ case <-time.After(10 * time.Second):
+ t.Fatal("Listeners outside launchd did not return")
+ }
+}
diff --git a/internal/launchd/activate_other.go b/internal/launchd/activate_other.go
new file mode 100644
index 000000000..6f0ef65a7
--- /dev/null
+++ b/internal/launchd/activate_other.go
@@ -0,0 +1,14 @@
+//go:build !darwin
+
+package launchd
+
+import (
+ "errors"
+ "net"
+)
+
+// Listeners is macOS only: elsewhere there is no launchd to hand over a
+// socket.
+func Listeners(name string) ([]net.Listener, error) {
+ return nil, errors.ErrUnsupported
+}
diff --git a/internal/launchd/activate_other_test.go b/internal/launchd/activate_other_test.go
new file mode 100644
index 000000000..4bf0d7fa8
--- /dev/null
+++ b/internal/launchd/activate_other_test.go
@@ -0,0 +1,15 @@
+//go:build !darwin
+
+package launchd
+
+import (
+ "errors"
+ "testing"
+)
+
+func TestLaunchdListenersUnsupported(t *testing.T) {
+ lns, err := Listeners("Listeners")
+ if !errors.Is(err, errors.ErrUnsupported) || lns != nil {
+ t.Fatalf("Listeners = %v, %v, want nil, ErrUnsupported", lns, err)
+ }
+}
diff --git a/internal/launchd/launchd.go b/internal/launchd/launchd.go
new file mode 100644
index 000000000..190228550
--- /dev/null
+++ b/internal/launchd/launchd.go
@@ -0,0 +1,21 @@
+// Package launchd takes the listening sockets launchd opened for this
+// process (a LaunchDaemon plist's Sockets entry), so a service can serve on a
+// port it may not bind itself. On macOS only port 443 needs it: launchd
+// binds as root, then starts the service as its own user (devbox mode on
+// macOS, #488).
+//
+// There is no cgo. On darwin the package calls launch_activate_socket(3)
+// and free(3) in libSystem the way golang.org/x/sys/unix calls libc: a
+// //go:cgo_import_dynamic for each symbol, an assembly trampoline that jumps
+// to it, and the syscall package's libc call path, reached by linkname.
+package launchd
+
+import "errors"
+
+var (
+ // ErrNotManaged: launchd did not start this process, so it holds no
+ // sockets for it (ESRCH).
+ ErrNotManaged = errors.New("launchd: this process was not started by launchd")
+ // ErrNoSocket: the job has no socket of that name (ENOENT).
+ ErrNoSocket = errors.New("launchd: no socket of that name for this job")
+)