carlos / platform Public

devbox mode (#474): carlos devbox, the unit, the Route53 policy and the runbook

carlos devbox share | unshare | list talk to the registrar on
$CARLOS_DEVBOX_SOCKET (default /run/carlos-devbox/devbox.sock) and render
every refusal code from the approved copy deck (DBX-C1..C54, all in
devboxCopyBuilt). share takes --port or --dir and a name, or folds the git
branch into one; --dir packs with edge.PackDir after naming any symlink or
special file. serve runs the registrar (socket 0666, ConnContext) and
edge.ServeDevbox under one context: SIGTERM or SIGINT stops both, and
either failing stops the other and returns its error.

infra/devbox: the carlos-devbox unit (User=carlos-devbox, CAP_NET_BIND_SERVICE
only, the edge unit's hardening where it applies), the IAM policy limited to
the _acme-challenge TXT record, and the runbook from the deck's rows.

docs/site/cli.md gets a carlos devbox heading with an example block only,
so the docsite command scan passes; its prose needs a deck row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f2ad85d1d5ec3fce7b388c1e3a8855d05010d548 parent 7b9e100
8 files changed, +1,355 −1
  • approved_devbox_copy_test.go +3 −1
  • devbox_cli.go +661 −0
  • devbox_cli_test.go +473 −0
  • docs/site/cli.md +9 −0
  • infra/devbox/README.md +116 −0
  • infra/devbox/carlos-devbox.service +67 −0
  • infra/devbox/route53-acme-policy.json +23 −0
  • main.go +3 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>a3f043757184e644d</task-id> <tool-use-id>toolu_01RXSHLVzQ8k1tJW6Cw9CwnW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/a3f043757184e644d.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: the registrar" 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>Status: DONE. Fix round 1 fixes all three of Astra's Important findings, in commit 7b9e1009 (not pushed). 1. The spool cap now counts every directory an upload creates, including the parents extraction makes for nested files. Admission also counts the link directory, `current` and the swap symlink. 2. If the directory sync fails after the rename, `current` is pointed back at the previous tree before the new tree is deleted. 3. When naming a snapshot, the registrar retries only a name that already exists. Any other Lstat error cleans up the temp tree and returns, so it can't loop forever while holding the lock. Tests: all 24 registrar tests pass, including three new regression tests, one per finding. The 7 Task 4 tests pass, one `-race` run passed, and gofmt and go vet are clean for linux, darwin and windows. I reverted each fix by hand and its test failed every time. Concerns: the seven from the first report still stand. The commit printed the same `packed-refs.lock` warning from another git process, but it landed and the tree is clean. Report (fix round appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/devbox-mode/.superpowers/sdd/2026-10-30-devbox-mode/task-5-report.md</result> <usage><subagent_tokens>173546</subagent_tokens><tool_uses>8</tool_uses><duration_ms>234804</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bdbapko9d</task-id> <tool-use-id>toolu_01Kk5Mo1jckC3xN8oPHVAumn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/bdbapko9d.output</output-file> <status>completed</status> <summary>Background command "Run Astra scoped re-review for Task 5" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 27.8 g CO₂e (3,379,042 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-devbox-mode, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/approved_devbox_copy_test.go b/approved_devbox_copy_test.go
index 36c882537..b39e530d0 100644
--- a/approved_devbox_copy_test.go
+++ b/approved_devbox_copy_test.go
@@ -34,7 +34,9 @@ var devboxCopyIDs = func() []string {
// devboxCopyBuilt is every deck id whose text the code or docs now carry.
// The task that writes a row's text adds its id here in the same commit.
-var devboxCopyBuilt = []string{}
+var devboxCopyBuilt = []string{
+ "DBX-C1", "DBX-C2", "DBX-C3", "DBX-C4", "DBX-C5", "DBX-C6", "DBX-C7", "DBX-C8", "DBX-C9", "DBX-C10", "DBX-C11", "DBX-C12", "DBX-C13", "DBX-C14", "DBX-C15", "DBX-C16", "DBX-C17", "DBX-C18", "DBX-C19", "DBX-C20", "DBX-C21", "DBX-C22", "DBX-C23", "DBX-C24", "DBX-C25", "DBX-C26", "DBX-C27", "DBX-C28", "DBX-C29", "DBX-C30", "DBX-C31", "DBX-C32", "DBX-C33", "DBX-C34", "DBX-C35", "DBX-C36", "DBX-C37", "DBX-C38", "DBX-C39", "DBX-C40", "DBX-C41", "DBX-C42", "DBX-C43", "DBX-C44", "DBX-C45", "DBX-C46", "DBX-C47", "DBX-C48", "DBX-C49", "DBX-C50", "DBX-C51", "DBX-C52", "DBX-C53", "DBX-C54",
+}
func mustParseDevboxRecord(t *testing.T) []copyRow {
t.Helper()
diff --git a/devbox_cli.go b/devbox_cli.go
new file mode 100644
index 000000000..3838c953b
--- /dev/null
+++ b/devbox_cli.go
@@ -0,0 +1,661 @@
+package main
+
+// carlos devbox: publish a dev server or a folder as a link on a shared
+// workstation (devbox mode design ยง5.6, #474). share, unshare and list talk
+// to the devbox service's registrar over its Unix socket; serve is what the
+// unit runs. The registrar answers with machine codes only, and every word
+// a person reads here comes from the copy deck
+// (docs/superpowers/plans/2026-10-30-devbox-mode-copy.md), one constant per
+// row.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "io/fs"
+ "log"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "os/exec"
+ "os/signal"
+ "os/user"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "text/tabwriter"
+ "time"
+
+ "github.com/carlosframework/platform/internal/devbox"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Copy deck rows (DBX-Cn). Each is the row's text, byte for byte.
+const (
+ devboxUsageShare = "usage: carlos devbox share [--port <port> or --dir <path>] [<name>]" // DBX-C2
+ devboxUsageUnshare = "usage: carlos devbox unshare [<name>]" // DBX-C3
+ devboxUsageList = "usage: carlos devbox list" // DBX-C4
+ devboxHelpShare = "share publishes https://<name>.<devbox domain> to people on the tailnet. without a name it uses your git branch" // DBX-C6
+ devboxHelpPort = "the port your dev server listens on, on 127.0.0.1. the link follows it live" // DBX-C7
+ devboxHelpDir = "a folder of static files to publish. the link serves a copy, and sharing again replaces it" // DBX-C8
+ devboxHelpUnshare = "unshare removes a link you published. without a name it uses your git branch" // DBX-C9
+ devboxHelpList = "list shows every link on this devbox, who owns it and whether it is answering" // DBX-C10
+ devboxListHeader = "name owner kind target age state" // DBX-C13
+ devboxListEmpty = "no links yet. publish one with: carlos devbox share --port <port> <name>" // DBX-C14
+ devboxKindLive = "live" // DBX-C15
+ devboxKindFolder = "folder" // DBX-C16
+ devboxAnswering = "answering" // DBX-C17
+ devboxNotAnswering = "not answering" // DBX-C18
+ devboxServing = "serving" // DBX-C19
+ devboxOwnerGone = "account removed" // DBX-C20
+ devboxEitherFlag = "give either --port for a dev server or --dir for a folder, not both and not neither" // DBX-C26
+ devboxSpoolFull = "the devbox has no room for another folder. remove one you no longer need with carlos devbox unshare, or tell whoever runs this devbox" // DBX-C30
+ devboxSandboxHint = "if you are inside an agent sandbox, that is the likely cause: the sandbox blocks the socket. run this command outside the sandbox" // DBX-C34
+ devboxNotUnderstood = "the devbox service answered with something this carlos does not understand. update carlos and try again" // DBX-C35
+ devboxInternal = "the devbox service could not finish that. try again, or tell whoever runs this devbox" // DBX-C54
+)
+
+// 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
+func devboxUnknownCommand(c string) string {
+ return fmt.Sprintf("unknown devbox command %s. use share, unshare or list", c) // DBX-C5
+}
+func devboxTaken(name, owner string) string {
+ return fmt.Sprintf("%s is taken by %s. pick another name", name, owner) // DBX-C21
+}
+func devboxInvalidName(name string) string {
+ return fmt.Sprintf("%s is not a name a link can have. use 1 to 63 lower case letters, digits or hyphens, with no hyphen at the start or end", name) // DBX-C22
+}
+func devboxBranchHasNoName(branch string) string {
+ return fmt.Sprintf("the branch %s has no letters or digits to make a name from. give a name: carlos devbox share <name>", branch) // DBX-C23
+}
+
+const devboxNoBranch = "no name given, and there is no git branch to take one from. give a name: carlos devbox share <name>" // DBX-C24
+
+func devboxBadPort(port string) string {
+ return fmt.Sprintf("%s is not a port. use a number from 1 to 65535. the link points at 127.0.0.1 on this machine", port) // DBX-C25
+}
+func devboxNotAFolder(path string) string { return fmt.Sprintf("%s is not a folder", path) } // DBX-C27
+func devboxFolderTooBig(path string) string {
+ return fmt.Sprintf("%s is over 200 MiB once packed. share a smaller folder", path) // DBX-C28
+}
+func devboxNotPlain(file string) string {
+ return fmt.Sprintf("%s is a symbolic link or a special file. only plain files and folders can be shared. remove it and try again", file) // DBX-C29
+}
+func devboxNotYours(owner string) string {
+ return fmt.Sprintf("not your link. ask its owner, %s, to remove it", owner) // DBX-C31
+}
+func devboxUnknownLink(name string) string {
+ return fmt.Sprintf("no link called %s. see what exists with: carlos devbox list", name) // DBX-C32
+}
+func devboxUnreachable(socket string) string {
+ return fmt.Sprintf("could not reach the devbox service at %s. check that it is running, or tell whoever runs this devbox", socket) // DBX-C33
+}
+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"
+
+// devboxSpoolCap is the total the folder spool may hold.
+const devboxSpoolCap = 5 << 30
+
+// errNoGitBranch: the working directory is not on a git branch (not a
+// repository, or a detached HEAD).
+var errNoGitBranch = errors.New("devbox: no git branch")
+
+// devboxCLI is one run of carlos devbox: where it prints, the socket it
+// talks to, and the seams a test replaces.
+type devboxCLI struct {
+ stdout, stderr io.Writer
+ socket string
+ branch func() (string, error)
+ now func() time.Time
+}
+
+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}
+}
+
+func runDevbox(args []string) {
+ if len(args) > 0 && args[0] == "serve" {
+ if err := runDevboxServe(args[1:]); err != nil {
+ log.Fatal(err)
+ }
+ return
+ }
+ if code := newDevboxCLI(os.Stdout, os.Stderr).run(args); code != 0 {
+ os.Exit(code)
+ }
+}
+
+// gitCurrentBranch is the branch HEAD names. symbolic-ref works on a branch
+// with no commits yet, and fails on a detached HEAD, which has no branch.
+func gitCurrentBranch() (string, error) {
+ out, err := exec.Command("git", "symbolic-ref", "--short", "-q", "HEAD").Output()
+ if err != nil {
+ return "", errNoGitBranch
+ }
+ b := strings.TrimSpace(string(out))
+ if b == "" {
+ return "", errNoGitBranch
+ }
+ return b, nil
+}
+
+// devboxRefusal is a sentence from the deck that ends the command with exit 1.
+// It holds two lines for an unreachable socket: DBX-C33, then DBX-C34.
+type devboxRefusal struct{ lines []string }
+
+func (r *devboxRefusal) Error() string { return strings.Join(r.lines, "\n") }
+
+func refuseWith(lines ...string) error { return &devboxRefusal{lines: lines} }
+
+func (c *devboxCLI) usage(w io.Writer) {
+ fmt.Fprintln(w, devboxUsageShare)
+ fmt.Fprintln(w, devboxUsageUnshare)
+ fmt.Fprintln(w, devboxUsageList)
+ fmt.Fprintln(w)
+ fmt.Fprintln(w, devboxHelpShare)
+ fmt.Fprintln(w, devboxHelpUnshare)
+ fmt.Fprintln(w, devboxHelpList)
+}
+
+// run is carlos devbox args, except serve. It returns the exit code: 0, 1
+// for a refusal, 2 for a command line that does not parse.
+func (c *devboxCLI) run(args []string) int {
+ if len(args) == 0 {
+ c.usage(c.stderr)
+ return 2
+ }
+ var err error
+ switch args[0] {
+ case "help", "-h", "--help":
+ c.usage(c.stdout)
+ return 0
+ case "share":
+ err = c.share(args[1:])
+ case "unshare":
+ err = c.unshare(args[1:])
+ case "list":
+ err = c.list(args[1:])
+ default:
+ fmt.Fprintln(c.stderr, devboxUnknownCommand(args[0]))
+ return 2
+ }
+ var ref *devboxRefusal
+ switch {
+ case err == nil:
+ return 0
+ case errors.Is(err, flag.ErrHelp):
+ return 0
+ case errors.Is(err, errDevboxUsage), errors.As(err, new(flagParseError)):
+ return 2
+ case errors.As(err, &ref):
+ for _, l := range ref.lines {
+ fmt.Fprintln(c.stderr, l)
+ }
+ return 1
+ default:
+ // Not a registrar answer and not a deck refusal: an error from this
+ // machine (reading the folder), shown as the system words it.
+ fmt.Fprintln(c.stderr, err.Error())
+ return 1
+ }
+}
+
+// errDevboxUsage: a command line with too many words; the usage has been
+// printed. (A flag the flag package refused is a flagParseError, from
+// parseInterspersed in config_cli.go, and it has printed its own.)
+var errDevboxUsage = errors.New("devbox: usage")
+
+func (c *devboxCLI) flagSet(name, usage, help string) *flag.FlagSet {
+ fs := flag.NewFlagSet("devbox "+name, flag.ContinueOnError)
+ fs.SetOutput(c.stderr)
+ fs.Usage = flagUsage(fs, usage+"\n"+help)
+ return fs
+}
+
+// linkName is the name a command acts on: the one typed, checked as typed,
+// or else the current git branch folded into a name.
+func (c *devboxCLI) linkName(pos []string) (string, error) {
+ if len(pos) > 0 {
+ if devbox.ValidName(pos[0]) != nil {
+ return "", refuseWith(devboxInvalidName(pos[0]))
+ }
+ return pos[0], nil
+ }
+ branch, err := c.branch()
+ if err != nil {
+ return "", refuseWith(devboxNoBranch)
+ }
+ name, err := devbox.NameFromBranch(branch)
+ if err != nil {
+ return "", refuseWith(devboxBranchHasNoName(branch))
+ }
+ return name, nil
+}
+
+func (c *devboxCLI) share(args []string) error {
+ fs := c.flagSet("share", devboxUsageShare, devboxHelpShare)
+ port := fs.String("port", "", devboxHelpPort)
+ dir := fs.String("dir", "", devboxHelpDir)
+ pos, err := parseInterspersed(fs, args)
+ if err != nil {
+ return err
+ }
+ if len(pos) > 1 {
+ fs.Usage()
+ return errDevboxUsage
+ }
+ portSet, dirSet := flagGiven(fs, "port"), flagGiven(fs, "dir")
+ if portSet == dirSet {
+ return refuseWith(devboxEitherFlag)
+ }
+ var portN int
+ if portSet {
+ portN, err = strconv.Atoi(*port)
+ if err != nil || portN < 1 || portN > 65535 {
+ return refuseWith(devboxBadPort(*port))
+ }
+ }
+ name, err := c.linkName(pos)
+ if err != nil {
+ return err
+ }
+ rc := refusalContext{name: name, port: *port, path: *dir}
+ var entry devbox.ListEntry
+ if portSet {
+ body, _ := json.Marshal(struct {
+ Name string `json:"name"`
+ Port int `json:"port"`
+ }{name, portN})
+ err = c.call(http.MethodPost, "/share/live", "application/json", body, rc, &entry)
+ } else {
+ var site []byte
+ site, err = packDevboxFolder(*dir)
+ if err != nil {
+ return err
+ }
+ err = c.call(http.MethodPost, "/share/folder?name="+url.QueryEscape(name), "application/gzip", site, rc, &entry)
+ }
+ if err != nil {
+ return err
+ }
+ fmt.Fprintln(c.stdout, devboxPrinted("https://"+entry.Host))
+ return nil
+}
+
+func flagGiven(fs *flag.FlagSet, name string) bool {
+ given := false
+ fs.Visit(func(f *flag.Flag) {
+ if f.Name == name {
+ given = true
+ }
+ })
+ return given
+}
+
+// packDevboxFolder packs a folder as the registrar takes it, refusing in the
+// deck's words what it cannot send. A folder given as a symlink is followed
+// once, at the top; below it nothing is.
+func packDevboxFolder(dir string) ([]byte, error) {
+ root, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ return nil, refuseWith(devboxNotAFolder(dir))
+ }
+ if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
+ return nil, refuseWith(devboxNotAFolder(dir))
+ }
+ // PackDir refuses the same entries, but names them by full path inside
+ // an error; walking first finds the file to name, relative to the folder.
+ var bad string
+ err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() || d.Type().IsRegular() {
+ return nil
+ }
+ bad, _ = filepath.Rel(root, p)
+ return filepath.SkipAll
+ })
+ if err != nil {
+ return nil, err
+ }
+ if bad != "" {
+ return nil, refuseWith(devboxNotPlain(filepath.ToSlash(bad)))
+ }
+ site, err := edge.PackDir(root)
+ if err != nil {
+ return nil, err
+ }
+ if len(site) > devbox.MaxFolderBytes {
+ return nil, refuseWith(devboxFolderTooBig(dir))
+ }
+ return site, nil
+}
+
+func (c *devboxCLI) unshare(args []string) error {
+ fs := c.flagSet("unshare", devboxUsageUnshare, devboxHelpUnshare)
+ pos, err := parseInterspersed(fs, args)
+ if err != nil {
+ return err
+ }
+ if len(pos) > 1 {
+ fs.Usage()
+ return errDevboxUsage
+ }
+ name, err := c.linkName(pos)
+ if err != nil {
+ return err
+ }
+ body, _ := json.Marshal(struct {
+ Name string `json:"name"`
+ }{name})
+ var entry devbox.ListEntry
+ if err := c.call(http.MethodPost, "/unshare", "application/json", body, refusalContext{name: name}, &entry); err != nil {
+ return err
+ }
+ fmt.Fprintln(c.stdout, devboxRemoved("https://"+entry.Host))
+ return nil
+}
+
+func (c *devboxCLI) list(args []string) error {
+ fs := c.flagSet("list", devboxUsageList, devboxHelpList)
+ pos, err := parseInterspersed(fs, args)
+ if err != nil {
+ return err
+ }
+ if len(pos) > 0 {
+ fs.Usage()
+ return errDevboxUsage
+ }
+ var entries []devbox.ListEntry
+ if err := c.call(http.MethodGet, "/list", "", nil, refusalContext{}, &entries); err != nil {
+ return err
+ }
+ if len(entries) == 0 {
+ fmt.Fprintln(c.stdout, devboxListEmpty)
+ return nil
+ }
+ slices.SortFunc(entries, func(a, b devbox.ListEntry) int { return strings.Compare(a.Name, b.Name) })
+ tw := tabwriter.NewWriter(c.stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(tw, strings.Join(strings.Fields(devboxListHeader), "\t"))
+ now := c.now()
+ for _, e := range entries {
+ kind, state := devboxKindLive, devboxNotAnswering
+ if e.Kind == devbox.KindFolder {
+ kind = devboxKindFolder
+ }
+ if e.Answering {
+ state = devboxAnswering
+ if e.Kind == devbox.KindFolder {
+ state = devboxServing
+ }
+ }
+ fmt.Fprintln(tw, strings.Join([]string{e.Name, devboxOwner(e), kind, e.Target, devboxAge(now.Sub(e.Created)), state}, "\t"))
+ }
+ return tw.Flush()
+}
+
+// devboxOwner is the owner column. The registrar shows an account it
+// cannot name as "uid N"; that account is gone from this machine.
+func devboxOwner(e devbox.ListEntry) string {
+ if e.Owner == "" || e.Owner == "uid "+strconv.FormatUint(uint64(e.OwnerUID), 10) {
+ return devboxOwnerGone
+ }
+ return e.Owner
+}
+
+// devboxAge is a count and one letter: 40s, 5m, 3h, 2d.
+func devboxAge(d time.Duration) string {
+ switch {
+ case d < time.Minute:
+ return strconv.Itoa(max(int(d/time.Second), 0)) + "s"
+ case d < time.Hour:
+ return strconv.Itoa(int(d/time.Minute)) + "m"
+ case d < 24*time.Hour:
+ return strconv.Itoa(int(d/time.Hour)) + "h"
+ }
+ return strconv.Itoa(int(d/(24*time.Hour))) + "d"
+}
+
+// refusalContext is what a refusal's sentence fills in: the name, the port
+// and the folder as the person typed them.
+type refusalContext struct{ name, port, path string }
+
+// render turns a registrar refusal into its deck sentence.
+func (rc refusalContext) render(w devbox.WireError) error {
+ switch w.Code {
+ case devbox.CodeOwned:
+ if w.Owner == "" {
+ return refuseWith(devboxInUse(rc.name))
+ }
+ return refuseWith(devboxTaken(rc.name, w.Owner))
+ case devbox.CodeInvalidName:
+ return refuseWith(devboxInvalidName(rc.name))
+ case devbox.CodeBadPort:
+ return refuseWith(devboxBadPort(rc.port))
+ case devbox.CodeFolderTooBig:
+ return refuseWith(devboxFolderTooBig(rc.path))
+ case devbox.CodeSpoolFull:
+ return refuseWith(devboxSpoolFull)
+ case devbox.CodeNotYours:
+ return refuseWith(devboxNotYours(w.Owner))
+ case devbox.CodeUnknownLink:
+ return refuseWith(devboxUnknownLink(rc.name))
+ case devbox.CodeInternal:
+ return refuseWith(devboxInternal)
+ }
+ return refuseWith(devboxNotUnderstood)
+}
+
+// devboxCallTimeout bounds one call. A folder upload may take the
+// registrar's two minutes to arrive, so it gets more.
+const (
+ devboxCallTimeout = 30 * time.Second
+ devboxUploadTimeout = 3 * time.Minute
+)
+
+// call sends one request to the registrar and decodes its answer into out.
+// A refusal comes back as its deck sentence; a socket that cannot be
+// reached as DBX-C33 and the sandbox hint.
+func (c *devboxCLI) call(method, path, contentType string, body []byte, rc refusalContext, out any) error {
+ timeout := devboxCallTimeout
+ if strings.HasPrefix(path, "/share/folder") {
+ timeout = devboxUploadTimeout
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+ tr := &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", c.socket)
+ },
+ }
+ defer tr.CloseIdleConnections()
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, "http://devbox"+path, rd)
+ if err != nil {
+ return err
+ }
+ if contentType != "" {
+ req.Header.Set("Content-Type", contentType)
+ }
+ resp, err := (&http.Client{Transport: tr}).Do(req)
+ if err != nil {
+ return refuseWith(devboxUnreachable(c.socket), devboxSandboxHint)
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
+ if err != nil {
+ return refuseWith(devboxUnreachable(c.socket), devboxSandboxHint)
+ }
+ if resp.StatusCode != http.StatusOK {
+ var w devbox.WireError
+ if json.Unmarshal(raw, &w) != nil {
+ return refuseWith(devboxNotUnderstood)
+ }
+ return rc.render(w)
+ }
+ if json.Unmarshal(raw, out) != nil {
+ return refuseWith(devboxNotUnderstood)
+ }
+ return nil
+}
+
+// ---- serve: what the unit runs ----------------------------------------------
+
+// runDevboxServe reads the unit's environment, opens the registry and the
+// 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)
+ }
+ listen := strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_LISTEN"))
+ domain := strings.ToLower(strings.TrimSpace(os.Getenv("CARLOS_DEVBOX_DOMAIN")))
+ dataDir := strings.TrimSpace(os.Getenv("CARLOS_DATA_DIR"))
+ switch {
+ case listen == "":
+ return errors.New("devbox serve: CARLOS_DEVBOX_LISTEN is unset; set it to the tailnet address and port, such as 100.64.0.10:443")
+ case domain == "":
+ return errors.New("devbox serve: CARLOS_DEVBOX_DOMAIN is unset")
+ case dataDir == "":
+ return errors.New("devbox serve: CARLOS_DATA_DIR is unset")
+ }
+ // The domain links live under must be the wildcard the edge obtains, or
+ // every link would fail its handshake.
+ if !slices.ContainsFunc(strings.Split(os.Getenv("CARLOS_WILDCARD_DOMAINS"), ","), func(d string) bool {
+ return strings.ToLower(strings.TrimSpace(d)) == domain
+ }) {
+ return fmt.Errorf("devbox serve: CARLOS_DEVBOX_DOMAIN %s is not in CARLOS_WILDCARD_DOMAINS", domain)
+ }
+ // 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)
+ }
+ reg, err := registry.Open(filepath.Join(dataDir, "registry.db"))
+ if err != nil {
+ return fmt.Errorf("devbox serve: %w", err)
+ }
+ defer reg.Close()
+ links, err := devbox.OpenLinks(filepath.Join(dataDir, "links.json"))
+ if err != nil {
+ return fmt.Errorf("devbox serve: %w", err)
+ }
+ spool := filepath.Join(dataDir, "spool")
+ r := &devbox.Registrar{
+ Reg: reg,
+ Links: links,
+ Domain: domain,
+ SpoolRoot: spool,
+ SpoolCap: devboxSpoolCap,
+ LookupUser: lookupUsername,
+ }
+ cfg := edge.DevboxConfig{Registry: reg, ListenAddr: listen, CertDir: filepath.Join(dataDir, "certs"), SpoolRoot: spool}
+
+ 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) })
+}
+
+// lookupUsername is the account name for uid, or "" when this machine has
+// none.
+func lookupUsername(uid uint32) string {
+ u, err := user.LookupId(strconv.FormatUint(uint64(uid), 10))
+ if err != nil {
+ return ""
+ }
+ return u.Username
+}
+
+// devboxDrain bounds the registrar's shutdown, as the edge's own drain is.
+const devboxDrain = 10 * time.Second
+
+// serveDevboxParts runs the registrar on sock and serveEdge under one
+// context. Cancelling ctx stops both. If either returns first, the other is
+// stopped and that error is returned: a devbox with only half of itself
+// running is a failed unit, which systemd restarts.
+func serveDevboxParts(ctx context.Context, sock string, r *devbox.Registrar, serveEdge func(context.Context) error) error {
+ // A socket left by a process that did not get to clean up would make
+ // the listen fail. Only a socket is removed, never anything else.
+ if fi, err := os.Lstat(sock); err == nil && fi.Mode()&fs.ModeSocket != 0 {
+ _ = os.Remove(sock)
+ }
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ return fmt.Errorf("devbox serve: %w", err)
+ }
+ // Every account on the machine may reach the registrar; it knows each
+ // caller by the uid the kernel reports, not by who could open the file.
+ if err := os.Chmod(sock, 0o666); err != nil {
+ ln.Close()
+ return fmt.Errorf("devbox serve: %w", err)
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ srv := &http.Server{
+ Handler: r.Handler(),
+ ConnContext: devbox.ConnContext,
+ ReadHeaderTimeout: 10 * time.Second,
+ }
+ served := make(chan error, 1)
+ go func() { served <- srv.Serve(ln) }()
+ edged := make(chan error, 1)
+ go func() { edged <- serveEdge(ctx) }()
+
+ var edgeErr, srvErr error
+ edgeDone, srvDone := false, false
+ select {
+ case <-ctx.Done():
+ case edgeErr = <-edged:
+ edgeDone = true
+ if edgeErr == nil {
+ edgeErr = errors.New("devbox serve: the edge stopped")
+ }
+ case srvErr = <-served:
+ srvDone = true
+ srvErr = fmt.Errorf("devbox serve: registrar: %w", srvErr)
+ }
+ cancel()
+ sctx, scancel := context.WithTimeout(context.Background(), devboxDrain)
+ defer scancel()
+ if err := srv.Shutdown(sctx); err != nil {
+ srv.Close()
+ if srvErr == nil {
+ srvErr = fmt.Errorf("devbox serve: registrar drain: %w", err)
+ }
+ }
+ // Serve closes the listener, which removes the socket file, before it
+ // returns; wait for that, so no socket outlives this call.
+ if !srvDone {
+ <-served
+ }
+ if !edgeDone {
+ edgeErr = <-edged
+ }
+ return errors.Join(edgeErr, srvErr)
+}
diff --git a/devbox_cli_test.go b/devbox_cli_test.go
new file mode 100644
index 000000000..41572b448
--- /dev/null
+++ b/devbox_cli_test.go
@@ -0,0 +1,473 @@
+//go:build linux
+
+package main
+
+// The carlos devbox CLI against the real registrar (ruling R3): each test
+// serves devbox.Registrar.Handler() on a temp Unix socket with ConnContext,
+// so the caller is known by its SO_PEERCRED uid exactly as in production.
+// No edge runs: the CLI never talks to one. Socket paths are limited to 108
+// bytes, so run these with a short TMPDIR (TMPDIR=/tmp/g).
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/devbox"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const devboxTestDomain = "devbox.example.com"
+
+type devboxHarness struct {
+ sock string
+ r *devbox.Registrar
+ spool string
+}
+
+// newDevboxHarness serves a registrar on a fresh socket. users maps a uid to
+// its username; a uid it does not name has no username.
+func newDevboxHarness(t *testing.T, users map[uint32]string) *devboxHarness {
+ t.Helper()
+ dir := t.TempDir()
+ reg, err := registry.Open(filepath.Join(dir, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ links, err := devbox.OpenLinks(filepath.Join(dir, "links.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := &devboxHarness{sock: filepath.Join(dir, "d.sock"), spool: filepath.Join(dir, "spool")}
+ h.r = &devbox.Registrar{
+ Reg: reg,
+ Links: links,
+ Domain: devboxTestDomain,
+ SpoolRoot: h.spool,
+ SpoolCap: 5 << 30,
+ LookupUser: func(uid uint32) string { return users[uid] },
+ }
+ ln, err := net.Listen("unix", h.sock)
+ if err != nil {
+ t.Fatalf("listen %s: %v (run with a short TMPDIR)", h.sock, err)
+ }
+ srv := &http.Server{Handler: h.r.Handler(), ConnContext: devbox.ConnContext}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+ return h
+}
+
+// runDevboxCLI runs carlos devbox args against sock and returns what it
+// printed and its exit code. mod, when set, adjusts the CLI before it runs.
+func runDevboxCLI(t *testing.T, sock string, mod func(*devboxCLI), args ...string) (string, string, int) {
+ t.Helper()
+ var out, errb bytes.Buffer
+ c := newDevboxCLI(&out, &errb)
+ c.socket = sock
+ if mod != nil {
+ mod(c)
+ }
+ code := c.run(args)
+ return out.String(), errb.String(), code
+}
+
+func me() uint32 { return uint32(os.Getuid()) }
+
+func TestDevboxShareLivePrintsURL(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--port", "8080", "shop")
+ if code != 0 || out != "https://shop.devbox.example.com\n" || errOut != "" {
+ t.Fatalf("share = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+ k, ok := h.r.Links.Get("shop")
+ if !ok || k.Kind != devbox.KindLive || k.Port != 8080 || k.OwnerUID != me() {
+ t.Fatalf("link = %+v, %v", k, ok)
+ }
+ // The name may come first, as the spec writes it.
+ out, errOut, code = runDevboxCLI(t, h.sock, nil, "share", "shop", "--port", "8081")
+ if code != 0 || out != "https://shop.devbox.example.com\n" {
+ t.Fatalf("share name-first = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+ if k, _ := h.r.Links.Get("shop"); k.Port != 8081 {
+ t.Fatalf("port = %d, want 8081", k.Port)
+ }
+}
+
+func TestDevboxShareDefaultsToBranchName(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ repo := t.TempDir()
+ git := exec.Command("git", "init", "-q", "-b", "Feature/Shop", repo)
+ git.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1")
+ if b, err := git.CombinedOutput(); err != nil {
+ t.Fatalf("git init: %v: %s", err, b)
+ }
+ t.Chdir(repo)
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--port", "8080")
+ if code != 0 || out != "https://feature-shop.devbox.example.com\n" {
+ t.Fatalf("share = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+ if _, ok := h.r.Links.Get("feature-shop"); !ok {
+ t.Fatal("no link called feature-shop")
+ }
+ out, errOut, code = runDevboxCLI(t, h.sock, nil, "unshare")
+ if code != 0 || out != "removed https://feature-shop.devbox.example.com\n" {
+ t.Fatalf("unshare = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+}
+
+func TestDevboxShareNameRefusals(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ file := filepath.Join(t.TempDir(), "notes.txt")
+ if err := os.WriteFile(file, []byte("hi"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cases := []struct {
+ name string
+ branch func() (string, error)
+ args []string
+ want string
+ }{
+ {"typed name", nil, []string{"share", "--port", "8080", "Shop"},
+ "Shop is not a name a link can have. use 1 to 63 lower case letters, digits or hyphens, with no hyphen at the start or end\n"},
+ {"branch with nothing in it", func() (string, error) { return "///", nil }, []string{"share", "--port", "8080"},
+ "the branch /// has no letters or digits to make a name from. give a name: carlos devbox share <name>\n"},
+ {"no branch", func() (string, error) { return "", errNoGitBranch }, []string{"share", "--port", "8080"},
+ "no name given, and there is no git branch to take one from. give a name: carlos devbox share <name>\n"},
+ {"bad port", nil, []string{"share", "--port", "70000", "shop"},
+ "70000 is not a port. use a number from 1 to 65535. the link points at 127.0.0.1 on this machine\n"},
+ {"port not a number", nil, []string{"share", "--port", "http", "shop"},
+ "http is not a port. use a number from 1 to 65535. the link points at 127.0.0.1 on this machine\n"},
+ {"neither", nil, []string{"share", "shop"},
+ "give either --port for a dev server or --dir for a folder, not both and not neither\n"},
+ {"both", nil, []string{"share", "--port", "8080", "--dir", ".", "shop"},
+ "give either --port for a dev server or --dir for a folder, not both and not neither\n"},
+ {"dir is a file", nil, []string{"share", "--dir", file, "shop"}, file + " is not a folder\n"},
+ {"dir is missing", nil, []string{"share", "--dir", file + "-gone", "shop"}, file + "-gone is not a folder\n"},
+ {"unknown command", nil, []string{"publish"},
+ "unknown devbox command publish. use share, unshare or list\n"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ mod := func(cli *devboxCLI) {
+ if c.branch != nil {
+ cli.branch = c.branch
+ }
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, c.args...)
+ if code == 0 || out != "" || errOut != c.want {
+ t.Fatalf("= %d, stdout %q, stderr %q; want stderr %q", code, out, errOut, c.want)
+ }
+ })
+ }
+ if n := len(h.r.Links.All()); n != 0 {
+ t.Fatalf("%d links registered by refused shares", n)
+ }
+}
+
+func TestDevboxShareDirPacksFolder(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ site := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(site, "css"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(site, "index.html"), []byte("<h1>hello</h1>"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(site, "css", "site.css"), []byte("h1{}"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--dir", site, "docs")
+ if code != 0 || out != "https://docs.devbox.example.com\n" {
+ t.Fatalf("share = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+ k, ok := h.r.Links.Get("docs")
+ if !ok || k.Kind != devbox.KindFolder {
+ t.Fatalf("link = %+v, %v", k, ok)
+ }
+ for name, want := range map[string]string{"index.html": "<h1>hello</h1>", "css/site.css": "h1{}"} {
+ got, err := os.ReadFile(filepath.Join(h.spool, "docs", "current", filepath.FromSlash(name)))
+ if err != nil || string(got) != want {
+ t.Fatalf("%s = %q, %v; want %q", name, got, err, want)
+ }
+ }
+}
+
+func TestDevboxShareDirRefusesSymlink(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ site := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(site, "assets"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(site, "index.html"), []byte("hi"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("/etc/passwd", filepath.Join(site, "assets", "passwd")); err != nil {
+ t.Fatal(err)
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--dir", site, "docs")
+ want := "assets/passwd is a symbolic link or a special file. only plain files and folders can be shared. remove it and try again\n"
+ if code == 0 || out != "" || errOut != want {
+ t.Fatalf("= %d, stdout %q, stderr %q; want %q", code, out, errOut, want)
+ }
+ if _, ok := h.r.Links.Get("docs"); ok {
+ t.Fatal("a refused folder was registered")
+ }
+}
+
+func TestDevboxUnreachableNamesSandbox(t *testing.T) {
+ sock := filepath.Join(t.TempDir(), "absent.sock")
+ for _, args := range [][]string{{"share", "--port", "8080", "shop"}, {"unshare", "shop"}, {"list"}} {
+ out, errOut, code := runDevboxCLI(t, sock, nil, args...)
+ want := "could not reach the devbox service at " + sock + ". check that it is running, or tell whoever runs this devbox\n" +
+ "if you are inside an agent sandbox, that is the likely cause: the sandbox blocks the socket. run this command outside the sandbox\n"
+ if code == 0 || out != "" || errOut != want {
+ t.Fatalf("%v = %d, stdout %q, stderr %q; want %q", args, code, out, errOut, want)
+ }
+ }
+}
+
+func TestDevboxSocketDefault(t *testing.T) {
+ t.Setenv("CARLOS_DEVBOX_SOCKET", "")
+ if got := newDevboxCLI(nil, nil).socket; got != "/run/carlos-devbox/devbox.sock" {
+ t.Fatalf("socket = %q", got)
+ }
+ t.Setenv("CARLOS_DEVBOX_SOCKET", "/tmp/x.sock")
+ if got := newDevboxCLI(nil, nil).socket; got != "/tmp/x.sock" {
+ t.Fatalf("socket = %q", got)
+ }
+}
+
+func TestDevboxListTable(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+
+ // An answering dev server, and a port nothing listens on.
+ up, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer up.Close()
+ upPort := up.Addr().(*net.TCPAddr).Port
+ gone, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ downPort := gone.Addr().(*net.TCPAddr).Port
+ gone.Close()
+
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "list")
+ if code != 0 || out != "no links yet. publish one with: carlos devbox share --port <port> <name>\n" {
+ t.Fatalf("empty list = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+
+ site := t.TempDir()
+ if err := os.WriteFile(filepath.Join(site, "index.html"), []byte("hi"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for _, args := range [][]string{
+ {"share", "--port", fmt.Sprint(upPort), "api"},
+ {"share", "--dir", site, "docs"},
+ {"share", "--port", fmt.Sprint(downPort), "shop"},
+ } {
+ if _, errOut, code := runDevboxCLI(t, h.sock, nil, args...); code != 0 {
+ t.Fatalf("%v = %d, %s", args, code, errOut)
+ }
+ }
+ later := func(c *devboxCLI) { c.now = func() time.Time { return time.Now().Add(3*time.Hour + time.Minute) } }
+ out, errOut, code = runDevboxCLI(t, h.sock, later, "list")
+ if code != 0 {
+ t.Fatalf("list = %d, stderr %q", code, errOut)
+ }
+ lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
+ want := [][]string{
+ {"name", "owner", "kind", "target", "age", "state"},
+ {"api", "alice", "live", fmt.Sprintf("127.0.0.1:%d", upPort), "3h", "answering"},
+ {"docs", "alice", "folder", "3h", "serving"}, // a folder's target is empty (ruling R10)
+ {"shop", "alice", "live", fmt.Sprintf("127.0.0.1:%d", downPort), "3h", "not", "answering"},
+ }
+ if len(lines) != len(want) {
+ t.Fatalf("list:\n%s", out)
+ }
+ stateCol := strings.Index(lines[0], "state")
+ for i, l := range lines {
+ if got := strings.Fields(l); strings.Join(got, "|") != strings.Join(want[i], "|") {
+ t.Fatalf("line %d = %q, want fields %q\n%s", i, l, want[i], out)
+ }
+ // Columns line up: every row's last column starts under "state".
+ last := want[i][len(want[i])-1]
+ if i == 3 {
+ last = "not answering"
+ }
+ if strings.Index(l, last) != stateCol {
+ t.Fatalf("line %d: state at %d, header at %d\n%s", i, strings.Index(l, last), stateCol, out)
+ }
+ }
+}
+
+// A link whose owner's account is gone shows "account removed".
+func TestDevboxListAccountRemoved(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ if _, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--port", "8080", "shop"); code != 0 {
+ t.Fatalf("share = %d, %s", code, errOut)
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "list")
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ if code != 0 || len(lines) != 2 || !strings.Contains(lines[1], " account removed ") {
+ t.Fatalf("list = %d, stdout %q, stderr %q", code, out, errOut)
+ }
+}
+
+// Someone else's name, through the real registrar: share is refused with
+// the owner's name, and so is unshare.
+func TestDevboxOthersLinkRefused(t *testing.T) {
+ const bob = 4242
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice", bob: "bob"})
+ now := time.Now().UTC()
+ if err := h.r.Links.Put(devbox.Link{Name: "shop", OwnerName: "bob", OwnerUID: bob, Kind: devbox.KindLive, Port: 9000, Created: now, Updated: now}); err != nil {
+ t.Fatal(err)
+ }
+ _, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--port", "8080", "shop")
+ if code == 0 || errOut != "shop is taken by bob. pick another name\n" {
+ t.Fatalf("share = %d, stderr %q", code, errOut)
+ }
+ _, errOut, code = runDevboxCLI(t, h.sock, nil, "unshare", "shop")
+ if code == 0 || errOut != "not your link. ask its owner, bob, to remove it\n" {
+ t.Fatalf("unshare = %d, stderr %q", code, errOut)
+ }
+ _, errOut, code = runDevboxCLI(t, h.sock, nil, "unshare", "nothing")
+ if code == 0 || errOut != "no link called nothing. see what exists with: carlos devbox list\n" {
+ t.Fatalf("unshare unknown = %d, stderr %q", code, errOut)
+ }
+}
+
+// Every registrar code renders through its deck row, and anything else
+// through DBX-C35. A fake service answers each with a fixed refusal.
+func TestDevboxRefusalsRenderFromDeck(t *testing.T) {
+ var mu sync.Mutex
+ var status int
+ var body string
+ sock := filepath.Join(t.TempDir(), "f.sock")
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ w.WriteHeader(status)
+ fmt.Fprint(w, body)
+ })}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+ refusal := func(code, owner string) string {
+ b, _ := json.Marshal(devbox.WireError{Code: code, Owner: owner})
+ return string(b)
+ }
+
+ site := t.TempDir()
+ if err := os.WriteFile(filepath.Join(site, "index.html"), []byte("hi"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ live := []string{"share", "--port", "8080", "shop"}
+ cases := []struct {
+ name string
+ status int
+ body string
+ args []string
+ want string
+ }{
+ {"owned", 409, refusal(devbox.CodeOwned, "bob"), live, "shop is taken by bob. pick another name"},
+ {"owned, no owner", 409, refusal(devbox.CodeOwned, ""), live, "shop is already in use on this devbox. pick another name"},
+ {"invalid name", 400, refusal(devbox.CodeInvalidName, ""), live,
+ "shop is not a name a link can have. use 1 to 63 lower case letters, digits or hyphens, with no hyphen at the start or end"},
+ {"bad port", 400, refusal(devbox.CodeBadPort, ""), live,
+ "8080 is not a port. use a number from 1 to 65535. the link points at 127.0.0.1 on this machine"},
+ {"folder too big", 413, refusal(devbox.CodeFolderTooBig, ""), []string{"share", "--dir", site, "docs"},
+ site + " is over 200 MiB once packed. share a smaller folder"},
+ {"spool full", 507, refusal(devbox.CodeSpoolFull, ""), []string{"share", "--dir", site, "docs"},
+ "the devbox has no room for another folder. remove one you no longer need with carlos devbox unshare, or tell whoever runs this devbox"},
+ {"not yours", 403, refusal(devbox.CodeNotYours, "bob"), []string{"unshare", "shop"}, "not your link. ask its owner, bob, to remove it"},
+ {"unknown link", 404, refusal(devbox.CodeUnknownLink, ""), []string{"unshare", "shop"}, "no link called shop. see what exists with: carlos devbox list"},
+ {"internal", 500, refusal(devbox.CodeInternal, ""), live, "the devbox service could not finish that. try again, or tell whoever runs this devbox"},
+ {"bad request", 400, refusal(devbox.CodeBadRequest, ""), live,
+ "the devbox service answered with something this carlos does not understand. update carlos and try again"},
+ {"unknown code", 409, refusal("frobbed", ""), live,
+ "the devbox service answered with something this carlos does not understand. update carlos and try again"},
+ {"not json", 502, "<html>", []string{"list"},
+ "the devbox service answered with something this carlos does not understand. update carlos and try again"},
+ {"success not json", 200, "<html>", live,
+ "the devbox service answered with something this carlos does not understand. update carlos and try again"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ mu.Lock()
+ status, body = c.status, c.body
+ mu.Unlock()
+ out, errOut, code := runDevboxCLI(t, sock, nil, c.args...)
+ if code == 0 || out != "" || errOut != c.want+"\n" {
+ t.Fatalf("= %d, stdout %q, stderr %q; want %q", code, out, errOut, c.want)
+ }
+ })
+ }
+}
+
+// serve composes the edge and the registrar under one context: when either
+// fails, the other is stopped and the error comes back.
+func TestDevboxServeStopsBothOnError(t *testing.T) {
+ sock := filepath.Join(t.TempDir(), "s.sock")
+ edgeStopped := make(chan struct{})
+ edgeFails := func(ctx context.Context) error { return fmt.Errorf("edge broke") }
+ edgeWaits := func(ctx context.Context) error { <-ctx.Done(); close(edgeStopped); return nil }
+
+ r := &devbox.Registrar{}
+ err := serveDevboxParts(context.Background(), sock, r, edgeFails)
+ if err == nil || !strings.Contains(err.Error(), "edge broke") {
+ t.Fatalf("serve = %v, want the edge's error", err)
+ }
+ if _, err := os.Stat(sock); err == nil {
+ t.Fatal("socket left behind after serve returned")
+ }
+
+ // A cancelled context (SIGTERM) stops both and returns cleanly; the
+ // socket is mode 0666 while it serves.
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- serveDevboxParts(ctx, sock, r, edgeWaits) }()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if fi, err := os.Stat(sock); err == nil {
+ if fi.Mode().Perm() != 0o666 {
+ t.Fatalf("socket mode = %v, want 0666", fi.Mode().Perm())
+ }
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("socket never appeared")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ cancel()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("serve after cancel = %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("serve did not stop")
+ }
+ select {
+ case <-edgeStopped:
+ default:
+ t.Fatal("the edge was not stopped")
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 7554e1071..f2729ada4 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -585,6 +585,15 @@ lease; there is no pointer to delete.
One thing this is not: traffic splitting. A canary is a URL, not a
percentage of production traffic on the app's own hostname.
+### carlos devbox
+
+```sh
+carlos devbox share --port 5173 shop
+carlos devbox share --dir ./dist docs
+carlos devbox unshare shop
+carlos devbox list
+```
+
### carlos restart
Cycles running processes with no new version and no config change. This is
diff --git a/infra/devbox/README.md b/infra/devbox/README.md
new file mode 100644
index 000000000..0aa19ab44
--- /dev/null
+++ b/infra/devbox/README.md
@@ -0,0 +1,116 @@
+# Devbox mode: one-time install
+
+Devbox mode lets anyone with an account on this machine publish a link such as https://shop.devbox.example.com. The link is open to the tailnet only, and it points at their own dev server or at a folder of static files. Someone with root does the steps below once. After that nobody needs root or sudo, and nothing runs as root.
+
+## Install, once, as root
+
+Create the service user. It is a system account with no login, and nobody else can read its files.
+
+```sh
+useradd --system --user-group --no-create-home \
+ --home-dir /var/lib/carlos-devbox --shell /usr/sbin/nologin carlos-devbox
+```
+
+Install the carlos binary and the unit file. The unit runs as that user and may bind port 443 and nothing else.
+
+```sh
+install -m 0755 carlos /usr/local/bin/carlos
+install -m 0644 infra/devbox/carlos-devbox.service /etc/systemd/system/carlos-devbox.service
+systemctl daemon-reload
+```
+
+Write the environment file, readable only by the service user. It holds the devbox's tailnet address and domain, and the AWS key for the certificate challenge record.
+
+```sh
+aws iam create-user --user-name carlos-devbox-acme
+aws iam create-access-key --user-name carlos-devbox-acme
+install -d -m 0750 -o root -g carlos-devbox /etc/carlos-devbox
+install -m 0600 -o carlos-devbox -g carlos-devbox /dev/null /etc/carlos-devbox/env
+"${EDITOR:-vi}" /etc/carlos-devbox/env
+```
+
+```sh
+# /etc/carlos-devbox/env
+CARLOS_DEVBOX_LISTEN=100.64.0.10:443
+CARLOS_DEVBOX_DOMAIN=devbox.example.com
+CARLOS_WILDCARD_DOMAINS=devbox.example.com
+CARLOS_DATA_DIR=/var/lib/carlos-devbox
+CARLOS_DNS_PROVIDER=route53
+AWS_ACCESS_KEY_ID=AKIA...
+AWS_SECRET_ACCESS_KEY=...
+```
+
+Create the IAM policy from route53-acme-policy.json, attach it to the key, and enable the unit.
+
+```sh
+ZONE_ID=Z0123456789EXAMPLE
+DOMAIN=devbox.example.com
+sed -e "s/HOSTED_ZONE_ID/$ZONE_ID/" -e "s/devbox\.example\.com/$DOMAIN/" \
+ infra/devbox/route53-acme-policy.json > policy.json
+aws iam create-policy --policy-name carlos-devbox-acme --policy-document file://policy.json
+aws iam attach-user-policy --user-name carlos-devbox-acme \
+ --policy-arn arn:aws:iam::123456789012:policy/carlos-devbox-acme
+systemctl enable --now carlos-devbox
+journalctl -u carlos-devbox -f
+```
+
+## DNS
+
+Add one A record, by hand, once: *.devbox.example.com pointing at this machine's tailnet IPv4 address.
+
+```
+*.devbox.example.com. 300 IN A 100.64.0.10
+```
+
+## Check that it works
+
+- [ ] As an ordinary user, then again as an agent account, run a dev server on 127.0.0.1, publish it, open the link from another device on the tailnet, and see an edit appear through live reload.
+
+ ```sh
+ npx vite --host 127.0.0.1 --port 5173
+ carlos devbox share --port 5173 shop
+ ```
+
+- [ ] Publish a folder and see it with its _headers file applied.
+
+ ```sh
+ carlos devbox share --dir ./dist docs
+ curl -sI https://docs.devbox.example.com/
+ ```
+
+- [ ] Try to repoint or remove the other account's link. Both must be refused, and carlos devbox list must show both links with their owners.
+
+ ```sh
+ carlos devbox share --port 5174 shop
+ carlos devbox unshare shop
+ carlos devbox list
+ ```
+
+- [ ] Check that no certificate order was placed for any name the wildcard does not cover, and that nothing listens on any address except the tailnet one.
+
+ ```sh
+ ls /var/lib/carlos-devbox/certs
+ journalctl -u carlos-devbox | grep -i acme
+ ss -ltnp | grep carlos
+ ```
+
+A dev server that checks the Host header needs the devbox domain added once per project. In Vite that is server.allowedHosts, and in Rails it is config.hosts.
+
+```js
+// vite.config.js
+server: { allowedHosts: ['.devbox.example.com'] }
+```
+
+```ruby
+# config/environments/development.rb
+config.hosts << '.devbox.example.com'
+```
+
+Live reload must connect on port 443. In Vite, set hmr.clientPort to 443.
+
+```js
+// vite.config.js
+server: { hmr: { clientPort: 443 } }
+```
+
+Loopback ports are shared by every account on this machine. The owner of a link controls where its name points, but not who is listening on that port.
diff --git a/infra/devbox/carlos-devbox.service b/infra/devbox/carlos-devbox.service
new file mode 100644
index 000000000..252b6e487
--- /dev/null
+++ b/infra/devbox/carlos-devbox.service
@@ -0,0 +1,67 @@
+# Devbox mode (#474): `carlos devbox serve` = the edge, on the tailnet
+# address only and with the DNS-01 wildcard as its only certificate, plus the
+# registrar that hands out link names on a Unix socket every local account
+# can reach. Runs as its own unprivileged user; nothing here runs as root
+# after the one-time install in infra/devbox/README.md.
+[Unit]
+Description=carlos devbox (named HTTPS links on the tailnet, and the registrar that hands them out)
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+# CARLOS_DEVBOX_LISTEN, CARLOS_DEVBOX_DOMAIN, CARLOS_WILDCARD_DOMAINS,
+# CARLOS_DATA_DIR, CARLOS_DNS_PROVIDER and the DNS credential. Mode 0600.
+EnvironmentFile=/etc/carlos-devbox/env
+ExecStart=/usr/local/bin/carlos devbox serve
+# The listen address is the tailnet's: if the tailnet is not up yet the bind
+# fails, and the unit tries again.
+Restart=always
+RestartSec=5
+
+User=carlos-devbox
+Group=carlos-devbox
+# /run/carlos-devbox holds the registrar socket (devbox.sock, mode 0666: the
+# registrar knows each caller by its SO_PEERCRED uid, not by who may open
+# the file). 0755 so every account can reach the socket.
+RuntimeDirectory=carlos-devbox
+RuntimeDirectoryMode=0755
+# /var/lib/carlos-devbox is CARLOS_DATA_DIR: registry.db, links.json, certs/
+# and spool/. Private to the service user.
+StateDirectory=carlos-devbox
+StateDirectoryMode=0700
+
+# --- hardening (from internal/host/units/carlos-edge.service, where it
+# applies; the devbox has no instances, mounts, cgroup delegation or slice) ---
+# Binding :443 on the tailnet address, and nothing else privileged.
+AmbientCapabilities=CAP_NET_BIND_SERVICE
+CapabilityBoundingSet=CAP_NET_BIND_SERVICE
+NoNewPrivileges=yes
+ProtectSystem=strict
+ProtectHome=yes
+PrivateTmp=yes
+PrivateDevices=yes
+ProtectClock=yes
+ProtectHostname=yes
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectKernelLogs=yes
+# Present here: the edge unit leaves it out only for Delegate=, which the
+# devbox does not use.
+ProtectControlGroups=yes
+ProtectProc=invisible
+RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
+RestrictNamespaces=yes
+RestrictRealtime=yes
+# Present here: the edge unit leaves it out because systemd refuses openat2
+# under it, and the devbox makes no openat2 call.
+RestrictSUIDSGID=yes
+LockPersonality=yes
+# Pure Go: the binary never maps writable+executable memory.
+MemoryDenyWriteExecute=yes
+SystemCallFilter=@system-service
+SystemCallErrorNumber=EPERM
+SystemCallArchitectures=native
+TasksMax=1024
+
+[Install]
+WantedBy=multi-user.target
diff --git a/infra/devbox/route53-acme-policy.json b/infra/devbox/route53-acme-policy.json
new file mode 100644
index 000000000..aa8b08f29
--- /dev/null
+++ b/infra/devbox/route53-acme-policy.json
@@ -0,0 +1,23 @@
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "DevboxAcmeChallengeRecordOnly",
+ "Effect": "Allow",
+ "Action": "route53:ChangeResourceRecordSets",
+ "Resource": "arn:aws:route53:::hostedzone/HOSTED_ZONE_ID",
+ "Condition": {
+ "ForAllValues:StringEquals": {
+ "route53:ChangeResourceRecordSetsNormalizedRecordNames": ["_acme-challenge.devbox.example.com"],
+ "route53:ChangeResourceRecordSetsRecordTypes": ["TXT"]
+ }
+ }
+ },
+ {
+ "Sid": "DevboxFindZoneAndWaitForChange",
+ "Effect": "Allow",
+ "Action": ["route53:ListHostedZonesByName", "route53:GetChange"],
+ "Resource": "*"
+ }
+ ]
+}
diff --git a/main.go b/main.go
index 62f138eb2..2fa35ec21 100644
--- a/main.go
+++ b/main.go
@@ -68,6 +68,8 @@ func main() {
}
case "edge":
edge.Run(args)
+ case "devbox":
+ runDevbox(args)
case "add":
runAdd(args)
case "remove":
@@ -257,6 +259,7 @@ Your apps โ€” ship and run software on a CARLOS deployment
deploy ship + promote + wait until the URL serves the new version
canary the same, onto a host and channel of this branch's own, so
nothing the app already serves changes: deploy | ls | rm
+ devbox publish a dev server or a folder as a link on this devbox
restart cycle an app's instances โ€” no new version, no config change;
--host or --environment narrows it, --dry-run names the set
db read a copy of an instance's database, restored from its