carlos / platform Public

devbox on macOS (#488) Task 2: serve --env-file, and the darwin socket default

carlos devbox serve takes --env-file PATH and reads it before anything
else: KEY=VALUE lines, blanks and # comments. The file must belong to the
effective user and be closed to group and other (checked on the opened
file); a bad line, an empty or non-name key, or a key set twice refuses
the whole file, and nothing is set unless all of it passes. A setting in
the file replaces one already in the environment. No refusal repeats a
value or an unparsed line. Works on Linux and macOS; on other OSes no
file passes the owner check.

The registrar socket defaults to /usr/local/var/run/carlos-devbox on
darwin and /run/carlos-devbox elsewhere; CARLOS_DEVBOX_SOCKET still wins.

Strings are DBX-C58..C65 as drafted (approved unchanged; built ids are
added with Task 4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2f14384af3d442cc0ae91bdeccae5cc11c0313e3 parent 6d47d84
5 files changed, +339 −15
  • devbox_cli.go +60 −15
  • devbox_cli_test.go +152 −0
  • devbox_envfile.go +101 −0
  • devbox_envfile_other.go +9 −0
  • devbox_envfile_unix.go +17 −0

Intent

Human

<task-notification> <task-id>adb6e89c9529fd992</task-id> <tool-use-id>toolu_01141NcSENNuLFA4TJc45grh</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/adb6e89c9529fd992.output</output-file> <status>completed</status> <summary>Agent "Build devbox macOS support (#488)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>DONE_WITH_CONCERNS: copy ready. Tasks 2 to 4 have not started, so resume me to build them. - **Commit:** `6d47d84a` adds the Task 1 copy rows, all `pending`. - **Rows:** DBX-C58 to DBX-C92, appended as a new "macOS (#488)" section of `docs/superpowers/plans/2026-10-30-devbox-mode-copy.md`. - C58 to C60: serve's usage, serve's help and the `--env-file` help. - C61 to C65: the env-file refusals (can't read it, open mode, wrong owner, bad line, duplicate key). - C66 to C71: the launchd refusals (not started by launchd, no socket by that name, more than one socket, not macOS, listening on every interface, wrong address). - C72 to C92: the runbook's macOS section, one sentence or heading per row. - **Gate:** the pinned inventory in `approved_devbox_copy_test.go` is now DBX-C1 to DBX-C92, and none of the new ids is in `devboxCopyBuilt`. The `TestDevboxCopy*` and `TestDevboxBuiltCopy*` tests pass. - **Concerns:** - C70 and C71 (the listener-address refusals) are printed by the CLI. The edge will return a typed error and serve turns it into those sentences, so the deck text stays out of `internal/edge`. - The deck section adds new placeholders: `&lt;env file&gt;`, `&lt;line&gt;`, `&lt;key&gt;`, `&lt;socket name&gt;`, `&lt;count&gt;` and `&lt;address&gt;`. - The rule that a setting in the file replaces one already in the environment is stated to the user in the `--env-file` help (C60). Report path, once I finish: `/home/paulca/.cache/tmp/devbox-macos-report.md`</result> <usage><subagent_tokens>98898</subagent_tokens><tool_uses>16</tool_uses><duration_ms>272795</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bzy0t79yv</task-id> <tool-use-id>toolu_01SdXFnx639djfuEyR7j7jeV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/bzy0t79yv.output</output-file> <status>completed</status> <summary>Background command "Wait for the macOS copy review result" completed (exit code 0)</summary> </task-notification>

Human

approved

diff --git a/devbox_cli.go b/devbox_cli.go
index 0d6f6065e..cfb4c9db9 100644
--- a/devbox_cli.go
+++ b/devbox_cli.go
@@ -26,6 +26,7 @@ import (
"os/signal"
"os/user"
"path/filepath"
+ "runtime"
"slices"
"strconv"
"strings"
@@ -63,6 +64,29 @@ const (
devboxInternal = "the devbox service could not finish that. try again, or tell whoever runs this devbox" // DBX-C54
)
+// serve's rows (macOS plan #488).
+const (
+ devboxUsageServe = "usage: carlos devbox serve [--env-file <env file>]" // DBX-C58
+ devboxHelpServe = "serve runs the devbox service. its systemd unit or launchd daemon starts it, and nobody else needs to" // DBX-C59
+ devboxHelpEnvFile = "a file of KEY=VALUE lines to read before serving. blank lines and lines starting with # are skipped, and values are taken as written, with no quotes. a setting in the file replaces one already in the environment. the file must belong to this account, and only this account may read or change it" // DBX-C60
+)
+
+func devboxEnvUnreadable(file string) string {
+ return fmt.Sprintf("could not read the environment file %s. check that it exists and that this account can read it", file) // DBX-C61
+}
+func devboxEnvOpen(file string) string {
+ return fmt.Sprintf("other accounts can read or change the environment file %s. make it private with: chmod 600 %s", file, file) // DBX-C62
+}
+func devboxEnvOwner(file string) string {
+ return fmt.Sprintf("the environment file %s belongs to another account. it must belong to the account the service runs as", file) // DBX-C63
+}
+func devboxEnvBadLine(line int, file string) string {
+ return fmt.Sprintf("line %d of %s is not KEY=VALUE, where KEY is letters, digits and underscores and does not start with a digit. each line must be a setting, a comment starting with #, or blank", line, file) // DBX-C64
+}
+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 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
@@ -104,8 +128,24 @@ func devboxInUse(name string) string {
return fmt.Sprintf("%s is already in use on this devbox. pick another name", name) // DBX-C53
}
-// devboxDefaultSocket is where the unit's RuntimeDirectory puts the socket.
-const devboxDefaultSocket = "/run/carlos-devbox/devbox.sock"
+// devboxDefaultSocket is where the service puts the registrar socket: the
+// systemd unit's RuntimeDirectory on Linux, and on macOS the folder the
+// runbook creates, since /var/run there is root's alone.
+func devboxDefaultSocket(goos string) string {
+ if goos == "darwin" {
+ return "/usr/local/var/run/carlos-devbox/devbox.sock"
+ }
+ return "/run/carlos-devbox/devbox.sock"
+}
+
+// devboxSocketPath is the registrar socket: CARLOS_DEVBOX_SOCKET, or this
+// OS's default.
+func devboxSocketPath() string {
+ if sock := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_SOCKET")); sock != "" {
+ return sock
+ }
+ return devboxDefaultSocket(runtime.GOOS)
+}
// devboxSpoolCap is the total the folder spool may hold.
const devboxSpoolCap = 5 << 30
@@ -124,16 +164,12 @@ type devboxCLI struct {
}
func newDevboxCLI(stdout, stderr io.Writer) *devboxCLI {
- sock := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_SOCKET"))
- if sock == "" {
- sock = devboxDefaultSocket
- }
- return &devboxCLI{stdout: stdout, stderr: stderr, socket: sock, branch: gitCurrentBranch, now: time.Now}
+ return &devboxCLI{stdout: stdout, stderr: stderr, socket: devboxSocketPath(), branch: gitCurrentBranch, now: time.Now}
}
func runDevbox(args []string) {
if len(args) > 0 && args[0] == "serve" {
- if err := runDevboxServe(args[1:]); err != nil {
+ if err := runDevboxServe(args[1:]); err != nil && !errors.Is(err, flag.ErrHelp) {
log.Fatal(err)
}
return
@@ -528,8 +564,21 @@ func (c *devboxCLI) call(method, path, contentType string, body []byte, rc refus
// link record under CARLOS_DATA_DIR, and serves the edge and the registrar
// until SIGTERM or SIGINT, or until either fails.
func runDevboxServe(args []string) error {
- if len(args) > 0 {
- return fmt.Errorf("devbox serve: takes no arguments, got %q", args)
+ fs := flag.NewFlagSet("devbox serve", flag.ContinueOnError)
+ fs.Usage = flagUsage(fs, devboxUsageServe+"\n"+devboxHelpServe)
+ envFile := fs.String("env-file", "", devboxHelpEnvFile)
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ if fs.NArg() > 0 {
+ return fmt.Errorf("devbox serve: takes no arguments, got %q", fs.Args())
+ }
+ // The file first, so that everything below reads the environment the
+ // service is meant to have.
+ if *envFile != "" {
+ if err := loadDevboxEnvFile(*envFile, os.Geteuid()); err != nil {
+ return err
+ }
}
listen := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_LISTEN"))
domain := strings.ToLower(strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_DOMAIN")))
@@ -575,11 +624,7 @@ func runDevboxServe(args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
- sock := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_SOCKET"))
- if sock == "" {
- sock = devboxDefaultSocket
- }
- return serveDevboxParts(ctx, sock, r, func(ctx context.Context) error { return edge.ServeDevbox(ctx, cfg) })
+ return serveDevboxParts(ctx, devboxSocketPath(), r, func(ctx context.Context) error { return edge.ServeDevbox(ctx, cfg) })
}
// 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 8121996cf..a45d8348a 100644
--- a/devbox_cli_test.go
+++ b/devbox_cli_test.go
@@ -12,12 +12,14 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"sync"
"testing"
@@ -489,3 +491,153 @@ func TestDevboxServeStopsBothOnError(t *testing.T) {
t.Fatal("the edge was not stopped")
}
}
+
+// ---- serve --env-file (macOS plan #488 Task 2) ------------------------------
+
+// writeDevboxEnvFile writes body to a fresh file with mode perm.
+func writeDevboxEnvFile(t *testing.T, body string, perm os.FileMode) string {
+ t.Helper()
+ p := filepath.Join(t.TempDir(), "env")
+ if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // WriteFile's mode is cut by the umask; Chmod is not.
+ if err := os.Chmod(p, perm); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// A 0600 file owned by this user sets its variables, over any already in
+// the environment, before serve reads its config.
+func TestDevboxServeEnvFileLoads(t *testing.T) {
+ for _, k := range []string{"DBX_TEST_A", "DBX_TEST_B", "DBX_TEST_C"} {
+ t.Setenv(k, "") // restored after the test
+ }
+ t.Setenv("DBX_TEST_B", "from the environment")
+ p := writeDevboxEnvFile(t, "# a comment\n\nDBX_TEST_A=one\n DBX_TEST_B=two=2 # not a comment\r\n\t# indented comment\nDBX_TEST_C=\n", 0o600)
+ if err := loadDevboxEnvFile(p, os.Geteuid()); err != nil {
+ t.Fatalf("load = %v", err)
+ }
+ for k, want := range map[string]string{"DBX_TEST_A": "one", "DBX_TEST_B": "two=2 # not a comment", "DBX_TEST_C": ""} {
+ if got := os.Getenv(k); got != want {
+ t.Errorf("%s = %q, want %q", k, got, want)
+ }
+ }
+
+ // Through serve itself: the file's domain is what serve checks against
+ // CARLOS_WILDCARD_DOMAINS, so the file was read before the config.
+ for _, k := range []string{"CARLOS_DEVBOX_LISTEN", "CARLOS_DEVBOX_DOMAIN", "CARLOS_DATA_DIR", "CARLOS_WILDCARD_DOMAINS", "CARLOS_DEVBOX_LAUNCHD_SOCKET"} {
+ t.Setenv(k, "")
+ }
+ t.Setenv("CARLOS_WILDCARD_DOMAINS", "other.example.com")
+ data := filepath.Join(t.TempDir(), "data")
+ p = writeDevboxEnvFile(t, "CARLOS_DEVBOX_LISTEN=127.0.0.1:8443\nCARLOS_DEVBOX_DOMAIN=from-file.example.com\nCARLOS_DATA_DIR="+data+"\n", 0o600)
+ err := runDevboxServe([]string{"--env-file", p})
+ if err == nil || !strings.Contains(err.Error(), "from-file.example.com is not in CARLOS_WILDCARD_DOMAINS") {
+ t.Fatalf("serve = %v, want the file's domain refused", err)
+ }
+ if _, err := os.Stat(data); err == nil {
+ t.Fatal("serve made the data dir before refusing its config")
+ }
+}
+
+func TestDevboxServeEnvFileRefusesOpenMode(t *testing.T) {
+ for _, perm := range []os.FileMode{0o640, 0o604, 0o620, 0o602, 0o601, 0o660} {
+ p := writeDevboxEnvFile(t, "DBX_TEST_A=one\n", perm)
+ t.Setenv("DBX_TEST_A", "")
+ err := loadDevboxEnvFile(p, os.Geteuid())
+ want := "other accounts can read or change the environment file " + p + ". make it private with: chmod 600 " + p
+ if err == nil || err.Error() != want {
+ t.Errorf("mode %o: load = %v, want %q", perm, err, want)
+ }
+ if os.Getenv("DBX_TEST_A") != "" {
+ t.Errorf("mode %o: a refused file set its variables", perm)
+ }
+ }
+ // 0400 is private too.
+ if err := loadDevboxEnvFile(writeDevboxEnvFile(t, "DBX_TEST_A=one\n", 0o400), os.Geteuid()); err != nil {
+ t.Errorf("mode 0400: load = %v", err)
+ }
+}
+
+func TestDevboxServeEnvFileRefusesOtherOwner(t *testing.T) {
+ p := writeDevboxEnvFile(t, "DBX_TEST_A=one\n", 0o600)
+ t.Setenv("DBX_TEST_A", "")
+ err := loadDevboxEnvFile(p, os.Geteuid()+1)
+ want := "the environment file " + p + " belongs to another account. it must belong to the account the service runs as"
+ if err == nil || err.Error() != want {
+ t.Fatalf("load = %v, want %q", err, want)
+ }
+ if os.Getenv("DBX_TEST_A") != "" {
+ t.Fatal("a refused file set its variables")
+ }
+}
+
+func TestDevboxServeEnvFileRefusesUnreadable(t *testing.T) {
+ p := filepath.Join(t.TempDir(), "missing")
+ err := loadDevboxEnvFile(p, os.Geteuid())
+ want := "could not read the environment file " + p + ". check that it exists and that this account can read it"
+ if err == nil || !strings.HasPrefix(err.Error(), want+"\n") || !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("load = %v, want %q then the system's words", err, want)
+ }
+}
+
+func TestDevboxServeEnvFileRefusesBadLine(t *testing.T) {
+ for _, tc := range []struct {
+ body string
+ line int
+ }{
+ {"DBX_TEST_A=one\nAKIASECRETWITHNOEQUALS\n", 2},
+ {"=value\n", 1},
+ {"# ok\nexport DBX_TEST_A=one\n", 2},
+ {"DBX_TEST_A =one\n", 1},
+ {"1DBX=one\n", 1},
+ {"DBX-TEST=one\n", 1},
+ } {
+ p := writeDevboxEnvFile(t, tc.body, 0o600)
+ t.Setenv("DBX_TEST_A", "")
+ err := loadDevboxEnvFile(p, os.Geteuid())
+ want := fmt.Sprintf("line %d of %s is not KEY=VALUE, where KEY is letters, digits and underscores and does not start with a digit. each line must be a setting, a comment starting with #, or blank", tc.line, p)
+ if err == nil || err.Error() != want {
+ t.Errorf("%q: load = %v, want %q", tc.body, err, want)
+ }
+ if strings.Contains(fmt.Sprint(err), "AKIA") || strings.Contains(fmt.Sprint(err), "value") {
+ t.Errorf("%q: the refusal repeats the file's contents: %v", tc.body, err)
+ }
+ if os.Getenv("DBX_TEST_A") != "" {
+ t.Errorf("%q: a refused file set its variables", tc.body)
+ }
+ }
+}
+
+func TestDevboxServeEnvFileRefusesDuplicate(t *testing.T) {
+ p := writeDevboxEnvFile(t, "DBX_TEST_A=one\n# x\nDBX_TEST_B=b\nDBX_TEST_A=two\n", 0o600)
+ t.Setenv("DBX_TEST_A", "")
+ t.Setenv("DBX_TEST_B", "")
+ err := loadDevboxEnvFile(p, os.Geteuid())
+ want := "DBX_TEST_A is set twice in " + p + ", on lines 1 and 4. keep one"
+ if err == nil || err.Error() != want {
+ t.Fatalf("load = %v, want %q", err, want)
+ }
+ if os.Getenv("DBX_TEST_A") != "" || os.Getenv("DBX_TEST_B") != "" {
+ t.Fatal("a refused file set its variables")
+ }
+}
+
+func TestDevboxDefaultSocketPath(t *testing.T) {
+ if got := devboxDefaultSocket("darwin"); got != "/usr/local/var/run/carlos-devbox/devbox.sock" {
+ t.Errorf("darwin = %q", got)
+ }
+ if got := devboxDefaultSocket("linux"); got != "/run/carlos-devbox/devbox.sock" {
+ t.Errorf("linux = %q", got)
+ }
+ t.Setenv("CARLOS_DEVBOX_SOCKET", "")
+ if got := devboxSocketPath(); got != devboxDefaultSocket(runtime.GOOS) {
+ t.Errorf("unset = %q", got)
+ }
+ t.Setenv("CARLOS_DEVBOX_SOCKET", " /tmp/x.sock ")
+ if got := devboxSocketPath(); got != "/tmp/x.sock" {
+ t.Errorf("override = %q", got)
+ }
+}
diff --git a/devbox_envfile.go b/devbox_envfile.go
new file mode 100644
index 000000000..80fcd6d9c
--- /dev/null
+++ b/devbox_envfile.go
@@ -0,0 +1,101 @@
+package main
+
+// carlos devbox serve --env-file: the service's settings, read by the
+// service itself. On macOS launchd would pass them from the plist, and every
+// account can read a plist, so the DNS credential lives in a file only the
+// service user can open (macOS plan #488). Linux's unit uses systemd's
+// EnvironmentFile and does not need this, but it works there too.
+//
+// The rules: the file belongs to the user the service runs as, and no other
+// account may read or change it; every line is KEY=VALUE, a # comment or
+// blank; a key appears once; and a setting in the file replaces one already
+// in the environment. Nothing is set unless the whole file passes. No
+// refusal repeats a value, or any part of a line that is not a setting.
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+)
+
+// devboxEnvFileMax bounds the read: an environment file is a few lines.
+const devboxEnvFileMax = 1 << 20
+
+// loadDevboxEnvFile reads path and sets each of its settings in this
+// process's environment. euid is the user the file must belong to (the
+// caller passes os.Geteuid(); a test passes another).
+func loadDevboxEnvFile(path string, euid int) error {
+ f, err := os.Open(path)
+ if err != nil {
+ return errors.Join(errors.New(devboxEnvUnreadable(path)), err)
+ }
+ defer f.Close()
+ // The checks are on the file that was opened, not on the path again.
+ fi, err := f.Stat()
+ if err != nil {
+ return errors.Join(errors.New(devboxEnvUnreadable(path)), err)
+ }
+ if !fi.Mode().IsRegular() {
+ return errors.Join(errors.New(devboxEnvUnreadable(path)), fmt.Errorf("%s is not a regular file", path))
+ }
+ if uid, ok := fileOwner(fi); !ok || uid != euid {
+ return errors.New(devboxEnvOwner(path))
+ }
+ if fi.Mode().Perm()&0o077 != 0 {
+ return errors.New(devboxEnvOpen(path))
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, devboxEnvFileMax+1))
+ if err != nil {
+ return errors.Join(errors.New(devboxEnvUnreadable(path)), err)
+ }
+ if len(raw) > devboxEnvFileMax {
+ return errors.Join(errors.New(devboxEnvUnreadable(path)), fmt.Errorf("%s is over %d bytes", path, devboxEnvFileMax))
+ }
+
+ type setting struct {
+ key, value string
+ }
+ var settings []setting
+ seen := map[string]int{}
+ for i, line := range strings.Split(string(raw), "\n") {
+ n := i + 1
+ line = strings.TrimSpace(line) // also drops a CRLF file's \r
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ key, value, ok := strings.Cut(line, "=")
+ if !ok || !devboxEnvKey(key) {
+ return errors.New(devboxEnvBadLine(n, path))
+ }
+ if first, dup := seen[key]; dup {
+ return errors.New(devboxEnvDuplicate(key, path, first, n))
+ }
+ seen[key] = n
+ settings = append(settings, setting{key, value})
+ }
+ for _, s := range settings {
+ if err := os.Setenv(s.key, s.value); err != nil {
+ // The key passed devboxEnvKey, so only a value the OS refuses
+ // (a NUL byte) gets here; say which line, not what it holds.
+ return fmt.Errorf("devbox serve: %s line %d: the value cannot be set in the environment", path, seen[s.key])
+ }
+ }
+ return nil
+}
+
+// devboxEnvKey reports whether k is a variable name: letters, digits and
+// underscores, not starting with a digit.
+func devboxEnvKey(k string) bool {
+ if k == "" || (k[0] >= '0' && k[0] <= '9') {
+ return false
+ }
+ for i := 0; i < len(k); i++ {
+ c := k[i]
+ if !(c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/devbox_envfile_other.go b/devbox_envfile_other.go
new file mode 100644
index 000000000..6624ce8fd
--- /dev/null
+++ b/devbox_envfile_other.go
@@ -0,0 +1,9 @@
+//go:build !unix
+
+package main
+
+import "os"
+
+// fileOwner has no uid to report here, so no environment file passes the
+// owner check: devbox serve runs only on Linux and macOS.
+func fileOwner(fi os.FileInfo) (int, bool) { return 0, false }
diff --git a/devbox_envfile_unix.go b/devbox_envfile_unix.go
new file mode 100644
index 000000000..18859f463
--- /dev/null
+++ b/devbox_envfile_unix.go
@@ -0,0 +1,17 @@
+//go:build unix
+
+package main
+
+import (
+ "os"
+ "syscall"
+)
+
+// fileOwner is the uid that owns the file fi describes.
+func fileOwner(fi os.FileInfo) (int, bool) {
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return int(st.Uid), true
+}