carlos / platform Public

Devbox identity and private targets (#486 A)

The devbox edge tells each link's upstream who is visiting, in
Carlos-Visitor-Login, -Name and -Node (Tailscale whois, cached; forged
copies stripped in any spelling). share --allow limits a link to named
logins, share --socket serves a tool's own Unix socket checked per
connection by owner uid, and list gains an access column. Linux only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Prompts:

  <task-notification>
  <task-id>bmy1qu943</task-id>
  <tool-use-id>toolu_013CYyAkhCV8BXijXdUtH4Xm</tool-use-id>
  <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/bmy1qu943.output</output-file>
  <status>completed</status>
  <summary>Background command "Commit design and run Astra builder check" completed (exit code 0)</summary>
  </task-notification>

  Sure

Squashed from design-devbox-identity into main.
claude agent, operated by paul@keymail.dev 9a064ebeba6fb07ecce97fdf276f8caa00d90c8a parent 1a9c752
36 files changed, +4,305 −65
  • approved_devbox_copy_test.go +8 −5
  • devbox_acl_linux.go +79 −0
  • devbox_acl_linux_test.go +135 −0
  • devbox_acl_other.go +20 −0
  • devbox_cli.go +236 −14
  • devbox_cli_test.go +6 −6
  • devbox_identity_cli_test.go +429 −0
  • devbox_identity_linux_test.go +190 −0
  • docs/superpowers/notes/census-proposal-devbox-identity.md +41 −0
  • docs/superpowers/plans/2026-10-30-devbox-mode-copy.md +50 −0
  • docs/superpowers/plans/2026-11-01-devbox-identity.md +158 −0
  • docs/superpowers/specs/2026-11-01-devbox-identity-design.md +242 −0
  • infra/devbox/README.md +30 −0
  • infra/devbox/carlos-devbox.service +2 −0
  • internal/devbox/links.go +7 −0
  • internal/devbox/links_test.go +1 −1
  • internal/devbox/registrar.go +204 −20
  • internal/devbox/registrar_socket_linux_test.go +296 −0
  • internal/devbox/registrar_socket_test.go +300 −0
  • internal/devbox/registrar_test.go +12 −11
  • internal/devbox/socketcheck_linux.go +55 −0
  • internal/devbox/socketcheck_other.go +12 −0
  • internal/edge/devbox.go +22 −5
  • internal/edge/devboxfront.go +198 −0
  • internal/edge/devboxfront_test.go +720 −0
  • internal/edge/devboxpeer_linux.go +31 −0
  • internal/edge/devboxpeer_other.go +9 −0
  • internal/edge/edge.go +11 −2
  • internal/edge/visitor.go +139 −0
  • internal/edge/visitor_test.go +330 −0
  • internal/provision/devbox_identity_census_test.go +62 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-devbox-identity.tsv +36 −0
  • internal/tsidentity/whois.go +86 −0
  • internal/tsidentity/whois_test.go +146 −0

CI passed — run details

landed from design-devbox-identity

diff --git a/approved_devbox_copy_test.go b/approved_devbox_copy_test.go
index 37bb82f55..87ac861fe 100644
--- a/approved_devbox_copy_test.go
+++ b/approved_devbox_copy_test.go
@@ -13,7 +13,7 @@ import (
// checked with its helpers, so "applied" means the same thing in every gate:
//
// - TestDevboxCopyRecordIsComplete: the deck names exactly DBX-C1 to
-// DBX-C93;
+// DBX-C123;
// - TestDevboxBuiltCopyIsApproved: an id in devboxCopyBuilt is an approved
// row (a string reaches code only after Paul has approved it);
// - TestDevboxBuiltCopyIsApplied: a built row's text is in the file it
@@ -23,10 +23,10 @@ const devboxCopyRecordPath = "docs/superpowers/plans/2026-10-30-devbox-mode-copy
var devboxCopyIDPattern = regexp.MustCompile(`^DBX-C[1-9][0-9]*$`)
-// devboxCopyIDs is the deck's inventory: DBX-C1 to DBX-C93, pinned.
+// devboxCopyIDs is the deck's inventory: DBX-C1 to DBX-C123, pinned.
var devboxCopyIDs = func() []string {
- ids := make([]string, 0, 93)
- for i := 1; i <= 93; i++ {
+ ids := make([]string, 0, 123)
+ for i := 1; i <= 123; i++ {
ids = append(ids, "DBX-C"+strconv.Itoa(i))
}
return ids
@@ -34,10 +34,13 @@ 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.
+// Identity replaces C2/C4/C13/C26 with C94/C113/C109/C97 respectively.
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", "DBX-C55", "DBX-C56", "DBX-C57",
+ "DBX-C1", "DBX-C3", "DBX-C5", "DBX-C6", "DBX-C7", "DBX-C8", "DBX-C9", "DBX-C10", "DBX-C11", "DBX-C12", "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-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", "DBX-C55", "DBX-C56", "DBX-C57",
// macOS (#488)
"DBX-C58", "DBX-C59", "DBX-C60", "DBX-C61", "DBX-C62", "DBX-C63", "DBX-C64", "DBX-C65", "DBX-C66", "DBX-C67", "DBX-C68", "DBX-C69", "DBX-C70", "DBX-C71", "DBX-C72", "DBX-C73", "DBX-C74", "DBX-C75", "DBX-C76", "DBX-C77", "DBX-C78", "DBX-C79", "DBX-C80", "DBX-C81", "DBX-C82", "DBX-C83", "DBX-C84", "DBX-C85", "DBX-C86", "DBX-C87", "DBX-C88", "DBX-C89", "DBX-C90", "DBX-C91", "DBX-C92", "DBX-C93",
+ // identity (#486 A)
+ "DBX-C94", "DBX-C95", "DBX-C96", "DBX-C97", "DBX-C98", "DBX-C99", "DBX-C100", "DBX-C101", "DBX-C102", "DBX-C103", "DBX-C104", "DBX-C105", "DBX-C106", "DBX-C107", "DBX-C108", "DBX-C109", "DBX-C110", "DBX-C111", "DBX-C112", "DBX-C113", "DBX-C114", "DBX-C115", "DBX-C116", "DBX-C117", "DBX-C118", "DBX-C119", "DBX-C120", "DBX-C121", "DBX-C122", "DBX-C123",
}
func mustParseDevboxRecord(t *testing.T) []copyRow {
diff --git a/devbox_acl_linux.go b/devbox_acl_linux.go
new file mode 100644
index 000000000..053f4244c
--- /dev/null
+++ b/devbox_acl_linux.go
@@ -0,0 +1,79 @@
+//go:build linux
+
+package main
+
+import (
+ "encoding/binary"
+ "os"
+ "runtime"
+ "strconv"
+
+ "golang.org/x/sys/unix"
+)
+
+// Pin the inode before inspecting it: the service owns the sticky parent
+// directory and can replace either the socket or the directory itself.
+func openDevboxSocket(path string, uid int) (*os.File, error) {
+ fd, err := unix.Open(path, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, refuseWith(devboxNotASocket(path))
+ }
+ var stat unix.Stat_t
+ if err := unix.Fstat(fd, &stat); err != nil || stat.Mode&unix.S_IFMT != unix.S_IFSOCK {
+ unix.Close(fd)
+ return nil, refuseWith(devboxNotASocket(path))
+ }
+ if int(stat.Uid) != uid {
+ unix.Close(fd)
+ return nil, refuseWith(devboxSocketNotYours(path))
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+
+func grantServiceACL(path string, serviceUID uint32) error {
+ socket, err := openDevboxSocket(path, os.Geteuid())
+ if err != nil {
+ return err
+ }
+ defer socket.Close()
+ return grantDevboxSocketACL(socket, serviceUID)
+}
+
+// O_PATH fds cannot use Fsetxattr. Procfs resolves this descriptor to the
+// checked inode even if its original name has been removed or replaced.
+// The ACL itself sets owner/mask/other mode bits; no separate chmod is needed.
+func grantDevboxSocketACL(socket *os.File, serviceUID uint32) error {
+ path := "/proc/self/fd/" + strconv.FormatUint(uint64(socket.Fd()), 10)
+ err := unix.Setxattr(path, "system.posix_acl_access", devboxServiceACL(serviceUID), 0)
+ runtime.KeepAlive(socket)
+ return err
+}
+
+func devboxServiceACL(serviceUID uint32) []byte {
+ const (
+ aclUserObj = 0x01
+ aclUser = 0x02
+ aclGroupObj = 0x04
+ aclMask = 0x10
+ aclOther = 0x20
+ )
+ entries := [...]struct {
+ tag, perm uint16
+ id uint32
+ }{
+ {aclUserObj, 6, 0xffffffff},
+ {aclUser, 6, serviceUID},
+ {aclGroupObj, 0, 0xffffffff},
+ {aclMask, 6, 0xffffffff},
+ {aclOther, 0, 0xffffffff},
+ }
+ data := make([]byte, 4+8*len(entries))
+ binary.LittleEndian.PutUint32(data, 2)
+ for i, entry := range entries {
+ offset := 4 + 8*i
+ binary.LittleEndian.PutUint16(data[offset:], entry.tag)
+ binary.LittleEndian.PutUint16(data[offset+2:], entry.perm)
+ binary.LittleEndian.PutUint32(data[offset+4:], entry.id)
+ }
+ return data
+}
diff --git a/devbox_acl_linux_test.go b/devbox_acl_linux_test.go
new file mode 100644
index 000000000..2a85d0c61
--- /dev/null
+++ b/devbox_acl_linux_test.go
@@ -0,0 +1,135 @@
+//go:build linux
+
+package main
+
+import (
+ "encoding/binary"
+ "errors"
+ "net"
+ "os"
+ "os/user"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "testing"
+
+ "golang.org/x/sys/unix"
+)
+
+type devboxACLEntry struct {
+ tag, perm uint16
+ id uint32
+}
+
+func decodeDevboxACL(t *testing.T, data []byte) []devboxACLEntry {
+ t.Helper()
+ if len(data) != 44 || binary.LittleEndian.Uint32(data[:4]) != 2 {
+ t.Fatalf("ACL header/length = %x", data)
+ }
+ var entries []devboxACLEntry
+ for offset := 4; offset < len(data); offset += 8 {
+ entries = append(entries, devboxACLEntry{binary.LittleEndian.Uint16(data[offset:]), binary.LittleEndian.Uint16(data[offset+2:]), binary.LittleEndian.Uint32(data[offset+4:])})
+ }
+ return entries
+}
+
+func TestGrantServiceACLEncodes(t *testing.T) {
+ for _, uid := range []uint32{0, 1001, 0x12345678} {
+ want := []devboxACLEntry{{1, 6, 0xffffffff}, {2, 6, uid}, {4, 0, 0xffffffff}, {16, 6, 0xffffffff}, {32, 0, 0xffffffff}}
+ if got := decodeDevboxACL(t, devboxServiceACL(uid)); !reflect.DeepEqual(got, want) {
+ t.Fatalf("ACL = %+v, want %+v", got, want)
+ }
+ }
+}
+
+func TestGrantServiceACLSocket(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "acl.sock")
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ if err := os.Chmod(path, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ err = grantServiceACL(path, uint32(os.Getuid()))
+ if errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.ENOSYS) {
+ fi, statErr := os.Stat(path)
+ if statErr != nil || fi.Mode().Perm() != 0o777 {
+ t.Fatalf("unsupported ACL changed permissions: %v, %v", fi, statErr)
+ }
+ t.Skipf("socket ACL unsupported: %v", err)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ data := make([]byte, 256)
+ n, err := unix.Getxattr(path, "system.posix_acl_access", data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := decodeDevboxACL(t, devboxServiceACL(uint32(os.Getuid())))
+ if got := decodeDevboxACL(t, data[:n]); !reflect.DeepEqual(got, want) {
+ t.Fatalf("read-back ACL = %+v, want %+v", got, want)
+ }
+ fi, err := os.Stat(path)
+ if err != nil || fi.Mode().Perm() != 0o660 {
+ t.Fatalf("mode with ACL mask = %v, %v", fi, err)
+ }
+}
+
+func TestDevboxServiceUID(t *testing.T) {
+ u, err := user.LookupId(strconv.Itoa(os.Getuid()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_DEVBOX_SERVICE_USER", u.Username)
+ uid, err := devboxServiceUID()
+ if err != nil || uid != uint32(os.Getuid()) {
+ t.Fatalf("service UID = %d, %v", uid, err)
+ }
+ t.Setenv("CARLOS_DEVBOX_SERVICE_USER", "carlos-devbox-test-nonexistent-user")
+ if _, err := devboxServiceUID(); err == nil {
+ t.Fatal("missing service account accepted")
+ }
+ t.Setenv("CARLOS_DEVBOX_SERVICE_USER", "")
+ want, lookupErr := user.Lookup("carlos-devbox")
+ uid, err = devboxServiceUID()
+ if lookupErr != nil {
+ if err == nil {
+ t.Fatal("missing default service account accepted")
+ }
+ } else if err != nil || strconv.FormatUint(uint64(uid), 10) != want.Uid {
+ t.Fatalf("default service UID = %d, %v; want %s", uid, err, want.Uid)
+ }
+}
+
+func TestGrantServiceACLRefusesSymlink(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "private")
+ if err := os.WriteFile(target, []byte("private data"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "tool.sock")
+ if err := os.Symlink(target, path); err != nil {
+ t.Fatal(err)
+ }
+ if err := grantServiceACL(path, uint32(os.Getuid())); err == nil {
+ t.Error("granted ACL through a symlink")
+ }
+ assertDevboxACLTargetUntouched(t, target)
+}
+
+func assertDevboxACLTargetUntouched(t *testing.T, path string) {
+ t.Helper()
+ fi, err := os.Stat(path)
+ if err != nil || fi.Mode().Perm() != 0600 {
+ t.Errorf("target mode = %v, %v; want 0600", fi, err)
+ }
+ if data, err := os.ReadFile(path); err != nil || string(data) != "private data" {
+ t.Errorf("target content = %q, %v", data, err)
+ }
+ if _, err := unix.Getxattr(path, "system.posix_acl_access", nil); !errors.Is(err, unix.ENODATA) {
+ t.Errorf("target ACL changed: %v", err)
+ }
+}
diff --git a/devbox_acl_other.go b/devbox_acl_other.go
new file mode 100644
index 000000000..89c508fbe
--- /dev/null
+++ b/devbox_acl_other.go
@@ -0,0 +1,20 @@
+//go:build !linux
+
+package main
+
+import (
+ "errors"
+ "os"
+)
+
+func grantServiceACL(path string, serviceUID uint32) error {
+ return errors.ErrUnsupported
+}
+
+func openDevboxSocket(path string, uid int) (*os.File, error) {
+ return nil, errors.ErrUnsupported
+}
+
+func grantDevboxSocketACL(socket *os.File, serviceUID uint32) error {
+ return errors.ErrUnsupported
+}
diff --git a/devbox_cli.go b/devbox_cli.go
index 529796fa4..9049ebbcc 100644
--- a/devbox_cli.go
+++ b/devbox_cli.go
@@ -38,19 +38,20 @@ import (
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/launchd"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tsidentity"
)
// 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
+ devboxUsageShare = "usage: carlos devbox share [--port <port>, --socket <path> or --dir <path>] [--allow <logins>] [<name>]" // DBX-C94
devboxUsageUnshare = "usage: carlos devbox unshare [<name>]" // DBX-C3
- devboxUsageList = "usage: carlos devbox list" // DBX-C4
+ devboxUsageList = "usage: carlos devbox list [--allowed]" // DBX-C113
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
+ devboxListHeader = "name owner kind target access age state" // DBX-C109
devboxListEmpty = "no links yet. publish one with: carlos devbox share --port <port> <name>" // DBX-C14
devboxKindLive = "live" // DBX-C15
devboxKindFolder = "folder" // DBX-C16
@@ -58,13 +59,60 @@ const (
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
+ devboxEitherFlag = "give one of --port for a dev server, --socket for a socket or --dir for a folder" // DBX-C97
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
)
+// Identity and private targets (#486 A).
+const (
+ devboxHelpAllow = "tailnet logins that may open the link, separated by commas, such as alice@github. anyone else sees a page saying the link is private. without --allow, everyone on the tailnet can open it. sharing again replaces the list" // DBX-C96
+ devboxSocketUnsupported = "--socket works on Linux devboxes only for now. on this devbox, use --port" // DBX-C104
+ devboxAllowUnsupported = "--allow works on Linux devboxes only for now. on this devbox, every link is open to the tailnet" // DBX-C105
+ devboxKindSocket = "socket" // DBX-C110
+ devboxPrivateAccess = "private" // DBX-C111
+ devboxTailnetAccess = "tailnet" // DBX-C112
+ devboxHelpAllowed = "also show who can open your private links" // DBX-C114
+)
+
+func devboxHelpSocket(dir string) string {
+ return fmt.Sprintf("a Unix socket your tool listens on, inside %s. share makes it private to you and the devbox service. if your tool restarts and makes a new socket, share again", dir) // DBX-C95
+}
+func devboxSocketPathRefusal(path, dir string) string {
+ return fmt.Sprintf("%s is not directly inside %s. have your tool create its socket there, then share it", path, dir) // DBX-C98
+}
+func devboxNotASocket(path string) string {
+ return fmt.Sprintf("%s is not a socket. give the path of the Unix socket your tool listens on", path) // DBX-C99
+}
+func devboxSocketNotYours(path string) string {
+ return fmt.Sprintf("%s belongs to another account. you can only share a socket you created", path) // DBX-C100
+}
+func devboxSocketUnreachable(path string) string {
+ return fmt.Sprintf("nothing is answering on %s. start your tool, then share again", path) // DBX-C101
+}
+func devboxSocketACLFailed(path string) string {
+ return fmt.Sprintf("could not let the devbox service open %s. check that the socket is yours, or tell whoever runs this devbox", path) // DBX-C102
+}
+func devboxMissingServiceUser(user string) string {
+ return fmt.Sprintf("this machine has no devbox service user called %s. tell whoever runs this devbox", user) // DBX-C103
+}
+func devboxBadAllow(login string) string {
+ return fmt.Sprintf("%s is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces", login) // DBX-C106
+}
+
+// Quote an empty entry so C106 still has a visible subject.
+func devboxAllowLogin(login string) string {
+ if login == "" {
+ return strconv.Quote(login)
+ }
+ return login
+}
+func devboxAllowedAccess(logins string) string {
+ return fmt.Sprintf("private: %s", logins) // DBX-C115
+}
+
// serve's rows (macOS plan #488).
const (
devboxUsageServe = "usage: carlos devbox serve [--env-file <env file>]" // DBX-C58
@@ -184,10 +232,14 @@ type devboxCLI struct {
socket string
branch func() (string, error)
now func() time.Time
+ goos string
+ uid int
+ serviceUID func() (uint32, error)
+ grantACL func(*os.File, uint32) error
}
func newDevboxCLI(stdout, stderr io.Writer) *devboxCLI {
- return &devboxCLI{stdout: stdout, stderr: stderr, socket: devboxSocketPath(), branch: gitCurrentBranch, now: time.Now}
+ return &devboxCLI{stdout: stdout, stderr: stderr, socket: devboxSocketPath(), branch: gitCurrentBranch, now: time.Now, goos: runtime.GOOS, uid: os.Geteuid(), serviceUID: devboxServiceUID, grantACL: grantDevboxSocketACL}
}
func runDevbox(args []string) {
@@ -313,18 +365,46 @@ func (c *devboxCLI) share(args []string) error {
fs := c.flagSet("share", devboxUsageShare, devboxHelpShare)
port := fs.String("port", "", devboxHelpPort)
dir := fs.String("dir", "", devboxHelpDir)
+ socket := fs.String("socket", "", devboxHelpSocket(devboxSocketsDir()))
+ allowFlag := fs.String("allow", "", devboxHelpAllow)
pos, err := parseInterspersed(fs, args)
if err != nil {
return err
}
+ portSet, dirSet, socketSet := flagGiven(fs, "port"), flagGiven(fs, "dir"), flagGiven(fs, "socket")
+ allowSet := flagGiven(fs, "allow")
+ if c.goos != "linux" {
+ if socketSet {
+ return refuseWith(devboxSocketUnsupported)
+ }
+ if allowSet {
+ return refuseWith(devboxAllowUnsupported)
+ }
+ }
if len(pos) > 1 {
fs.Usage()
return errDevboxUsage
}
- portSet, dirSet := flagGiven(fs, "port"), flagGiven(fs, "dir")
- if portSet == dirSet {
+ targets := 0
+ for _, set := range []bool{portSet, dirSet, socketSet} {
+ if set {
+ targets++
+ }
+ }
+ if targets != 1 {
return refuseWith(devboxEitherFlag)
}
+ var allow []string
+ if allowSet {
+ var invalid *devbox.AllowError
+ allow, err = devbox.ValidateAllow(strings.Split(*allowFlag, ","))
+ if err != nil {
+ if errors.As(err, &invalid) {
+ return refuseWith(devboxBadAllow(devboxAllowLogin(invalid.Login)))
+ }
+ return err
+ }
+ }
var portN int
if portSet {
portN, err = strconv.Atoi(*port)
@@ -336,21 +416,36 @@ func (c *devboxCLI) share(args []string) error {
if err != nil {
return err
}
- rc := refusalContext{name: name, port: *port, path: *dir}
+ rc := refusalContext{name: name, port: *port, path: *dir, allow: *allowFlag}
var entry devbox.ListEntry
if portSet {
body, _ := json.Marshal(struct {
- Name string `json:"name"`
- Port int `json:"port"`
- }{name, portN})
+ Name string `json:"name"`
+ Port int `json:"port"`
+ Allow []string `json:"allow"`
+ }{name, portN, allow})
err = c.call(http.MethodPost, "/share/live", "application/json", body, rc, &entry)
+ } else if socketSet {
+ rc.path = *socket
+ var path string
+ path, err = c.prepareSocket(*socket)
+ if err != nil {
+ return err
+ }
+ body, _ := json.Marshal(struct {
+ Name string `json:"name"`
+ Path string `json:"path"`
+ Allow []string `json:"allow"`
+ }{name, path, allow})
+ err = c.call(http.MethodPost, "/share/socket", "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)
+ query := url.Values{"name": {name}, "allow": allow}
+ err = c.call(http.MethodPost, "/share/folder?"+query.Encode(), "application/gzip", site, rc, &entry)
}
if err != nil {
return err
@@ -436,6 +531,7 @@ func (c *devboxCLI) unshare(args []string) error {
func (c *devboxCLI) list(args []string) error {
fs := c.flagSet("list", devboxUsageList, devboxHelpList)
+ allowed := fs.Bool("allowed", false, devboxHelpAllowed)
pos, err := parseInterspersed(fs, args)
if err != nil {
return err
@@ -460,6 +556,15 @@ func (c *devboxCLI) list(args []string) error {
kind, state := devboxKindLive, devboxNotAnswering
if e.Kind == devbox.KindFolder {
kind = devboxKindFolder
+ } else if e.Kind == devbox.KindSocket {
+ kind = devboxKindSocket
+ }
+ access := devboxTailnetAccess
+ if e.Private {
+ access = devboxPrivateAccess
+ if *allowed && e.OwnerUID == uint32(c.uid) && len(e.Allow) > 0 {
+ access = devboxAllowedAccess(strings.Join(e.Allow, ","))
+ }
}
if e.Answering {
state = devboxAnswering
@@ -467,7 +572,7 @@ func (c *devboxCLI) list(args []string) error {
state = devboxServing
}
}
- fmt.Fprintln(tw, strings.Join([]string{e.Name, devboxOwner(e), kind, e.Target, devboxAge(now.Sub(e.Created)), state}, "\t"))
+ fmt.Fprintln(tw, strings.Join([]string{e.Name, devboxOwner(e), kind, e.Target, access, devboxAge(now.Sub(e.Created)), state}, "\t"))
}
return tw.Flush()
}
@@ -497,7 +602,7 @@ func devboxAge(d time.Duration) string {
// 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 }
+type refusalContext struct{ name, port, path, allow string }
// render turns a registrar refusal into its deck sentence.
func (rc refusalContext) render(w devbox.WireError) error {
@@ -519,6 +624,26 @@ func (rc refusalContext) render(w devbox.WireError) error {
return refuseWith(devboxNotYours(w.Owner))
case devbox.CodeUnknownLink:
return refuseWith(devboxUnknownLink(rc.name))
+ case devbox.CodeSocketPath:
+ if w.SocketsDir == "" {
+ return refuseWith(devboxNotUnderstood)
+ }
+ return refuseWith(devboxSocketPathRefusal(rc.path, w.SocketsDir))
+ case devbox.CodeNotASocket:
+ return refuseWith(devboxNotASocket(rc.path))
+ case devbox.CodeSocketNotYours:
+ return refuseWith(devboxSocketNotYours(rc.path))
+ case devbox.CodeSocketUnreachable:
+ return refuseWith(devboxSocketUnreachable(rc.path))
+ case devbox.CodeSocketUnsupported:
+ return refuseWith(devboxSocketUnsupported)
+ case devbox.CodeBadAllow:
+ _, err := devbox.ValidateAllow(strings.Split(rc.allow, ","))
+ var invalid *devbox.AllowError
+ if errors.As(err, &invalid) {
+ return refuseWith(devboxBadAllow(devboxAllowLogin(invalid.Login)))
+ }
+ return refuseWith(devboxNotUnderstood)
case devbox.CodeInternal:
return refuseWith(devboxInternal)
}
@@ -662,6 +787,9 @@ func runDevboxServe(args []string) error {
LookupUser: lookupUsername,
}
cfg := edge.DevboxConfig{Registry: reg, ListenAddr: listen, Listener: given, CertDir: filepath.Join(dataDir, "certs"), SpoolRoot: spool}
+ if err := configureDevboxIdentity(runtime.GOOS, r, &cfg); err != nil {
+ return fmt.Errorf("devbox serve: %w", err)
+ }
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
@@ -670,6 +798,100 @@ func runDevboxServe(args []string) error {
})
}
+func configureDevboxIdentity(goos string, r *devbox.Registrar, cfg *edge.DevboxConfig) error {
+ cfg.AllowFor = r.AllowFor
+ if goos != "linux" {
+ return nil
+ }
+ dir := devboxSocketsDir()
+ if err := prepareDevboxSocketsDir(dir, os.Geteuid()); err != nil {
+ return err
+ }
+ r.SocketsDir = dir
+ socket := os.Getenv("CARLOS_DEVBOX_TAILSCALED_SOCKET")
+ if socket == "" {
+ socket = "/var/run/tailscale/tailscaled.sock"
+ }
+ cfg.Identity = edge.NewCachedIdentity(tsidentity.New(socket, 2*time.Second), time.Now)
+ for _, node := range strings.Split(os.Getenv("CARLOS_DEVBOX_SHARED_NODES"), ",") {
+ if node = strings.TrimSpace(node); node != "" {
+ cfg.SharedNodes = append(cfg.SharedNodes, node)
+ }
+ }
+ cfg.SocketOwnerFor = r.SocketOwnerFor
+ return nil
+}
+
+func prepareDevboxSocketsDir(path string, uid int) error {
+ const mode = os.ModeSticky | 0o733
+ mkdirErr := os.Mkdir(path, mode)
+ if mkdirErr != nil && !errors.Is(mkdirErr, os.ErrExist) {
+ return mkdirErr
+ }
+ fi, err := os.Lstat(path)
+ if err != nil {
+ return err
+ }
+ if fi.Mode()&os.ModeSymlink != 0 {
+ return &os.PathError{Op: "lstat", Path: path, Err: syscall.ELOOP}
+ }
+ if !fi.IsDir() {
+ return &os.PathError{Op: "lstat", Path: path, Err: syscall.ENOTDIR}
+ }
+ if owner, ok := fileOwner(fi); !ok || owner != uid {
+ return &os.PathError{Op: "lstat", Path: path, Err: os.ErrPermission}
+ }
+ if mkdirErr == nil || fi.Mode() != os.ModeDir|mode {
+ return os.Chmod(path, mode)
+ }
+ return nil
+}
+
+func devboxSocketsDir() string {
+ if dir := os.Getenv("CARLOS_DEVBOX_SOCKETS_DIR"); dir != "" {
+ return dir
+ }
+ return devbox.DefaultSocketsDir
+}
+
+func devboxServiceUser() string {
+ if name := os.Getenv("CARLOS_DEVBOX_SERVICE_USER"); name != "" {
+ return name
+ }
+ return "carlos-devbox"
+}
+
+// Local checks precede the ACL write. The registrar checks the socket and
+// connected peer again before it registers the link.
+func (c *devboxCLI) prepareSocket(path string) (string, error) {
+ clean := filepath.Clean(path)
+ if !filepath.IsAbs(clean) || filepath.Dir(clean) != filepath.Clean(devboxSocketsDir()) {
+ return "", refuseWith(devboxSocketPathRefusal(path, devboxSocketsDir()))
+ }
+ socket, err := openDevboxSocket(clean, c.uid)
+ if err != nil {
+ return "", err
+ }
+ defer socket.Close()
+ uid, err := c.serviceUID()
+ if err != nil {
+ return "", refuseWith(devboxMissingServiceUser(devboxServiceUser()))
+ }
+ if err := c.grantACL(socket, uid); err != nil {
+ return "", refuseWith(devboxSocketACLFailed(path))
+ }
+ return clean, nil
+}
+
+func devboxServiceUID() (uint32, error) {
+ u, err := user.Lookup(devboxServiceUser())
+ if err != nil {
+ return 0, err
+ }
+ uid, err := strconv.ParseUint(u.Uid, 10, 32)
+ return uint32(uid), err
+}
+
// devboxLaunchdListener takes the one listening socket launchd opened for
// the plist's Sockets entry called name, refusing in the deck's words what
// it cannot serve on. take is launchd.Listeners (a test replaces it).
diff --git a/devbox_cli_test.go b/devbox_cli_test.go
index d0b3f241c..af2ef3d2a 100644
--- a/devbox_cli_test.go
+++ b/devbox_cli_test.go
@@ -154,9 +154,9 @@ func TestDevboxShareNameRefusals(t *testing.T) {
{"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"},
+ "give one of --port for a dev server, --socket for a socket or --dir for a folder\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"},
+ "give one of --port for a dev server, --socket for a socket or --dir for a folder\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"},
@@ -295,10 +295,10 @@ func TestDevboxListTable(t *testing.T) {
}
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"},
+ {"name", "owner", "kind", "target", "access", "age", "state"},
+ {"api", "alice", "live", fmt.Sprintf("127.0.0.1:%d", upPort), "tailnet", "3h", "answering"},
+ {"docs", "alice", "folder", "tailnet", "3h", "serving"}, // a folder's target is empty (ruling R10)
+ {"shop", "alice", "live", fmt.Sprintf("127.0.0.1:%d", downPort), "tailnet", "3h", "not", "answering"},
}
if len(lines) != len(want) {
t.Fatalf("list:\n%s", out)
diff --git a/devbox_identity_cli_test.go b/devbox_identity_cli_test.go
new file mode 100644
index 000000000..118e3cfd9
--- /dev/null
+++ b/devbox_identity_cli_test.go
@@ -0,0 +1,429 @@
+//go:build linux
+
+package main
+
+import (
+ "net"
+ "os"
+ "os/user"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/devbox"
+)
+
+func devboxSocketTarget(t *testing.T, h *devboxHarness) string {
+ t.Helper()
+ dir := t.TempDir()
+ h.r.SocketsDir = dir
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", dir)
+ u, err := user.Current()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_DEVBOX_SERVICE_USER", u.Username)
+ path := filepath.Join(dir, "tool.sock")
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ t.Cleanup(func() { ln.Close(); <-done })
+ return path
+}
+
+func TestDevboxShareSocketCLI(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ path := devboxSocketTarget(t, h)
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--socket", path, "shop")
+ if code != 0 || out != "https://shop.devbox.example.com\n" || errOut != "" {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ k, ok := h.r.Links.Get("shop")
+ if !ok || k.Kind != devbox.KindSocket || k.Socket != path || k.OwnerUID != me() {
+ t.Fatalf("link = %+v, %v", k, ok)
+ }
+ out, errOut, code = runDevboxCLI(t, h.sock, nil, "list")
+ if code != 0 || !strings.Contains(out, path) || !strings.Contains(out, "socket") || !strings.Contains(out, "answering") {
+ t.Fatalf("list = %d, %q, %q", code, out, errOut)
+ }
+}
+
+func TestDevboxShareAllowFlag(t *testing.T) {
+ for _, kind := range []string{"port", "dir", "socket"} {
+ t.Run(kind, func(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice"})
+ target := "8080"
+ if kind == "dir" {
+ target = t.TempDir()
+ if err := os.WriteFile(filepath.Join(target, "index.html"), []byte("hi"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if kind == "socket" {
+ target = devboxSocketTarget(t, h)
+ }
+ for _, want := range [][]string{{"alice@github", "bob+dev@example.com"}, {"carol@github"}, nil} {
+ args := []string{"share", "shop", "--" + kind, target}
+ if want != nil {
+ raw := strings.Join(want, ",")
+ if len(want) == 2 {
+ raw = "Alice@GitHub,bob+dev@example.com,ALICE@GITHUB"
+ }
+ args = append(args, "--allow", raw)
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, args...)
+ if code != 0 {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ k, _ := h.r.Links.Get("shop")
+ if !slices.Equal(k.Allow, want) {
+ t.Fatalf("stored allow = %q, want %q", k.Allow, want)
+ }
+ }
+ })
+ }
+}
+
+func TestDevboxShareAllowMalformed(t *testing.T) {
+ for _, bad := range []string{"", "bad login", "tab\tlogin", "é@github", strings.Repeat("a", devbox.MaxAllowLogin+1)} {
+ t.Run(bad, func(t *testing.T) {
+ out, errOut, code := runDevboxCLI(t, "/missing", nil, "share", "--port", "8080", "--allow", "alice@github,"+bad, "shop")
+ if bad == "" {
+ bad = `""`
+ }
+ want := bad + " is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q; want %q", code, out, errOut, want)
+ }
+ })
+ }
+}
+
+func TestDevboxListAccessAndAllowed(t *testing.T) {
+ h := newDevboxHarness(t, map[uint32]string{me(): "alice", me() + 1: "bob"})
+ now := time.Now()
+ for _, link := range []devbox.Link{
+ {Name: "mine", OwnerUID: me(), Kind: devbox.KindLive, Port: 1, Allow: []string{"alice@github", "carol@github"}, Created: now, Updated: now},
+ {Name: "other", OwnerUID: me() + 1, Kind: devbox.KindLive, Port: 1, Allow: []string{"bob@github"}, Created: now, Updated: now},
+ {Name: "open", OwnerUID: me(), Kind: devbox.KindLive, Port: 1, Created: now, Updated: now},
+ } {
+ if err := h.r.Links.Put(link); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, allowed := range []bool{false, true} {
+ args := []string{"list"}
+ if allowed {
+ args = append(args, "--allowed")
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, args...)
+ if code != 0 {
+ t.Fatalf("list = %d, %q, %q", code, out, errOut)
+ }
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ if strings.Join(strings.Fields(lines[0]), " ") != "name owner kind target access age state" {
+ t.Fatalf("header = %q", lines[0])
+ }
+ if strings.Contains(out, "bob@github") {
+ t.Fatalf("other owner's list exposed: %q", out)
+ }
+ if allowed != strings.Contains(out, "private: alice@github,carol@github") {
+ t.Fatalf("own allow list = %q", out)
+ }
+ if !allowed && strings.Contains(out, "@") {
+ t.Fatalf("list exposed without --allowed: %q", out)
+ }
+ if !strings.Contains(lines[1], "private") || !strings.Contains(lines[2], "tailnet") || !strings.Contains(lines[3], "private") {
+ t.Fatalf("access = %q", out)
+ }
+ }
+}
+
+func TestDevboxSocketRefusedOnDarwin(t *testing.T) {
+ for _, args := range [][]string{
+ {"share", "--socket", "/missing", "shop"},
+ {"share", "--socket", "", "--port", "invalid", "--allow", "bad login", "Shop", "extra"},
+ } {
+ mod := func(c *devboxCLI) {
+ c.goos = "darwin"
+ c.serviceUID = func() (uint32, error) { t.Fatal("looked up service user"); return 0, nil }
+ c.grantACL = func(*os.File, uint32) error { t.Fatal("wrote ACL"); return nil }
+ }
+ out, errOut, code := runDevboxCLI(t, "/missing", mod, args...)
+ want := "--socket works on Linux devboxes only for now. on this devbox, use --port\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ }
+}
+
+func TestDevboxAllowRefusedOnDarwin(t *testing.T) {
+ for _, args := range [][]string{
+ {"share", "--port", "8080", "--allow", "alice@github", "shop"},
+ {"share", "--dir", "/missing", "--allow", "", "shop"},
+ {"share", "--allow", "bad login", "Shop", "extra"},
+ } {
+ out, errOut, code := runDevboxCLI(t, "/missing", func(c *devboxCLI) { c.goos = "darwin" }, args...)
+ want := "--allow works on Linux devboxes only for now. on this devbox, every link is open to the tailnet\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ }
+}
+
+func TestDevboxSocketLocalRefusals(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ socket := devboxSocketTarget(t, h)
+ dir := filepath.Dir(socket)
+ plain := filepath.Join(dir, "plain")
+ if err := os.WriteFile(plain, []byte("hi"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ symlink := filepath.Join(dir, "link")
+ if err := os.Symlink(socket, symlink); err != nil {
+ t.Fatal(err)
+ }
+ cases := []struct {
+ name, path, want string
+ other bool
+ }{
+ {"outside", filepath.Join(filepath.Dir(dir), "other.sock"), "path", false},
+ {"nested", filepath.Join(dir, "nested", "tool.sock"), "path", false},
+ {"relative", "tool.sock", "path", false},
+ {"directory", dir, "path", false},
+ {"plain", plain, "socket", false},
+ {"symlink", symlink, "socket", false},
+ {"missing", filepath.Join(dir, "missing"), "socket", false},
+ {"owner", socket, "owner", true},
+ }
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ mod := func(c *devboxCLI) {
+ if tt.other {
+ c.uid++
+ }
+ c.serviceUID = func() (uint32, error) { t.Fatal("looked up service user before local refusal"); return 0, nil }
+ c.grantACL = func(*os.File, uint32) error { t.Fatal("wrote ACL before local refusal"); return nil }
+ }
+ want := tt.path + " is not directly inside " + dir + ". have your tool create its socket there, then share it"
+ if tt.want == "socket" {
+ want = tt.path + " is not a socket. give the path of the Unix socket your tool listens on"
+ }
+ if tt.want == "owner" {
+ want = tt.path + " belongs to another account. you can only share a socket you created"
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, "share", "--socket", tt.path, "shop")
+ if code != 1 || out != "" || errOut != want+"\n" {
+ t.Fatalf("share = %d, %q, %q; want %q", code, out, errOut, want)
+ }
+ })
+ }
+ if len(h.r.Links.All()) != 0 {
+ t.Fatal("refused socket registered")
+ }
+}
+
+func TestDevboxSocketSetupRefusals(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ path := devboxSocketTarget(t, h)
+ t.Run("missing user", func(t *testing.T) {
+ t.Setenv("CARLOS_DEVBOX_SERVICE_USER", "devbox-no-such-user-486")
+ mod := func(c *devboxCLI) {
+ c.grantACL = func(*os.File, uint32) error { t.Fatal("ACL written without user"); return nil }
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, "share", "--socket", path, "shop")
+ want := "this machine has no devbox service user called devbox-no-such-user-486. tell whoever runs this devbox\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ })
+ t.Run("acl", func(t *testing.T) {
+ mod := func(c *devboxCLI) {
+ c.grantACL = func(got *os.File, uid uint32) error {
+ if got.Name() != path || uid != me() {
+ t.Fatalf("grant = %q, %d", got.Name(), uid)
+ }
+ return os.ErrPermission
+ }
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, "share", "--socket", path, "shop")
+ want := "could not let the devbox service open " + path + ". check that the socket is yours, or tell whoever runs this devbox\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ })
+ if len(h.r.Links.All()) != 0 {
+ t.Fatal("refused socket registered")
+ }
+}
+
+func TestDevboxSocketUnreachableCLI(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ dir := t.TempDir()
+ h.r.SocketsDir = dir
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", dir)
+ path := filepath.Join(dir, "gone.sock")
+ ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ln.SetUnlinkOnClose(false)
+ ln.Close()
+ mod := func(c *devboxCLI) { c.serviceUID = func() (uint32, error) { return me(), nil } }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, "share", "--socket", path, "shop")
+ want := "nothing is answering on " + path + ". start your tool, then share again\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ if len(h.r.Links.All()) != 0 {
+ t.Fatal("unreachable socket registered")
+ }
+}
+
+func TestDevboxIdentityRefusalRendering(t *testing.T) {
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", "")
+ path := "/run/carlos-devbox/sockets/shop.sock"
+ rc := refusalContext{path: path, allow: "alice@github"}
+ for _, tt := range []struct{ code, want string }{
+ {devbox.CodeSocketPath, path + " is not directly inside /run/carlos-devbox/sockets. have your tool create its socket there, then share it"},
+ {devbox.CodeNotASocket, path + " is not a socket. give the path of the Unix socket your tool listens on"},
+ {devbox.CodeSocketNotYours, path + " belongs to another account. you can only share a socket you created"},
+ {devbox.CodeSocketUnreachable, "nothing is answering on " + path + ". start your tool, then share again"},
+ {devbox.CodeSocketUnsupported, "--socket works on Linux devboxes only for now. on this devbox, use --port"},
+ {devbox.CodeBadAllow, devboxNotUnderstood},
+ } {
+ t.Run(tt.code, func(t *testing.T) {
+ if err := rc.render(devbox.WireError{Code: tt.code, SocketsDir: devbox.DefaultSocketsDir}); err == nil || err.Error() != tt.want {
+ t.Fatalf("render = %v, want %q", err, tt.want)
+ }
+ })
+ }
+}
+
+func TestDevboxShareOneTarget(t *testing.T) {
+ for _, flags := range [][]string{
+ nil, {"--port", "8080", "--socket", "/missing"}, {"--dir", ".", "--socket", "/missing"},
+ {"--port", "8080", "--dir", ".", "--socket", "/missing"},
+ } {
+ out, errOut, code := runDevboxCLI(t, "/missing", nil, append([]string{"share", "shop"}, flags...)...)
+ if code != 1 || out != "" || errOut != "give one of --port for a dev server, --socket for a socket or --dir for a folder\n" {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+ }
+}
+
+func TestDevboxShareAllowCap(t *testing.T) {
+ raw := strings.Repeat("alice@github,", devbox.MaxAllowEntries) + "overflow@github"
+ out, errOut, code := runDevboxCLI(t, "/missing", nil, "share", "shop", "--port", "8080", "--allow", raw)
+ if code != 1 || out != "" || errOut != "overflow@github is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces\n" {
+ t.Fatalf("share = %d, %q, %q", code, out, errOut)
+ }
+}
+
+func TestDevboxIdentityHelp(t *testing.T) {
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", "/example/sockets")
+ for _, tt := range []struct {
+ verb string
+ want []string
+ }{
+ {"share", []string{
+ "usage: carlos devbox share [--port <port>, --socket <path> or --dir <path>] [--allow <logins>] [<name>]",
+ "a Unix socket your tool listens on, inside /example/sockets. share makes it private to you and the devbox service. if your tool restarts and makes a new socket, share again",
+ "tailnet logins that may open the link, separated by commas, such as alice@github. anyone else sees a page saying the link is private. without --allow, everyone on the tailnet can open it. sharing again replaces the list",
+ }},
+ {"list", []string{"usage: carlos devbox list [--allowed]", "also show who can open your private links"}},
+ } {
+ _, errOut, code := runDevboxCLI(t, "/missing", nil, tt.verb, "--help")
+ if code != 0 {
+ t.Fatalf("help = %d, %q", code, errOut)
+ }
+ for _, want := range tt.want {
+ if !strings.Contains(errOut, want) {
+ t.Errorf("%s help missing %q: %q", tt.verb, want, errOut)
+ }
+ }
+ }
+}
+
+func TestDevboxSocketACLPathSwap(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ path := devboxSocketTarget(t, h)
+ target := filepath.Join(t.TempDir(), "private")
+ if err := os.WriteFile(target, []byte("private data"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ moved := path + ".old"
+ mod := func(c *devboxCLI) {
+ c.grantACL = func(got *os.File, uid uint32) error {
+ if err := os.Rename(path, moved); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, path); err != nil {
+ t.Fatal(err)
+ }
+ return grantDevboxSocketACL(got, uid)
+ }
+ }
+ out, errOut, code := runDevboxCLI(t, h.sock, mod, "share", "--socket", path, "shop")
+ if code != 1 || out != "" || errOut != devboxNotASocket(path)+"\n" {
+ t.Errorf("share = %d, %q, %q", code, out, errOut)
+ }
+ assertDevboxACLTargetUntouched(t, target)
+ fi, err := os.Stat(moved)
+ if err != nil || fi.Mode().Perm() != 0660 {
+ t.Errorf("pinned socket mode = %v, %v; want 0660", fi, err)
+ }
+ if len(h.r.Links.All()) != 0 {
+ t.Fatal("swapped socket registered")
+ }
+}
+
+func TestDevboxSocketDirectoryMismatch(t *testing.T) {
+ h := newDevboxHarness(t, nil)
+ path := devboxSocketTarget(t, h)
+ h.r.SocketsDir = t.TempDir()
+ out, errOut, code := runDevboxCLI(t, h.sock, nil, "share", "--socket", path, "shop")
+ want := devboxSocketPathRefusal(path, h.r.SocketsDir) + "\n"
+ if code != 1 || out != "" || errOut != want {
+ t.Fatalf("share = %d, %q, %q; want %q", code, out, errOut, want)
+ }
+}
+
+func TestDevboxBadAllowRendering(t *testing.T) {
+ for _, tt := range []struct{ raw, want string }{
+ {"alice@github,bob@github", devboxNotUnderstood},
+ {"alice@github,bad login", "bad login is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces"},
+ {"alice@github,", `"" is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces`},
+ {"", `"" is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces`},
+ } {
+ rc := refusalContext{allow: tt.raw}
+ if err := rc.render(devbox.WireError{Code: devbox.CodeBadAllow}); err == nil || err.Error() != tt.want {
+ t.Errorf("render %q = %v, want %q", tt.raw, err, tt.want)
+ }
+ }
+ out, errOut, code := runDevboxCLI(t, "/missing", nil, "share", "--port", "8080", "--allow", "", "shop")
+ if code != 1 || out != "" || errOut != "\"\" is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces\n" {
+ t.Fatalf("empty allow = %d, %q, %q", code, out, errOut)
+ }
+}
+
+func TestDevboxSocketPathWithoutRegistrarDirectory(t *testing.T) {
+ rc := refusalContext{path: "/example/tool.sock"}
+ if err := rc.render(devbox.WireError{Code: devbox.CodeSocketPath}); err == nil || err.Error() != devboxNotUnderstood {
+ t.Fatalf("old registrar path refusal = %v", err)
+ }
+}
diff --git a/devbox_identity_linux_test.go b/devbox_identity_linux_test.go
new file mode 100644
index 000000000..e50ef3036
--- /dev/null
+++ b/devbox_identity_linux_test.go
@@ -0,0 +1,190 @@
+//go:build linux
+
+package main
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/devbox"
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func TestDevboxServeIdentityWiring(t *testing.T) {
+ dir := t.TempDir()
+ sockets := filepath.Join(dir, "sockets")
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", sockets)
+ t.Setenv("CARLOS_DEVBOX_SHARED_NODES", " , shared-one,shared-two , ,")
+ sock := filepath.Join(dir, "ts.sock")
+ t.Setenv("CARLOS_DEVBOX_TAILSCALED_SOCKET", sock)
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var calls atomic.Int32
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if r.URL.Path != "/localapi/v0/whois" || r.URL.Query().Get("addr") != "100.64.0.2:1234" {
+ t.Errorf("whois request = %s", r.URL)
+ }
+ _, _ = w.Write([]byte(`{"Node":{"ComputedName":"laptop"},"UserProfile":{"LoginName":"alice@github","DisplayName":"Alice"}}`))
+ })}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+ links, err := devbox.OpenLinks(filepath.Join(dir, "links.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := &devbox.Registrar{Links: links, Domain: "devbox.example.com"}
+ cfg := edge.DevboxConfig{ListenAddr: "127.0.0.1:8443"}
+ if err := configureDevboxIdentity("linux", r, &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if r.SocketsDir != sockets || cfg.Identity == nil || cfg.AllowFor == nil || cfg.SocketOwnerFor == nil {
+ t.Fatalf("incomplete wiring: registrar %+v, config %+v", r, cfg)
+ }
+ if !reflect.DeepEqual(cfg.SharedNodes, []string{"shared-one", "shared-two"}) || cfg.ListenAddr != "127.0.0.1:8443" {
+ t.Fatalf("config = %+v", cfg)
+ }
+ for _, port := range []uint16{1234, 5678} {
+ visitor, ok, err := cfg.Identity.Who(context.Background(), netip.AddrPortFrom(netip.MustParseAddr("100.64.0.2"), port))
+ if err != nil || !ok || visitor != (edge.Visitor{Login: "alice@github", Name: "Alice", Node: "laptop"}) {
+ t.Fatalf("Who = %+v, %v, %v", visitor, ok, err)
+ }
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("LocalAPI calls = %d, want cached answer", calls.Load())
+ }
+ link := devbox.Link{Name: "shop", Kind: devbox.KindSocket, OwnerUID: 1234, Socket: filepath.Join(sockets, "shop.sock"), Allow: []string{"alice@github"}}
+ for _, allow := range [][]string{{"alice@github"}, {"bob@github"}} {
+ link.Allow = allow
+ if err := links.Put(link); err != nil {
+ t.Fatal(err)
+ }
+ if got := cfg.AllowFor("shop.devbox.example.com"); !reflect.DeepEqual(got, allow) {
+ t.Fatalf("AllowFor = %v, want %v", got, allow)
+ }
+ path, uid, ok := cfg.SocketOwnerFor("shop.devbox.example.com")
+ if !ok || path != link.Socket || uid != link.OwnerUID {
+ t.Fatalf("SocketOwnerFor = %q, %d, %v", path, uid, ok)
+ }
+ }
+}
+
+func TestDevboxServeDarwinIdentityUnchanged(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sockets")
+ t.Setenv("CARLOS_DEVBOX_SOCKETS_DIR", path)
+ t.Setenv("CARLOS_DEVBOX_SHARED_NODES", "shared-one")
+ t.Setenv("CARLOS_DEVBOX_TAILSCALED_SOCKET", "/nonexistent")
+ links, err := devbox.OpenLinks(filepath.Join(dir, "links.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := &devbox.Registrar{Links: links, Domain: "devbox.example.com"}
+ cfg := edge.DevboxConfig{}
+ if err := configureDevboxIdentity("darwin", r, &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if r.SocketsDir != "" || cfg.Identity != nil || cfg.SharedNodes != nil || cfg.AllowFor == nil || cfg.SocketOwnerFor != nil {
+ t.Fatalf("darwin identity configuration: %+v, %+v", r, cfg)
+ }
+ for _, kind := range []devbox.Kind{devbox.KindLive, devbox.KindFolder} {
+ for _, allow := range [][]string{{"alice@github"}, {"bob@github"}, nil} {
+ if err := links.Put(devbox.Link{Name: "shop", Kind: kind, Allow: allow}); err != nil {
+ t.Fatal(err)
+ }
+ if got := cfg.AllowFor("shop.devbox.example.com"); !reflect.DeepEqual(got, allow) {
+ t.Fatalf("darwin AllowFor for %s = %v, want %v", kind, got, allow)
+ }
+ }
+ }
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("darwin sockets directory: %v", err)
+ }
+}
+
+func TestDevboxSocketsDir(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sockets")
+ for _, mode := range []os.FileMode{0, 0o755, 0o777 | os.ModeSetgid, 0o733 | os.ModeSticky} {
+ if mode != 0 {
+ if err := os.Chmod(path, mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := prepareDevboxSocketsDir(path, os.Geteuid()); err != nil {
+ t.Fatal(err)
+ }
+ fi, err := os.Lstat(path)
+ if err != nil || fi.Mode() != os.ModeDir|os.ModeSticky|0o733 {
+ t.Fatalf("sockets directory = %v, %v", fi, err)
+ }
+ }
+}
+
+func TestDevboxSocketsDirRefuses(t *testing.T) {
+ for _, kind := range []string{"file", "symlink", "dangling", "owner"} {
+ t.Run(kind, func(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sockets")
+ uid := os.Geteuid()
+ var err error
+ switch kind {
+ case "file":
+ err = os.WriteFile(path, nil, 0o600)
+ case "symlink":
+ err = os.Symlink(dir, path)
+ case "dangling":
+ err = os.Symlink(filepath.Join(dir, "missing"), path)
+ case "owner":
+ err = os.Mkdir(path, 0o700)
+ uid++
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, err := os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareDevboxSocketsDir(path, uid); err == nil {
+ t.Fatal("unsafe sockets directory accepted")
+ }
+ after, err := os.Lstat(path)
+ if err != nil || before.Mode() != after.Mode() {
+ t.Fatalf("refused path changed: %v, %v", after, err)
+ }
+ })
+ }
+}
+
+func TestDevboxServeSocketsDirFailure(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sockets")
+ if err := os.WriteFile(path, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ for key, value := range map[string]string{
+ "CARLOS_DEVBOX_LISTEN": "127.0.0.1:8443",
+ "CARLOS_DEVBOX_DOMAIN": "devbox.example.com",
+ "CARLOS_WILDCARD_DOMAINS": "devbox.example.com",
+ "CARLOS_DATA_DIR": dir,
+ "CARLOS_DEVBOX_LAUNCHD_SOCKET": "",
+ "CARLOS_DEVBOX_SOCKETS_DIR": path,
+ } {
+ t.Setenv(key, value)
+ }
+ err := runDevboxServe(nil)
+ var pe *os.PathError
+ if !errors.As(err, &pe) || pe.Path != path || err.Error() != "devbox serve: "+pe.Error() {
+ t.Fatalf("serve = %v, want wrapped path error", err)
+ }
+}
diff --git a/docs/superpowers/notes/census-proposal-devbox-identity.md b/docs/superpowers/notes/census-proposal-devbox-identity.md
new file mode 100644
index 000000000..9f3dae9e1
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-devbox-identity.md
@@ -0,0 +1,41 @@
+# Census approval: devbox-identity
+
+Ruling `census-ruling-devbox-identity`. The independent reviewer approves or rejects every change below, 7 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `devbox_cli.go` `runDevboxServe` | body | unchanged (3) | #486 A: carlos devbox serve runs as the carlos-devbox service user, not root. Adds configureDevboxIdentity before serving: reads CARLOS_DEVBOX_SOCKETS_DIR, CARLOS_DEVBOX_TAILSCALED_SOCKET and CARLOS_DEVBOX_SHARED_NODES, checks/creates the service-owned sockets directory, and wires the cached LocalAPI adapter plus allow/socket-owner lookups. Existing registry.db, links.json and optional env-file reads remain in the service account; no additional direct scanned read site in this unit. |
+| `infra/devbox/carlos-devbox.service` `external` | body | unchanged (1) | #486 A: adds RuntimeDirectoryPreserve=yes so stopping the service preserves caller sockets under /run/carlos-devbox. ExecStart still runs carlos devbox serve with User=Group=carlos-devbox, never as root; only CAP_NET_BIND_SERVICE remains. No new executable or environment-file read; the existing systemd EnvironmentFile and hardening are unchanged. |
+| `internal/devbox/registrar.go` `Registrar.list` | body | unchanged (1) | #486 A: the carlos-devbox service user, not root, reads its in-memory links and passes the kernel-authenticated caller UID into entry so allow names are returned only to their owner. Adds bounded connect-and-close probes of stored socket paths without sending data; a replaced symlink can be followed by this availability probe. Existing folder-current EvalSymlinks and loopback probes remain; forwarding separately checks peer UID. |
+| `internal/devbox/registrar.go` `Registrar.serveShareLive` | body | unchanged (1) | #486 A: the carlos-devbox service user, not root, now reads and validates the request JSON allow list, stores the normalized list with the local link, and returns owner-filtered allow details through entry(link, uid). Existing SO_PEERCRED identity, claim ownership/registry reads and UpsertUnlessRootfs remain; no new filesystem or deployment-record read. |
+| `internal/devbox/registrar.go` `Registrar.serveUnshare` | body | unchanged (1) | #486 A: the carlos-devbox service user, not root, now passes the authenticated caller UID to entry(prev, uid) so the response exposes allow names only to their owner. Reads the same local link and registry row, checks ownership, then deletes with the existing rollback; no new read. |
+| `internal/devbox/registrar.go` `Registrar.serveShareFolder` | sites | -file:Query | #486 A: the carlos-devbox service user, not root, replaces req.URL.Query with strict url.ParseQuery(req.URL.RawQuery), refuses malformed query encoding, and validates repeated allow values before reading the capped upload body. Stores the normalized allow list in its local links.json and returns owner-filtered entry data. The scanner loses file:Query; existing archive, spool and local registry reads remain, with no new filesystem or deployment-record read. |
+| `internal/edge/edge.go` `Edge.Reload` | sites | +registry:Socket | #486 A: only the devbox edge created by newDevboxEdge (carlos-devbox service user, not root) enables the new proxy hooks. Saves the existing DispatchArm result and reads t.Socket from an already-listed route when that arm is ArmSocket, passing it to configureDevboxProxy for per-request expected-owner validation and visitor-header rewriting. Adds one registry:Socket field site; no new registry query or file open, and ordinary fleet/agent edges leave the hook disabled. Final fix wave: its devbox-only outgoing-header/trailer hooks now also strip case-insensitive underscore/hyphen aliases through stripVisitorHeaders; no new read. |
+
+Envelopes re-pinned: `.`, `infra/devbox`, `internal/devbox`, `internal/edge`, `internal/tsidentity`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `devbox_cli.go` `runDevboxServe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: carlos devbox serve, run by the carlos-devbox unit as the unprivileged carlos-devbox user, reads its config from the environment (CARLOS_DEVBOX_LISTEN, CARLOS_DEVBOX_DOMAIN, CARLOS_DATA_DIR, CARLOS_WILDCARD_DOMAINS, CARLOS_DEVBOX_SOCKET) and opens registry.db and links.json under its own StateDirectory. Not root;rev3=census-ruling-devbox-macos;basis=devbox on macOS (#488): serve now parses flags; --env-file PATH loads the service user's own env file (loadDevboxEnvFile) before reading the same environment as before; with CARLOS_DEVBOX_LAUNCHD_SOCKET set it takes launchd's listening socket (launchd.Listeners, macOS only; elsewhere it refuses) and holds it to CARLOS_DEVBOX_LISTEN (edge.CheckDevboxListener) before making anything; the socket path comes from devboxSocketPath (CARLOS_DEVBOX_SOCKET, or the OS default). Runs as the unprivileged service user (carlos-devbox on Linux, _carlos-devbox on macOS), never root; no new read beyond the env file named on its own command line
+- `infra/devbox/carlos-devbox.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: systemd unit for devbox mode on a developer workstation, installed once by hand per infra/devbox/README.md. Runs carlos devbox serve as User=carlos-devbox with only CAP_NET_BIND_SERVICE, NoNewPrivileges, ProtectSystem=strict and the hardening of carlos-edge.service; not installed by user_data or any CARLOS box path
+- `internal/devbox/registrar.go` `Registrar.list`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) EvalSymlinks <spool>/<name>/current only to report whether a folder link resolves. Not root
+- `internal/devbox/registrar.go` `Registrar.serveShareLive`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row via claim and writes a service row 127.0.0.1:<port> with UpsertUnlessRootfs. Caller identity is SO_PEERCRED only. Not root
+- `internal/devbox/registrar.go` `Registrar.serveUnshare`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row before deleting it, so a failed links delete can restore it. Caller identity is SO_PEERCRED only. Not root
+- `internal/devbox/registrar.go` `Registrar.serveShareFolder`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads the name from the query and the upload body (Content-Length required, capped at 200 MiB), scans it with scanSite (now also refusing a root _headers or _redirects over the edge's limit, final review fix) and reads its own registry row via claim. Caller identity is SO_PEERCRED only. Not root
+- `internal/edge/edge.go` `Edge.Reload`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload);rev3=census-ruling-tunnel-websockets;basis=The ArmTunnel arm now records its tenancy (Account, App, Tunnel) copied from the row t that Reload already lists; no new registry query, no file read. Also the reload mutex taken first and held to return, five nil-in-production test hooks, and the sweepUpgrades call after the swap, which reads only the map Reload has just built (spec 7, Tasks 3 and 4).;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5, rule 3): the two fleet proxy builds pass the row to fleetBoxOf(t) instead of reading t.FleetBox (-registry:FleetBox x2, +whole:Route x2); fleetBoxOf answers FleetLabel as authoritative when set, else FleetBox; an authoritative box has no fallback to another of the fleet's channels (503 errFleetDark instead). The edge in the agent, not root; it routes to fewer channels, never more.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): after the new upstream map is published, closes the held streams of any host the new map no longer holds (absent, not hibernating, route no longer Hibernate). Reads the freshly built in-memory map m and the in-memory held set; no read added beyond the rebuild Reload already does.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `devbox_acl_linux.go:openDevboxSocket`: reads +file:Fstat, +file:Open; written legacy, accepted-legacy, frozen
+- new `devbox_cli.go:prepareDevboxSocketsDir`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+- new `internal/devbox/registrar.go:Registrar.serveShareSocket`: reads +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/devbox/socketcheck_linux.go:checkSocket`: reads +file:Open; written legacy, accepted-legacy, frozen
+- new `internal/devbox/socketcheck_linux.go:var#1`: reads +file:Fstat; written legacy, accepted-legacy, frozen
+- new `internal/edge/devboxfront.go:devboxTrailerBody.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen
+- new `internal/tsidentity/whois.go:identity.Who`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
+
+Seal: `3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe` → `66a5df05f18f70c3162ad05aa316c1e69c0f053d54f8b682262c266d6aa50772`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-devbox-identity.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-30-devbox-mode-copy.md b/docs/superpowers/plans/2026-10-30-devbox-mode-copy.md
index 4b15cb952..37cc830aa 100644
--- a/docs/superpowers/plans/2026-10-30-devbox-mode-copy.md
+++ b/docs/superpowers/plans/2026-10-30-devbox-mode-copy.md
@@ -55,6 +55,9 @@ target is the folder's name as it was shared.
| DBX-C8 | devbox_cli.go | a folder of static files to publish. the link serves a copy, and sharing again replaces it | approved |
| DBX-C9 | devbox_cli.go | unshare removes a link you published. without a name it uses your git branch | approved |
| DBX-C10 | devbox_cli.go | list shows every link on this devbox, who owns it and whether it is answering | approved |
+
+DBX-C2 and DBX-C4 are superseded by DBX-C94 and DBX-C113, respectively.
+
## Output
| id | file | text | status |
@@ -69,6 +72,9 @@ target is the folder's name as it was shared.
| DBX-C18 | devbox_cli.go | not answering | approved |
| DBX-C19 | devbox_cli.go | serving | approved |
| DBX-C20 | devbox_cli.go | account removed | approved |
+
+DBX-C13 is superseded by DBX-C109.
+
## Refusals
| id | file | text | status |
@@ -90,6 +96,9 @@ target is the folder's name as it was shared.
| DBX-C35 | devbox_cli.go | the devbox service answered with something this carlos does not understand. update carlos and try again | approved |
| DBX-C53 | devbox_cli.go | <name> is already in use on this devbox. pick another name | approved |
| DBX-C54 | devbox_cli.go | the devbox service could not finish that. try again, or tell whoever runs this devbox | approved |
+
+DBX-C26 is superseded by DBX-C97.
+
## Runbook: infra/devbox/README.md
Headings, the purpose paragraph, one sentence for each one-time root step and
@@ -175,3 +184,44 @@ plist's `Sockets` entry, such as `Listeners`; `<count>` a number;
| DBX-C91 | infra/devbox/README.md | Then add the DNS record and run the checks below. | approved |
| DBX-C92 | infra/devbox/README.md | On a Mac, use lsof instead of ss to see what is listening, and read the log file instead of journalctl. | approved |
| DBX-C93 | devbox_cli.go | the environment file <env file> has an access control list, which can let other accounts read or change it. remove it with: chmod -N <env file> | approved |
+
+## Identity and private targets (#486 A): socket links, --allow, list access, the private page and the runbook section
+
+Drafted 2026-11-01 for docs/superpowers/plans/2026-11-01-devbox-identity.md and
+approved by Paul 2026-11-02, unedited. More placeholders: `<sockets dir>` the
+shared sockets folder, /run/carlos-devbox/sockets; `<user>` the devbox service
+account, usually carlos-devbox; `<login>` one tailnet login, such as
+alice@github; `<logins>` a comma-separated list of them.
+
+| id | file | text | status |
+|---|---|---|---|
+| DBX-C94 | devbox_cli.go | usage: carlos devbox share [--port <port>, --socket <path> or --dir <path>] [--allow <logins>] [<name>] | approved |
+| DBX-C95 | devbox_cli.go | a Unix socket your tool listens on, inside <sockets dir>. share makes it private to you and the devbox service. if your tool restarts and makes a new socket, share again | approved |
+| DBX-C96 | devbox_cli.go | tailnet logins that may open the link, separated by commas, such as alice@github. anyone else sees a page saying the link is private. without --allow, everyone on the tailnet can open it. sharing again replaces the list | approved |
+| DBX-C97 | devbox_cli.go | give one of --port for a dev server, --socket for a socket or --dir for a folder | approved |
+| DBX-C98 | devbox_cli.go | <path> is not directly inside <sockets dir>. have your tool create its socket there, then share it | approved |
+| DBX-C99 | devbox_cli.go | <path> is not a socket. give the path of the Unix socket your tool listens on | approved |
+| DBX-C100 | devbox_cli.go | <path> belongs to another account. you can only share a socket you created | approved |
+| DBX-C101 | devbox_cli.go | nothing is answering on <path>. start your tool, then share again | approved |
+| DBX-C102 | devbox_cli.go | could not let the devbox service open <path>. check that the socket is yours, or tell whoever runs this devbox | approved |
+| DBX-C103 | devbox_cli.go | this machine has no devbox service user called <user>. tell whoever runs this devbox | approved |
+| DBX-C104 | devbox_cli.go | --socket works on Linux devboxes only for now. on this devbox, use --port | approved |
+| DBX-C105 | devbox_cli.go | --allow works on Linux devboxes only for now. on this devbox, every link is open to the tailnet | approved |
+| DBX-C106 | devbox_cli.go | <login> is not a tailnet login. give logins such as alice@github, separated by commas, with no spaces | approved |
+| DBX-C107 | internal/edge/devboxfront.go | This link is private | approved |
+| DBX-C108 | internal/edge/devboxfront.go | Only the people it was shared with can open it, from their own devices on the tailnet. | approved |
+| DBX-C109 | devbox_cli.go | name owner kind target access age state | approved |
+| DBX-C110 | devbox_cli.go | socket | approved |
+| DBX-C111 | devbox_cli.go | private | approved |
+| DBX-C112 | devbox_cli.go | tailnet | approved |
+| DBX-C113 | devbox_cli.go | usage: carlos devbox list [--allowed] | approved |
+| DBX-C114 | devbox_cli.go | also show who can open your private links | approved |
+| DBX-C115 | devbox_cli.go | private: <logins> | approved |
+| DBX-C116 | infra/devbox/README.md | ## Visitor identity and private links | approved |
+| DBX-C117 | infra/devbox/README.md | The service tells each link's upstream who is visiting, in the Carlos-Visitor-Login, Carlos-Visitor-Name and Carlos-Visitor-Node headers. It removes any a visitor sends, so a tool behind a link can trust them. | approved |
+| DBX-C118 | infra/devbox/README.md | Tailscale names a device's owner, not the person using it. So a visit from this machine, or from any node listed in CARLOS_DEVBOX_SHARED_NODES, carries no identity, and a link shared with --allow refuses it. | approved |
+| DBX-C119 | infra/devbox/README.md | Add every other shared machine, such as another devbox, to CARLOS_DEVBOX_SHARED_NODES in the environment file, as machine names separated by commas. | approved |
+| DBX-C120 | infra/devbox/README.md | The service user asks tailscaled who each visitor is. If it cannot, every visitor is anonymous, and links shared with --allow refuse everyone. | approved |
+| DBX-C121 | infra/devbox/README.md | The service creates /run/carlos-devbox/sockets when it starts. Any account can create a socket there, but nobody can list the folder, and only a socket's owner can remove it. | approved |
+| DBX-C122 | infra/devbox/README.md | Share a socket link and open it from another device. Check that another account on this machine cannot connect to the socket. | approved |
+| DBX-C123 | infra/devbox/README.md | Share a link with --allow and your own login. Check that it opens from your own device and shows the private page from a browser on this machine. | approved |
diff --git a/docs/superpowers/plans/2026-11-01-devbox-identity.md b/docs/superpowers/plans/2026-11-01-devbox-identity.md
new file mode 100644
index 000000000..aec0fc760
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-01-devbox-identity.md
@@ -0,0 +1,158 @@
+# Devbox Identity and Private Targets (#486 A) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Devbox links tell the upstream who is looking: Tailscale login, personal devices only. A link can point at a private Unix socket, and `--allow` makes a link answer only named logins.
+
+**Architecture:** `edge.ServeDevbox` wraps the edge handler in a front-door middleware. The middleware:
+
+1. strips `Carlos-Visitor-*` headers;
+2. asks a `VisitorIdentity` adapter about the remote address;
+3. drops identity for shared machines;
+4. enforces the link's allow list, fetched through a lookup the registrar hands it in-process;
+5. sets the headers.
+
+The registrar gains socket targets, checked against the caller's uid in a sticky sockets directory the service creates, and per-link allow lists. The CLI makes the socket private and grants the service user access with a POSIX ACL.
+
+**Tech Stack:** Go, `golang.org/x/sys/unix`, plain HTTP over Unix sockets. No new modules.
+
+**Spec:** `docs/superpowers/specs/2026-11-01-devbox-identity-design.md`, approved by Paul 2026-11-01.
+
+## Global Constraints
+
+- Header names are exactly `Carlos-Visitor-Login`, `Carlos-Visitor-Name` and `Carlos-Visitor-Node`. The edge deletes them from every incoming request, whatever the case and whatever the link kind, WebSocket upgrades included.
+- Identity is never inferred. If the lookup fails, the visitor is anonymous. A request from the devbox's own listen IP, or from a node named in `CARLOS_DEVBOX_SHARED_NODES` (a comma list of node names), is anonymous too. An allow-listed link refuses anonymous visitors.
+- Whois cache: 60 s for an answer, 5 s for a failure. Lookups go over tailscaled's LocalAPI at `/var/run/tailscale/tailscaled.sock`, as plain HTTP over the Unix socket.
+- Allow matching is exact and case-insensitive on Login, with no globs. A refusal is HTTP 403 with the approved private-link page. It never echoes the list or the owner.
+- Sockets live directly in `/run/carlos-devbox/sockets/`, created by `serve` at start with mode 1733. The socket file is mode 0600 with an ACL entry for the service user: rw for the service uid only. The registrar requires the owner uid to equal the caller uid, a socket type, no symlink, and a successful connect.
+- Linux only for `--socket` and identity. On darwin, `--socket` is refused with deck copy and identity is off. Darwin must still build.
+- User-facing strings come only from approved copy deck rows: DBX-C94 onwards, appended to `docs/superpowers/plans/2026-10-30-devbox-mode-copy.md`. No em dashes.
+- **Verification budget** (Paul, 2026-10-31):
+ - mutation checks only on refusal and security paths, at most about 10 per task, each with targeted `-run`;
+ - run tests once with `-count=1`, plus one `-race`;
+ - locally, run only the touched packages; CI runs the full suite;
+ - smoke-test on docs-t1 as soon as a link works end to end.
+- Commit subjects under 80 characters; body after a blank line.
+
+## Review Focus
+
+1. **Spoofing:** a visitor sends `carlos-visitor-login: paulca@github`, in mixed case. The upstream never sees it. Test in Task 3.
+2. **A request from the devbox itself:** no identity, so an allow-listed link refuses it, even when the box owner's login is on the list. Test in Task 3.
+3. **tailscaled down or slow:** an allow-listed link answers 403 within the request deadline, and an open link serves anonymously. Test in Task 2 (adapter timeout) and Task 3 (refusal).
+4. **A socket owned by someone else, a symlink to one, or a path outside the sockets directory:** refused before anything is written. Test in Task 4.
+5. **Re-share changes the allow list** (a list to none, or none to a list): the edge applies the change on the next request, with no restart. Test in Task 3 and Task 4.
+
+---
+
+### Task 1: Copy deck (controller and Paul)
+
+Draft rows DBX-C94 onwards for:
+
+- the `--socket` help and the `--allow` help;
+- the refusals:
+ - socket outside the sockets directory;
+ - not a socket;
+ - not yours;
+ - the service can't connect;
+ - the ACL couldn't be set;
+ - `--socket` on macOS;
+ - a malformed login in `--allow`;
+- the 403 private-link page (title and one sentence);
+- `list` states: "private" and "tailnet";
+- the runbook: the sockets directory, and the identity rule for shared machines (`CARLOS_DEVBOX_SHARED_NODES`).
+
+Run copy review with Paul, apply his text verbatim, and bump the gate's inventory.
+
+### Task 2: The identity adapter
+
+**Files:**
+- Create `internal/edge/visitor.go`: the interface, the cache, and the shared-node rule helper.
+- Create `internal/tsidentity/whois.go`: the Tailscale adapter.
+- Tests: `internal/edge/visitor_test.go`, `internal/tsidentity/whois_test.go`.
+
+**Interfaces (produces):**
+
+```go
+// internal/edge
+type Visitor struct{ Login, Name, Node string }
+type VisitorIdentity interface {
+ Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error)
+}
+func NewCachedIdentity(inner VisitorIdentity, now func() time.Time) VisitorIdentity // 60 s hit, 5 s miss
+// internal/tsidentity
+func New(socketPath string, timeout time.Duration) edge.VisitorIdentity // GET /localapi/v0/whois?addr=<ip:port>
+```
+
+The Tailscale adapter treats a tagged node, or an empty `UserProfile.LoginName`, as ok=false. Its timeout is 2 s (my call).
+
+- [ ] **Tests:**
+ - `TestWhoisParsesLoginNameNode`: a fake LocalAPI on a temp Unix socket returns the whois JSON, and the adapter maps `UserProfile.LoginName`, `UserProfile.DisplayName` and `Node.ComputedName`.
+ - `TestWhoisTaggedNodeIsAnonymous`.
+ - `TestWhoisTimeout`: a fake that never answers gives an error in about 2 s.
+ - `TestCachedIdentityTTLs`: a hit is reused for up to 60 s and refetched after. A miss is reused for up to 5 s.
+- [ ] **Implement, run, commit.** Before wiring it in, the builder checks once on docs-t1 that the `carlos-devbox` user can call whois. Run `sudo -u carlos-devbox` only if Paul agrees, or else as an unprivileged non-operator account. Record the result in the report. If whois is refused, STOP and report; the spec says the fallback must not need root.
+
+### Task 3: The front-door middleware
+
+**Files:**
+- Modify `internal/edge/devbox.go`: `DevboxConfig` gains `Identity VisitorIdentity`, `SharedNodes []string` and `AllowFor func(host string) []string`, and `srv.Handler` becomes `devboxFront(e, cfg)`.
+- Create `internal/edge/devboxfront.go`.
+- Test: `internal/edge/devboxfront_test.go`.
+
+**Interfaces:** `func devboxFront(next http.Handler, cfg DevboxConfig, selfIP netip.Addr) http.Handler`. `selfIP` comes from `ListenAddr`.
+
+- [ ] **Tests:**
+ - `TestFrontStripsVisitorHeaders`: Review Focus 1, with mixed case, and on an upgrade request too.
+ - `TestFrontSetsIdentity`.
+ - `TestFrontSelfIPIsAnonymous`: Review Focus 2.
+ - `TestFrontSharedNodeIsAnonymous`.
+ - `TestFrontAllowRefusesOthers`: the 403 body is the deck page and doesn't contain the allowed login.
+ - `TestFrontAllowRefusesAnonymous`: Review Focus 3, with an adapter error.
+ - `TestFrontOpenLinkServesAnonymous`.
+ - `TestFrontAllowListChangeTakesEffect`: Review Focus 5, a changed `AllowFor` result applies on the next request.
+- [ ] **Implement, run** `go test ./internal/edge -run 'TestFront|TestDevbox' -count=1`, **then commit.**
+
+### Task 4: Registrar: socket targets and allow lists
+
+**Files:**
+- Modify `internal/devbox/links.go`: `Link` gains `Socket string` (`json:"socket,omitempty"`) and `Allow []string` (`json:"allow,omitempty"`); `Kind` gains `"socket"`.
+- Modify `internal/devbox/registrar.go`: `POST /share/socket {name, path, allow}`; `allow` on `/share/live` and `/share/folder`; `func (r *Registrar) AllowFor(host string) []string`; `list` carries `private bool`.
+- Create `internal/devbox/socketcheck_linux.go` and `socketcheck_other.go`.
+- Test: `internal/devbox/registrar_socket_test.go`.
+
+The registry row for a socket link is `{Host, Kind: "service", Socket: path, App: name, Status: "ready"}`, written with `UpsertUnlessRootfs`. The checks run on an `O_PATH|O_NOFOLLOW` fd plus `fstat`: the parent is exactly `SocketsDir`, the file is a socket, and the owner uid equals the caller. A connect test with a 300 ms timeout comes last. New codes: `socket-path`, `not-a-socket`, `socket-not-yours`, `socket-unreachable` and `bad-allow`.
+
+- [ ] **Tests:**
+ - `TestShareSocketWritesSocketRoute`.
+ - `TestShareSocketRefusesOtherOwner`, `TestShareSocketRefusesSymlink` and `TestShareSocketRefusesOutsideDir`: Review Focus 4. Fake the owner uid through a seam where the test can't chown.
+ - `TestShareSocketUnreachable`.
+ - `TestAllowForReturnsList`; `TestReshareReplacesAllow`, for Review Focus 5.
+ - `TestBadAllowLogin`: an empty entry, whitespace, or more than 254 characters.
+ - `TestListMarksPrivate`.
+- [ ] **Implement, run** `TMPDIR=/tmp/g go test ./internal/devbox -count=1`, **then commit.**
+
+### Task 5: CLI, serve wiring, runbook
+
+**Files:**
+- Modify `devbox_cli.go`:
+ - `share` gains `--socket PATH` and `--allow LIST`;
+ - `list` gains the private/tailnet state;
+ - `serve` creates `SocketsDir` at mode 1733, builds `tsidentity.New` behind `NewCachedIdentity` and reads `CARLOS_DEVBOX_SHARED_NODES`, and passes `Identity`, `SharedNodes` and `AllowFor` into `DevboxConfig`.
+- Create `devbox_acl_linux.go`, `devbox_acl_other.go`, and the test `devbox_acl_linux_test.go`. `func grantServiceACL(path string, serviceUID uint32) error` sets mode 0600 and writes `system.posix_acl_access` (owner rw, named user serviceUID rw, mask rw, group none, other none) with `unix.Setxattr`. The service uid comes from looking up the user `carlos-devbox` (`CARLOS_DEVBOX_SERVICE_USER` overrides).
+- Modify `infra/devbox/README.md` with the deck's runbook rows.
+
+- [ ] **Tests:**
+ - `TestGrantServiceACLEncodes`: the xattr bytes round-trip through a decoder.
+ - `TestDevboxShareSocketCLI`: against the in-process registrar.
+ - `TestDevboxShareAllowFlag`.
+ - `TestDevboxSocketRefusedOnDarwin`: a GOOS seam.
+- [ ] **Implement, run** `TMPDIR=/tmp/g go test -run TestDevbox . -count=1` and the copy gate, **then commit.**
+- [ ] **Smoke on docs-t1** after a release, or with a dev build that Paul installs:
+ - a socket link served through the edge;
+ - another account can't connect to the socket;
+ - `--allow paulca@github` serves Paul's MacBook and refuses from docs-t1 itself;
+ - stopping tailscaled makes allow-listed links refuse.
+
+### Task 6: Census and docs
+
+Run `make census-card` and `make census-propose NAME=devbox-identity`, plus the 9B8 overlay if sites are rejected. The `carlos:devbox` skill update (`--socket`, `--allow`, identity headers) goes to the skills repo as a follow-up PR.
diff --git a/docs/superpowers/specs/2026-11-01-devbox-identity-design.md b/docs/superpowers/specs/2026-11-01-devbox-identity-design.md
new file mode 100644
index 000000000..82b8db559
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-devbox-identity-design.md
@@ -0,0 +1,242 @@
+# Devbox identity and private targets (#486, part A)
+
+Status: design, 2026-11-01. Discussion: amadan #486. Builds on devbox mode
+(docs/superpowers/specs/2026-10-30-devbox-mode-design.md, merged 2c66e563;
+macOS 90c4d3a). Part B of #486, internal deployed apps on fleet boxes, is a
+separate design.
+
+## 1. Why
+
+The first internal tool is the copy-review daemon (paulca/agent-skills #1).
+It runs on a devbox behind a devbox link, because it reads each agent's local
+files. It wants only its owner to be able to open reviews. Today it can't
+know who is looking: a devbox link passes no visitor identity, and its
+upstream is a loopback port that any account on the machine can reach
+directly, so even a passed identity could be forged by connecting around
+the edge. Its spec asks devbox for exactly two things: visitor identity, and
+a Unix-socket target only the devbox service and the owner can open.
+
+The private network already knows every visitor. On a tailnet, Tailscale
+knows each peer's login. The edge only has to ask, pass the answer on, and be
+the only way in.
+
+## 2. What it is
+
+1. **Visitor identity on every devbox link.** For each request, the edge
+ asks the private network who the visitor is and passes it to the upstream
+ in headers the edge controls.
+2. **Socket targets.** `carlos devbox share --socket <path>` points a live
+ link at a Unix socket owned by the caller. Only the caller and the devbox
+ service can open it, so the edge is the only way in and the identity
+ headers can be trusted.
+3. **An optional allow list, enforced by the edge.** For example,
+ `carlos devbox share ... --allow paulca@github`. A visitor whose login is
+ not on the list gets a refusal page. With no list, a link stays open to
+ the whole tailnet, as today. This works for folder links too.
+
+## 3. Goals, non-goals, anti-goals
+
+Goals:
+
+- A tool behind a devbox link can rely on knowing who is looking, without its
+ own sign-in.
+- A link can be made private to named people with one flag, with no code in
+ the tool.
+- The copy-review daemon's two open questions are answered as its spec
+ describes: identity header plus socket target.
+
+Non-goals:
+
+- Our own access control, VPN or user directory. Tailscale's ACLs stay the
+ network gate. The allow list only narrows who, among those the network
+ already lets in, sees a link.
+- Part B: internal deployed apps on fleet boxes, and app sign-in from
+ identity (automatic sign-in or account linking).
+- macOS socket targets and identity in the first cut. The macOS devbox keeps
+ today's behaviour until a follow-up (its ACL and Tailscale LocalAPI paths
+ differ).
+
+Anti-goals:
+
+- **Forgeable identity.** A visitor-supplied identity header must never
+ reach an upstream. The edge strips the header names on every request,
+ whatever the link.
+- **Failing open.** If the identity lookup fails, the request carries no
+ identity. A link with an allow list then refuses it. It is never let
+ through as "probably fine".
+- **The core depending on Tailscale.** Identity comes through an adapter.
+ Tailscale is the one implementation.
+- A socket target that lets one account point a link at another account's
+ socket.
+- One account on a shared machine borrowing the machine owner's identity.
+
+## 4. Decided
+
+Paul, 2026-11-01:
+
+- Part A first, because it unblocks copy review; part B is its own design.
+- Identity headers on every link, always.
+- The allow list is optional. With no list, a link stays open to the
+ tailnet, so sharing with a colleague keeps working.
+- Automatic sign-in for apps is welcome later, not required ("either would
+ be fine").
+- Identity means a personal device. Requests from a shared machine (the
+ devbox itself, plus configured shared nodes) are anonymous, so a private
+ link can't be opened from a browser on the devbox (Paul, after the builder
+ check: "Sure").
+
+## 5. Shape
+
+### 5.1 The identity adapter
+
+An interface in the edge package (the name is the builder's):
+
+ type VisitorIdentity interface {
+ // Who returns the visitor at remote, or ok=false if unknown.
+ Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error)
+ }
+ type Visitor struct { Login, Name, Node string }
+
+The Tailscale implementation calls tailscaled's LocalAPI `whois` for the
+remote address, over its Unix socket (`/var/run/tailscale/tailscaled.sock`,
+mode 0666 on the first devbox). It uses plain HTTP over the socket: no new
+module dependency (my call).
+
+- **Login** is the user's login name (`paulca@github`).
+- **Name** is the display name.
+- **Node** is the machine name.
+- A **tagged device** has no user login, so `Who` returns ok=false and the
+ request is anonymous.
+
+**Identity means a personal device.** Tailscale identifies the device's
+owner, not the person or Unix account using it. Both devboxes are listed
+under one person's login (`doc@`), so anything on a devbox would otherwise
+be identified as that person. So a request from a **shared machine** gets no
+identity: no headers, and allow-listed links refuse it. The shared machines
+are:
+
+- the devbox itself, meaning any request whose source is the address in
+ `CARLOS_DEVBOX_LISTEN`, always;
+- every node named in `CARLOS_DEVBOX_SHARED_NODES`, a comma list of node
+ names as the identity adapter reports them, such as the other devbox.
+ The match is on the node, not the login.
+
+The adapter returns the node with the visitor so the edge can apply this
+rule. The rule lives in the edge, not the adapter, so another provider gets
+it for free (my call).
+
+**Caching:** an answer is cached per remote address for 60 seconds, and a
+failure for 5 seconds (my call). Tailnet addresses are stable per device,
+and this keeps LocalAPI off the request path.
+
+The builder must check on the first devbox that the devbox service user (not
+root, not the Tailscale operator) is allowed to call `whois`. If it isn't,
+the fallback is the builder's call, and must not need root or sudo for
+day-to-day running.
+
+### 5.2 The headers
+
+On every request through a devbox link, the edge:
+
+1. deletes every request header named `Carlos-Visitor-Login`,
+ `Carlos-Visitor-Name` or `Carlos-Visitor-Node`, in any case, before
+ anything else;
+2. if `Who` returns a visitor, sets those three headers. Values are
+ restricted to printable ASCII; anything else is dropped, not escaped (my
+ call).
+
+This applies to live links (port and socket) and to folder links (where the
+headers just aren't used). It applies to WebSocket upgrades too.
+
+### 5.3 Socket targets
+
+`carlos devbox share --socket <path> [name]` (Linux):
+
+- **Where the socket lives:** under a directory the devbox service provides,
+ `/run/carlos-devbox/sockets/`, created by the service at start with mode
+ 1733 (`wx` for others, sticky, and not listable). Callers create their
+ socket file there. The CLI refuses any other path (my call). A user's home
+ directory isn't traversable by the service user, and this spot is the same
+ on every devbox.
+- **Who can open it:** before registering, the CLI, running as the caller,
+ makes the socket private (mode 0600). It then grants the devbox service's
+ user read and write through a POSIX ACL entry, set in Go through the
+ `system.posix_acl_access` extended attribute with no external `setfacl`.
+ The tool doesn't have to do anything.
+- **The registrar's checks:** the path is directly inside the sockets
+ directory and is a socket, not a symlink; its owner uid is the caller's
+ uid; and the devbox service can connect to it. The checks use the file it
+ opens, not the path (the builder picks the race-free way).
+- **The route:** the registry route uses the existing `Socket` upstream
+ field (`internal/registry`), so the edge needs no new proxy path.
+- **The list:** `list` shows the socket path as the target and "answering"
+ by a connect test, as for ports.
+- **If the tool recreates its socket** (a restart), the ACL is gone and
+ links stop answering. The CLI help and the skill say to share again after
+ a restart. A future option could make the service re-apply the grant (not
+ in this cut).
+
+### 5.4 The allow list
+
+`--allow <login>[,<login>…]` on `share`, for any link kind:
+
+- It's stored with the link's owner record (the registrar's links file), not
+ in the registry. The devbox edge and the registrar run in one process
+ (`carlos devbox serve`), so the edge reads it in memory through a lookup
+ the registrar hands it (my call, which avoids a registry schema change).
+- **Matching:** exact and case-insensitive on Login. Glob patterns and
+ domains (`*@company`) are out of the first cut.
+- **Refusal:** the edge answers 403 with a short page saying the link is
+ private (that text goes through copy review). It must not echo the allow
+ list or the owner.
+- **Updates:** re-sharing a link with a different `--allow`, or none,
+ replaces the list. Only the owner can do this, as for any change to a
+ link.
+- **`list`:** shows a link as "private" or "tailnet", without the names (my
+ call). Owners see their own lists with a flag (builder's call).
+
+## 6. Boundaries
+
+- **Provider-neutral:** identity is an adapter. The core edge knows
+ `VisitorIdentity`, not Tailscale. With no adapter configured, every
+ request is anonymous: allow-listed links refuse and others work as today.
+- **Request budget:** no S3 or other object-store requests. LocalAPI calls
+ are local, at most one per new visitor address per minute.
+- **Census:** the devbox service is unprivileged. The CLI's ACL write runs
+ as the calling user on their own socket.
+- **Copy:** the `--socket` and `--allow` help, the refusals (bad socket
+ path, not your socket, unreachable), the private-link page and the
+ runbook and skill updates all go through copy review.
+
+## 7. Outside this repo
+
+- The `carlos:devbox` skill gains `--socket` and `--allow`.
+- The copy-review daemon's spec, section 2, can switch from secret URLs to
+ identity: it checks `Carlos-Visitor-Login` and uses `--socket` and
+ `--allow paulca@github`.
+
+## 8. Left to the builder
+
+- Names for the interface, the cache and the header constants.
+- How the race-free socket checks are done.
+- The fallback if the service user can't call `whois` (subject to "no root
+ for day-to-day running").
+- How owners see their own allow lists in `list`.
+
+## 9. Done when
+
+On the first devbox:
+
+1. A live link shows the visitor's `Carlos-Visitor-Login` to the upstream,
+ and a visitor-sent header of the same name never arrives.
+2. A link shared with `--socket` answers through the edge. Another account on
+ the box can't connect to that socket, and the CLI refuses a socket owned
+ by someone else.
+3. A link shared with `--allow paulca@github` serves Paul and refuses another
+ tailnet login with the private-link page. A folder link with `--allow`
+ behaves the same.
+4. With tailscaled stopped, an allow-listed link refuses and an open link
+ still serves.
+5. A request made from the devbox itself (any account) carries no identity
+ headers, and an allow-listed link refuses it, even one allowing the
+ devbox's owner.
diff --git a/infra/devbox/README.md b/infra/devbox/README.md
index a8ffe7bd2..8e991eba4 100644
--- a/infra/devbox/README.md
+++ b/infra/devbox/README.md
@@ -151,6 +151,22 @@ Add one A record, by hand, once: *.devbox.example.com pointing at this machine's
*.devbox.example.com. 300 IN A 100.64.0.10
```
+## Visitor identity and private links
+
+The service tells each link's upstream who is visiting, in the Carlos-Visitor-Login, Carlos-Visitor-Name and Carlos-Visitor-Node headers. It removes any a visitor sends, so a tool behind a link can trust them.
+
+Tailscale names a device's owner, not the person using it. So a visit from this machine, or from any node listed in CARLOS_DEVBOX_SHARED_NODES, carries no identity, and a link shared with --allow refuses it.
+
+Add every other shared machine, such as another devbox, to CARLOS_DEVBOX_SHARED_NODES in the environment file, as machine names separated by commas.
+
+```sh
+CARLOS_DEVBOX_SHARED_NODES=devbox-2
+```
+
+The service user asks tailscaled who each visitor is. If it cannot, every visitor is anonymous, and links shared with --allow refuse everyone.
+
+The service creates /run/carlos-devbox/sockets when it starts. Any account can create a socket there, but nobody can list the folder, and only a socket's owner can remove it.
+
## 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.
@@ -183,6 +199,20 @@ Add one A record, by hand, once: *.devbox.example.com pointing at this machine's
ss -ltnp | grep carlos
```
+- [ ] Share a socket link and open it from another device. Check that another account on this machine cannot connect to the socket.
+
+ ```sh
+ carlos devbox share --socket /run/carlos-devbox/sockets/shop.sock shop
+ curl --unix-socket /run/carlos-devbox/sockets/shop.sock http://localhost/
+ ```
+
+- [ ] Share a link with --allow and your own login. Check that it opens from your own device and shows the private page from a browser on this machine.
+
+ ```sh
+ carlos devbox share --socket /run/carlos-devbox/sockets/shop.sock --allow alice@github shop
+ carlos devbox list --allowed
+ ```
+
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
diff --git a/infra/devbox/carlos-devbox.service b/infra/devbox/carlos-devbox.service
index 252b6e487..69b61ff3a 100644
--- a/infra/devbox/carlos-devbox.service
+++ b/infra/devbox/carlos-devbox.service
@@ -25,6 +25,8 @@ Group=carlos-devbox
# the file). 0755 so every account can reach the socket.
RuntimeDirectory=carlos-devbox
RuntimeDirectoryMode=0755
+# Keep users' sockets when the service stops.
+RuntimeDirectoryPreserve=yes
# /var/lib/carlos-devbox is CARLOS_DATA_DIR: registry.db, links.json, certs/
# and spool/. Private to the service user.
StateDirectory=carlos-devbox
diff --git a/internal/devbox/links.go b/internal/devbox/links.go
index da8c0dccc..b86926829 100644
--- a/internal/devbox/links.go
+++ b/internal/devbox/links.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"runtime"
+ "slices"
"sort"
"sync"
"time"
@@ -18,6 +19,7 @@ type Kind string
const (
KindLive Kind = "live"
KindFolder Kind = "folder"
+ KindSocket Kind = "socket"
)
// Link is the record of one published name.
@@ -26,6 +28,8 @@ type Link struct {
OwnerName string `json:"ownerName"`
OwnerUID uint32 `json:"ownerUID"`
Kind Kind `json:"kind"`
+ Socket string `json:"socket,omitempty"`
+ Allow []string `json:"allow,omitempty"`
Port int `json:"port,omitempty"` // live only
Snapshot string `json:"snapshot,omitempty"` // folder only: current snapshot dir name
Created time.Time `json:"created"`
@@ -74,6 +78,7 @@ func (l *Links) Get(name string) (Link, bool) {
l.mu.Lock()
defer l.mu.Unlock()
k, ok := l.links[name]
+ k.Allow = slices.Clone(k.Allow)
return k, ok
}
@@ -95,6 +100,7 @@ func (l *Links) Put(link Link) error {
l.mu.Lock()
defer l.mu.Unlock()
next := l.copyLocked()
+ link.Allow = slices.Clone(link.Allow)
next[link.Name] = link
return l.commitLocked(next)
}
@@ -130,6 +136,7 @@ func (l *Links) All() []Link {
defer l.mu.Unlock()
out := make([]Link, 0, len(l.links))
for _, k := range l.links {
+ k.Allow = slices.Clone(k.Allow)
out = append(out, k)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
diff --git a/internal/devbox/links_test.go b/internal/devbox/links_test.go
index 2e60b0f07..3cc750fdc 100644
--- a/internal/devbox/links_test.go
+++ b/internal/devbox/links_test.go
@@ -167,7 +167,7 @@ func TestLinksUnsyncedPutAndDeleteArePublished(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if got, ok := again.Get("shop"); !ok || got != sample("shop") {
+ if got, ok := again.Get("shop"); !ok || !reflect.DeepEqual(got, sample("shop")) {
t.Fatalf("reopened: %+v %v", got, ok)
}
diff --git a/internal/devbox/registrar.go b/internal/devbox/registrar.go
index 7c3a2b4c0..17e1804a6 100644
--- a/internal/devbox/registrar.go
+++ b/internal/devbox/registrar.go
@@ -24,6 +24,7 @@ import (
"log"
"net"
"net/http"
+ "net/url"
"os"
"path"
"path/filepath"
@@ -50,13 +51,27 @@ const (
// CodeInternal is not a refusal: the registrar failed (a registry or
// disk error) and rolled back. The CLI treats it as an answer it does
// not understand.
- CodeInternal = "internal"
+ CodeInternal = "internal"
+ CodeSocketPath = "socket-path"
+ CodeNotASocket = "not-a-socket"
+ CodeSocketNotYours = "socket-not-yours"
+ CodeSocketUnreachable = "socket-unreachable"
+ CodeSocketUnsupported = "socket-unsupported"
+ CodeBadAllow = "bad-allow"
)
const (
// MaxFolderBytes caps one folder upload, the compressed site.tar.gz.
MaxFolderBytes = 200 << 20
- // AnswerTimeout bounds each /list dial to a live link's port.
+
+ // DefaultSocketsDir is set by serve; an empty SocketsDir refuses socket shares.
+ DefaultSocketsDir = "/run/carlos-devbox/sockets"
+ // MaxAllowEntries caps the number of requested allow entries before deduplication.
+ MaxAllowEntries = 64
+ // MaxAllowLogin caps the length of a trimmed ASCII login.
+ MaxAllowLogin = 254
+
+ // AnswerTimeout bounds port and socket connection checks.
AnswerTimeout = 300 * time.Millisecond
// maxFolderEntries caps what one upload creates: its archive entries
@@ -96,6 +111,7 @@ const (
// Registrar owns the devbox's link names. The exported fields are its
// configuration; set them before the first request and leave them.
type Registrar struct {
+ SocketsDir string // set by serve; empty refuses socket shares
Reg *registry.Registry
Links *Links
Domain string // wildcard parent, e.g. "devbox.example.com"
@@ -112,8 +128,9 @@ type Registrar struct {
// WireError is the body of every refusal.
type WireError struct {
- Code string `json:"code"`
- Owner string `json:"owner,omitempty"`
+ Code string `json:"code"`
+ Owner string `json:"owner,omitempty"`
+ SocketsDir string `json:"socketsDir,omitempty"`
}
// ListEntry is one link as share, unshare and /list report it.
@@ -125,12 +142,14 @@ type ListEntry struct {
Owner string `json:"owner"`
OwnerUID uint32 `json:"ownerUID"`
Kind Kind `json:"kind"`
- Target string `json:"target"` // live: 127.0.0.1:<port>; folder: ""
+ Target string `json:"target"` // live: 127.0.0.1:<port>; socket: path; folder: ""
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
- // Answering: live, the port took a connection within AnswerTimeout;
+ // Answering: live or socket, a connection succeeded within AnswerTimeout;
// folder, the current snapshot resolves.
- Answering bool `json:"answering"`
+ Answering bool `json:"answering"`
+ Private bool `json:"private"`
+ Allow []string `json:"allow,omitempty"`
}
type peerKey struct{}
@@ -193,12 +212,14 @@ func (r *Registrar) Handler() http.Handler {
switch route {
case "POST /share/live":
out, ref = r.serveShareLive(uid, w, req)
+ case "POST /share/socket":
+ out, ref = r.serveShareSocket(uid, w, req)
case "POST /share/folder":
out, ref = r.serveShareFolder(uid, w, req)
case "POST /unshare":
out, ref = r.serveUnshare(uid, w, req)
case "GET /list":
- out = r.list(req.Context())
+ out = r.list(req.Context(), uid)
default:
ref = refuse(http.StatusNotFound, CodeBadRequest)
}
@@ -247,11 +268,16 @@ func (r *Registrar) lookupName(uid uint32) string {
return r.LookupUser(uid)
}
-func (r *Registrar) entry(k Link) ListEntry {
+func (r *Registrar) entry(k Link, uid uint32) ListEntry {
e := ListEntry{Name: k.Name, Host: r.host(k.Name), Owner: r.lookupName(k.OwnerUID), OwnerUID: k.OwnerUID,
- Kind: k.Kind, Created: k.Created, Updated: k.Updated}
+ Kind: k.Kind, Created: k.Created, Updated: k.Updated, Private: len(k.Allow) != 0}
+ if k.OwnerUID == uid {
+ e.Allow = append([]string(nil), k.Allow...)
+ }
if k.Kind == KindLive {
e.Target = liveAddr(k.Port)
+ } else if k.Kind == KindSocket {
+ e.Target = k.Socket
}
return e
}
@@ -310,8 +336,9 @@ func (r *Registrar) putFailed(name string, prev Link, had bool, err error) *refu
func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) {
var in struct {
- Name string `json:"name"`
- Port int `json:"port"`
+ Name string `json:"name"`
+ Port int `json:"port"`
+ Allow []string `json:"allow"`
}
if ref := decodeJSON(w, req, &in); ref != nil {
return nil, ref
@@ -319,6 +346,10 @@ func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.
if ValidName(in.Name) != nil {
return nil, refuse(http.StatusBadRequest, CodeInvalidName)
}
+ allow, ref := validateAllow(in.Allow)
+ if ref != nil {
+ return nil, ref
+ }
if in.Port < 1 || in.Port > 65535 {
return nil, refuse(http.StatusBadRequest, CodeBadPort)
}
@@ -330,7 +361,7 @@ func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.
return nil, ref
}
now := time.Now().UTC()
- link := Link{Name: in.Name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindLive, Port: in.Port, Created: now, Updated: now}
+ link := Link{Name: in.Name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindLive, Port: in.Port, Allow: allow, Created: now, Updated: now}
if had {
link.Created = prev.Created
}
@@ -345,7 +376,7 @@ func (r *Registrar) serveShareLive(uid uint32, w http.ResponseWriter, req *http.
if had && prev.Kind == KindFolder {
r.removeSpool(in.Name)
}
- return r.entry(link), nil
+ return r.entry(link, uid), nil
}
func (r *Registrar) serveUnshare(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) {
@@ -383,7 +414,7 @@ func (r *Registrar) serveUnshare(uid uint32, w http.ResponseWriter, req *http.Re
return nil, internalErr("links delete", err)
}
r.removeSpool(in.Name)
- return r.entry(prev), nil
+ return r.entry(prev, uid), nil
}
// undoUnshare rolls back an unshare whose Links.Delete failed after its row
@@ -410,7 +441,16 @@ func (r *Registrar) undoUnshare(name string, prev Link, prevRow *registry.Route,
}
func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) {
- name := req.URL.Query().Get("name")
+ // Folder bodies are tar archives; allow entries are repeated query values.
+ query, err := url.ParseQuery(req.URL.RawQuery)
+ if err != nil {
+ return nil, refuse(http.StatusBadRequest, CodeBadRequest)
+ }
+ name := query.Get("name")
+ allow, ref := validateAllow(query["allow"])
+ if ref != nil {
+ return nil, ref
+ }
if ValidName(name) != nil {
return nil, refuse(http.StatusBadRequest, CodeInvalidName)
}
@@ -502,7 +542,7 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
snapDir := filepath.Join(dir, snap)
now := time.Now().UTC()
- link := Link{Name: name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindFolder, Snapshot: snap, Created: now, Updated: now}
+ link := Link{Name: name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindFolder, Snapshot: snap, Allow: allow, Created: now, Updated: now}
if had {
link.Created = prev.Created
}
@@ -535,7 +575,7 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
return nil, internalErr("registry upsert", err)
}
pruneSnapshots(dir, snap, prevSnap)
- return r.entry(link), nil
+ return r.entry(link, uid), nil
}
// repointCurrent points current back at prevSnap during a rollback. A
@@ -793,12 +833,12 @@ func scanSite(data []byte, limit int64) (int64, *refusal) {
// list reports every link. It holds no registrar lock: Links.All is a
// consistent copy on its own, and the dials must not stall a share.
-func (r *Registrar) list(ctx context.Context) []ListEntry {
+func (r *Registrar) list(ctx context.Context, uid uint32) []ListEntry {
links := r.Links.All()
out := make([]ListEntry, len(links))
var wg sync.WaitGroup
for i, k := range links {
- out[i] = r.entry(k)
+ out[i] = r.entry(k, uid)
switch k.Kind {
case KindLive:
wg.Add(1)
@@ -806,6 +846,18 @@ func (r *Registrar) list(ctx context.Context) []ListEntry {
defer wg.Done()
out[i].Answering = dialAnswer(ctx, port)
}(i, k.Port)
+ case KindSocket:
+ wg.Add(1)
+ go func(i int, path string) {
+ defer wg.Done()
+ // This probe may follow a replaced symlink; it connects and closes
+ // without sending data. Forwarding checks the listener uid separately.
+ c, err := connectSocket(ctx, path)
+ if err == nil {
+ c.Close()
+ out[i].Answering = true
+ }
+ }(i, k.Socket)
case KindFolder:
_, err := filepath.EvalSymlinks(filepath.Join(r.SpoolRoot, k.Name, currentLink))
out[i].Answering = err == nil
@@ -829,3 +881,135 @@ func answering(ctx context.Context, port int) bool {
c.Close()
return true
}
+
+// AllowError identifies the entry refused by ValidateAllow.
+type AllowError struct{ Login string }
+
+func (e *AllowError) Error() string { return "devbox: invalid allow entry" }
+
+// ValidateAllow normalizes and deduplicates logins for both the CLI and
+// registrar. It trims entries, then requires nonempty printable ASCII within
+// the caps.
+func ValidateAllow(entries []string) ([]string, error) {
+ if len(entries) > MaxAllowEntries {
+ return nil, &AllowError{Login: entries[MaxAllowEntries]}
+ }
+ var allow []string
+ seen := make(map[string]bool, len(entries))
+ for _, entry := range entries {
+ entry = strings.TrimSpace(entry)
+ if len(entry) == 0 || len(entry) > MaxAllowLogin {
+ return nil, &AllowError{Login: entry}
+ }
+ for i := range entry {
+ if entry[i] < '!' || entry[i] > '~' {
+ return nil, &AllowError{Login: entry}
+ }
+ }
+ entry = strings.ToLower(entry)
+ if !seen[entry] {
+ allow = append(allow, entry)
+ seen[entry] = true
+ }
+ }
+ return allow, nil
+}
+
+func validateAllow(entries []string) ([]string, *refusal) {
+ allow, err := ValidateAllow(entries)
+ if err != nil {
+ return nil, refuse(http.StatusBadRequest, CodeBadAllow)
+ }
+ return allow, nil
+}
+
+// AllowFor returns a copy of the allow list for a host under Domain.
+// The copy comes from Links.Get through linkForHost.
+func (r *Registrar) AllowFor(host string) []string {
+ link, ok := r.linkForHost(host)
+ if !ok || len(link.Allow) == 0 {
+ return nil
+ }
+ return link.Allow
+}
+
+// linkForHost gives both edge lookups the same host matching rules.
+func (r *Registrar) linkForHost(host string) (Link, bool) {
+ if h, _, err := net.SplitHostPort(host); err == nil {
+ host = h
+ }
+ host = strings.ToLower(strings.TrimSuffix(host, "."))
+ domain := "." + strings.ToLower(strings.TrimSuffix(r.Domain, "."))
+ if !strings.HasSuffix(host, domain) {
+ return Link{}, false
+ }
+ name := strings.TrimSuffix(host, domain)
+ if ValidName(name) != nil {
+ return Link{}, false
+ }
+ return r.Links.Get(name)
+}
+
+// SocketOwnerFor returns the socket path and owner of the link served at host.
+// Several links can retain the same path after its listener changes owners.
+func (r *Registrar) SocketOwnerFor(host string) (path string, uid uint32, ok bool) {
+ link, ok := r.linkForHost(host)
+ if !ok || link.Kind != KindSocket {
+ return "", 0, false
+ }
+ return link.Socket, link.OwnerUID, true
+}
+
+func (r *Registrar) serveShareSocket(uid uint32, w http.ResponseWriter, req *http.Request) (any, *refusal) {
+ var in struct {
+ Name string `json:"name"`
+ Path string `json:"path"`
+ Allow []string `json:"allow"`
+ }
+ if ref := decodeJSON(w, req, &in); ref != nil {
+ return nil, ref
+ }
+ if ValidName(in.Name) != nil {
+ return nil, refuse(http.StatusBadRequest, CodeInvalidName)
+ }
+ allow, ref := validateAllow(in.Allow)
+ if ref != nil {
+ return nil, ref
+ }
+ socket, ref := checkSocket(req.Context(), r.SocketsDir, in.Path, uid)
+ if ref != nil {
+ if ref.body.Code == CodeSocketPath {
+ ref.body.SocketsDir = r.SocketsDir
+ }
+ return nil, ref
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ prev, had, ref := r.claim(uid, in.Name)
+ if ref != nil {
+ return nil, ref
+ }
+ now := time.Now().UTC()
+ link := Link{Name: in.Name, OwnerName: r.lookupName(uid), OwnerUID: uid, Kind: KindSocket, Socket: socket, Allow: allow, Created: now, Updated: now}
+ if had {
+ link.Created = prev.Created
+ }
+ if err := r.Links.Put(link); err != nil {
+ return nil, r.putFailed(in.Name, prev, had, err)
+ }
+ row := registry.Route{Host: r.host(in.Name), Kind: "service", Socket: socket, App: in.Name, Status: "ready"}
+ if err := r.Reg.UpsertUnlessRootfs(row); err != nil {
+ r.restoreLink(in.Name, prev, had)
+ return nil, internalErr("registry upsert", err)
+ }
+ if had && prev.Kind == KindFolder {
+ r.removeSpool(in.Name)
+ }
+ return r.entry(link, uid), nil
+}
+
+func connectSocket(ctx context.Context, path string) (net.Conn, error) {
+ d := net.Dialer{Timeout: AnswerTimeout}
+ return d.DialContext(ctx, "unix", path)
+}
diff --git a/internal/devbox/registrar_socket_linux_test.go b/internal/devbox/registrar_socket_linux_test.go
new file mode 100644
index 000000000..767803023
--- /dev/null
+++ b/internal/devbox/registrar_socket_linux_test.go
@@ -0,0 +1,296 @@
+//go:build linux
+
+package devbox
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "golang.org/x/sys/unix"
+)
+
+func socketFixture(t *testing.T) (*fixture, string, net.Listener) {
+ t.Helper()
+ f := newFixture(t)
+ dir, err := os.MkdirTemp(os.TempDir(), "sock-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ f.r.SocketsDir = dir
+ path := filepath.Join(dir, "shop.sock")
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ t.Cleanup(func() { ln.Close(); <-done })
+ return f, path, ln
+}
+
+func fakeSocketUIDs(t *testing.T, fileUID, peerUID uint32) {
+ t.Helper()
+ oldStat, oldPeer := socketFstat, socketPeerUID
+ socketFstat = func(fd int, stat *unix.Stat_t) error {
+ if err := unix.Fstat(fd, stat); err != nil {
+ return err
+ }
+ stat.Uid = fileUID
+ return nil
+ }
+ socketPeerUID = func(net.Conn) (uint32, error) { return peerUID, nil }
+ t.Cleanup(func() { socketFstat, socketPeerUID = oldStat, oldPeer })
+}
+
+func noSocketWrite(t *testing.T, f *fixture) {
+ t.Helper()
+ if len(f.r.Links.All()) != 0 || f.row(t, "shop") != nil {
+ t.Fatal("refused socket wrote state")
+ }
+ checkOwnedRoutes(t, f)
+}
+
+func TestShareSocketWritesSocketRoute(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ uid := uint32(os.Getuid())
+ wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, []string{"Alice@GitHub"}))
+ rt := f.row(t, "shop")
+ if rt == nil {
+ t.Fatal("no row")
+ }
+ got := registry.Route{Host: rt.Host, Kind: rt.Kind, Socket: rt.Socket, App: rt.App, Status: rt.Status}
+ want := registry.Route{Host: "shop." + testDomain, Kind: "service", Socket: path, App: "shop", Status: "ready"}
+ if got != want || rt.Addr != "" || rt.Addrs != "" || rt.Runtime != "" {
+ t.Fatalf("row = %+v", rt)
+ }
+ k, ok := f.r.Links.Get("shop")
+ if !ok || k.Kind != KindSocket || k.Socket != path || k.OwnerUID != uid || k.Port != 0 || k.Snapshot != "" || !equal(k.Allow, []string{"alice@github"}) {
+ t.Fatalf("link = %+v", k)
+ }
+ again := checkOwnedRoutes(t, f)
+ saved, _ := again.Get("shop")
+ if !reflect.DeepEqual(k, saved) {
+ t.Fatalf("saved = %+v", saved)
+ }
+ if DefaultSocketsDir != "/run/carlos-devbox/sockets" {
+ t.Fatalf("default sockets dir = %q", DefaultSocketsDir)
+ }
+}
+
+func TestShareSocketRefusesOtherOwner(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ fakeSocketUIDs(t, 1002, 1001)
+ wantCode(t, shareAllow(t, f, 1001, KindSocket, "shop", path, nil), CodeSocketNotYours)
+ noSocketWrite(t, f)
+}
+
+func TestShareSocketRefusesPeerUIDMismatch(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ fakeSocketUIDs(t, 1001, 1002)
+ wantCode(t, shareAllow(t, f, 1001, KindSocket, "shop", path, nil), CodeSocketNotYours)
+ noSocketWrite(t, f)
+ socketPeerUID = func(net.Conn) (uint32, error) { return 1001, unix.EIO }
+ wantCode(t, shareAllow(t, f, 1001, KindSocket, "shop", path, nil), CodeSocketNotYours)
+ noSocketWrite(t, f)
+}
+
+func TestShareSocketRefusesSymlink(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ link := filepath.Join(f.r.SocketsDir, "link.sock")
+ if err := os.Symlink(path, link); err != nil {
+ t.Fatal(err)
+ }
+ wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", link, nil), CodeNotASocket)
+ noSocketWrite(t, f)
+}
+
+func TestShareSocketRefusesOutsideDir(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ f.r.SocketsDir = filepath.Join(f.r.SocketsDir, "inside")
+ if got := wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", path, nil), CodeSocketPath); got.SocketsDir != f.r.SocketsDir {
+ t.Fatalf("sockets directory = %q, want %q", got.SocketsDir, f.r.SocketsDir)
+ }
+ noSocketWrite(t, f)
+}
+
+func TestShareSocketRefusesBadPath(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ for _, path := range []string{"", "relative.sock", "@abstract", f.r.SocketsDir, filepath.Join(f.r.SocketsDir, "missing"), filepath.Join(f.r.SocketsDir, "nested", "shop.sock"), f.r.SocketsDir + "/../shop.sock"} {
+ if got := wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", path, nil), CodeSocketPath); got.SocketsDir != f.r.SocketsDir {
+ t.Fatalf("sockets directory = %q, want %q", got.SocketsDir, f.r.SocketsDir)
+ }
+ }
+ file := filepath.Join(f.r.SocketsDir, "file")
+ if err := os.WriteFile(file, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", file, nil), CodeNotASocket)
+ dir := filepath.Join(f.r.SocketsDir, "dir")
+ if err := os.Mkdir(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", dir, nil), CodeNotASocket)
+ noSocketWrite(t, f)
+ f.r.SocketsDir += "/."
+ wantOK(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", filepath.Dir(path)+"/./shop.sock", nil))
+ if row := f.row(t, "shop"); row.Socket != path {
+ t.Fatalf("unclean socket = %q", row.Socket)
+ }
+}
+
+func TestShareSocketUnreachable(t *testing.T) {
+ f, path, ln := socketFixture(t)
+ ln.(*net.UnixListener).SetUnlinkOnClose(false)
+ ln.Close()
+ wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", path, nil), CodeSocketUnreachable)
+ noSocketWrite(t, f)
+}
+
+func TestSocketOwnerForLifecycle(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ uid := uint32(os.Getuid())
+ wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, nil))
+ host := "shop." + testDomain
+ if gotPath, gotUID, ok := f.r.SocketOwnerFor(host); !ok || gotUID != uid || gotPath != path {
+ t.Fatalf("SocketOwnerFor(%q) = %q, %d, %v", host, gotPath, gotUID, ok)
+ }
+ if _, _, ok := f.r.SocketOwnerFor("missing." + testDomain); ok {
+ t.Fatal("unknown socket found")
+ }
+
+ wantOK(t, f.shareLive(t, uid, "shop", 8080))
+ if _, _, ok := f.r.SocketOwnerFor(host); ok {
+ t.Fatal("live link retained socket owner")
+ }
+ k, _ := f.r.Links.Get("shop")
+ k.Socket = path
+ if err := f.r.Links.Put(k); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, ok := f.r.SocketOwnerFor(host); ok {
+ t.Fatal("non-socket kind used as socket owner")
+ }
+ wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, nil))
+ wantOK(t, f.unshare(t, uid, "shop"))
+ if _, _, ok := f.r.SocketOwnerFor(host); ok {
+ t.Fatal("unshared socket found")
+ }
+ if _, err := os.Stat(path); err != nil {
+ t.Fatalf("unshare removed caller's socket: %v", err)
+ }
+ if f.row(t, "shop") != nil {
+ t.Fatal("unshare left row")
+ }
+}
+
+func TestSocketReshareSwitchesKindAndAllow(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ uid := uint32(os.Getuid())
+ wantOK(t, shareAllow(t, f, uid, KindLive, "shop", "", []string{"alice@github"}))
+ first, _ := f.r.Links.Get("shop")
+ for _, kind := range []Kind{KindSocket, KindFolder, KindSocket, KindLive, KindFolder, KindSocket} {
+ wantOK(t, shareAllow(t, f, uid, kind, "shop", path, []string{"bob@example.com"}))
+ k, _ := f.r.Links.Get("shop")
+ if !k.Created.Equal(first.Created) || !equal(k.Allow, []string{"bob@example.com"}) {
+ t.Fatalf("reshare = %+v", k)
+ }
+ rt := f.row(t, "shop")
+ switch kind {
+ case KindSocket:
+ if rt.Kind != "service" || rt.Socket != path || rt.Addr != "" || k.Port != 0 || k.Snapshot != "" {
+ t.Fatalf("socket = %+v, %+v", rt, k)
+ }
+ case KindLive:
+ if rt.Kind != "service" || rt.Socket != "" || rt.Addr != liveAddr(8080) || k.Socket != "" || k.Snapshot != "" {
+ t.Fatalf("live = %+v, %+v", rt, k)
+ }
+ case KindFolder:
+ if rt.Kind != "static" || rt.Socket != "" || rt.Addr != "" || k.Socket != "" || k.Port != 0 {
+ t.Fatalf("folder = %+v, %+v", rt, k)
+ }
+ }
+ if kind != KindFolder {
+ if _, err := os.Stat(filepath.Join(f.spool, "shop")); !os.IsNotExist(err) {
+ t.Fatalf("spool remains: %v", err)
+ }
+ }
+ }
+ for _, allow := range [][]string{{}, {"alice@github"}, nil} {
+ wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, allow))
+ if got := f.r.AllowFor("shop." + testDomain); !equal(got, allow) {
+ t.Fatalf("socket allow = %v", got)
+ }
+ }
+ fakeSocketUIDs(t, uid+1, uid+1)
+ wantCode(t, shareAllow(t, f, uid+1, KindSocket, "shop", path, []string{"other@example.com"}), CodeOwned)
+ wantCode(t, f.unshare(t, uid+1, "shop"), CodeNotYours)
+}
+
+func TestListSocketAnsweringAndPrivacy(t *testing.T) {
+ f, path, ln := socketFixture(t)
+ uid := uint32(os.Getuid())
+ wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, []string{"alice@github"}))
+ for _, caller := range []uint32{uid, uid + 1} {
+ got := f.list(t, caller)
+ if len(got) != 1 || got[0].Kind != KindSocket || got[0].Target != path || !got[0].Answering || !got[0].Private {
+ t.Fatalf("list = %+v", got)
+ }
+ if caller != uid && got[0].Allow != nil {
+ t.Fatalf("allow leaked: %+v", got)
+ }
+ if caller == uid && !equal(got[0].Allow, []string{"alice@github"}) {
+ t.Fatalf("owner list = %+v", got)
+ }
+ }
+ old := socketPeerUID
+ socketPeerUID = func(net.Conn) (uint32, error) { t.Error("list checked peer uid"); return 0, unix.EIO }
+ t.Cleanup(func() { socketPeerUID = old })
+ if got := f.list(t, uid); !got[0].Answering {
+ t.Fatal("list depended on peer uid")
+ }
+ ln.Close()
+ if got := f.list(t, uid); got[0].Answering {
+ t.Fatal("closed socket answering")
+ }
+}
+
+func TestSocketShareRollback(t *testing.T) {
+ for _, failure := range []string{"links-sync", "registry"} {
+ t.Run(failure, func(t *testing.T) {
+ f, path, _ := socketFixture(t)
+ uid := uint32(os.Getuid())
+ wantOK(t, shareAllow(t, f, uid, KindFolder, "shop", "", []string{"alice@github"}))
+ before, _ := f.r.Links.Get("shop")
+ if failure == "links-sync" {
+ failLinksSyncOnce(t)
+ } else {
+ if err := f.reg.Upsert(registry.Route{Host: "shop." + testDomain, Kind: "instance", Runtime: registry.RuntimeRootfsV1, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ wantCode(t, shareAllow(t, f, uid, KindSocket, "shop", path, []string{"bob@example.com"}), CodeInternal)
+ after, _ := f.r.Links.Get("shop")
+ if !reflect.DeepEqual(before, after) {
+ t.Fatalf("rollback = %+v, want %+v", after, before)
+ }
+ if got := readCurrent(t, f.spool, "shop", "index.html"); got != "shop" {
+ t.Fatalf("spool = %q", got)
+ }
+ checkOwnedRoutes(t, f)
+ })
+ }
+}
diff --git a/internal/devbox/registrar_socket_test.go b/internal/devbox/registrar_socket_test.go
new file mode 100644
index 000000000..023980677
--- /dev/null
+++ b/internal/devbox/registrar_socket_test.go
@@ -0,0 +1,300 @@
+package devbox
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "reflect"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func TestShareSocketRequiresConfiguredDirectory(t *testing.T) {
+ f := newFixture(t)
+ code := CodeSocketPath
+ if runtime.GOOS != "linux" {
+ code = CodeSocketUnsupported
+ }
+ wantCode(t, f.do(t, 1001, "POST", "/share/socket", strings.NewReader(`{"name":"shop","path":"/run/carlos-devbox/sockets/shop.sock"}`)), code)
+}
+
+func TestShareLiveStoresAllow(t *testing.T) {
+ f := newFixture(t)
+ wantOK(t, f.do(t, 1001, "POST", "/share/live", strings.NewReader(`{"name":"shop","port":8080,"allow":[" Alice@GitHub ","alice@github","bob@example.com"]}`)))
+ k, _ := f.r.Links.Get("shop")
+ data, err := json.Marshal(k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct {
+ Allow []string `json:"allow"`
+ }
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatal(err)
+ }
+ if !equal(got.Allow, []string{"alice@github", "bob@example.com"}) {
+ t.Fatalf("allow = %v", got.Allow)
+ }
+}
+
+func TestBadAllowLoginBeforeWrite(t *testing.T) {
+ f := newFixture(t)
+ wantCode(t, f.do(t, 1001, "POST", "/share/live", strings.NewReader(`{"name":"shop","port":8080,"allow":["alice @github"]}`)), "bad-allow")
+ if len(f.r.Links.All()) != 0 || f.row(t, "shop") != nil {
+ t.Fatal("invalid allow wrote state")
+ }
+}
+
+func shareAllow(t *testing.T, f *fixture, uid uint32, kind Kind, name, path string, allow []string) *httptest.ResponseRecorder {
+ t.Helper()
+ if kind == KindFolder {
+ q := url.Values{"name": {name}}
+ for _, login := range allow {
+ q.Add("allow", login)
+ }
+ return f.do(t, uid, "POST", "/share/folder?"+q.Encode(), bytes.NewReader(packSite(t, map[string]string{"index.html": "shop"})))
+ }
+ in := map[string]any{"name": name, "port": 8080, "path": path}
+ if allow != nil {
+ in["allow"] = allow
+ }
+ data, err := json.Marshal(in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return f.do(t, uid, "POST", "/share/"+string(kind), bytes.NewReader(data))
+}
+
+func TestAllowForReturnsList(t *testing.T) {
+ f := newFixture(t)
+ wantOK(t, shareAllow(t, f, 1001, KindLive, "shop", "", []string{"Alice@GitHub", "bob@example.com"}))
+ wantOK(t, f.shareLive(t, 1001, "open", 8080))
+ want := []string{"alice@github", "bob@example.com"}
+ for _, host := range []string{"shop." + testDomain, "SHOP.DEVBOX.EXAMPLE.COM", "shop." + testDomain + ".", "shop." + testDomain + ":443", "SHOP.DEVBOX.EXAMPLE.COM.:443"} {
+ got := f.r.AllowFor(host)
+ if !equal(got, want) {
+ t.Fatalf("AllowFor(%q) = %v", host, got)
+ }
+ got[0] = "changed@example.com"
+ }
+ for _, host := range []string{"open." + testDomain, "missing." + testDomain, "shop", testDomain, "shop.other.example.com", "shop." + testDomain + ".evil", "prefix.shop." + testDomain, "shop." + testDomain + ":443:444"} {
+ if got := f.r.AllowFor(host); got != nil {
+ t.Fatalf("AllowFor(%q) = %v, want nil", host, got)
+ }
+ }
+ f.r.Domain = strings.ToUpper(testDomain) + "."
+ if got := f.r.AllowFor("shop." + testDomain); !equal(got, want) {
+ t.Fatalf("configured domain match = %v", got)
+ }
+}
+
+func TestReshareReplacesAllow(t *testing.T) {
+ f := newFixture(t)
+ for _, kind := range []Kind{KindLive, KindFolder, KindLive} {
+ for _, allow := range [][]string{{"Alice@GitHub"}, {"bob@example.com"}, {}, {"alice@github"}, nil} {
+ wantOK(t, shareAllow(t, f, 1001, kind, "shop", "", allow))
+ want := make([]string, len(allow))
+ for i, login := range allow {
+ want[i] = strings.ToLower(login)
+ }
+ if got := f.r.AllowFor("shop." + testDomain); !equal(got, want) {
+ t.Fatalf("%s: allow = %v, want %v", kind, got, want)
+ }
+ before, _ := f.r.Links.Get("shop")
+ wantCode(t, shareAllow(t, f, 1002, kind, "shop", "", []string{"other@example.com"}), CodeOwned)
+ after, _ := f.r.Links.Get("shop")
+ if !reflect.DeepEqual(before, after) {
+ t.Fatal("other owner changed link")
+ }
+ }
+ }
+}
+
+func TestBadAllowLogin(t *testing.T) {
+ cases := map[string][]string{
+ "empty": {""}, "blank": {" \t "}, "space": {"alice @github"}, "tab": {"alice\t@github"},
+ "newline": {"alice\n@github"}, "control": {"alice\x00@github"}, "delete": {"alice\x7f@github"},
+ "non-ascii": {"alíce@github"}, "long": {strings.Repeat("a", 255)},
+ "too-many": make([]string, 65),
+ }
+ for i := range cases["too-many"] {
+ cases["too-many"][i] = "alice@github"
+ }
+ for name, allow := range cases {
+ t.Run(name, func(t *testing.T) {
+ for _, kind := range []Kind{KindLive, KindFolder, KindSocket} {
+ f := newFixture(t)
+ wantCode(t, shareAllow(t, f, 1001, kind, "shop", "", allow), CodeBadAllow)
+ if len(f.r.Links.All()) != 0 || f.row(t, "shop") != nil {
+ t.Fatalf("%s wrote state", kind)
+ }
+ if _, err := os.Stat(f.spool); !os.IsNotExist(err) {
+ t.Fatalf("%s spool: %v", kind, err)
+ }
+ wantOK(t, shareAllow(t, f, 1001, KindLive, "shop", "", []string{"alice@github"}))
+ before, _ := f.r.Links.Get("shop")
+ wantCode(t, shareAllow(t, f, 1002, kind, "shop", "", allow), CodeBadAllow)
+ after, _ := f.r.Links.Get("shop")
+ if !reflect.DeepEqual(before, after) {
+ t.Fatal("invalid allow changed existing link")
+ }
+ }
+ })
+ }
+ f := newFixture(t)
+ allow := []string{strings.Repeat("a", 254)}
+ for i := 1; i < 64; i++ {
+ allow = append(allow, fmt.Sprintf("alice%d@example.com", i))
+ }
+ wantOK(t, shareAllow(t, f, 1001, KindLive, "shop", "", allow))
+ if got := f.r.AllowFor("shop." + testDomain); !equal(got, allow) {
+ t.Fatalf("boundary allow = %v", got)
+ }
+}
+
+func TestListMarksPrivate(t *testing.T) {
+ f := newFixture(t)
+ wantOK(t, shareAllow(t, f, 1001, KindLive, "shop", "", []string{"alice@github"}))
+ wantOK(t, shareAllow(t, f, 1002, KindFolder, "site", "", []string{"bob@example.com"}))
+ wantOK(t, f.shareLive(t, 1001, "open", 8080))
+ for _, uid := range []uint32{1001, 1002, 1003} {
+ for _, entry := range f.list(t, uid) {
+ if entry.Private != (entry.Name != "open") {
+ t.Fatalf("private = %+v", entry)
+ }
+ if entry.OwnerUID == uid && entry.Private {
+ want := []string{"alice@github"}
+ if uid == 1002 {
+ want = []string{"bob@example.com"}
+ }
+ if !equal(entry.Allow, want) {
+ t.Fatalf("owner list = %+v", entry)
+ }
+ } else if entry.Allow != nil {
+ t.Fatalf("allow leaked: %+v", entry)
+ }
+ }
+ }
+ rec := f.do(t, 1003, "GET", "/list", nil)
+ if strings.Contains(rec.Body.String(), `"allow"`) || strings.Contains(rec.Body.String(), "@") {
+ t.Fatalf("wire leaked allow: %s", rec.Body)
+ }
+ if !strings.Contains(rec.Body.String(), `"private":false`) {
+ t.Fatal("public entry omitted private=false")
+ }
+}
+
+func TestLinksAllowCopiesAndPersistence(t *testing.T) {
+ f := newFixture(t)
+ k := sample("shop")
+ k.Allow = []string{"alice@github"}
+ if err := f.r.Links.Put(k); err != nil {
+ t.Fatal(err)
+ }
+ k.Allow[0] = "changed@example.com"
+ got, _ := f.r.Links.Get("shop")
+ if got.Allow[0] != "alice@github" {
+ t.Fatal("Put retained caller slice")
+ }
+ got.Allow[0] = "changed@example.com"
+ all := f.r.Links.All()
+ if all[0].Allow[0] != "alice@github" {
+ t.Fatal("Get exposed store slice")
+ }
+ all[0].Allow[0] = "changed@example.com"
+ got, _ = f.r.Links.Get("shop")
+ if got.Allow[0] != "alice@github" {
+ t.Fatal("All exposed store slice")
+ }
+ again, err := OpenLinks(f.linksPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ saved, _ := again.Get("shop")
+ if !reflect.DeepEqual(got, saved) {
+ t.Fatalf("disk = %+v, memory = %+v", saved, got)
+ }
+}
+
+func TestAllowForConcurrentReads(t *testing.T) {
+ f := newFixture(t)
+ k := sample("shop")
+ k.Allow = []string{"alice@github"}
+ if err := f.r.Links.Put(k); err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ for range 4 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for range 100 {
+ got := f.r.AllowFor("shop." + testDomain)
+ if len(got) != 1 || got[0] != "alice@github" {
+ t.Errorf("allow = %v", got)
+ return
+ }
+ got[0] = "changed@example.com"
+ }
+ }()
+ }
+ for range 20 {
+ if err := f.r.Links.Put(k); err != nil {
+ t.Fatal(err)
+ }
+ }
+ wg.Wait()
+}
+
+func TestSocketOwnerForSharedPath(t *testing.T) {
+ for _, names := range [][2]string{{"zzz", "copy"}, {"copy", "zzz"}} {
+ t.Run(names[0], func(t *testing.T) {
+ f := newFixture(t)
+ path := DefaultSocketsDir + "/shop.sock"
+ for i, name := range names {
+ link := sample(name)
+ link.Kind, link.Port, link.Socket = KindSocket, 0, path
+ link.OwnerUID = uint32(1001 + i)
+ if i == 1 {
+ link.Allow = []string{"bob@example.com"}
+ }
+ if err := f.r.Links.Put(link); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for i, name := range names {
+ for _, host := range []string{name + "." + testDomain, strings.ToUpper(name + "." + testDomain), name + "." + testDomain + ".", name + "." + testDomain + ":443", strings.ToUpper(name+"."+testDomain) + ".:443"} {
+ gotPath, uid, ok := f.r.SocketOwnerFor(host)
+ if !ok || gotPath != path || uid != uint32(1001+i) {
+ t.Fatalf("SocketOwnerFor(%q) = %q, %d, %v", host, gotPath, uid, ok)
+ }
+ allow := f.r.AllowFor(host)
+ if i == 0 && allow != nil || i == 1 && !equal(allow, []string{"bob@example.com"}) {
+ t.Fatalf("AllowFor(%q) = %v", host, allow)
+ }
+ }
+ }
+ link := sample("live")
+ link.Socket = path
+ if err := f.r.Links.Put(link); err != nil {
+ t.Fatal(err)
+ }
+ for _, host := range []string{"live." + testDomain, "missing." + testDomain, "zzz.other.example.com", "copy." + testDomain + ".evil", "nested.copy." + testDomain, "copy", testDomain, "copy." + testDomain + ":443:444"} {
+ gotPath, uid, ok := f.r.SocketOwnerFor(host)
+ if ok || gotPath != "" || uid != 0 {
+ t.Fatalf("SocketOwnerFor(%q) = %q, %d, %v; want no socket", host, gotPath, uid, ok)
+ }
+ }
+ f.r.Domain = strings.ToUpper(testDomain) + "."
+ if gotPath, uid, ok := f.r.SocketOwnerFor(names[1] + "." + testDomain); !ok || gotPath != path || uid != 1002 {
+ t.Fatalf("configured domain match = %q, %d, %v", gotPath, uid, ok)
+ }
+ })
+ }
+}
diff --git a/internal/devbox/registrar_test.go b/internal/devbox/registrar_test.go
index 75ce97a70..9633162f2 100644
--- a/internal/devbox/registrar_test.go
+++ b/internal/devbox/registrar_test.go
@@ -133,11 +133,12 @@ func wantCode(t *testing.T, rec *httptest.ResponseRecorder, code string) WireErr
if rec.Code < 400 {
t.Fatalf("refusal %q answered %d", code, rec.Code)
}
- // R1: codes and data only. The body has no field beyond code and owner.
+ // R1: codes and data only. A socket-path refusal may name the service
+ // sockets directory; other refusals carry only code and owner.
var raw map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &raw)
for k := range raw {
- if k != "code" && k != "owner" {
+ if k != "code" && k != "owner" && !(k == "socketsDir" && code == CodeSocketPath) {
t.Fatalf("wire error carries %q: %s", k, rec.Body)
}
}
@@ -296,7 +297,7 @@ func TestShareRefusesOtherOwnersName(t *testing.T) {
}
after, _ := f.r.Links.Get("shop")
- if after != before {
+ if !reflect.DeepEqual(after, before) {
t.Fatalf("link changed: %+v -> %+v", before, after)
}
if rowAfter := f.row(t, "shop"); rowAfter.Addr != rowBefore.Addr || rowAfter.Kind != rowBefore.Kind {
@@ -339,13 +340,13 @@ func TestShareRollsBackLinksOnRegistryFailure(t *testing.T) {
if rec := g.shareLive(t, 1001, "mock", 6000); rec.Code != 500 {
t.Fatalf("reshare live over a rootfs row = %d %s", rec.Code, rec.Body)
}
- if k, _ := g.r.Links.Get("mock"); k != k0 {
+ if k, _ := g.r.Links.Get("mock"); !reflect.DeepEqual(k, k0) {
t.Fatalf("live reshare not rolled back: %+v -> %+v", k0, k)
}
if rec := g.shareFolder(t, 1001, "mock", packSite(t, map[string]string{"index.html": "two"})); rec.Code != 500 {
t.Fatalf("reshare folder over a rootfs row = %d %s", rec.Code, rec.Body)
}
- if k, _ := g.r.Links.Get("mock"); k != k0 {
+ if k, _ := g.r.Links.Get("mock"); !reflect.DeepEqual(k, k0) {
t.Fatalf("folder reshare not rolled back: %+v -> %+v", k0, k)
}
if got := readCurrent(t, g.spool, "mock", "index.html"); got != "one" {
@@ -359,7 +360,7 @@ func TestShareRollsBackLinksOnRegistryFailure(t *testing.T) {
}
if again, err := OpenLinks(g.linksPath); err != nil {
t.Fatal(err)
- } else if k, _ := again.Get("mock"); k != k0 {
+ } else if k, _ := again.Get("mock"); !reflect.DeepEqual(k, k0) {
t.Fatalf("on disk: %+v", k)
}
@@ -373,7 +374,7 @@ func TestShareRollsBackLinksOnRegistryFailure(t *testing.T) {
if rec.Code < 500 {
t.Fatalf("share with a closed registry = %d %s", rec.Code, rec.Body)
}
- if after, _ := f.r.Links.Get("shop"); after != before {
+ if after, _ := f.r.Links.Get("shop"); !reflect.DeepEqual(after, before) {
t.Fatalf("link not rolled back: %+v -> %+v", before, after)
}
rec = f.shareLive(t, 1001, "fresh", 6000)
@@ -1002,7 +1003,7 @@ func TestShareFolderSyncFailureRestoresCurrent(t *testing.T) {
if target, _ := os.Readlink(filepath.Join(f.spool, "shop", "current")); target != k0.Snapshot {
t.Fatalf("current -> %q, want %q", target, k0.Snapshot)
}
- if k, _ := f.r.Links.Get("shop"); k != k0 {
+ if k, _ := f.r.Links.Get("shop"); !reflect.DeepEqual(k, k0) {
t.Fatalf("link not restored: %+v -> %+v", k0, k)
}
if names := dirNames(t, filepath.Join(f.spool, "shop")); !equal(names, sorted("current", k0.Snapshot)) {
@@ -1165,10 +1166,10 @@ func TestShareRollsBackUnsyncedLink(t *testing.T) {
if _, err := os.Lstat(filepath.Join(f.spool, "page")); !os.IsNotExist(err) {
t.Fatalf("page: spool dir left: %v", err)
}
- if k, _ := again.Get("live"); k != live0 {
+ if k, _ := again.Get("live"); !reflect.DeepEqual(k, live0) {
t.Fatalf("live on disk %+v, want %+v", k, live0)
}
- if k, _ := again.Get("site"); k != site0 {
+ if k, _ := again.Get("site"); !reflect.DeepEqual(k, site0) {
t.Fatalf("site on disk %+v, want %+v", k, site0)
}
if rt := f.row(t, "live"); rt.Addr != liveAddr(5173) {
@@ -1212,7 +1213,7 @@ func TestUnshareRollsBackUnsyncedLink(t *testing.T) {
wantCode(t, f.unshare(t, 1001, "site"), CodeInternal)
again := checkOwnedRoutes(t, f)
- if k, _ := again.Get("shop"); k != shop0 {
+ if k, _ := again.Get("shop"); !reflect.DeepEqual(k, shop0) {
t.Fatalf("shop on disk %+v, want %+v", k, shop0)
}
if rt := f.row(t, "shop"); rt == nil || rt.Addr != liveAddr(5173) {
diff --git a/internal/devbox/socketcheck_linux.go b/internal/devbox/socketcheck_linux.go
new file mode 100644
index 000000000..a958f643e
--- /dev/null
+++ b/internal/devbox/socketcheck_linux.go
@@ -0,0 +1,55 @@
+//go:build linux
+
+package devbox
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "path/filepath"
+
+ "golang.org/x/sys/unix"
+)
+
+// Tests can substitute ownership without chown or a second Unix account.
+var (
+ socketFstat = unix.Fstat
+ socketPeerUID = PeerUID
+)
+
+func checkSocket(ctx context.Context, dir, path string, uid uint32) (string, *refusal) {
+ path = filepath.Clean(path)
+ base := filepath.Base(path)
+ if dir == "" || !filepath.IsAbs(path) || filepath.Dir(path) != filepath.Clean(dir) || base == "." || base == ".." {
+ return "", refuse(http.StatusBadRequest, CodeSocketPath)
+ }
+ fd, err := unix.Open(path, unix.O_PATH|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if err != nil {
+ if errors.Is(err, unix.ELOOP) {
+ return "", refuse(http.StatusBadRequest, CodeNotASocket)
+ }
+ return "", refuse(http.StatusBadRequest, CodeSocketPath)
+ }
+ defer unix.Close(fd)
+ var stat unix.Stat_t
+ if err := socketFstat(fd, &stat); err != nil {
+ return "", refuse(http.StatusBadRequest, CodeSocketPath)
+ }
+ // O_PATH with O_NOFOLLOW can open the symlink itself; fstat refuses it.
+ if stat.Mode&unix.S_IFMT != unix.S_IFSOCK {
+ return "", refuse(http.StatusBadRequest, CodeNotASocket)
+ }
+ if stat.Uid != uid {
+ return "", refuse(http.StatusForbidden, CodeSocketNotYours)
+ }
+ c, err := connectSocket(ctx, path)
+ if err != nil {
+ return "", refuse(http.StatusBadRequest, CodeSocketUnreachable)
+ }
+ defer c.Close()
+ peer, err := socketPeerUID(c)
+ if err != nil || peer != uid {
+ return "", refuse(http.StatusForbidden, CodeSocketNotYours)
+ }
+ return path, nil
+}
diff --git a/internal/devbox/socketcheck_other.go b/internal/devbox/socketcheck_other.go
new file mode 100644
index 000000000..3050fdd48
--- /dev/null
+++ b/internal/devbox/socketcheck_other.go
@@ -0,0 +1,12 @@
+//go:build !linux
+
+package devbox
+
+import (
+ "context"
+ "net/http"
+)
+
+func checkSocket(context.Context, string, string, uint32) (string, *refusal) {
+ return "", refuse(http.StatusBadRequest, CodeSocketUnsupported)
+}
diff --git a/internal/edge/devbox.go b/internal/edge/devbox.go
index b85c7c1c4..6987d871f 100644
--- a/internal/edge/devbox.go
+++ b/internal/edge/devbox.go
@@ -36,10 +36,24 @@ import (
// 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
+ // Identity resolves visitors; nil, errors and timeouts mean anonymous.
+ // Who must honor its context, which has a maximum two-second deadline.
+ Identity VisitorIdentity
+ // SharedNodes names devices whose visitors are anonymous, matched
+ // case-insensitively. The ListenAddr IP is always anonymous too.
+ SharedNodes []string
+ // AllowFor reads the current login list for the unmodified request Host.
+ // A nil callback or empty list allows anonymous visitors.
+ AllowFor func(host string) []string
+ // SocketOwnerFor returns the expected socket path and listener UID for
+ // the unmodified request Host. Nil or ok=false refuses socket routes.
+ // Each socket request uses a fresh connection and peer-UID check: pooling
+ // would let an earlier connection bypass a changed owner expectation.
+ SocketOwnerFor func(host string) (path string, uid uint32, ok bool)
+ 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
// Listener, when set, is served on instead of binding ListenAddr: on
// macOS launchd binds port 443 and hands the socket over (#488). It
// must be on ListenAddr exactly (CheckDevboxListener). ServeDevbox
@@ -206,8 +220,10 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error
// ReadHeaderTimeout for the same slow-header reason as Run's servers,
// and no Read/WriteTimeout, which would cut proxied WebSockets.
+ selfHost, _, _ := net.SplitHostPort(cfg.ListenAddr)
+ selfIP, _ := netip.ParseAddr(selfHost) // checked before building the edge
srv := &http.Server{
- Handler: e,
+ Handler: devboxFront(e, cfg, selfIP),
TLSConfig: &tls.Config{
GetCertificate: devboxGetCertificate(w),
// No acme-tls/1: there is no per-host order for it to answer.
@@ -259,6 +275,7 @@ func newDevboxEdge(cfg DevboxConfig) (*Edge, error) {
if err != nil {
return nil, fmt.Errorf("edge: devbox: %w", err)
}
+ e.devbox = true
WithLocalStatic(cfg.SpoolRoot)(e)
e.guard = guardOff
e.rateMode = RateOff
diff --git a/internal/edge/devboxfront.go b/internal/edge/devboxfront.go
new file mode 100644
index 000000000..f3a38455b
--- /dev/null
+++ b/internal/edge/devboxfront.go
@@ -0,0 +1,198 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "html"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/netip"
+ "strings"
+ "time"
+)
+
+// Approved private-page copy (#486 A, DBX-C107/C108).
+const devboxPrivateTitle = "This link is private"
+const devboxPrivateSentence = "Only the people it was shared with can open it, from their own devices on the tailnet."
+
+const devboxIdentityTimeout = 2 * time.Second
+
+type devboxFrontKey struct{}
+
+type devboxSocketOwner struct {
+ path string
+ uid uint32
+}
+
+type devboxFrontRequest struct {
+ visitor *Visitor
+ socketOwner *devboxSocketOwner
+}
+
+func devboxFront(next http.Handler, cfg DevboxConfig, selfIP netip.Addr) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ stripVisitorHeaders(r.Header)
+ stripVisitorHeaders(r.Trailer)
+ if r.Body != nil && r.Body != http.NoBody {
+ r.Body = &devboxTrailerBody{ReadCloser: r.Body, request: r}
+ }
+ var visitor Visitor
+ var known bool
+ remote, err := netip.ParseAddrPort(r.RemoteAddr)
+ if err == nil {
+ remote = netip.AddrPortFrom(remote.Addr().Unmap(), remote.Port())
+ if cfg.Identity != nil {
+ lookupCtx, cancel := context.WithTimeout(r.Context(), devboxIdentityTimeout)
+ visitor, known, err = cfg.Identity.Who(lookupCtx, remote)
+ known = known && err == nil && lookupCtx.Err() == nil
+ cancel()
+ }
+ if anonymousSource(remote.Addr(), selfIP, visitor, cfg.SharedNodes) {
+ known = false
+ }
+ }
+ var allow []string
+ if cfg.AllowFor != nil {
+ allow = cfg.AllowFor(r.Host)
+ }
+ if len(allow) > 0 {
+ allowed := false
+ if known {
+ for _, login := range allow {
+ if strings.EqualFold(visitor.Login, login) {
+ allowed = true
+ break
+ }
+ }
+ }
+ if !allowed {
+ devboxPrivate(w)
+ return
+ }
+ }
+ front := devboxFrontRequest{}
+ if known {
+ setVisitorHeaders(r.Header, visitor)
+ front.visitor = &visitor
+ }
+ if cfg.SocketOwnerFor != nil {
+ if path, uid, ok := cfg.SocketOwnerFor(r.Host); ok {
+ front.socketOwner = &devboxSocketOwner{path: path, uid: uid}
+ }
+ }
+ next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), devboxFrontKey{}, front)))
+ })
+}
+
+// HTTP request trailers are populated at EOF. Strip again before a handler
+// can read them; stripping only the initial declarations leaves late values.
+type devboxTrailerBody struct {
+ io.ReadCloser
+ request *http.Request
+}
+
+func (b *devboxTrailerBody) Read(p []byte) (int, error) {
+ n, err := b.ReadCloser.Read(p)
+ if err == io.EOF {
+ stripVisitorHeaders(b.request.Trailer)
+ }
+ return n, err
+}
+
+func stripVisitorHeaders(h http.Header) {
+ for key := range h {
+ // CGI, Rack and WSGI fold underscores and hyphens to the same key.
+ name := strings.ReplaceAll(key, "_", "-")
+ if strings.EqualFold(name, "Carlos-Visitor-Login") || strings.EqualFold(name, "Carlos-Visitor-Name") || strings.EqualFold(name, "Carlos-Visitor-Node") {
+ delete(h, key)
+ }
+ }
+}
+
+func setVisitorHeaders(h http.Header, v Visitor) {
+ for _, field := range []struct{ name, value string }{
+ {"Carlos-Visitor-Login", v.Login}, {"Carlos-Visitor-Name", v.Name}, {"Carlos-Visitor-Node", v.Node},
+ } {
+ printable := true
+ for i := 0; i < len(field.value); i++ {
+ if field.value[i] < 0x20 || field.value[i] > 0x7e {
+ printable = false
+ break
+ }
+ }
+ if printable {
+ h.Set(field.name, field.value)
+ }
+ }
+}
+
+func devboxPrivate(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.WriteHeader(http.StatusForbidden)
+ fmt.Fprintf(w, "<!doctype html><html><head><meta charset=\"utf-8\"><title>%s</title></head><body><h1>%s</h1><p>%s</p></body></html>",
+ html.EscapeString(devboxPrivateTitle), html.EscapeString(devboxPrivateTitle), html.EscapeString(devboxPrivateSentence))
+}
+
+// Only newDevboxEdge installs these hooks. Rewrite runs after hop-header
+// removal, so a client cannot suppress identity with Connection header tokens.
+func configureDevboxProxy(p *httputil.ReverseProxy, socketPath string) {
+ rewrite := p.Rewrite
+ p.Rewrite = func(pr *httputil.ProxyRequest) {
+ rewrite(pr)
+ stripVisitorHeaders(pr.Out.Trailer)
+ if front, ok := pr.In.Context().Value(devboxFrontKey{}).(devboxFrontRequest); ok {
+ stripVisitorHeaders(pr.Out.Header)
+ if front.visitor != nil {
+ setVisitorHeaders(pr.Out.Header, *front.visitor)
+ }
+ }
+ }
+ p.Transport = devboxProxyTransport{base: p.Transport, socketPath: socketPath}
+}
+
+var errDevboxSocketOwner = errors.New("edge: devbox socket owner mismatch")
+
+type devboxProxyTransport struct {
+ base http.RoundTripper
+ socketPath string
+}
+
+func (t devboxProxyTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ front, _ := r.Context().Value(devboxFrontKey{}).(devboxFrontRequest)
+ expected := front.socketOwner
+ if expected == nil {
+ if t.socketPath != "" {
+ return nil, errDevboxSocketOwner
+ }
+ return t.base.RoundTrip(r)
+ }
+ if t.socketPath == "" || t.socketPath != expected.path {
+ return nil, errDevboxSocketOwner
+ }
+ base, ok := t.base.(*http.Transport)
+ if !ok {
+ return nil, errDevboxSocketOwner
+ }
+ // An owner can change between requests without an edge reload. Each
+ // socket request needs its own checked connection, never an idle pool's.
+ tr := base.Clone()
+ tr.DisableKeepAlives = true
+ tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
+ conn, err := dialUnixWithRetry(ctx, &net.Dialer{}, t.socketPath)
+ if err != nil {
+ return nil, err
+ }
+ uid, err := devboxPeerUID(conn)
+ if err != nil || uid != expected.uid {
+ conn.Close()
+ return nil, errDevboxSocketOwner
+ }
+ return conn, nil
+ }
+ return tr.RoundTrip(r)
+}
diff --git a/internal/edge/devboxfront_test.go b/internal/edge/devboxfront_test.go
new file mode 100644
index 000000000..6743ee9dc
--- /dev/null
+++ b/internal/edge/devboxfront_test.go
@@ -0,0 +1,720 @@
+package edge
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+var frontVisitor = Visitor{Login: "alice@github", Name: "Alice Example", Node: "laptop"}
+var frontSelf = netip.MustParseAddr("100.64.0.1")
+
+func frontIdentity(v Visitor) VisitorIdentity {
+ return visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { return v, true, nil })
+}
+
+func frontRequest() *http.Request {
+ r := httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil)
+ r.RemoteAddr = "100.64.0.2:12345"
+ return r
+}
+
+func assertNoVisitorHeaders(t *testing.T, h http.Header) {
+ t.Helper()
+ for k := range h {
+ for _, name := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} {
+ if strings.ToUpper(strings.ReplaceAll(k, "-", "_")) == strings.ToUpper(strings.ReplaceAll(name, "-", "_")) {
+ t.Errorf("visitor header remains: %q = %q", k, h[k])
+ }
+ }
+ }
+}
+
+// CGI/Rack/WSGI map every separator combination to the same variable.
+var frontVisitorAliases = []string{
+ "cArLoS_Visitor_Login", "Carlos_Visitor-Login", "Carlos-Visitor_Login",
+ "cArLoS_Visitor_Name", "Carlos_Visitor-Name", "Carlos-Visitor_Name",
+ "cArLoS_Visitor_Node", "Carlos_Visitor-Node", "Carlos-Visitor_Node",
+}
+
+func assertNoVisitorAliases(t *testing.T, h http.Header) {
+ t.Helper()
+ rest := h.Clone()
+ for _, name := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} {
+ rest.Del(name)
+ }
+ assertNoVisitorHeaders(t, rest)
+}
+
+func TestFrontStripsVisitorHeaders(t *testing.T) {
+ for _, upgrade := range []bool{false, true} {
+ t.Run(map[bool]string{false: "ordinary", true: "upgrade"}[upgrade], func(t *testing.T) {
+ r := frontRequest()
+ r.Header = http.Header{
+ "Carlos-Visitor-Login": {"forged"}, "cArLoS-vIsItOr-LoGiN": {"forged too"},
+ "carlos-visitor-name": {"forged"}, "CARLOS-VISITOR-NODE": {"forged"},
+ }
+ for _, name := range frontVisitorAliases {
+ r.Header[name] = []string{"forged alias"}
+ }
+ if upgrade {
+ r.Header.Set("Connection", "Upgrade")
+ r.Header.Set("Upgrade", "websocket")
+ }
+ calls := 0
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ assertNoVisitorHeaders(t, r.Header)
+ return Visitor{}, false, nil
+ })}
+ reached := false
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ reached = true
+ assertNoVisitorHeaders(t, r.Header)
+ }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r)
+ if !reached || calls != 1 {
+ t.Fatalf("next=%v lookup calls=%d", reached, calls)
+ }
+ })
+ }
+}
+
+func TestFrontSetsIdentity(t *testing.T) {
+ r := frontRequest()
+ r.RemoteAddr = "[::ffff:100.64.0.2]:12345"
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(_ context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ if remote != netip.MustParseAddrPort("100.64.0.2:12345") {
+ t.Errorf("remote = %v", remote)
+ }
+ return frontVisitor, true, nil
+ })}
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} {
+ if got := r.Header.Get(k); got != want {
+ t.Errorf("%s = %q, want %q", k, got, want)
+ }
+ }
+ }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r)
+}
+
+func assertFrontAnonymous(t *testing.T, cfg DevboxConfig, remote string) {
+ t.Helper()
+ for _, private := range []bool{false, true} {
+ calls := 0
+ cfg.AllowFor = func(string) []string {
+ if private {
+ return []string{frontVisitor.Login}
+ }
+ return nil
+ }
+ h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ assertNoVisitorHeaders(t, r.Header)
+ }), cfg, frontSelf)
+ r := frontRequest()
+ r.RemoteAddr = remote
+ r.Header.Set("Carlos-Visitor-Login", frontVisitor.Login)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if private {
+ if w.Code != http.StatusForbidden || calls != 0 {
+ t.Fatalf("private: code=%d next calls=%d", w.Code, calls)
+ }
+ } else if w.Code != http.StatusOK || calls != 1 {
+ t.Fatalf("open: code=%d next calls=%d", w.Code, calls)
+ }
+ }
+}
+
+func TestFrontSelfIPIsAnonymous(t *testing.T) {
+ assertFrontAnonymous(t, DevboxConfig{Identity: frontIdentity(frontVisitor)}, "[::ffff:100.64.0.1]:12345")
+}
+func TestFrontSharedNodeIsAnonymous(t *testing.T) {
+ assertFrontAnonymous(t, DevboxConfig{Identity: frontIdentity(frontVisitor), SharedNodes: []string{"LAPTOP"}}, "100.64.0.2:12345")
+}
+func TestFrontNilIdentityIsAnonymous(t *testing.T) {
+ assertFrontAnonymous(t, DevboxConfig{}, "100.64.0.2:12345")
+}
+func TestFrontMalformedRemoteIsAnonymous(t *testing.T) {
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ t.Error("lookup called for invalid remote")
+ return frontVisitor, true, nil
+ })}
+ for _, remote := range []string{"", "100.64.0.2", "laptop:12345", "100.64.0.2:bad"} {
+ assertFrontAnonymous(t, cfg, remote)
+ }
+}
+func TestFrontAllowRefusesAnonymous(t *testing.T) {
+ for _, err := range []error{nil, errors.New("lookup failed")} {
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ return frontVisitor, err != nil, err
+ })}
+ assertFrontAnonymous(t, cfg, "100.64.0.2:12345")
+ }
+}
+func TestFrontOpenLinkServesAnonymous(t *testing.T) {
+ calls := 0
+ cfg := DevboxConfig{}
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; assertNoVisitorHeaders(t, r.Header) }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest())
+ if calls != 1 {
+ t.Fatalf("next calls=%d", calls)
+ }
+}
+
+func TestFrontAllowRefusesOthers(t *testing.T) {
+ for _, upgrade := range []bool{false, true} {
+ r := frontRequest()
+ if upgrade {
+ r.Header.Set("Connection", "Upgrade")
+ r.Header.Set("Upgrade", "websocket")
+ }
+ cfg := DevboxConfig{Identity: frontIdentity(frontVisitor), AllowFor: func(host string) []string {
+ if host != r.Host {
+ t.Errorf("host = %q, want %q", host, r.Host)
+ }
+ return []string{"bob@github", "*@github"}
+ }}
+ w := httptest.NewRecorder()
+ devboxFront(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("refused request reached next") }), cfg, frontSelf).ServeHTTP(w, r)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("code=%d", w.Code)
+ }
+ for k, want := range map[string]string{"Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"} {
+ if got := w.Header().Get(k); got != want {
+ t.Errorf("%s = %q, want %q", k, got, want)
+ }
+ }
+ body := w.Body.String()
+ for _, want := range []string{"<title>This link is private</title>", "<h1>This link is private</h1>", "<p>Only the people it was shared with can open it, from their own devices on the tailnet.</p>"} {
+ if !strings.Contains(body, want) {
+ t.Errorf("body %q lacks %q", body, want)
+ }
+ }
+ for _, secret := range []string{"bob@github", "*@github", "owner", frontVisitor.Login} {
+ if strings.Contains(strings.ToLower(body), strings.ToLower(secret)) {
+ t.Errorf("body discloses %q", secret)
+ }
+ }
+ }
+}
+
+func TestFrontAllowListChangeTakesEffect(t *testing.T) {
+ allow := []string{"ALICE@GITHUB"}
+ cfg := DevboxConfig{Identity: frontIdentity(frontVisitor), AllowFor: func(host string) []string {
+ if host != "SHOP.Example.com.:443" {
+ t.Errorf("host changed: %q", host)
+ }
+ return allow
+ }}
+ h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }), cfg, frontSelf)
+ for _, step := range []struct {
+ allow []string
+ code int
+ }{
+ {allow, http.StatusNoContent}, {[]string{"bob@github"}, http.StatusForbidden}, {nil, http.StatusNoContent},
+ } {
+ allow = step.allow
+ r := frontRequest()
+ r.Host = "SHOP.Example.com.:443"
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != step.code {
+ t.Errorf("allow=%v code=%d want=%d", allow, w.Code, step.code)
+ }
+ }
+}
+
+func TestFrontDropsNonPrintableHeaderValues(t *testing.T) {
+ for _, bad := range []string{"\x00", "\t", "\r\n", "\x1f", "\x7f", "é", "\xff"} {
+ for _, field := range []string{"login", "name", "node"} {
+ t.Run(field+"/"+bad, func(t *testing.T) {
+ v := frontVisitor
+ key := "Carlos-Visitor-" + field
+ switch field {
+ case "login":
+ v.Login += bad
+ case "name":
+ v.Name += bad
+ case "node":
+ v.Node += bad
+ }
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if _, exists := r.Header[http.CanonicalHeaderKey(key)]; exists {
+ t.Errorf("invalid %s header was set", field)
+ }
+ if len(r.Header) != 2 {
+ t.Errorf("headers = %v, want the other two values", r.Header)
+ }
+ }), DevboxConfig{Identity: frontIdentity(v)}, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest())
+ })
+ }
+ }
+}
+
+func frontSocketBackend(t *testing.T, handler http.Handler) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "up.sock")
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: handler}}
+ srv.Start()
+ t.Cleanup(srv.Close)
+ return path
+}
+
+func TestDevboxFrontUnixUpstreamIdentityAndOwner(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ var calls atomic.Int32
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ assertNoVisitorAliases(t, r.Header)
+ for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} {
+ if got := r.Header.Get(k); got != want {
+ t.Errorf("upstream %s=%q want=%q", k, got, want)
+ }
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ wantPath, wantUID := path, uint32(os.Getuid())
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(host string) (string, uint32, bool) {
+ if host != "shop.example.com:443" {
+ t.Errorf("socket host changed: %q", host)
+ }
+ return wantPath, wantUID, true
+ }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := devboxFront(e, cfg, frontSelf)
+ for _, step := range []struct {
+ name string
+ path string
+ uid uint32
+ code int
+ }{
+ {"match", path, uint32(os.Getuid()), http.StatusNoContent},
+ {"uid mismatch after success", path, uint32(os.Getuid()) + 1, http.StatusBadGateway},
+ {"path mismatch", path + ".other", uint32(os.Getuid()), http.StatusBadGateway},
+ {"match again", path, uint32(os.Getuid()), http.StatusNoContent},
+ } {
+ t.Run(step.name, func(t *testing.T) {
+ wantPath, wantUID = step.path, step.uid
+ r := frontRequest()
+ r.Host = "shop.example.com:443"
+ r.Header.Set("Carlos-Visitor-Login", "mallory@github")
+ for _, name := range frontVisitorAliases {
+ r.Header[name] = []string{"forged alias"}
+ }
+ r.Header["cArLoS-vIsItOr-LoGiN"] = []string{"forged"}
+ r.Header.Set("Connection", "Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node")
+
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != step.code {
+ t.Fatalf("code=%d want=%d body=%s", w.Code, step.code, w.Body)
+ }
+ })
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("upstream calls=%d, want 2", calls.Load())
+ }
+}
+
+func TestDevboxFrontSocketExpectationRefusesTCP(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("socket expectation reached TCP upstream") }))
+ defer upstream.Close()
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Addr: upstream.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), SocketOwnerFor: func(string) (string, uint32, bool) {
+ return "/run/carlos-devbox/sockets/shop.sock", uint32(os.Getuid()), true
+ }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ devboxFront(e, cfg, frontSelf).ServeHTTP(w, frontRequest())
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("code=%d want 502", w.Code)
+ }
+}
+
+func TestFrontOrderAndHostLookups(t *testing.T) {
+ r := frontRequest()
+ r.Host = "SHOP.Example.com.:443"
+ r.Header.Set("Carlos-Visitor-Login", "forged")
+ var order []string
+ cfg := DevboxConfig{
+ Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ assertNoVisitorHeaders(t, r.Header)
+ order = append(order, "identity")
+ return frontVisitor, true, nil
+ }),
+ AllowFor: func(host string) []string {
+ assertNoVisitorHeaders(t, r.Header)
+ if host != r.Host {
+ t.Errorf("allow host=%q want=%q", host, r.Host)
+ }
+ order = append(order, "allow")
+ return []string{"ALICE@GITHUB"}
+ },
+ SocketOwnerFor: func(host string) (string, uint32, bool) {
+ if host != r.Host {
+ t.Errorf("socket host=%q want=%q", host, r.Host)
+ }
+ if r.Header.Get("Carlos-Visitor-Login") != frontVisitor.Login {
+ t.Error("identity not set after allow")
+ }
+ order = append(order, "socket")
+ return "/run/carlos-devbox/sockets/shop.sock", 1234, true
+ },
+ }
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ order = append(order, "next")
+ front := r.Context().Value(devboxFrontKey{}).(devboxFrontRequest)
+ if front.socketOwner == nil || front.socketOwner.path != "/run/carlos-devbox/sockets/shop.sock" || front.socketOwner.uid != 1234 {
+ t.Errorf("socket owner=%+v", front.socketOwner)
+ }
+ }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r)
+ if got := strings.Join(order, ","); got != "identity,allow,socket,next" {
+ t.Errorf("order=%s", got)
+ }
+}
+
+func TestFrontSelfStillLooksUpIdentity(t *testing.T) {
+ calls := 0
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { calls++; return frontVisitor, true, nil })}
+ assertFrontAnonymous(t, cfg, "100.64.0.1:12345")
+ if calls != 2 {
+ t.Errorf("lookup calls=%d want=2", calls)
+ }
+}
+
+func TestDevboxSocketExpectationAbsent(t *testing.T) {
+ var calls atomic.Int32
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir()}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, mode := range []string{"nil callback", "unknown host", "no front door"} {
+ t.Run(mode, func(t *testing.T) {
+ if mode == "unknown host" {
+ cfg.SocketOwnerFor = func(string) (string, uint32, bool) { return "ignored", ^uint32(0), false }
+ }
+ var h http.Handler = devboxFront(e, cfg, frontSelf)
+ if mode == "no front door" {
+ h = e
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, frontRequest())
+ if w.Code != http.StatusBadGateway {
+ t.Errorf("code=%d want=502", w.Code)
+ }
+ })
+ }
+ if got := calls.Load(); got != 0 {
+ t.Errorf("unchecked upstream calls=%d want=0", got)
+ }
+ ordinary, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ ordinary.ServeHTTP(w, frontRequest())
+ if w.Code != http.StatusNoContent || calls.Load() != 1 {
+ t.Errorf("ordinary edge code=%d calls=%d want=204,1", w.Code, calls.Load())
+ }
+}
+
+func TestUnixProxyWithoutDevboxExpectation(t *testing.T) {
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Carlos-Visitor-Login") != "unchanged" {
+ t.Error("normal Unix proxy changed visitor header")
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ p := unixProxy(path)
+ tr, ok := p.Transport.(*http.Transport)
+ if !ok {
+ t.Fatal("normal Unix proxy transport changed")
+ }
+ defer tr.CloseIdleConnections()
+ r := frontRequest()
+ r.Header.Set("Carlos-Visitor-Login", "unchanged")
+ w := httptest.NewRecorder()
+ p.ServeHTTP(w, r)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("code=%d want=204", w.Code)
+ }
+}
+
+func TestFrontPrintableASCIIBoundaries(t *testing.T) {
+ v := Visitor{Login: " ~", Name: " ~", Node: " ~"}
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ for _, key := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} {
+ if got := r.Header.Get(key); got != " ~" {
+ t.Errorf("%s=%q", key, got)
+ }
+ }
+ }), DevboxConfig{Identity: frontIdentity(v)}, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest())
+}
+
+func frontTrailerRequest(t *testing.T) *http.Request {
+ t.Helper()
+ declared := append([]string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node", "X-Other"}, frontVisitorAliases...)
+ raw := "POST / HTTP/1.1\r\nHost: shop.example.com\r\nTransfer-Encoding: chunked\r\nTrailer: " + strings.Join(declared, ", ") + "\r\n\r\n" +
+ "4\r\nbody\r\n0\r\ncArLoS-vIsItOr-LoGiN: mallory@github\r\ncarlos-visitor-name: Mallory\r\nCARLOS-VISITOR-NODE: forged\r\nX-Other: preserved\r\n"
+ for _, name := range frontVisitorAliases {
+ raw += name + ": forged alias\r\n"
+ }
+ raw += "\r\n"
+ r, err := http.ReadRequest(bufio.NewReader(strings.NewReader(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.RemoteAddr = "100.64.0.2:12345"
+ t.Cleanup(func() { r.Body.Close() })
+ return r
+}
+
+func TestFrontStripsVisitorTrailers(t *testing.T) {
+ r := frontTrailerRequest(t)
+ r.Trailer["cArLoS-vIsItOr-LoGiN"] = []string{"already populated"}
+ for _, name := range frontVisitorAliases {
+ r.Trailer[name] = []string{"already populated alias"}
+ }
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ return frontVisitor, true, nil
+ })}
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ body, err := io.ReadAll(r.Body)
+ if err != nil || string(body) != "body" {
+ t.Errorf("body=%q err=%v", body, err)
+ }
+ assertNoVisitorHeaders(t, r.Trailer)
+ if got := r.Trailer.Get("X-Other"); got != "preserved" {
+ t.Errorf("unrelated trailer=%q", got)
+ }
+ }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r)
+}
+
+func TestDevboxFrontUnixStripsVisitorTrailers(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ if _, err := io.Copy(io.Discard, r.Body); err != nil {
+ t.Error(err)
+ }
+ assertNoVisitorHeaders(t, r.Trailer)
+ if got := r.Header.Get("Carlos-Visitor-Login"); got != frontVisitor.Login {
+ t.Errorf("login=%q", got)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(string) (string, uint32, bool) { return path, uint32(os.Getuid()), true }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := frontTrailerRequest(t)
+ w := httptest.NewRecorder()
+ devboxFront(e, cfg, frontSelf).ServeHTTP(w, r)
+ if w.Code != http.StatusNoContent {
+ t.Errorf("code=%d want=204", w.Code)
+ }
+}
+
+func TestFrontIdentityDeadline(t *testing.T) {
+ for _, private := range []bool{false, true} {
+ t.Run(fmt.Sprintf("private=%v", private), func(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ started := time.Now()
+ lookups := 0
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(ctx context.Context, _ netip.AddrPort) (Visitor, bool, error) {
+ lookups++
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ t.Error("lookup has no deadline")
+ return Visitor{}, false, errors.New("no deadline")
+ }
+ if got := deadline.Sub(started); got != 2*time.Second {
+ t.Errorf("lookup budget=%s want=2s", got)
+ }
+ <-ctx.Done()
+ return Visitor{}, false, ctx.Err()
+ })}
+ cfg.Identity = NewCachedIdentity(cfg.Identity, time.Now)
+ if private {
+ cfg.AllowFor = func(string) []string { return []string{frontVisitor.Login} }
+ }
+ calls := 0
+ h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ assertNoVisitorHeaders(t, r.Header)
+ if err := r.Context().Err(); err != nil {
+ t.Errorf("lookup canceled request context: %v", err)
+ }
+ }), cfg, frontSelf)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, frontRequest())
+ wantCode, wantCalls := http.StatusOK, 1
+ if private {
+ wantCode, wantCalls = http.StatusForbidden, 0
+ }
+ if w.Code != wantCode || calls != wantCalls {
+ t.Errorf("code=%d calls=%d want=%d,%d", w.Code, calls, wantCode, wantCalls)
+ }
+ if elapsed := time.Since(started); elapsed != 2*time.Second {
+ t.Errorf("elapsed=%s want=2s", elapsed)
+ }
+ cachedStart := time.Now()
+ w = httptest.NewRecorder()
+ h.ServeHTTP(w, frontRequest())
+ if w.Code != wantCode || lookups != 1 || time.Since(cachedStart) != 0 {
+ t.Errorf("cached timeout: code=%d lookups=%d elapsed=%s", w.Code, lookups, time.Since(cachedStart))
+ }
+ })
+ })
+ }
+}
+
+func TestDevboxFrontUnixUpgrade101(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ done := make(chan struct{})
+ echo := upgradeEchoHandler("socket")
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(done)
+ assertNoVisitorAliases(t, r.Header)
+ for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} {
+ if got := r.Header.Get(k); got != want {
+ t.Errorf("upstream %s=%q want=%q", k, got, want)
+ }
+ }
+ echo.ServeHTTP(w, r)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(string) (string, uint32, bool) { return path, uint32(os.Getuid()), true }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(devboxFront(e, cfg, frontSelf))
+ defer srv.Close()
+ conn, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ _, err = fmt.Fprint(conn, "GET /ws HTTP/1.1\r\nHost: shop.example.com\r\nConnection: Upgrade, Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node\r\nUpgrade: websocket\r\ncArLoS-vIsItOr-LoGiN: mallory@github\r\nCarlos-Visitor-Name: Forged\r\nCarlos-Visitor-Node: Forged\r\ncArLoS_Visitor_Login: forged\r\nCarlos_Visitor-Name: forged\r\nCarlos-Visitor_Node: forged\r\n\r\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reader := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(reader, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("status=%d want=101", resp.StatusCode)
+ }
+ if _, err := fmt.Fprint(conn, "hello\n"); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := reader.ReadString('\n'); err != nil || got != "socket:hello\n" {
+ t.Fatalf("echo=%q err=%v", got, err)
+ }
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("upgraded upstream did not finish")
+ }
+}
+
+func TestDevboxFrontUnixAnonymousAliases(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assertNoVisitorHeaders(t, r.Header)
+ assertNoVisitorHeaders(t, r.Trailer)
+ if _, err := io.Copy(io.Discard, r.Body); err != nil {
+ t.Error(err)
+ }
+ assertNoVisitorHeaders(t, r.Trailer)
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), SocketOwnerFor: func(string) (string, uint32, bool) { return path, uint32(os.Getuid()), true }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := frontTrailerRequest(t)
+ for _, name := range frontVisitorAliases {
+ r.Header[name] = []string{"forged alias"}
+ }
+ w := httptest.NewRecorder()
+ devboxFront(e, cfg, frontSelf).ServeHTTP(w, r)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("code=%d want=204", w.Code)
+ }
+}
diff --git a/internal/edge/devboxpeer_linux.go b/internal/edge/devboxpeer_linux.go
new file mode 100644
index 000000000..080f177c7
--- /dev/null
+++ b/internal/edge/devboxpeer_linux.go
@@ -0,0 +1,31 @@
+//go:build linux
+
+package edge
+
+import (
+ "net"
+
+ "golang.org/x/sys/unix"
+)
+
+func devboxPeerUID(conn net.Conn) (uint32, error) {
+ uc, ok := conn.(*net.UnixConn)
+ if !ok {
+ return 0, errDevboxSocketOwner
+ }
+ raw, err := uc.SyscallConn()
+ if err != nil {
+ return 0, err
+ }
+ var cred *unix.Ucred
+ var sockErr error
+ if err := raw.Control(func(fd uintptr) {
+ cred, sockErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED)
+ }); err != nil {
+ return 0, err
+ }
+ if sockErr != nil {
+ return 0, sockErr
+ }
+ return cred.Uid, nil
+}
diff --git a/internal/edge/devboxpeer_other.go b/internal/edge/devboxpeer_other.go
new file mode 100644
index 000000000..9787549c0
--- /dev/null
+++ b/internal/edge/devboxpeer_other.go
@@ -0,0 +1,9 @@
+//go:build !linux
+
+package edge
+
+import "net"
+
+func devboxPeerUID(net.Conn) (uint32, error) {
+ return 0, errDevboxSocketOwner
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index e19487d51..41757f75f 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -113,7 +113,8 @@ type Activator interface {
// its backend. The host→backend map is swapped atomically, so reloads and
// zero-downtime deploys never drop a live connection.
type Edge struct {
- reg *registry.Registry
+ devbox bool // installs front-door proxy hooks on every reload
+ reg *registry.Registry
// hold is this Edge's local-upstream hold settings (localhold.go), set
// before the startup Reload and read by it.
hold localHold
@@ -941,7 +942,8 @@ func (e *Edge) Reload() error {
// fold below (its Served, the destination after that fold, is what
// the console's held-host reason FPR-C08 reads).
served, viaFleet := verdict.Arm[t.Host]
- switch DispatchArm(t, viaFleet, e.tunnels != nil) {
+ arm := DispatchArm(t, viaFleet, e.tunnels != nil)
+ switch arm {
// A forward row (fleet public routes spec §4.2) is the hub's row for
// an app placed on a fleet: it runs nothing here, and the only way it
// is ever served is through its fleet's tunnel. FIRST, ahead of the
@@ -1146,6 +1148,13 @@ func (e *Edge) Reload() error {
// Wrapping the handler covers each way the proxy is reached: the
// ordinary path, the upgrade branch, the activator and a fill.
if p, ok := proxy.(*httputil.ReverseProxy); ok {
+ if e.devbox {
+ socketPath := ""
+ if arm == ArmSocket {
+ socketPath = t.Socket
+ }
+ configureDevboxProxy(p, socketPath)
+ }
proxy = assetScrubbedProxy{p}
}
if t.Version != "" && t.Kind != "static" && t.Kind != "status" && !genManaged {
diff --git a/internal/edge/visitor.go b/internal/edge/visitor.go
new file mode 100644
index 000000000..e52cd610b
--- /dev/null
+++ b/internal/edge/visitor.go
@@ -0,0 +1,139 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Visitor identifies the owner of a personal device. Values are supplied by
+// the identity provider; the front door sanitizes them before setting headers.
+type Visitor struct{ Login, Name, Node string }
+
+type VisitorIdentity interface {
+ // Who returns the visitor at remote, or ok=false if unknown.
+ Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error)
+}
+
+const visitorCacheLimit = 4096
+
+type visitorCacheEntry struct {
+ visitor Visitor
+ ok bool
+ expires time.Time
+ ready chan struct{}
+}
+
+type cachedIdentity struct {
+ inner VisitorIdentity
+ now func() time.Time
+ mu sync.Mutex
+ entries map[netip.Addr]*visitorCacheEntry
+}
+
+// NewCachedIdentity caches identities by unmapped IP for 60 seconds, and
+// misses or errors for 5 seconds. Cached errors return an anonymous miss with
+// nil error. Deadlines are cached as failures; explicit caller cancellation
+// and panics are not cached, so waiters retry.
+// At 4096 entries, a new IP resets the cache to bound memory.
+func NewCachedIdentity(inner VisitorIdentity, now func() time.Time) VisitorIdentity {
+ return &cachedIdentity{inner: inner, now: now, entries: make(map[netip.Addr]*visitorCacheEntry)}
+}
+
+func (c *cachedIdentity) Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ key := remote.Addr().Unmap()
+ for {
+ if err := ctx.Err(); err != nil {
+ return Visitor{}, false, err
+ }
+ c.mu.Lock()
+ if entry := c.entries[key]; entry != nil {
+ if entry.ready != nil {
+ ready := entry.ready
+ c.mu.Unlock()
+ select {
+ case <-ctx.Done():
+ return Visitor{}, false, ctx.Err()
+ case <-ready:
+ continue
+ }
+ }
+ if c.now().Before(entry.expires) {
+ visitor, ok := entry.visitor, entry.ok
+ c.mu.Unlock()
+ return visitor, ok, nil
+ }
+ delete(c.entries, key)
+ }
+ if len(c.entries) >= visitorCacheLimit {
+ clear(c.entries)
+ }
+ entry := &visitorCacheEntry{ready: make(chan struct{})}
+ c.entries[key] = entry
+ c.mu.Unlock()
+
+ return c.lookup(ctx, remote, entry)
+ }
+}
+
+func (c *cachedIdentity) lookup(ctx context.Context, remote netip.AddrPort, entry *visitorCacheEntry) (Visitor, bool, error) {
+ // A canceled lookup or panic must release waiters without leaving a miss.
+ // Keep any replacement entry installed after a cap reset. Panics still
+ // propagate to the caller, where net/http can recover them as usual.
+ defer func() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if entry.ready != nil {
+ key := remote.Addr().Unmap()
+ if c.entries[key] == entry {
+ delete(c.entries, key)
+ }
+ close(entry.ready)
+ entry.ready = nil
+ }
+ }()
+
+ // Keep the full AddrPort for the provider. If this caller cancels, the
+ // other callers retry under their own contexts instead of caching a miss.
+ visitor, ok, err := c.inner.Who(ctx, remote)
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ if errors.Is(ctxErr, context.Canceled) {
+ return Visitor{}, false, ctxErr
+ }
+ // R11: a deadline is a lookup failure, even if the provider returned
+ // an answer after its budget expired. Cache the miss for five seconds.
+ err = ctxErr
+ }
+ if errors.Is(err, context.Canceled) {
+ return Visitor{}, false, err
+ }
+ ttl := 60 * time.Second
+ if !ok || err != nil {
+ visitor, ok = Visitor{}, false
+ ttl = 5 * time.Second
+ }
+ c.mu.Lock()
+ entry.visitor, entry.ok, entry.expires = visitor, ok, c.now().Add(ttl)
+ close(entry.ready)
+ entry.ready = nil
+ c.mu.Unlock()
+ return visitor, ok, err
+}
+
+// anonymousSource is the front door's shared-machine rule: the devbox's own
+// IP (unmapped on both sides), or an exact, case-insensitive shared node name.
+// Match Node, not Login: a shared machine identifies its owner, not its user.
+func anonymousSource(remote netip.Addr, self netip.Addr, v Visitor, sharedNodes []string) bool {
+ if remote.Unmap() == self.Unmap() {
+ return true
+ }
+ for _, node := range sharedNodes {
+ if strings.EqualFold(v.Node, node) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/edge/visitor_test.go b/internal/edge/visitor_test.go
new file mode 100644
index 000000000..042f38294
--- /dev/null
+++ b/internal/edge/visitor_test.go
@@ -0,0 +1,330 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+)
+
+type visitorIdentityFunc func(context.Context, netip.AddrPort) (Visitor, bool, error)
+
+func (f visitorIdentityFunc) Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ return f(ctx, remote)
+}
+
+func TestCachedIdentityTTLs(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ ok bool
+ err error
+ ttl time.Duration
+ }{
+ {"hit", true, nil, 60 * time.Second},
+ {"miss", false, nil, 5 * time.Second},
+ {"error", true, errors.New("lookup failed"), 5 * time.Second},
+ {"provider deadline", true, context.DeadlineExceeded, 5 * time.Second},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ now := time.Unix(1000, 0)
+ calls := 0
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ visitor := Visitor{"alice@github", "Alice", "laptop"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(ctx context.Context, got netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ if got != remote {
+ t.Errorf("remote = %v, want %v", got, remote)
+ }
+ return visitor, tc.ok, tc.err
+ }), func() time.Time { return now })
+ got, ok, err := identity.Who(context.Background(), remote)
+ wantOK := tc.ok && tc.err == nil
+ if ok != wantOK || !errors.Is(err, tc.err) {
+ t.Fatalf("first lookup = %v, %v", ok, err)
+ }
+ if wantOK && got != visitor {
+ t.Fatalf("visitor = %+v", got)
+ }
+ if !wantOK && got != (Visitor{}) {
+ t.Fatalf("anonymous lookup leaked %+v", got)
+ }
+ now = now.Add(tc.ttl - time.Nanosecond)
+ got, ok, err = identity.Who(context.Background(), remote)
+ if ok != wantOK || err != nil || calls != 1 {
+ t.Fatalf("cached lookup = %v, %v; calls %d", ok, err, calls)
+ }
+ if !wantOK && got != (Visitor{}) {
+ t.Fatalf("cached miss leaked %+v", got)
+ }
+ now = now.Add(time.Nanosecond)
+ _, _, _ = identity.Who(context.Background(), remote)
+ if calls != 2 {
+ t.Fatalf("at expiry: calls %d, want 2", calls)
+ }
+ })
+ }
+}
+
+func TestCachedIdentityKeysByUnmappedIP(t *testing.T) {
+ calls := 0
+ first := netip.MustParseAddrPort("[::ffff:100.64.0.1]:1234")
+ identity := NewCachedIdentity(visitorIdentityFunc(func(_ context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ if calls == 1 && remote != first {
+ t.Errorf("inner remote = %v, want full %v", remote, first)
+ }
+ return Visitor{Login: remote.Addr().Unmap().String()}, true, nil
+ }), time.Now)
+ a, _, _ := identity.Who(context.Background(), first)
+ b, _, _ := identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:5678"))
+ c, _, _ := identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.2:5678"))
+ if calls != 2 || a != b || a == c {
+ t.Fatalf("calls %d; visitors %+v, %+v, %+v", calls, a, b, c)
+ }
+}
+
+func TestCachedIdentityBound(t *testing.T) {
+ calls := 0
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ return Visitor{}, false, nil
+ }), func() time.Time { return time.Unix(1000, 0) })
+ remote := func(i int) netip.AddrPort {
+ return netip.AddrPortFrom(netip.AddrFrom4([4]byte{100, 64, byte(i >> 8), byte(i)}), 1234)
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ }
+ if calls != 4096 {
+ t.Fatalf("cache reset before cap: calls %d", calls)
+ }
+ _, _, _ = identity.Who(context.Background(), remote(4096))
+ cache := identity.(*cachedIdentity)
+ if len(cache.entries) != 1 {
+ t.Fatalf("after full reset: entries %d, want 1", len(cache.entries))
+ }
+ if _, ok := cache.entries[remote(4096).Addr()]; !ok {
+ t.Fatal("new entry missing after reset")
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ if calls != 4098+i {
+ t.Fatalf("entry %d retained after reset: calls %d", i, calls)
+ }
+ }
+ if len(cache.entries) != 1 {
+ t.Fatalf("after second reset: entries %d, want 1", len(cache.entries))
+ }
+}
+
+func TestCachedIdentityConcurrent(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started, release := make(chan struct{}), make(chan struct{})
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ }
+ <-release
+ return Visitor{Login: "alice@github"}, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ var wg sync.WaitGroup
+ for i := 0; i < 32; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ v, ok, err := identity.Who(context.Background(), remote)
+ if !ok || err != nil || v.Login != "alice@github" {
+ t.Errorf("lookup = %+v, %v, %v", v, ok, err)
+ }
+ }()
+ }
+ <-started
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { _, _, err := identity.Who(ctx, remote); done <- err }()
+ synctest.Wait()
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("canceled waiter: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Error("canceled waiter blocked behind lookup")
+ }
+ close(release)
+ wg.Wait()
+ if calls.Load() != 1 {
+ t.Fatalf("concurrent lookups: %d, want 1", calls.Load())
+ }
+ })
+}
+
+func TestCachedIdentityCanceledLookup(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started := make(chan struct{})
+ want := Visitor{Login: "alice@github", Node: "laptop"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(ctx context.Context, _ netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ <-ctx.Done()
+ return Visitor{}, false, ctx.Err()
+ }
+ return want, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ leader := make(chan error, 1)
+ go func() { _, _, err := identity.Who(ctx, remote); leader <- err }()
+ <-started
+ waiter := make(chan struct{})
+ go func() {
+ defer close(waiter)
+ v, ok, err := identity.Who(context.Background(), remote)
+ if v != want || !ok || err != nil {
+ t.Errorf("waiter: %+v, %v, %v", v, ok, err)
+ }
+ }()
+ synctest.Wait()
+ cancel()
+ if err := <-leader; !errors.Is(err, context.Canceled) {
+ t.Errorf("leader: %v", err)
+ }
+ <-waiter
+ v, ok, err := identity.Who(context.Background(), remote)
+ if v != want || !ok || err != nil {
+ t.Fatalf("later call: %+v, %v, %v", v, ok, err)
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("lookups = %d, want canceled lookup plus one retry", calls.Load())
+ }
+ })
+}
+
+func TestCachedIdentityPanicReleasesWaiters(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started, release := make(chan struct{}), make(chan struct{})
+ want := Visitor{Login: "alice@github"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ <-release
+ panic("lookup panic")
+ }
+ return want, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ panicked := make(chan any, 1)
+ go func() {
+ defer func() { panicked <- recover() }()
+ _, _, _ = identity.Who(context.Background(), remote)
+ }()
+ <-started
+ waiter := make(chan struct{})
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ go func() {
+ defer close(waiter)
+ v, ok, err := identity.Who(ctx, remote)
+ if v != want || !ok || err != nil {
+ t.Errorf("waiter after panic: %+v, %v, %v", v, ok, err)
+ }
+ }()
+ synctest.Wait()
+ close(release)
+ if got := <-panicked; got != "lookup panic" {
+ t.Errorf("panic = %v", got)
+ }
+ <-waiter
+ v, ok, err := identity.Who(ctx, remote)
+ if v != want || !ok || err != nil {
+ t.Fatalf("later call: %+v, %v, %v", v, ok, err)
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("lookups = %d, want panic plus one retry", calls.Load())
+ }
+ })
+}
+
+func TestAnonymousSource(t *testing.T) {
+ self := netip.MustParseAddr("100.64.0.1")
+ for _, tc := range []struct {
+ name, remote, node string
+ shared []string
+ want bool
+ }{
+ {"self", "100.64.0.1", "laptop", nil, true},
+ {"mapped self", "::ffff:100.64.0.1", "laptop", nil, true},
+ {"shared mixed case", "100.64.0.2", "SHOP-DEV", []string{"other", "shop-dev"}, true},
+ {"personal", "100.64.0.2", "laptop", []string{"shop-dev"}, false},
+ {"not prefix", "100.64.0.2", "shop-dev-extra", []string{"shop-dev"}, false},
+ {"not suffix", "100.64.0.2", "my-shop-dev", []string{"shop-dev"}, false},
+ {"not login", "100.64.0.2", "laptop", []string{"alice@github"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ v := Visitor{Login: "alice@github", Node: tc.node}
+ for _, local := range []netip.Addr{self, netip.MustParseAddr("::ffff:100.64.0.1")} {
+ if got := anonymousSource(netip.MustParseAddr(tc.remote), local, v, tc.shared); got != tc.want {
+ t.Fatalf("anonymousSource = %v, want %v", got, tc.want)
+ }
+ }
+ })
+ }
+}
+
+func TestCachedIdentityDeadlineFailureTTL(t *testing.T) {
+ for _, lateSuccess := range []bool{false, true} {
+ name := "deadline error"
+ if lateSuccess {
+ name = "answer after deadline"
+ }
+ t.Run(name, func(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ now := time.Unix(1000, 0)
+ calls := 0
+ want := Visitor{Login: "alice@github"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(ctx context.Context, _ netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ if calls == 1 {
+ <-ctx.Done()
+ if lateSuccess {
+ return want, true, nil
+ }
+ return Visitor{}, false, ctx.Err()
+ }
+ return want, true, nil
+ }), func() time.Time { return now })
+ remote := netip.MustParseAddrPort("100.64.0.2:1234")
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ v, ok, err := identity.Who(ctx, remote)
+ if v != (Visitor{}) || ok || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("deadline = %+v, %v, %v", v, ok, err)
+ }
+ now = now.Add(5*time.Second - time.Nanosecond)
+ v, ok, err = identity.Who(context.Background(), remote)
+ if v != (Visitor{}) || ok || err != nil || calls != 1 {
+ t.Fatalf("cached deadline = %+v, %v, %v; calls %d", v, ok, err, calls)
+ }
+ now = now.Add(time.Nanosecond)
+ v, ok, err = identity.Who(context.Background(), remote)
+ if v != want || !ok || err != nil || calls != 2 {
+ t.Fatalf("after expiry = %+v, %v, %v; calls %d", v, ok, err, calls)
+ }
+ })
+ })
+ }
+}
diff --git a/internal/provision/devbox_identity_census_test.go b/internal/provision/devbox_identity_census_test.go
new file mode 100644
index 000000000..072bdc485
--- /dev/null
+++ b/internal/provision/devbox_identity_census_test.go
@@ -0,0 +1,62 @@
+package provision
+
+// Devbox identity (#486 A, Task 6) record-write claims, layered on the
+// inventory at 9ca74dd0. These are the author's source classifications;
+// the independent reviewer gives the census verdict separately.
+// See docs/superpowers/notes/census-proposal-devbox-identity.md.
+//
+// All four units run in the carlos-devbox service account, not root. Handler
+// obtains the caller UID from ConnContext/SO_PEERCRED, and each share calls
+// claim under the registrar mutex before persisting a link. Links.Put writes
+// the service's own links.json via commitLocked/write (0600 temporary file,
+// fsync, rename, directory fsync). The other writes are local registry rows
+// and, for folders, the local spool. None constructs a deployment record key
+// or writes to an object store, so each remains nonrecord.
+func devboxIdentityWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), statelessReplicasWriteCensusInventory()...)
+ repins := []censusEntry{
+ // #486 A: clone Allow before storing the link so callers cannot mutate
+ // the saved list through an alias. Same local links.json Put and commit.
+ {"internal/devbox/links.go", "Links.Put", "nonrecord", "def:Put", "aded1d9f65b5d02e4646d3ddab41042e5d9b6aaaa747f2132c96891d11940fd8"},
+ // #486 A: validate JSON Allow and replace it on the live link. Same
+ // owner claim, Links.Put, local UpsertUnlessRootfs and rollback; the
+ // response now filters allow names by caller UID.
+ {"internal/devbox/registrar.go", "Registrar.serveShareLive", "nonrecord", "sel:Put", "1c7a4ee89befbe125f16b8e846270b6be2007f42f2dffb053f5aa60f5d401141"},
+ // #486 A: strictly parse the query and validate repeated allow values
+ // before the archive upload. Put the new allow list in links.json;
+ // preserve the upload/spool limits, owner claim, snapshot swap, local
+ // UpsertUnlessRootfs and rollback. Return owner-filtered allow names.
+ {"internal/devbox/registrar.go", "Registrar.serveShareFolder", "nonrecord", "sel:Put", "dce50fcab6a2b64a712d58a6f236cdf19ec6264ce7bccba96116ab94c1a81d58"},
+ }
+ for _, r := range repins {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("devbox-identity re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("devbox-identity re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ added := []censusEntry{
+ // #486 A: the new socket share validates name/allow, checks a direct
+ // child socket's inode owner and connected peer UID, then claims the
+ // name and Puts the socket link/allow list in local links.json. The
+ // local socket route uses UpsertUnlessRootfs, with link rollback on
+ // failure and old folder spool cleanup only after success. No bucket.
+ {"internal/devbox/registrar.go", "Registrar.serveShareSocket", "nonrecord", "sel:Put", "b3389aa29c77785657375b60208aac3ac4a086baf9b2c24be4d7d6d98e12791c"},
+ }
+ for _, a := range added {
+ for _, e := range entries {
+ if e.File == a.File && e.Unit == a.Unit {
+ panic("devbox-identity addition of an already listed unit " + a.File + ":" + a.Unit)
+ }
+ }
+ entries = append(entries, a)
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index dcd3668c9..a3aa2a17e 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := statelessReplicasWriteCensusInventory()
+ inventory := devboxIdentityWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 678a612cf..92b87fd69 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -64,3 +64,4 @@ plan14-root-reads-edge-protect-hard-block.tsv 3b6cd29b87d2728254936722ab45fdadcf
plan14-root-reads-edge-held-first-ping.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
plan14-root-reads-fleet-examined-519.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
plan14-root-reads-domains-zone-credentials.tsv 3b6cd29b87d2728254936722ab45fdadcfbb8c1f5b74fdfa19d1921b9dfd1dbe
+plan14-root-reads-devbox-identity.tsv 66a5df05f18f70c3162ad05aa316c1e69c0f053d54f8b682262c266d6aa50772
diff --git a/internal/provision/testdata/plan14-root-reads-devbox-identity.tsv b/internal/provision/testdata/plan14-root-reads-devbox-identity.tsv
new file mode 100644
index 000000000..1fd500c84
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-devbox-identity.tsv
@@ -0,0 +1,36 @@
+# Census overlay devbox-identity, written by census-propose (#369). census-ruling-devbox-identity, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-devbox-identity.md.
+# 5 body, 2 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 7 new dispositions: 0 reads re-frozen at their disposition with the claim, 7 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 9be1020ba7045fd8f7e6861ed5995676a14c026e6c7c5413afbdfb5c22a30492 devbox_cli.go runDevboxServe legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: carlos devbox serve, run by the carlos-devbox unit as the unprivileged carlos-devbox user, reads its config from the environment (CARLOS_DEVBOX_LISTEN, CARLOS_DEVBOX_DOMAIN, CARLOS_DATA_DIR, CARLOS_WILDCARD_DOMAINS, CARLOS_DEVBOX_SOCKET) and opens registry.db and links.json under its own StateDirectory. Not root;rev3=census-ruling-devbox-macos;basis=devbox on macOS (#488): serve now parses flags; --env-file PATH loads the service user's own env file (loadDevboxEnvFile) before reading the same environment as before; with CARLOS_DEVBOX_LAUNCHD_SOCKET set it takes launchd's listening socket (launchd.Listeners, macOS only; elsewhere it refuses) and holds it to CARLOS_DEVBOX_LISTEN (edge.CheckDevboxListener) before making anything; the socket path comes from devboxSocketPath (CARLOS_DEVBOX_SOCKET, or the OS default). Runs as the unprivileged service user (carlos-devbox on Linux, _carlos-devbox on macOS), never root; no new read beyond the env file named on its own command line;rev3=census-ruling-devbox-identity;basis=#486 A: carlos devbox serve runs as the carlos-devbox service user, not root. Adds configureDevboxIdentity before serving: reads CARLOS_DEVBOX_SOCKETS_DIR, CARLOS_DEVBOX_TAILSCALED_SOCKET and CARLOS_DEVBOX_SHARED_NODES, checks/creates the service-owned sockets directory, and wires the cached LocalAPI adapter plus allow/socket-owner lookups. Existing registry.db, links.json and optional env-file reads remain in the service account; no additional direct scanned read site in this unit. data-literal@1086,data-literal@776,file:Open@2328 adb0176fb0901ac32d80f16259b19d0f98c1978c3c28410bab3c6c0bafeaf0ab
+@legacy 1745f2d1f4392fd9e083ca4c2870380665133e9da1a4104fadddfc20a34a2ab7 infra/devbox/carlos-devbox.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: systemd unit for devbox mode on a developer workstation, installed once by hand per infra/devbox/README.md. Runs carlos devbox serve as User=carlos-devbox with only CAP_NET_BIND_SERVICE, NoNewPrivileges, ProtectSystem=strict and the hardening of carlos-edge.service; not installed by user_data or any CARLOS box path;rev3=census-ruling-devbox-identity;basis=#486 A: adds RuntimeDirectoryPreserve=yes so stopping the service preserves caller sockets under /run/carlos-devbox. ExecStart still runs carlos devbox serve with User=Group=carlos-devbox, never as root; only CAP_NET_BIND_SERVICE remains. No new executable or environment-file read; the existing systemd EnvironmentFile and hardening are unchanged. file:external@0 72440fc94179ddaa03203a6b897893b58a608c8ee878972908f97576e860aae8
+@legacy e4ec31441c78c739c0c6906526c48a93a62619b4cea067f0790b9faac4d63783 internal/devbox/registrar.go Registrar.list legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) EvalSymlinks <spool>/<name>/current only to report whether a folder link resolves. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, reads its in-memory links and passes the kernel-authenticated caller UID into entry so allow names are returned only to their owner. Adds bounded connect-and-close probes of stored socket paths without sending data; a replaced symlink can be followed by this availability probe. Existing folder-current EvalSymlinks and loopback probes remain; forwarding separately checks peer UID. file:EvalSymlinks@758 775ff5462af8d4afd4614a476d9f31f73ac6fa487d05a3b9b2656e7597dfa19a
+@legacy 656a1ee633f19b2029d6e43a8ae6725bfcb4f4791061629252689236a0e4c0af internal/devbox/registrar.go Registrar.serveShareLive legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row via claim and writes a service row 127.0.0.1:<port> with UpsertUnlessRootfs. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, now reads and validates the request JSON allow list, stores the normalized list with the local link, and returns owner-filtered allow details through entry(link, uid). Existing SO_PEERCRED identity, claim ownership/registry reads and UpsertUnlessRootfs remain; no new filesystem or deployment-record read. whole:Route@1142 1c7a4ee89befbe125f16b8e846270b6be2007f42f2dffb053f5aa60f5d401141
+@legacy 129f661ca978314c692e1e97a2de80f4ac0198c79a7375d5c3896a4c8a40f5b5 internal/devbox/registrar.go Registrar.serveUnshare legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row before deleting it, so a failed links delete can restore it. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, now passes the authenticated caller UID to entry(prev, uid) so the response exposes allow names only to their owner. Reads the same local link and registry row, checks ownership, then deletes with the existing rollback; no new read. whole:Route@1063 3592daffbb3f6595131372fbe6d0c869a077cad884c4a524858d3ff79464b427
+@legacy 096d71994c223f1cf231ff0f031ba9c59f40e4c3f13f8abf2dd655a82db2fe36 devbox_acl_linux.go openDevboxSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the calling user CLI, not root or the service account, opens the socket path with O_PATH|O_NOFOLLOW|O_CLOEXEC and fstats that same descriptor. Refuses non-sockets including symlinks and a UID different from the caller. New reads are inode metadata (Open and Fstat), not file contents; the descriptor remains pinned through the subsequent ACL Setxattr via /proc/self/fd/N, so pathname replacement cannot redirect that write. file:Fstat@241,file:Open@76 35f35391fe1dab42cc7089790be2276b4cfd8f537e6302cfa44ff1431a363776
+@legacy 4ffe7566a837d7bbf13c07e80f3fd851ff08c7a48c28417513c4671a47519407 devbox_cli.go prepareDevboxSocketsDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, creates its configured sockets directory and Lstats it to read type, ownership and mode. Refuses symlinks, non-directories and foreign ownership; creates/repairs sticky mode 1733. The new read is metadata of CARLOS_DEVBOX_SOCKETS_DIR (default /run/carlos-devbox/sockets), not tenant file content. file:Lstat@221 eda56f2447387c7d1892b49ac127ced19d71cbde7ae1c9dfa73b3f050c9e82e4
+@legacy d6ccdaaa66c2b308b077a67d08300103d618a914fd57f6717fb00180a5c95669 internal/devbox/registrar.go Registrar.serveShareSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, decodes name/path/allow from the SO_PEERCRED-authenticated request, validates name/list, and calls checkSocket for direct-child path, inode owner/type and connected peer UID. Under its mutex it reads its local link/registry claim, persists a socket link in links.json and constructs the whole registry.Route passed to UpsertUnlessRootfs, with rollback on failure. No deployment bucket/record read; socket-path refusals return the configured directory as machine data. whole:Route@1231 b3389aa29c77785657375b60208aac3ac4a086baf9b2c24be4d7d6d98e12791c
+@legacy 199bf1e752ba186ccfc21f14976e7c05ffb3ff6dc39eb5b993a8dea04f8497cc internal/devbox/socketcheck_linux.go checkSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, validates the cleaned absolute socket path is directly inside its configured directory, opens with O_PATH|O_NOFOLLOW|O_CLOEXEC, and uses socketFstat to require a socket owned by the kernel-authenticated caller UID. Then a bounded connect and SO_PEERCRED lookup require the listening process to have that same UID. New reads are socket inode metadata and peer credentials, with no request payload sent and no file content read. file:Open@338 1eaaca6537d425a9bf1c6e507dc46d6814538676d022eac1fb79b331e5efa61b
+@legacy 59bb57b3c10ca15f1581b4f608d5ce65a4e0cd007ad2fb311a6a5045ad816361 internal/devbox/socketcheck_linux.go var#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: production assigns socketFstat=unix.Fstat and socketPeerUID=PeerUID as test seams for checkSocket. The carlos-devbox service user, not root, later uses these functions for the opened socket inode metadata and connected peer UID. The new file:Fstat site is a function value here; initialization itself performs no I/O. file:Fstat@23 aeebbb8ef221155002eec748d1269875edeceb1e199d85086bc6d1e829be6e91
+@legacy 8d141edc4545a978b8220d5103b667cc1d9bbf086ac502c5ce73981a742ff745 internal/edge/devboxfront.go devboxTrailerBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, reads the incoming HTTP request body through its wrapped ReadCloser. At EOF it strips all visitor identity trailer names before a handler can use late-populated trailers. The scanner counts Read identifiers as file reads; these are network request-body reads, not filesystem opens or root-owned data. Final fix wave: the shared stripping helper now normalizes underscores to hyphens for comparisons, covering late EOF trailers as well as request and outgoing headers/trailers; this Read body and its reads are unchanged. file:Read@28,file:Read@69 66eacb35174eb545872491665ef53c06c92a740c973a012825d67a3126abdfbc
+@legacy 8824c9d68ebeb9b9384d15e614f4ff38f64a868d15930943851cc5a2d2e71d0e internal/tsidentity/whois.go identity.Who legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, queries tailscaled LocalAPI whois over the configured Unix socket (default /var/run/tailscale/tailscaled.sock) for the visitor remote address. New ReadAll reads at most 1 MiB plus one overflow byte from the HTTP response; redirects/errors and oversized or malformed JSON fail, and tagged devices or missing logins are anonymous. No ordinary file or deployment-record read; timeout/cancellation are bounded by the adapter and front door. R11 final fix wave: the enclosing cachedIdentity now caches provider timeouts and expired lookup contexts as anonymous failures for five seconds, discards late answers, and leaves explicit caller cancellation uncached; this adapter body and its reads are unchanged. file:ReadAll@748 faa815685cac4ee4cae548179dbd45e1e852bc5b1a9a13ab899d59ef0670747b
+@legacy 39aaf4f9c6d9d4ab294be001cd688a16c1ae97c25edac77c85f41e5887c039c1 internal/devbox/registrar.go Registrar.serveShareFolder legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads the name from the query and the upload body (Content-Length required, capped at 200 MiB), scans it with scanSite (now also refusing a root _headers or _redirects over the edge's limit, final review fix) and reads its own registry row via claim. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, replaces req.URL.Query with strict url.ParseQuery(req.URL.RawQuery), refuses malformed query encoding, and validates repeated allow values before reading the capped upload body. Stores the normalized allow list in its local links.json and returns owner-filtered entry data. The scanner loses file:Query; existing archive, spool and local registry reads remain, with no new filesystem or deployment-record read. file:Read@1922,whole:Route@4070 dce50fcab6a2b64a712d58a6f236cdf19ec6264ce7bccba96116ab94c1a81d58
+@legacy 0f2f7d7faf890a21e73df0d04cc7866a5de113b533c9575dea109a69373fed89 internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload);rev3=census-ruling-tunnel-websockets;basis=The ArmTunnel arm now records its tenancy (Account, App, Tunnel) copied from the row t that Reload already lists; no new registry query, no file read. Also the reload mutex taken first and held to return, five nil-in-production test hooks, and the sweepUpgrades call after the swap, which reads only the map Reload has just built (spec 7, Tasks 3 and 4).;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5, rule 3): the two fleet proxy builds pass the row to fleetBoxOf(t) instead of reading t.FleetBox (-registry:FleetBox x2, +whole:Route x2); fleetBoxOf answers FleetLabel as authoritative when set, else FleetBox; an authoritative box has no fallback to another of the fleet's channels (503 errFleetDark instead). The edge in the agent, not root; it routes to fewer channels, never more.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): after the new upstream map is published, closes the held streams of any host the new map no longer holds (absent, not hibernating, route no longer Hibernate). Reads the freshly built in-memory map m and the in-memory held set; no read added beyond the rebuild Reload already does.;rev3=census-ruling-devbox-identity;basis=#486 A: only the devbox edge created by newDevboxEdge (carlos-devbox service user, not root) enables the new proxy hooks. Saves the existing DispatchArm result and reads t.Socket from an already-listed route when that arm is ArmSocket, passing it to configureDevboxProxy for per-request expected-owner validation and visitor-header rewriting. Adds one registry:Socket field site; no new registry query or file open, and ordinary fleet/agent edges leave the hook disabled. Final fix wave: its devbox-only outgoing-header/trailer hooks now also strip case-insensitive underscore/hyphen aliases through stripVisitorHeaders; no new read. registry:Account@9457,registry:Alias@24401,registry:Alias@24488,registry:Alias@25068,registry:App@9473,registry:Health@13198,registry:Health@13324,registry:Hibernate@28588,registry:Host@10784,registry:Host@10841,registry:Host@10877,registry:Host@11620,registry:Host@13807,registry:Host@13902,registry:Host@14190,registry:Host@14216,registry:Host@14268,registry:Host@18863,registry:Host@20770,registry:Host@21078,registry:Host@21105,registry:Host@21920,registry:Host@22492,registry:Host@24822,registry:Host@24871,registry:Host@4701,registry:Host@4755,registry:Host@4805,registry:Host@5826,registry:Kind@17199,registry:Kind@17221,registry:Prefix@22467,registry:Socket@11684,registry:Socket@17078,registry:Socket@21086,registry:Status@4626,registry:Target@22479,registry:Tunnel@9317,registry:Tunnel@9488,registry:Version@17180,registry:Version@17282,whole:RegionalDomain@25710,whole:Route@10932,whole:Route@11040,whole:Route@11740,whole:Route@14341,whole:Route@14405,whole:Route@14456,whole:Route@21138,whole:Route@21145,whole:Route@21241,whole:Route@22355,whole:Route@23523,whole:Route@25702,whole:Route@28590,whole:Route@294,whole:Route@3381,whole:Route@3439,whole:Route@5855,whole:Route@6744,whole:Route@6852,whole:Route@9379,whole:RouteAlias@24372,whole:RoutePath@21898 af3657d000b8ac5c22f10a2efe355d1e9748c7ddb24f6ef067b80dd166954ebf
+devbox_cli.go runDevboxServe legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: carlos devbox serve, run by the carlos-devbox unit as the unprivileged carlos-devbox user, reads its config from the environment (CARLOS_DEVBOX_LISTEN, CARLOS_DEVBOX_DOMAIN, CARLOS_DATA_DIR, CARLOS_WILDCARD_DOMAINS, CARLOS_DEVBOX_SOCKET) and opens registry.db and links.json under its own StateDirectory. Not root;rev3=census-ruling-devbox-macos;basis=devbox on macOS (#488): serve now parses flags; --env-file PATH loads the service user's own env file (loadDevboxEnvFile) before reading the same environment as before; with CARLOS_DEVBOX_LAUNCHD_SOCKET set it takes launchd's listening socket (launchd.Listeners, macOS only; elsewhere it refuses) and holds it to CARLOS_DEVBOX_LISTEN (edge.CheckDevboxListener) before making anything; the socket path comes from devboxSocketPath (CARLOS_DEVBOX_SOCKET, or the OS default). Runs as the unprivileged service user (carlos-devbox on Linux, _carlos-devbox on macOS), never root; no new read beyond the env file named on its own command line;rev3=census-ruling-devbox-identity;basis=#486 A: carlos devbox serve runs as the carlos-devbox service user, not root. Adds configureDevboxIdentity before serving: reads CARLOS_DEVBOX_SOCKETS_DIR, CARLOS_DEVBOX_TAILSCALED_SOCKET and CARLOS_DEVBOX_SHARED_NODES, checks/creates the service-owned sockets directory, and wires the cached LocalAPI adapter plus allow/socket-owner lookups. Existing registry.db, links.json and optional env-file reads remain in the service account; no additional direct scanned read site in this unit. data-literal@1086,data-literal@776,file:Open@2328 adb0176fb0901ac32d80f16259b19d0f98c1978c3c28410bab3c6c0bafeaf0ab
+infra/devbox/carlos-devbox.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: systemd unit for devbox mode on a developer workstation, installed once by hand per infra/devbox/README.md. Runs carlos devbox serve as User=carlos-devbox with only CAP_NET_BIND_SERVICE, NoNewPrivileges, ProtectSystem=strict and the hardening of carlos-edge.service; not installed by user_data or any CARLOS box path;rev3=census-ruling-devbox-identity;basis=#486 A: adds RuntimeDirectoryPreserve=yes so stopping the service preserves caller sockets under /run/carlos-devbox. ExecStart still runs carlos devbox serve with User=Group=carlos-devbox, never as root; only CAP_NET_BIND_SERVICE remains. No new executable or environment-file read; the existing systemd EnvironmentFile and hardening are unchanged. file:external@0 72440fc94179ddaa03203a6b897893b58a608c8ee878972908f97576e860aae8
+internal/devbox/registrar.go Registrar.list legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) EvalSymlinks <spool>/<name>/current only to report whether a folder link resolves. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, reads its in-memory links and passes the kernel-authenticated caller UID into entry so allow names are returned only to their owner. Adds bounded connect-and-close probes of stored socket paths without sending data; a replaced symlink can be followed by this availability probe. Existing folder-current EvalSymlinks and loopback probes remain; forwarding separately checks peer UID. file:EvalSymlinks@758 775ff5462af8d4afd4614a476d9f31f73ac6fa487d05a3b9b2656e7597dfa19a
+internal/devbox/registrar.go Registrar.serveShareLive legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row via claim and writes a service row 127.0.0.1:<port> with UpsertUnlessRootfs. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, now reads and validates the request JSON allow list, stores the normalized list with the local link, and returns owner-filtered allow details through entry(link, uid). Existing SO_PEERCRED identity, claim ownership/registry reads and UpsertUnlessRootfs remain; no new filesystem or deployment-record read. whole:Route@1142 1c7a4ee89befbe125f16b8e846270b6be2007f42f2dffb053f5aa60f5d401141
+internal/devbox/registrar.go Registrar.serveUnshare legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads its own registry row before deleting it, so a failed links delete can restore it. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, now passes the authenticated caller UID to entry(prev, uid) so the response exposes allow names only to their owner. Reads the same local link and registry row, checks ownership, then deletes with the existing rollback; no new read. whole:Route@1063 3592daffbb3f6595131372fbe6d0c869a077cad884c4a524858d3ff79464b427
+devbox_acl_linux.go openDevboxSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the calling user CLI, not root or the service account, opens the socket path with O_PATH|O_NOFOLLOW|O_CLOEXEC and fstats that same descriptor. Refuses non-sockets including symlinks and a UID different from the caller. New reads are inode metadata (Open and Fstat), not file contents; the descriptor remains pinned through the subsequent ACL Setxattr via /proc/self/fd/N, so pathname replacement cannot redirect that write. file:Fstat@241,file:Open@76 35f35391fe1dab42cc7089790be2276b4cfd8f537e6302cfa44ff1431a363776
+devbox_cli.go prepareDevboxSocketsDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, creates its configured sockets directory and Lstats it to read type, ownership and mode. Refuses symlinks, non-directories and foreign ownership; creates/repairs sticky mode 1733. The new read is metadata of CARLOS_DEVBOX_SOCKETS_DIR (default /run/carlos-devbox/sockets), not tenant file content. file:Lstat@221 eda56f2447387c7d1892b49ac127ced19d71cbde7ae1c9dfa73b3f050c9e82e4
+internal/devbox/registrar.go Registrar.serveShareSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, decodes name/path/allow from the SO_PEERCRED-authenticated request, validates name/list, and calls checkSocket for direct-child path, inode owner/type and connected peer UID. Under its mutex it reads its local link/registry claim, persists a socket link in links.json and constructs the whole registry.Route passed to UpsertUnlessRootfs, with rollback on failure. No deployment bucket/record read; socket-path refusals return the configured directory as machine data. whole:Route@1231 b3389aa29c77785657375b60208aac3ac4a086baf9b2c24be4d7d6d98e12791c
+internal/devbox/socketcheck_linux.go checkSocket legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, validates the cleaned absolute socket path is directly inside its configured directory, opens with O_PATH|O_NOFOLLOW|O_CLOEXEC, and uses socketFstat to require a socket owned by the kernel-authenticated caller UID. Then a bounded connect and SO_PEERCRED lookup require the listening process to have that same UID. New reads are socket inode metadata and peer credentials, with no request payload sent and no file content read. file:Open@338 1eaaca6537d425a9bf1c6e507dc46d6814538676d022eac1fb79b331e5efa61b
+internal/devbox/socketcheck_linux.go var#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: production assigns socketFstat=unix.Fstat and socketPeerUID=PeerUID as test seams for checkSocket. The carlos-devbox service user, not root, later uses these functions for the opened socket inode metadata and connected peer UID. The new file:Fstat site is a function value here; initialization itself performs no I/O. file:Fstat@23 aeebbb8ef221155002eec748d1269875edeceb1e199d85086bc6d1e829be6e91
+internal/edge/devboxfront.go devboxTrailerBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, reads the incoming HTTP request body through its wrapped ReadCloser. At EOF it strips all visitor identity trailer names before a handler can use late-populated trailers. The scanner counts Read identifiers as file reads; these are network request-body reads, not filesystem opens or root-owned data. Final fix wave: the shared stripping helper now normalizes underscores to hyphens for comparisons, covering late EOF trailers as well as request and outgoing headers/trailers; this Read body and its reads are unchanged. file:Read@28,file:Read@69 66eacb35174eb545872491665ef53c06c92a740c973a012825d67a3126abdfbc
+internal/tsidentity/whois.go identity.Who legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, queries tailscaled LocalAPI whois over the configured Unix socket (default /var/run/tailscale/tailscaled.sock) for the visitor remote address. New ReadAll reads at most 1 MiB plus one overflow byte from the HTTP response; redirects/errors and oversized or malformed JSON fail, and tagged devices or missing logins are anonymous. No ordinary file or deployment-record read; timeout/cancellation are bounded by the adapter and front door. R11 final fix wave: the enclosing cachedIdentity now caches provider timeouts and expired lookup contexts as anonymous failures for five seconds, discards late answers, and leaves explicit caller cancellation uncached; this adapter body and its reads are unchanged. file:ReadAll@748 faa815685cac4ee4cae548179dbd45e1e852bc5b1a9a13ab899d59ef0670747b
+internal/devbox/registrar.go Registrar.serveShareFolder legacy accepted-legacy accepted-legacy;rev3=census-ruling-devbox-mode;basis=new: the registrar (carlos-devbox user) reads the name from the query and the upload body (Content-Length required, capped at 200 MiB), scans it with scanSite (now also refusing a root _headers or _redirects over the edge's limit, final review fix) and reads its own registry row via claim. Caller identity is SO_PEERCRED only. Not root;rev3=census-ruling-devbox-identity;basis=#486 A: the carlos-devbox service user, not root, replaces req.URL.Query with strict url.ParseQuery(req.URL.RawQuery), refuses malformed query encoding, and validates repeated allow values before reading the capped upload body. Stores the normalized allow list in its local links.json and returns owner-filtered entry data. The scanner loses file:Query; existing archive, spool and local registry reads remain, with no new filesystem or deployment-record read. file:Read@1922,whole:Route@4070 dce50fcab6a2b64a712d58a6f236cdf19ec6264ce7bccba96116ab94c1a81d58
+internal/edge/edge.go Edge.Reload legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-design-edge-rate-limit-358;basis=each route's upstream entry gains rate: e.parseRateSettings(t), the row's rate_limit column parsed once per reload; the one added site is that whole:Route pass of t (parseRateSettings is a new unit, classified in the decisions overlay); no other read added;rev3=census-ruling-certwarm-wake;basis=the single reload hook call becomes runReloadHooks(), which runs every registered hook in order (#386); no read added, same 57 sites (56 before #358 landed on main);rev3=census-ruling-edge-asset-cache-3;basis=each tenant reverse proxy built in the switch (the tunnel, fleet, socket and TCP arms, every *httputil.ReverseProxy) is installed behind assetScrubbedProxy, which hands the proxy an assetInformationalScrub writer so an app's 1xx (103) loses the asset cache's reserved headers (X-Carlos-Asset-Fill, -Fill-Ack, -Expires, Carlos-Cache) on every local path, as the backhaul already does (final review F6); a type check of the proxy it just built and a wrapper around it; static and status handlers untouched; read sites unchanged (57), offsets moved; no read added;rev3=census-ruling-alias-wake-338;basis=#338 follow-up: after the path fold, a resolved platform alias takes its source's own upstream entry (same proxy, route, hibernating: the existing activator wake, lease and fence), keeping its own prefix map (none for a minted apex) and never inheriting the source's (Astra r2 P1); a refused alias, or one whose source has no entry, is dropped from the map (not served, not Allowed); the attached-hostname fold clears platformAlias;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test (generation proxy, hib, no-activator 404) is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance goes through the activator; binary rows unchanged;rev3=census-ruling-edge-roll-blip;basis=the tcpProxy and multiProxy calls pass e.hold (the per-Edge localHold set once in newEdge): a loopback TCP upstream that refuses is redialled for up to 13 s and a probed route with a local upstream waits for prober readmission instead of answering 502/503 (#434 part B); edge-side dial policy only, no read added, same 52 sites;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: after the alias fold, reads the regional_domains rows (e.reg.ListRegional; an error aborts the reload as every registry read here does) and applies them with foldRegional against the routes slice the same reload read; the added reads are that one registry list and the routes already read;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 4 and 6: the forward case (fleetProxy toward the binding's FleetBox, throttled refusal); one refusal check before the switch from FleetArmVerdict (sidecar not judged; a non-ready forward row refused; a forward row always judged by FleetServeEligible, any other row only where tunnels are on; an alias of a refused source refused with it); the accountless note; path rows of a forward host not folded; no alias folded onto a refused row; refusedHosts held through every fold. ListFleets and FleetChannelAuth read before the loop (+registry:FleetBox, +registry:Host x7, +whole:Route x3). Serving only; the hub's agent, not root. Review R1 finding 2: the switch reads verdict.Served (FleetArmVerdict) by host; the forward case and the fleet-placed case take their fleet from it (served.Fleet) instead of FleetPlacement(t.Region), and an admitted forward row not Served continues rather than falling through (+registry:Host, -registry:Region); the same rows take the same arms; no read added. Review R2: the switch is on DispatchArm(t, viaFleet, tunnels) (the order moved there unchanged: forward only when in Arm, own Tunnel, fleet, socket, addrs, static, status, else continue), the fleet cases read verdict.Arm (renamed from Served), and the platform-alias fold is foldPlatformAliases with the same take (source entry, own paths, alias marks) and the same refusal log (-registry:Kind x2, -registry:Socket, -registry:Tunnel, +whole:Route: those reads moved into DispatchArm); same rows, same arms, same entries; no read added.;rev3=census-ruling-fleet-routes-followups;basis=the owners map is now e.reg.FleetOwners() instead of ListFleets folded inline: the same fresh-connection ListFleets read and the same name->account map (-registry:Account, -registry:Name, -whole:Fleet x2 move into Registry.FleetOwners); no read added; same error path (abort the reload);rev3=census-ruling-tunnel-websockets;basis=The ArmTunnel arm now records its tenancy (Account, App, Tunnel) copied from the row t that Reload already lists; no new registry query, no file read. Also the reload mutex taken first and held to return, five nil-in-production test hooks, and the sweepUpgrades call after the swap, which reads only the map Reload has just built (spec 7, Tasks 3 and 4).;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 5, rule 3): the two fleet proxy builds pass the row to fleetBoxOf(t) instead of reading t.FleetBox (-registry:FleetBox x2, +whole:Route x2); fleetBoxOf answers FleetLabel as authoritative when set, else FleetBox; an authoritative box has no fallback to another of the fleet's channels (503 errFleetDark instead). The edge in the agent, not root; it routes to fewer channels, never more.;rev3=census-ruling-edge-held-streams;basis=the edge in the agent (carlos-edge.service, user carlos): after the new upstream map is published, closes the held streams of any host the new map no longer holds (absent, not hibernating, route no longer Hibernate). Reads the freshly built in-memory map m and the in-memory held set; no read added beyond the rebuild Reload already does.;rev3=census-ruling-devbox-identity;basis=#486 A: only the devbox edge created by newDevboxEdge (carlos-devbox service user, not root) enables the new proxy hooks. Saves the existing DispatchArm result and reads t.Socket from an already-listed route when that arm is ArmSocket, passing it to configureDevboxProxy for per-request expected-owner validation and visitor-header rewriting. Adds one registry:Socket field site; no new registry query or file open, and ordinary fleet/agent edges leave the hook disabled. Final fix wave: its devbox-only outgoing-header/trailer hooks now also strip case-insensitive underscore/hyphen aliases through stripVisitorHeaders; no new read. registry:Account@9457,registry:Alias@24401,registry:Alias@24488,registry:Alias@25068,registry:App@9473,registry:Health@13198,registry:Health@13324,registry:Hibernate@28588,registry:Host@10784,registry:Host@10841,registry:Host@10877,registry:Host@11620,registry:Host@13807,registry:Host@13902,registry:Host@14190,registry:Host@14216,registry:Host@14268,registry:Host@18863,registry:Host@20770,registry:Host@21078,registry:Host@21105,registry:Host@21920,registry:Host@22492,registry:Host@24822,registry:Host@24871,registry:Host@4701,registry:Host@4755,registry:Host@4805,registry:Host@5826,registry:Kind@17199,registry:Kind@17221,registry:Prefix@22467,registry:Socket@11684,registry:Socket@17078,registry:Socket@21086,registry:Status@4626,registry:Target@22479,registry:Tunnel@9317,registry:Tunnel@9488,registry:Version@17180,registry:Version@17282,whole:RegionalDomain@25710,whole:Route@10932,whole:Route@11040,whole:Route@11740,whole:Route@14341,whole:Route@14405,whole:Route@14456,whole:Route@21138,whole:Route@21145,whole:Route@21241,whole:Route@22355,whole:Route@23523,whole:Route@25702,whole:Route@28590,whole:Route@294,whole:Route@3381,whole:Route@3439,whole:Route@5855,whole:Route@6744,whole:Route@6852,whole:Route@9379,whole:RouteAlias@24372,whole:RoutePath@21898 af3657d000b8ac5c22f10a2efe355d1e9748c7ddb24f6ef067b80dd166954ebf
+@coverage . b3277622b6f7d81984c39d0fe569500b659ab762733e32611b1777621c69e409
+@coverage infra/devbox a4d597f456ba1a8e0bbc0671e249eed6afd457ac206d84c724809b54051b8e10
+@coverage internal/devbox 42f6830904ebc3c1ffad34df93de727aaf64de4f548d33444e9a81b6596a8cc6
+@coverage internal/edge 08baebed603b9ecc1e175b5ee83712b9f1da7ab89e892680dca4448588d63d01
+@coverage internal/tsidentity 580665b5051ea5ce8cd092d848d813ca1c24af424e2342b7b47f4ade4a21873e
diff --git a/internal/tsidentity/whois.go b/internal/tsidentity/whois.go
new file mode 100644
index 000000000..eb1596826
--- /dev/null
+++ b/internal/tsidentity/whois.go
@@ -0,0 +1,86 @@
+// Package tsidentity resolves visitor identities through tailscaled's LocalAPI.
+package tsidentity
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+const maxWhoisBody = 1 << 20
+
+type identity struct {
+ client *http.Client
+}
+
+// New uses HTTP over socketPath with the caller's context and a request
+// timeout. A nonpositive timeout uses the devbox default of two seconds.
+func New(socketPath string, timeout time.Duration) edge.VisitorIdentity {
+ if timeout <= 0 {
+ timeout = 2 * time.Second
+ }
+ dialer := &net.Dialer{}
+ return &identity{client: &http.Client{
+ Timeout: timeout,
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, "unix", socketPath)
+ },
+ // Calls are cached by the edge; no idle socket needs to outlive a lookup.
+ DisableKeepAlives: true,
+ },
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }}
+}
+
+func (i *identity) Who(ctx context.Context, remote netip.AddrPort) (edge.Visitor, bool, error) {
+ remote = netip.AddrPortFrom(remote.Addr().Unmap(), remote.Port())
+ endpoint := "http://local-tailscaled.sock/localapi/v0/whois?" + url.Values{"addr": {remote.String()}}.Encode()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return edge.Visitor{}, false, err
+ }
+ resp, err := i.client.Do(req)
+ if err != nil {
+ return edge.Visitor{}, false, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusNotFound {
+ return edge.Visitor{}, false, nil
+ }
+ if resp.StatusCode != http.StatusOK {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: HTTP %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxWhoisBody+1))
+ if err != nil {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: read response: %w", err)
+ }
+ if len(body) > maxWhoisBody {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: response exceeds %d bytes", maxWhoisBody)
+ }
+ var result struct {
+ Node struct {
+ ComputedName string
+ Tags []string
+ }
+ UserProfile struct {
+ LoginName string
+ DisplayName string
+ }
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: decode response: %w", err)
+ }
+ if len(result.Node.Tags) > 0 || result.UserProfile.LoginName == "" {
+ return edge.Visitor{}, false, nil
+ }
+ return edge.Visitor{Login: result.UserProfile.LoginName, Name: result.UserProfile.DisplayName, Node: result.Node.ComputedName}, true, nil
+}
diff --git a/internal/tsidentity/whois_test.go b/internal/tsidentity/whois_test.go
new file mode 100644
index 000000000..22f70bec5
--- /dev/null
+++ b/internal/tsidentity/whois_test.go
@@ -0,0 +1,146 @@
+package tsidentity
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func fakeWhois(t *testing.T, handler http.HandlerFunc) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "whois.sock")
+ listener, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewUnstartedServer(handler)
+ if err := server.Listener.Close(); err != nil {
+ t.Fatal(err)
+ }
+ server.Listener = listener
+ server.Start()
+ t.Cleanup(server.Close)
+ return path
+}
+
+func TestWhoisParsesLoginNameNode(t *testing.T) {
+ for _, addr := range []string{"100.64.0.1:4321", "[fd7a:115c:a1e0::1]:4321", "[::ffff:100.64.0.1]:4321"} {
+ t.Run(addr, func(t *testing.T) {
+ wantAddr := addr
+ if addr == "[::ffff:100.64.0.1]:4321" {
+ wantAddr = "100.64.0.1:4321"
+ }
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "GET" || r.Host != "local-tailscaled.sock" || r.URL.Path != "/localapi/v0/whois" || r.URL.Query().Get("addr") != wantAddr {
+ t.Errorf("request: %s %s host=%q", r.Method, r.URL, r.Host)
+ }
+ fmt.Fprint(w, `{"Node":{"ComputedName":"Laptop","Tags":null},"UserProfile":{"LoginName":"Alice@github","DisplayName":"Alïce\r\n"}}`)
+ })
+ got, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort(addr))
+ want := edge.Visitor{Login: "Alice@github", Name: "Alïce\r\n", Node: "Laptop"}
+ if err != nil || !ok || got != want {
+ t.Fatalf("Who = %+v, %v, %v; want %+v", got, ok, err, want)
+ }
+ })
+ }
+}
+
+func TestWhoisTaggedNodeIsAnonymous(t *testing.T) {
+ for _, body := range []string{
+ `{"Node":{"ComputedName":"shop-dev","Tags":["tag:server"]},"UserProfile":{"LoginName":"alice@github"}}`,
+ `{"Node":{"ComputedName":"laptop"},"UserProfile":{"LoginName":"","DisplayName":"Alice"}}`,
+ `{}`, `null`,
+ } {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) })
+ v, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if err != nil || ok || v != (edge.Visitor{}) {
+ t.Fatalf("body %s: %+v, %v, %v", body, v, ok, err)
+ }
+ }
+}
+
+func TestWhoisResponses(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ wantErr bool
+ }{
+ {"not found", 404, "not found", false},
+ {"forbidden", 403, "forbidden", true},
+ {"unavailable", 503, "unavailable", true},
+ {"redirect", 302, "", true},
+ {"other success", 204, "", true},
+ {"invalid JSON", 200, "{", true},
+ {"trailing JSON", 200, `{"UserProfile":{"LoginName":"alice@github"}}{}`, true},
+ {"oversized", 200, `{"UserProfile":{"LoginName":"alice@github"},"padding":"` + strings.Repeat("x", 1<<20) + `"}`, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var requests atomic.Int32
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ if tc.status == 302 {
+ w.Header().Set("Location", "/redirected")
+ }
+ w.WriteHeader(tc.status)
+ fmt.Fprint(w, tc.body)
+ })
+ v, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if (err != nil) != tc.wantErr || ok || v != (edge.Visitor{}) {
+ t.Fatalf("Who = %+v, %v, %v", v, ok, err)
+ }
+ if requests.Load() != 1 {
+ t.Fatalf("requests = %d, want 1", requests.Load())
+ }
+ })
+ }
+}
+
+func TestWhoisTimeout(t *testing.T) {
+ for _, bodyStarted := range []bool{false, true} {
+ t.Run(fmt.Sprintf("body=%v", bodyStarted), func(t *testing.T) {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ if bodyStarted {
+ w.WriteHeader(200)
+ w.(http.Flusher).Flush()
+ }
+ <-r.Context().Done()
+ })
+ start := time.Now()
+ _, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ elapsed := time.Since(start)
+ if ok || !errors.Is(err, context.DeadlineExceeded) || elapsed < 1500*time.Millisecond || elapsed > 4*time.Second {
+ t.Fatalf("Who = %v, %v after %v", ok, err, elapsed)
+ }
+ })
+ }
+}
+
+func TestWhoisCallerContext(t *testing.T) {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ _, ok, err := New(path, 2*time.Second).Who(ctx, netip.MustParseAddrPort("100.64.0.1:4321"))
+ if ok || !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > time.Second {
+ t.Fatalf("Who = %v, %v after %v", ok, err, time.Since(start))
+ }
+}
+
+func TestWhoisMissingSocket(t *testing.T) {
+ _, ok, err := New(filepath.Join(t.TempDir(), "absent.sock"), 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if ok || err == nil {
+ t.Fatalf("Who = %v, %v", ok, err)
+ }
+}