Add devbox socket targets and per-link allow lists
Validate socket paths, file ownership and listener credentials before sharing. Persist normalized allow lists and expose owner-scoped list data and edge lookups. Cover refusals, kind changes, rollback and concurrent reads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+797
−28
internal/devbox/links.go+7 −0internal/devbox/links_test.go+1 −1internal/devbox/registrar.go+169 −18internal/devbox/registrar_socket_linux_test.go+292 −0internal/devbox/registrar_socket_test.go+252 −0internal/devbox/registrar_test.go+9 −9internal/devbox/socketcheck_linux.go+55 −0internal/devbox/socketcheck_other.go+12 −0
CI failed — run details
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..56c548abb 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,21 @@ 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 = "/run/carlos-devbox/sockets" |
| + // AnswerTimeout bounds port and socket connection checks. |
| AnswerTimeout = 300 * time.Millisecond |
| // maxFolderEntries caps what one upload creates: its archive entries |
| @@ -96,6 +105,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 |
| Reg *registry.Registry |
| Links *Links |
| Domain string // wildcard parent, e.g. "devbox.example.com" |
| @@ -125,12 +135,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 +205,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 +261,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 +329,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 +339,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 +354,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 +369,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 +407,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 +434,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 +535,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 +568,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 +826,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 +839,16 @@ 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() |
| + 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 +872,111 @@ func answering(ctx context.Context, port int) bool { |
| c.Close() |
| return true |
| } |
| + |
| +func validateAllow(entries []string) ([]string, *refusal) { |
| + if len(entries) > 64 { |
| + return nil, refuse(http.StatusBadRequest, CodeBadAllow) |
| + } |
| + var allow []string |
| + seen := make(map[string]bool, len(entries)) |
| + for _, entry := range entries { |
| + entry = strings.TrimSpace(entry) |
| + if len(entry) == 0 || len(entry) > 254 { |
| + return nil, refuse(http.StatusBadRequest, CodeBadAllow) |
| + } |
| + for i := range entry { |
| + if entry[i] < '!' || entry[i] > '~' { |
| + return nil, refuse(http.StatusBadRequest, CodeBadAllow) |
| + } |
| + } |
| + entry = strings.ToLower(entry) |
| + if !seen[entry] { |
| + allow = append(allow, entry) |
| + seen[entry] = true |
| + } |
| + } |
| + return allow, nil |
| +} |
| + |
| +// AllowFor returns a copy of the allow list for a host under Domain. |
| +func (r *Registrar) AllowFor(host string) []string { |
| + 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 nil |
| + } |
| + name := strings.TrimSuffix(host, domain) |
| + if ValidName(name) != nil { |
| + return nil |
| + } |
| + link, ok := r.Links.Get(name) |
| + if !ok || len(link.Allow) == 0 { |
| + return nil |
| + } |
| + return link.Allow |
| +} |
| + |
| +// SocketOwner returns the recorded owner of a socket target. |
| +func (r *Registrar) SocketOwner(path string) (uint32, bool) { |
| + path = filepath.Clean(path) |
| + for _, link := range r.Links.All() { |
| + if link.Kind == KindSocket && filepath.Clean(link.Socket) == path { |
| + return link.OwnerUID, true |
| + } |
| + } |
| + return 0, false |
| +} |
| + |
| +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 { |
| + 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..3c3a75630 |
| --- /dev/null |
| +++ b/internal/devbox/registrar_socket_linux_test.go |
| @@ -0,0 +1,292 @@ |
| +//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") |
| + wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", path, nil), CodeSocketPath) |
| + 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"} { |
| + wantCode(t, shareAllow(t, f, uint32(os.Getuid()), KindSocket, "shop", path, nil), CodeSocketPath) |
| + } |
| + 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 TestSocketOwner(t *testing.T) { |
| + f, path, _ := socketFixture(t) |
| + uid := uint32(os.Getuid()) |
| + wantOK(t, shareAllow(t, f, uid, KindSocket, "shop", path, nil)) |
| + for _, path := range []string{path, filepath.Dir(path) + "/./shop.sock"} { |
| + if got, ok := f.r.SocketOwner(path); !ok || got != uid { |
| + t.Fatalf("SocketOwner(%q) = %d,%v", path, got, ok) |
| + } |
| + } |
| + if _, ok := f.r.SocketOwner(path + ".other"); ok { |
| + t.Fatal("unknown socket found") |
| + } |
| + wantOK(t, f.shareLive(t, uid, "shop", 8080)) |
| + if _, ok := f.r.SocketOwner(path); 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.SocketOwner(path); 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.SocketOwner(path); 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..3b6911972 |
| --- /dev/null |
| +++ b/internal/devbox/registrar_socket_test.go |
| @@ -0,0 +1,252 @@ |
| +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() |
| +} |
diff --git a/internal/devbox/registrar_test.go b/internal/devbox/registrar_test.go| index 75ce97a70..b409e3dda 100644 |
| --- a/internal/devbox/registrar_test.go |
| +++ b/internal/devbox/registrar_test.go |
| @@ -296,7 +296,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 +339,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 +359,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 +373,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 +1002,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 +1165,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 +1212,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) |
| +} |