carlos / platform Public

devbox mode (#474): ServeDevbox, the wildcard-only front door

ServeDevbox serves the registry over one HTTPS listener on a named IP, with
the DNS-01 wildcard as its only certificate. The handshake chain is
wrapGetCertificate with a refusal where Run has autocert, so an uncovered
name, the parent apex, a tls-alpn-01 hello, or any name before the wildcard
exists fails the handshake and places no order. No :80, no cert mirror, home
map, door, release store or cert warm; guard, rate limit and response cache
are off. Empty, unspecified (including ::ffff:0.0.0.0) and host-name listen
addresses are refused, as is an environment with no CARLOS_WILDCARD_DOMAINS
or no DNS provider. Refusals and bind failures are returned; on ctx done it
drains for up to 10s and returns nil.

Tests count DNS present calls and ACME directory requests (R4): zero for
every refused name, and zero end to end with a cached wildcard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3a8a59f6335be5d13c2c3133c251f0486be705d0 parent 49996ce
2 files changed, +483 −0
  • internal/edge/devbox.go +194 −0
  • internal/edge/devbox_test.go +289 −0

Intent

Human

<task-notification> <task-id>a06f0cefa6fdc8103</task-id> <tool-use-id>toolu_012vkdEifnB8Sio8ygEACtyt</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/a06f0cefa6fdc8103.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: local static tree" 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_WITH_CONCERNS Commit: 49996ce3 "devbox mode (#474): the edge serves a local static tree" Tests: the brief's command passes (8 tests, including two extras I added), `-run TestStatic` still passes, and `-race` on the new tests passes. gofmt and `go vet ./internal/edge` are clean. RED was `undefined: newLocalStaticHandler` and `undefined: WithLocalStatic`. The sandbox's Go cache is read-only, so I ran the test commands with the sandbox disabled. Concerns: - **Brief deviation:** the existing `parseHeaders` rejects `X-Mock: yes`, because it only allows five headers. The five are Cache-Control, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Cross-Origin-Resource-Policy and Timing-Allow-Origin. The tests use `Access-Control-Allow-Origin: *` and `Cache-Control: max-age=60`/`max-age=120` instead. Later devbox tasks and copy should not promise arbitrary headers. - **Mid-swap 404:** a request in flight when the registrar deletes the old tree gets a 404 for the file it lost. - **App-name guard:** an app name that is empty, "." or "..", or that contains a path separator, serves the "static serving not configured" 404. That guard is beyond the brief. - **Cache:** the header and redirect cache keeps only the most recent resolved target, as you specified. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/devbox-mode/.superpowers/sdd/2026-10-30-devbox-mode/task-2-report.md</result> <usage><subagent_tokens>62721</subagent_tokens><tool_uses>15</tool_uses><duration_ms>173724</duration_ms></usage> </task-notification>

Human

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

Attributed to this commit: 6.13 g CO₂e (778,787 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/internal/edge/devbox.go b/internal/edge/devbox.go
new file mode 100644
index 000000000..ddac66f02
--- /dev/null
+++ b/internal/edge/devbox.go
@@ -0,0 +1,194 @@
+package edge
+
+// Devbox mode's front door (devbox mode design §5.2, #474). A devbox is a
+// shared workstation on a private network: no CA can reach it, so HTTP-01
+// and TLS-ALPN-01 never validate there, and its only certificate is one
+// DNS-01 wildcard, *.<devbox domain>, obtained by the existing wildcard
+// manager. Run is the wrong shape for that. It always binds :80 and always
+// falls through to autocert's per-host issuance for any name the wildcard
+// does not cover, including every name before the wildcard first arrives;
+// on a devbox each of those handshakes would place an order that can only
+// fail, and spend Let's Encrypt's failed-validation allowance doing it.
+//
+// ServeDevbox is a separate, smaller entrypoint built from Run's parts: one
+// HTTPS listener on a named address, the wildcard and nothing behind it. A
+// name the wildcard does not cover, or any name before the wildcard exists,
+// fails the handshake. Nothing here builds an autocert.Manager, so no
+// handshake can reach one.
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// DevboxConfig is what ServeDevbox needs beyond the environment. The
+// wildcard parent and the DNS provider come from the environment Run already
+// reads (CARLOS_WILDCARD_DOMAINS, CARLOS_DNS_PROVIDER and its credential).
+type DevboxConfig struct {
+ Registry *registry.Registry
+ 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
+}
+
+// ServeDevbox serves the registry's routes over HTTPS on cfg.ListenAddr with
+// the wildcard as the only certificate, until ctx is done; then it drains
+// in-flight requests for up to 10s, as Run does, and returns nil. Every
+// refusal and bind failure is returned, never fatal: a caller may run this
+// beside another server in one process.
+func ServeDevbox(ctx context.Context, cfg DevboxConfig) error {
+ // 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.
+ if err := checkDevboxListenAddr(cfg.ListenAddr); err != nil {
+ return err
+ }
+ if cfg.Registry == nil {
+ return errors.New("edge: devbox: no registry")
+ }
+ // Both are paths the edge writes or reads relative to: empty would mean
+ // the process's working directory.
+ if cfg.CertDir == "" {
+ return errors.New("edge: devbox: no certificate directory")
+ }
+ if cfg.SpoolRoot == "" {
+ return errors.New("edge: devbox: no spool root")
+ }
+ // The devbox's parent is a configured one. An apps domain alone would
+ // make newWildcardFromEnv build a manager whose parents come only from
+ // routes, which is not the one wildcard a devbox is set up for.
+ if len(splitDomains(os.Getenv("CARLOS_WILDCARD_DOMAINS"))) == 0 {
+ return errors.New("edge: devbox: CARLOS_WILDCARD_DOMAINS is unset; the wildcard is the only certificate devbox mode serves")
+ }
+
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ return err
+ }
+ certCache, err := newCertCache(cfg.CertDir)
+ if err != nil {
+ return fmt.Errorf("edge: devbox: %w", err)
+ }
+ // No issuer gate (e.issuer is nil, so ungated): a devbox is a deployment
+ // of one, and its manager is the only thing that orders.
+ w := newWildcardFromEnv(e, certCache)
+ if w == nil {
+ // newWildcardFromEnv has logged why (no DNS provider, or its config
+ // failed to load).
+ return errors.New("edge: devbox: wildcard certificates are off; devbox mode needs CARLOS_DNS_PROVIDER and its credential")
+ }
+
+ // Bind before starting anything, so a bind failure leaves no goroutine
+ // 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
+ }
+
+ stop := make(chan struct{})
+ defer close(stop)
+ e.OnReload(w.refresh)
+ w.refresh()
+ go w.run() // process-lifetime, as in Run: run has no stop
+ go e.Watch(stop)
+
+ // ReadHeaderTimeout for the same slow-header reason as Run's servers,
+ // and no Read/WriteTimeout, which would cut proxied WebSockets.
+ srv := &http.Server{
+ Handler: e,
+ TLSConfig: &tls.Config{
+ GetCertificate: devboxGetCertificate(w),
+ // No acme-tls/1: there is no per-host order for it to answer.
+ NextProtos: []string{"h2", "http/1.1"},
+ MinVersion: tls.VersionTLS12,
+ },
+ ReadHeaderTimeout: 10 * time.Second,
+ }
+ served := make(chan error, 1)
+ go func() { served <- srv.ServeTLS(ln, "", "") }()
+ log.Printf("edge: devbox: serving %d route(s) on %s, wildcard only (parents %v)",
+ len(e.current()), ln.Addr(), w.currentParents())
+
+ select {
+ case <-ctx.Done():
+ case err := <-served:
+ return fmt.Errorf("edge: https listener %s: %w", cfg.ListenAddr, err)
+ }
+ log.Printf("edge: devbox: draining and shutting down")
+ sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ _ = srv.Shutdown(sctx)
+ return nil
+}
+
+// newDevboxEdge builds the edge ServeDevbox serves: static routes from the
+// spool, and the request guard, the rate limit and the response cache off
+// whatever the environment says. Each of those is for a public edge; on a
+// devbox every caller is a developer on the tailnet looking at their own
+// work, where a block page, a 429 or a stale cached page is only in the way.
+func newDevboxEdge(cfg DevboxConfig) (*Edge, error) {
+ e, err := New(cfg.Registry, nil)
+ if err != nil {
+ return nil, fmt.Errorf("edge: devbox: %w", err)
+ }
+ WithLocalStatic(cfg.SpoolRoot)(e)
+ e.guard = guardOff
+ e.rateMode = RateOff
+ e.EnableCache(nil)
+ // New's startup Reload ran before the spool root was set; build the
+ // table again so static routes get local handlers from the start rather
+ // than at the watcher's first tick.
+ if err := e.Reload(); err != nil {
+ return nil, fmt.Errorf("edge: devbox: %w", err)
+ }
+ return e, nil
+}
+
+// checkDevboxListenAddr refuses any address that is not one specific IP and
+// a port. An empty host, 0.0.0.0, :: and the IPv4 wildcard written as IPv6
+// all bind every interface, and a host name could resolve to anything.
+func checkDevboxListenAddr(addr string) error {
+ host, port, err := net.SplitHostPort(addr)
+ if err != nil {
+ return fmt.Errorf("edge: devbox: listen address %q: %w", addr, err)
+ }
+ ip, err := netip.ParseAddr(host)
+ if err != nil {
+ return fmt.Errorf("edge: devbox: listen address %q: the host must be a specific IP address, such as the tailnet address", addr)
+ }
+ // Unmap: Go binds ::ffff:0.0.0.0 as the IPv4 wildcard.
+ if ip.Unmap().IsUnspecified() {
+ return fmt.Errorf("edge: devbox: listen address %q binds every interface; give the tailnet address", addr)
+ }
+ if port == "" {
+ return fmt.Errorf("edge: devbox: listen address %q has no port", addr)
+ }
+ return nil
+}
+
+// devboxGetCertificate is the devbox handshake chain: the wildcard for a
+// name one label under its parent, once the wildcard exists, and a refusal
+// for everything else. It is wrapGetCertificate with a refusal where Run has
+// autocert, so the wildcard's matching (and its tls-alpn-01 rule, which here
+// refuses too) is exactly Run's, and nothing behind it can order.
+func devboxGetCertificate(w *wildcardManager) func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
+ return wrapGetCertificate(w, devboxNoCertificate)
+}
+
+// devboxNoCertificate fails the handshake. The server logs it as a TLS
+// handshake error; the name is quoted because the client chose it.
+func devboxNoCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ return nil, fmt.Errorf("edge: devbox: no certificate for %q: devbox mode serves only names one label under its wildcard, once the wildcard is obtained", hello.ServerName)
+}
diff --git a/internal/edge/devbox_test.go b/internal/edge/devbox_test.go
new file mode 100644
index 000000000..059e8007e
--- /dev/null
+++ b/internal/edge/devbox_test.go
@@ -0,0 +1,289 @@
+package edge
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "net"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/acme/autocert"
+)
+
+// devboxParent is the one wildcard parent these tests run under.
+const devboxParent = "devbox.example.com"
+
+// devboxEnv is the environment a devbox runs with: one wildcard parent, a DNS
+// provider, nothing else that could add a parent, and ACME pointed at ca.
+func devboxEnv(t *testing.T, caURL string) {
+ t.Helper()
+ t.Setenv("CARLOS_WILDCARD_DOMAINS", devboxParent)
+ t.Setenv("PLATFORM_APPS_DOMAIN", "")
+ t.Setenv("CARLOS_STEERING_ZONE_ID", "")
+ t.Setenv("CARLOS_ACME_DELEGATION_ZONE", "")
+ t.Setenv("CARLOS_CERT_CACHE", "")
+ t.Setenv("CARLOS_DNS_PROVIDER", "dnsimple")
+ t.Setenv("CARLOS_DNSIMPLE_TOKEN", "test-token")
+ t.Setenv("CARLOS_ACME_DIRECTORY", caURL)
+}
+
+// countingDNS counts present calls. Safe across goroutines, unlike fakeDNS:
+// the manager's run loop and a handshake can both reach it.
+type countingDNS struct{ presents atomic.Int32 }
+
+func (c *countingDNS) present(context.Context, string, string) (func(context.Context) error, error) {
+ c.presents.Add(1)
+ return func(context.Context) error { return nil }, nil
+}
+
+func TestDevboxRefusesUnspecifiedListenAddr(t *testing.T) {
+ ca, requests := countingCA(t)
+ devboxEnv(t, ca.URL)
+ reg := openReg(t)
+ for _, addr := range []string{
+ "",
+ ":443",
+ "0.0.0.0:443",
+ "[::]:443",
+ "[::ffff:0.0.0.0]:443", // the IPv4 wildcard spelled as IPv6: Go binds it as 0.0.0.0
+ "localhost:443", // a name, which could resolve to anything
+ "127.0.0.1", // no port
+ } {
+ cfg := DevboxConfig{Registry: reg, ListenAddr: addr, CertDir: t.TempDir(), SpoolRoot: t.TempDir()}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ err := ServeDevbox(ctx, cfg)
+ cancel()
+ if err == nil {
+ t.Errorf("ServeDevbox(ListenAddr %q) = nil, want a refusal", addr)
+ continue
+ }
+ if !strings.Contains(err.Error(), "listen address") {
+ t.Errorf("ServeDevbox(ListenAddr %q) = %v, want the listen address refused", addr, err)
+ }
+ }
+ for _, addr := range []string{"127.0.0.1:443", "100.119.180.57:443", "[fd7a:115c:a1e0::1]:443"} {
+ if err := checkDevboxListenAddr(addr); err != nil {
+ t.Errorf("checkDevboxListenAddr(%q) = %v, want nil", addr, err)
+ }
+ }
+ if n := requests.Load(); n != 0 {
+ t.Fatalf("the CA saw %d request(s), want 0", n)
+ }
+}
+
+func TestDevboxRefusesNoWildcard(t *testing.T) {
+ ca, _ := countingCA(t)
+ reg := openReg(t)
+ cases := []struct {
+ name string
+ env map[string]string
+ }{
+ {"no wildcard domains", map[string]string{"CARLOS_WILDCARD_DOMAINS": ""}},
+ // An apps domain alone makes newWildcardFromEnv build a manager, but
+ // its parents come from routes, not from the devbox's one parent.
+ {"apps domain only", map[string]string{"CARLOS_WILDCARD_DOMAINS": "", "PLATFORM_APPS_DOMAIN": "example.org"}},
+ // A domain with no DNS provider: newWildcardFromEnv returns nil.
+ {"no dns provider", map[string]string{"CARLOS_DNS_PROVIDER": "", "CARLOS_DNSIMPLE_TOKEN": ""}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ devboxEnv(t, ca.URL)
+ for k, v := range c.env {
+ t.Setenv(k, v)
+ }
+ cfg := DevboxConfig{Registry: reg, ListenAddr: "127.0.0.1:0", CertDir: t.TempDir(), SpoolRoot: t.TempDir()}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := ServeDevbox(ctx, cfg); err == nil || ctx.Err() != nil {
+ t.Fatalf("ServeDevbox = %v (ctx %v), want an immediate refusal", err, ctx.Err())
+ }
+ })
+ }
+}
+
+// R4: no handshake places an order. The manager's DNS provider counts
+// present calls and its ACME directory is a counting server; neither may be
+// touched by any name the devbox chain refuses, and the chain never builds
+// an autocert.Manager (its account key would land in the cache dir).
+func TestDevboxCertForUncoveredNameFails(t *testing.T) {
+ ca, requests := countingCA(t)
+ t.Setenv("CARLOS_ACME_DIRECTORY", ca.URL) // the seam newWildcardManager reads
+ dns := &countingDNS{}
+ cacheDir := t.TempDir()
+ w := newWildcardManager([]string{devboxParent}, "", func() []string { return nil },
+ nil, "", autocert.DirCache(cacheDir), dns)
+ if w.directory != ca.URL {
+ t.Fatalf("directory = %q, want the counting CA", w.directory)
+ }
+ w.refresh()
+ get := devboxGetCertificate(w)
+
+ refused := []*tls.ClientHelloInfo{
+ {ServerName: "other.example.net"}, // not under the parent
+ {ServerName: devboxParent}, // the parent apex: a wildcard never covers it
+ {ServerName: "app." + devboxParent}, // covered, but no wildcard yet
+ {ServerName: "x.app." + devboxParent},
+ {ServerName: "app." + devboxParent, SupportedProtos: []string{"acme-tls/1"}},
+ {ServerName: ""},
+ }
+ for _, hello := range refused {
+ if c, err := get(hello); err == nil || c != nil {
+ t.Errorf("before the wildcard: %q (protos %v) = (%v, %v), want a refusal", hello.ServerName, hello.SupportedProtos, c, err)
+ }
+ }
+
+ cert, _ := selfSignedWildcard(t, devboxParent, time.Now().Add(60*24*time.Hour))
+ w.mu.Lock()
+ w.certs[devboxParent] = cert
+ w.mu.Unlock()
+ if c, err := get(&tls.ClientHelloInfo{ServerName: "app." + devboxParent}); err != nil || c != cert {
+ t.Fatalf("covered name with the wildcard = (%v, %v), want the wildcard", c, err)
+ }
+ for _, hello := range []*tls.ClientHelloInfo{
+ {ServerName: "other.example.net"},
+ {ServerName: devboxParent},
+ {ServerName: "x.app." + devboxParent},
+ {ServerName: "app." + devboxParent, SupportedProtos: []string{"acme-tls/1"}},
+ } {
+ if c, err := get(hello); err == nil || c != nil {
+ t.Errorf("with the wildcard: %q (protos %v) = (%v, %v), want a refusal", hello.ServerName, hello.SupportedProtos, c, err)
+ }
+ }
+
+ if n := dns.presents.Load(); n != 0 {
+ t.Errorf("DNS provider saw %d present call(s), want 0", n)
+ }
+ if n := requests.Load(); n != 0 {
+ t.Errorf("the CA saw %d request(s), want 0", n)
+ }
+ if entries, err := os.ReadDir(cacheDir); err != nil || len(entries) != 0 {
+ t.Errorf("cert cache holds %v (err %v), want nothing: no autocert account, no order", entries, err)
+ }
+}
+
+func TestDevboxEdgeSwitchesOff(t *testing.T) {
+ t.Setenv("CARLOS_EDGE_PROTECT", "block")
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+ spool := t.TempDir()
+ e, err := newDevboxEdge(DevboxConfig{Registry: openReg(t), SpoolRoot: spool})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if e.cache != nil {
+ t.Error("cache is on, want nil")
+ }
+ if e.guard != guardOff {
+ t.Errorf("guard = %v, want guardOff", e.guard)
+ }
+ if e.rateMode != RateOff {
+ t.Errorf("rateMode = %v, want RateOff", e.rateMode)
+ }
+ if e.localStaticRoot != spool {
+ t.Errorf("localStaticRoot = %q, want %q", e.localStaticRoot, spool)
+ }
+}
+
+// End to end: with the wildcard already in the cert cache (so the manager's
+// run loop loads it and orders nothing), ServeDevbox serves it for a covered
+// name, fails the handshake for any other, and drains and returns nil when
+// its context ends, leaving the port free.
+func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
+ ca, requests := countingCA(t)
+ devboxEnv(t, ca.URL)
+
+ certDir := t.TempDir()
+ cert, key := selfSignedWildcard(t, devboxParent, time.Now().Add(60*24*time.Hour))
+ raw, err := encodeWildcardPEM(cert, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := autocert.DirCache(certDir).Put(context.Background(), wildcardPEMKey(devboxParent), raw); err != nil {
+ t.Fatal(err)
+ }
+
+ probe, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ addr := probe.Addr().String()
+ probe.Close()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ cfg := DevboxConfig{Registry: openReg(t), ListenAddr: addr, CertDir: certDir, SpoolRoot: t.TempDir()}
+ done := make(chan error, 1)
+ go func() { done <- ServeDevbox(ctx, cfg) }()
+
+ roots := x509.NewCertPool()
+ roots.AddCert(cert.Leaf)
+ dial := func(sni string) error {
+ d := &net.Dialer{Timeout: time.Second}
+ conn, err := tls.DialWithDialer(d, "tcp", addr, &tls.Config{ServerName: sni, RootCAs: roots})
+ if err == nil {
+ conn.Close()
+ }
+ return err
+ }
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ err := dial("app." + devboxParent)
+ if err == nil {
+ break
+ }
+ select {
+ case serveErr := <-done:
+ t.Fatalf("ServeDevbox returned early: %v", serveErr)
+ default:
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("covered name never got the cached wildcard: %v", err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if err := dial("other.example.net"); err == nil {
+ t.Fatal("uncovered name completed a handshake")
+ }
+ if err := dial(devboxParent); err == nil {
+ t.Fatal("the parent apex completed a handshake")
+ }
+
+ cancel()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("ServeDevbox after cancel = %v, want nil", err)
+ }
+ case <-time.After(15 * time.Second):
+ t.Fatal("ServeDevbox did not return after its context ended")
+ }
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ t.Fatalf("port still held after ServeDevbox returned: %v", err)
+ }
+ ln.Close()
+ if n := requests.Load(); n != 0 {
+ t.Fatalf("the CA saw %d request(s), want 0", n)
+ }
+}
+
+// A bind failure is an error for the caller, never a log.Fatal: a later task
+// runs ServeDevbox beside another server in one process.
+func TestDevboxBindFailureIsAnError(t *testing.T) {
+ ca, _ := countingCA(t)
+ devboxEnv(t, ca.URL)
+ held, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ err = ServeDevbox(ctx, DevboxConfig{Registry: openReg(t), ListenAddr: held.Addr().String(), CertDir: t.TempDir(), SpoolRoot: t.TempDir()})
+ if err == nil || ctx.Err() != nil {
+ t.Fatalf("ServeDevbox on a held port = %v (ctx %v), want an immediate bind error", err, ctx.Err())
+ }
+}