跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

0011-client-project-transport.patch

995 行 · 29.4 KB历史下载
1diff --git a/pkg/reversesshfs/rooted.go b/pkg/reversesshfs/rooted.go
2index 84fb0b2..ab7e0ee 100644
3--- a/pkg/reversesshfs/rooted.go
4+++ b/pkg/reversesshfs/rooted.go
5@@ -28,6 +28,7 @@ import (
6 type rootedHandlers struct {
7 rootPath string // slash-separated, cleaned
8 root *os.Root
9+ cloud bool // stricter checks for the remote desktop project transport
10 readonly bool
11 readonlyNames []string
12 foldedNames []string // readonlyNames as FoldName gives them
13@@ -110,7 +111,7 @@ func (h *rootedHandlers) writableRel(p string, entry bool) (string, error) {
14 if err != nil {
15 return "", err
16 }
17- if h.isReadonlyName(r) || !writableName(r) {
18+ if h.isReadonlyName(r) || !writableName(r) || (h.cloud && (r == "." || CloudPathHidden(r))) {
19 return "", errDenied
20 }
21 if lexicalGuard {
22@@ -135,7 +136,7 @@ func (h *rootedHandlers) writableRel(p string, entry bool) (string, error) {
23 var Guard func(root, rel string, entry bool) bool
24
25 func (h *rootedHandlers) guard(rel string, entry bool) error {
26- if Guard != nil && !Guard(h.guardRoot, rel, entry) {
27+ if !h.cloud && Guard != nil && !Guard(h.guardRoot, rel, entry) {
28 return errDenied
29 }
30 return nil
31@@ -208,7 +209,7 @@ func (f writableFile) WriteAt(b []byte, off int64) (int, error) {
32 }
33
34 func (h *rootedHandlers) openWritable(r *sftp.Request) (writableFile, error) {
35- if r.Pflags().Creat {
36+ if !h.cloud && r.Pflags().Creat {
37 h.creating(r.Filepath)
38 }
39 f, err := h.openFile(r)
40@@ -412,11 +413,12 @@ func (h *rootedHandlers) RealPath(p string) (string, error) {
41 // by the path f was opened with, which the client could have made a symlink to a folder
42 // outside the root), so the entries are those of f whatever it was renamed to.
43 type dirLister struct {
44- mu sync.Mutex
45- f *os.File
46- buf []os.FileInfo // read, not listed yet
47- next int64 // offset of buf[0]
48- eof bool
49+ cloud bool
50+ mu sync.Mutex
51+ f *os.File
52+ buf []os.FileInfo // read, not listed yet
53+ next int64 // offset of buf[0]
54+ eof bool
55 }
56
57 func (d *dirLister) ListAt(ls []os.FileInfo, offset int64) (int, error) {
58@@ -427,6 +429,11 @@ func (d *dirLister) ListAt(ls []os.FileInfo, offset int64) (int, error) {
59 }
60 for len(d.buf) < len(ls) && !d.eof {
61 fis, err := d.f.Readdir(len(ls) - len(d.buf))
62+ if d.cloud {
63+ fis = slices.DeleteFunc(fis, func(info os.FileInfo) bool {
64+ return CloudPathHidden(info.Name()) || !(info.IsDir() || info.Mode().IsRegular())
65+ })
66+ }
67 d.buf = append(d.buf, fis...)
68 if errors.Is(err, io.EOF) {
69 d.eof = true
70@@ -444,7 +451,11 @@ func (d *dirLister) ListAt(ls []os.FileInfo, offset int64) (int, error) {
71 }
72
73 func (d *dirLister) Close() error {
74- return d.f.Close()
75+ err := d.f.Close()
76+ if d.cloud {
77+ <-cloudSlots
78+ }
79+ return err
80 }
81
82 type listerAt []os.FileInfo
83diff --git a/pkg/reversesshfs/rooted_darwin.go b/pkg/reversesshfs/rooted_darwin.go
84index 589c215..624cbdf 100644
85--- a/pkg/reversesshfs/rooted_darwin.go
86+++ b/pkg/reversesshfs/rooted_darwin.go
87@@ -37,3 +37,24 @@ func fchmodatNoFollow(dirfd int, base string, mode uint32) error {
88 }
89 return unix.Fchmodat(dirfd, base, mode, unix.AT_SYMLINK_NOFOLLOW)
90 }
91+
92+// Open each component without following links and keep the client on the
93+// selected volume. Truncation is deferred until the descriptor is checked.
94+func cloudOpenat(fd int, name string, flags int, mode uint32) (int, error) {
95+ next, err := unix.Openat(fd, name, flags, mode)
96+ if err != nil {
97+ return -1, err
98+ }
99+ var parent, child unix.Stat_t
100+ if err = unix.Fstat(fd, &parent); err == nil {
101+ err = unix.Fstat(next, &child)
102+ }
103+ if err == nil && parent.Dev != child.Dev {
104+ err = unix.EXDEV
105+ }
106+ if err != nil {
107+ unix.Close(next)
108+ return -1, err
109+ }
110+ return next, nil
111+}
112diff --git a/pkg/reversesshfs/rooted_linux.go b/pkg/reversesshfs/rooted_linux.go
113index 2ae2e83..344d435 100644
114--- a/pkg/reversesshfs/rooted_linux.go
115+++ b/pkg/reversesshfs/rooted_linux.go
116@@ -56,3 +56,12 @@ func fchmodatOPath(dirfd int, base string, mode uint32) error {
117 }
118 return unix.Chmod("/proc/self/fd/"+strconv.Itoa(fd), mode)
119 }
120+
121+// NO_XDEV also catches a bind mount pointing outside the authorized directory
122+// on the same filesystem. Kernels without openat2 fail closed.
123+func cloudOpenat(fd int, name string, flags int, mode uint32) (int, error) {
124+ if flags&unix.O_CREAT == 0 {
125+ mode = 0
126+ }
127+ return unix.Openat2(fd, name, &unix.OpenHow{Flags: uint64(flags), Mode: uint64(mode), Resolve: unix.RESOLVE_NO_XDEV | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH})
128+}
129diff --git a/pkg/reversesshfs/rooted_unix.go b/pkg/reversesshfs/rooted_unix.go
130index 6515874..cfa3104 100644
131--- a/pkg/reversesshfs/rooted_unix.go
132+++ b/pkg/reversesshfs/rooted_unix.go
133@@ -81,7 +81,7 @@ func (h *rootedHandlers) openParent(rel string) (int, string, error) {
134 unix.Close(fd)
135 return -1, "", unix.EACCES
136 }
137- next, err := unix.Openat(fd, c, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0)
138+ next, err := h.openat(fd, c, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0)
139 unix.Close(fd)
140 if err != nil {
141 return -1, "", err
142@@ -114,7 +114,7 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
143 if pf.Creat {
144 flags |= unix.O_CREAT
145 }
146- if pf.Trunc {
147+ if pf.Trunc && !h.cloud {
148 flags |= unix.O_TRUNC
149 }
150 if pf.Excl {
151@@ -131,18 +131,24 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
152 defer unix.Close(dirfd)
153 // O_NONBLOCK: a FIFO would block the server, which handles one request at a time.
154 // It has no effect on regular files, the only ones served.
155- fd, err := unix.Openat(dirfd, base, flags|unix.O_NONBLOCK, mode)
156+ fd, err := h.openat(dirfd, base, flags|unix.O_NONBLOCK, mode)
157 if err != nil {
158 return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
159 }
160 var st unix.Stat_t
161- if err := unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG {
162+ if err := unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || (h.cloud && st.Nlink != 1) {
163 unix.Close(fd)
164 if err == nil {
165 err = errDenied
166 }
167 return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
168 }
169+ if h.cloud && pf.Trunc {
170+ if err := unix.Ftruncate(fd, 0); err != nil {
171+ unix.Close(fd)
172+ return nil, err
173+ }
174+ }
175 return os.NewFile(uintptr(fd), r.Filepath), nil
176 }
177
178@@ -332,3 +338,11 @@ func (h *rootedHandlers) StatVFS(r *sftp.Request) (*sftp.StatVFS, error) {
179 }
180 return statVFS(&st), nil
181 }
182+
183+// Cloud shares stop at nested mounts, including when walking parent directories.
184+func (h *rootedHandlers) openat(fd int, name string, flags int, mode uint32) (int, error) {
185+ if h.cloud {
186+ return cloudOpenat(fd, name, flags, mode)
187+ }
188+ return unix.Openat(fd, name, flags, mode)
189+}
190diff --git a/pkg/reversesshfs/rooted_windows.go b/pkg/reversesshfs/rooted_windows.go
191index e4c87c1..cf67ab0 100644
192--- a/pkg/reversesshfs/rooted_windows.go
193+++ b/pkg/reversesshfs/rooted_windows.go
194@@ -193,6 +193,9 @@ func (h *rootedHandlers) checkHandle(fh windows.Handle) error {
195 if err != nil {
196 return err
197 }
198+ if h.cloud && CloudPathHidden(rel) {
199+ return errDenied
200+ }
201 if rel == "." {
202 return nil
203 }
204@@ -356,6 +359,14 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
205 windows.CloseHandle(fh)
206 return nil, err
207 }
208+ if h.cloud {
209+ var fi windows.ByHandleFileInformation
210+ err := windows.GetFileInformationByHandle(fh, &fi)
211+ if err != nil || fi.NumberOfLinks != 1 || fi.FileAttributes&(windows.FILE_ATTRIBUTE_DIRECTORY|windows.FILE_ATTRIBUTE_REPARSE_POINT|windows.FILE_ATTRIBUTE_DEVICE) != 0 {
212+ windows.CloseHandle(fh)
213+ return nil, errDenied
214+ }
215+ }
216 if pf.Trunc {
217 if err := windows.Ftruncate(fh, 0); err != nil {
218 windows.CloseHandle(fh)
219diff --git a/pkg/reversesshfs/cloud.go b/pkg/reversesshfs/cloud.go
220new file mode 100644
221index 0000000..478459c
222--- /dev/null
223+++ b/pkg/reversesshfs/cloud.go
224@@ -0,0 +1,275 @@
225+//go:build linux || darwin || windows
226+
227+package reversesshfs
228+
229+import (
230+ "errors"
231+ "io"
232+ "os"
233+ "path"
234+ "path/filepath"
235+ "strings"
236+ "sync"
237+
238+ "github.com/pkg/sftp"
239+)
240+
241+// CloudShare pins one local directory for one authenticated client-initiated
242+// stream. Only a virtual "/" is visible to the peer. The caller authorizes and
243+// validates the physical project directory before creating this grant.
244+type CloudShare struct {
245+ mu sync.Mutex
246+ handlers *cloudHandlers
247+ stream io.ReadWriteCloser
248+ done chan struct{}
249+ closed bool
250+}
251+
252+// OpenCloudShare expects an absolute, symlink-resolved path supplied by the local picker.
253+func OpenCloudShare(directory string, readOnly bool) (*CloudShare, error) {
254+ if !filepath.IsAbs(directory) || filepath.Clean(directory) != directory || filepath.Dir(directory) == directory || CloudPathHidden(filepath.ToSlash(directory)) {
255+ return nil, os.ErrPermission
256+ }
257+ sys, err := openCloudRoot(directory)
258+ if err != nil {
259+ return nil, err
260+ }
261+ h := &cloudHandlers{&rootedHandlers{rootPath: "/", guardRoot: directory, rootedSys: sys, readonly: readOnly, cloud: true}}
262+ return &CloudShare{handlers: h}, nil
263+}
264+
265+// Serve consumes stream, including when the grant has already been revoked.
266+func (c *CloudShare) Serve(stream io.ReadWriteCloser) error {
267+ c.mu.Lock()
268+ if c.closed || c.stream != nil {
269+ c.mu.Unlock()
270+ stream.Close()
271+ return os.ErrClosed
272+ }
273+ c.stream, c.done = stream, make(chan struct{})
274+ h := c.handlers
275+ c.mu.Unlock()
276+
277+ srv := sftp.NewRequestServer(stream, sftp.Handlers{FileGet: h, FilePut: h, FileCmd: h, FileList: h},
278+ sftp.WithRSSequential(), sftp.WithRSMaxHandles(64), sftp.WithRSMaxTxPacket(64*1024))
279+ err := srv.Serve()
280+ stream.Close()
281+ c.mu.Lock()
282+ h.rootedSys.close()
283+ c.closed = true
284+ close(c.done)
285+ c.mu.Unlock()
286+ return err
287+}
288+
289+// Close revokes the grant and waits until buffered requests and open file
290+// handles have been retired. A closed grant cannot attach to another stream.
291+func (c *CloudShare) Close() error {
292+ c.mu.Lock()
293+ if c.stream == nil {
294+ defer c.mu.Unlock()
295+ if c.closed {
296+ return nil
297+ }
298+ c.closed = true
299+ return c.handlers.rootedSys.close()
300+ }
301+ stream, done, closed := c.stream, c.done, c.closed
302+ c.closed = true
303+ c.mu.Unlock()
304+ if !closed {
305+ stream.Close()
306+ }
307+ <-done
308+ return nil
309+}
310+
311+// CloudPathHidden reports whether the file policy withholds this relative
312+// path, including credential stores, Git history and host hooks.
313+// This filename policy cannot identify secrets embedded in ordinary source.
314+func CloudPathHidden(rel string) bool {
315+ for _, name := range strings.Split(rel, "/") {
316+ n := FoldName(name)
317+ switch n {
318+ case ".git", ".hg", ".sl", ".jj", ".ssh", ".gnupg", ".aws", ".kube", ".azure", ".docker", ".config", ".claude-cage", ".agent-vm", ".lima",
319+ ".env", ".envrc", ".netrc", "_netrc", ".npmrc", ".pypirc", ".git-credentials", ".gitconfig", ".gitmodules",
320+ ".claude", ".codex", ".cursor", ".vscode", ".idea", ".zed", ".gemini", ".devcontainer", ".devcontainer.json",
321+ ".dir-locals.el", ".mcp.json", ".githooks", ".husky", ".pre-commit-config.yaml",
322+ ".yarn", ".yarnrc.yml", ".pnpmfile.cjs", ".cargo", ".lfsconfig", ".mise", "mise.toml", "mise.local.toml", ".mise.toml", ".mise.local.toml",
323+ "lefthook.yml", ".lefthook.yml", "lefthook.yaml", ".lefthook.yaml", "lefthook-local.yml", ".lefthook-local.yml",
324+ "..namedfork", "desktop.ini", ".ds_store":
325+ return true
326+ }
327+ if strings.HasPrefix(n, ".env.") || strings.HasPrefix(n, "id_rsa") || strings.HasPrefix(n, "id_ed25519") || strings.HasPrefix(n, "id_ecdsa") || strings.HasPrefix(n, "id_dsa") {
328+ return true
329+ }
330+ switch path.Ext(n) {
331+ case ".pem", ".key", ".p12", ".pfx", ".ppk", ".lnk", ".url", ".scf", ".library-ms", ".searchconnector-ms":
332+ return true
333+ }
334+ }
335+ return false
336+}
337+
338+// Use the confined server's handle-relative writes. All reads and metadata
339+// requests use the same no-follow path walk, including the leaf. An internal
340+// symlink could otherwise expose a protected path under another name.
341+type cloudHandlers struct{ *rootedHandlers }
342+
343+func (h *cloudHandlers) accessible(p string) (string, error) {
344+ rel, err := h.rel(p)
345+ if err != nil || !writableName(rel) || CloudPathHidden(rel) {
346+ return "", errDenied
347+ }
348+ return rel, nil
349+}
350+
351+// One desktop process can serve several grants. Bound long-lived descriptors
352+// across all of them, leaving room for the SSH connections and the workbench.
353+var cloudSlots = make(chan struct{}, 128)
354+
355+func acquireCloudSlot() error {
356+ select {
357+ case cloudSlots <- struct{}{}:
358+ return nil
359+ default:
360+ return errors.New("too many open project files")
361+ }
362+}
363+
364+type cloudFile struct {
365+ writableFile
366+ writable bool
367+}
368+
369+func (f cloudFile) Close() error {
370+ err := f.File.Close()
371+ <-cloudSlots
372+ return err
373+}
374+
375+func (h *cloudHandlers) fileHandle(r *sftp.Request, write bool) (cloudFile, error) {
376+ if err := acquireCloudSlot(); err != nil {
377+ return cloudFile{}, err
378+ }
379+ var f writableFile
380+ var err error
381+ if write {
382+ f, err = h.openWritable(r)
383+ } else {
384+ var rel string
385+ if rel, err = h.accessible(r.Filepath); err == nil {
386+ f.File, err = h.cloudOpenRead(rel)
387+ }
388+ }
389+ if err != nil {
390+ <-cloudSlots
391+ return cloudFile{}, err
392+ }
393+ return cloudFile{writableFile: f, writable: write}, nil
394+}
395+
396+func (h *cloudHandlers) Fileread(r *sftp.Request) (io.ReaderAt, error) { return h.fileHandle(r, false) }
397+func (h *cloudHandlers) Filewrite(r *sftp.Request) (io.WriterAt, error) { return h.fileHandle(r, true) }
398+func (h *cloudHandlers) OpenFile(r *sftp.Request) (sftp.WriterAtReaderAt, error) {
399+ return h.fileHandle(r, true)
400+}
401+
402+func (h *cloudHandlers) Filelist(r *sftp.Request) (sftp.ListerAt, error) {
403+ rel, err := h.accessible(r.Filepath)
404+ if err != nil {
405+ return nil, err
406+ }
407+ if r.Method == "Stat" {
408+ if file, ok := r.HandleFile().(interface{ Stat() (os.FileInfo, error) }); ok {
409+ info, err := file.Stat()
410+ if err != nil {
411+ return nil, err
412+ }
413+ return listerAt{info}, nil
414+ }
415+ }
416+ f, err := h.cloudOpenRead(rel)
417+ if err != nil {
418+ return nil, err
419+ }
420+ if r.Method == "List" {
421+ if err := acquireCloudSlot(); err != nil {
422+ f.Close()
423+ return nil, err
424+ }
425+ return &dirLister{f: f, cloud: true}, nil
426+ }
427+ defer f.Close()
428+ info, err := f.Stat()
429+ if err != nil {
430+ return nil, err
431+ }
432+ return listerAt{info}, nil
433+}
434+
435+func (h *cloudHandlers) Lstat(r *sftp.Request) (sftp.ListerAt, error) { return h.Filelist(r) }
436+func (h *cloudHandlers) Readlink(string) (string, error) { return "", errDenied }
437+func (h *cloudHandlers) RealPath(p string) (string, error) {
438+ rel, err := h.accessible(p)
439+ if err != nil {
440+ return "", err
441+ }
442+ return path.Join("/", rel), nil
443+}
444+
445+func (h *cloudHandlers) Filecmd(r *sftp.Request) error {
446+ switch r.Method {
447+ case "Setstat":
448+ if h.readonly || r.AttrFlags().UidGid {
449+ return errDenied
450+ }
451+ if f, ok := r.HandleFile().(cloudFile); ok && f.writable {
452+ return h.fsetstat(f.File, r)
453+ }
454+ // A read handle cannot acquire write access through FSETSTAT.
455+ if r.HandleFile() != nil {
456+ return errDenied
457+ }
458+ f, err := h.openFile(&sftp.Request{Filepath: r.Filepath, Flags: 2 /* SSH_FXF_WRITE */})
459+ if err != nil {
460+ return err
461+ }
462+ defer f.Close()
463+ return h.fsetstat(f, r)
464+ case "Rename":
465+ return h.rename(r, true)
466+ case "Remove", "Rmdir":
467+ return h.remove(r)
468+ case "Mkdir":
469+ return h.mkdir(r)
470+ default:
471+ // Refuse both hard-link and symbolic-link creation.
472+ return errDenied
473+ }
474+}
475+
476+// The remote environment owns its own disk reports; querying the desktop
477+// volume via an SFTP extension would disclose unrelated host information.
478+func (h *cloudHandlers) StatVFS(*sftp.Request) (*sftp.StatVFS, error) {
479+ return nil, sftp.ErrSSHFxOpUnsupported
480+}
481+
482+func (h *cloudHandlers) PosixRename(r *sftp.Request) error { return h.rename(r, false) }
483+
484+// MatchesRoot compares the directory as picked before validation with the one
485+// actually held by this grant. Replacing the picker path invalidates the grant.
486+func (c *CloudShare) MatchesRoot(selected os.FileInfo) bool {
487+ c.mu.Lock()
488+ defer c.mu.Unlock()
489+ if c.closed || selected == nil {
490+ return false
491+ }
492+ f, err := c.handlers.cloudOpenRead(".")
493+ if err != nil {
494+ return false
495+ }
496+ defer f.Close()
497+ info, err := f.Stat()
498+ return err == nil && info.IsDir() && os.SameFile(info, selected)
499+}
500diff --git a/pkg/reversesshfs/cloud_test.go b/pkg/reversesshfs/cloud_test.go
501new file mode 100644
502index 0000000..90edff5
503--- /dev/null
504+++ b/pkg/reversesshfs/cloud_test.go
505@@ -0,0 +1,244 @@
506+//go:build linux || darwin || windows
507+
508+package reversesshfs
509+
510+import (
511+ "errors"
512+ "io"
513+ "net"
514+ "os"
515+ "path/filepath"
516+ "runtime"
517+ "slices"
518+ "testing"
519+
520+ "github.com/pkg/sftp"
521+)
522+
523+func cloudClient(t *testing.T, directory string, ro bool) (*CloudShare, *sftp.Client) {
524+ t.Helper()
525+ dir, err := filepath.EvalSymlinks(directory)
526+ if err != nil {
527+ t.Fatal(err)
528+ }
529+ grant, err := OpenCloudShare(dir, ro)
530+ if err != nil {
531+ t.Fatal(err)
532+ }
533+ info, err := os.Stat(dir)
534+ if err != nil || !grant.MatchesRoot(info) {
535+ t.Fatal("grant does not match selected directory", err)
536+ }
537+ a, b := net.Pipe()
538+ t.Cleanup(func() { b.Close(); grant.Close() })
539+ go grant.Serve(a)
540+ c, err := sftp.NewClientPipe(b, b)
541+ if err != nil {
542+ t.Fatal(err)
543+ }
544+ return grant, c
545+}
546+
547+func TestCloudProjectLifecycle(t *testing.T) {
548+ root := t.TempDir()
549+ hostFile := filepath.Join(root, "source.go")
550+ if err := os.WriteFile(hostFile, []byte("before"), 0644); err != nil {
551+ t.Fatal(err)
552+ }
553+ grant, c := cloudClient(t, root, false)
554+ f, err := c.Open("/source.go")
555+ if err != nil {
556+ t.Fatal(err)
557+ }
558+ data, err := io.ReadAll(f)
559+ if err != nil || string(data) != "before" {
560+ t.Fatalf("remote read = %q, %v", data, err)
561+ }
562+ f.Close()
563+ if err = c.Mkdir("/src"); err != nil {
564+ t.Fatal(err)
565+ }
566+ tmp, err := c.Create("/src/save")
567+ if err != nil {
568+ t.Fatal(err)
569+ }
570+ if _, err = tmp.Write([]byte("after")); err != nil {
571+ t.Fatal(err)
572+ }
573+ if err = tmp.Close(); err != nil {
574+ t.Fatal(err)
575+ }
576+ if err = c.PosixRename("/src/save", "/source.go"); err != nil {
577+ t.Fatal(err)
578+ }
579+ data, err = os.ReadFile(hostFile)
580+ if err != nil || string(data) != "after" {
581+ t.Fatalf("local read = %q, %v", data, err)
582+ }
583+ open, err := c.OpenFile("/source.go", os.O_WRONLY)
584+ if err != nil {
585+ t.Fatal(err)
586+ }
587+ if err = grant.Close(); err != nil {
588+ t.Fatal(err)
589+ }
590+ if _, err = open.Write([]byte("revoked")); err == nil {
591+ t.Fatal("revoked open handle wrote")
592+ }
593+ if _, err = c.Stat("/source.go"); err == nil {
594+ t.Fatal("revoked grant usable")
595+ }
596+}
597+
598+func TestCloudHostileClient(t *testing.T) {
599+ tmp := t.TempDir()
600+ root := filepath.Join(tmp, "project")
601+ if err := os.MkdirAll(filepath.Join(root, ".Git"), 0700); err != nil {
602+ t.Fatal(err)
603+ }
604+ out := filepath.Join(tmp, "outside")
605+ for _, name := range []string{out, filepath.Join(root, ".eNv.production"), filepath.Join(root, ".Git", "config")} {
606+ if err := os.WriteFile(name, []byte("private"), 0600); err != nil {
607+ t.Fatal(err)
608+ }
609+ }
610+ hard := filepath.Join(root, "alias")
611+ if err := os.Link(out, hard); err != nil {
612+ t.Fatal(err)
613+ }
614+ if runtime.GOOS != "windows" {
615+ if err := os.Symlink(out, filepath.Join(root, "symlink")); err != nil {
616+ t.Fatal(err)
617+ }
618+ if err := os.Symlink(".Git", filepath.Join(root, "inner")); err != nil {
619+ t.Fatal(err)
620+ }
621+ }
622+ _, c := cloudClient(t, root, false)
623+ for _, p := range []string{"../outside", "/alias", "/symlink", "/inner/config", "/.Git/config", "/.eNv.production", "/id_ed25519", "/file.key"} {
624+ if _, err := c.Open(p); err == nil {
625+ t.Fatalf("opened %s", p)
626+ }
627+ }
628+ for _, p := range []string{"/alias", "/.Git/config", "/.eNv.production", "/id_ed25519", "/file.key"} {
629+ if _, err := c.Create(p); err == nil {
630+ t.Fatalf("created/truncated %s", p)
631+ }
632+ if err := c.Truncate(p, 0); err == nil {
633+ t.Fatalf("truncate %s", p)
634+ }
635+ }
636+ if err := c.Link("/alias", "/link"); err == nil {
637+ t.Fatal("hard link created")
638+ }
639+ if err := c.Symlink("../outside", "/link"); err == nil {
640+ t.Fatal("symlink created")
641+ }
642+ if err := c.PosixRename("/alias", "/.env"); err == nil {
643+ t.Fatal("replaced secret")
644+ }
645+ files, err := c.ReadDir("/")
646+ if err != nil {
647+ t.Fatal(err)
648+ }
649+ if slices.ContainsFunc(files, func(fi os.FileInfo) bool { return CloudPathHidden(fi.Name()) }) {
650+ t.Fatal("listed protected file")
651+ }
652+ content, err := os.ReadFile(out)
653+ if err != nil || string(content) != "private" {
654+ t.Fatal("outside data changed", err)
655+ }
656+}
657+
658+func TestCloudReadOnlyAndRootReplacement(t *testing.T) {
659+ original := t.TempDir()
660+ if err := os.WriteFile(filepath.Join(original, "allowed"), []byte("ok"), 0600); err != nil {
661+ t.Fatal(err)
662+ }
663+ g, c := cloudClient(t, original, true)
664+ if _, err := c.Create("/new"); err == nil {
665+ t.Fatal("created on read-only grant")
666+ }
667+ if err := c.Remove("/allowed"); err == nil {
668+ t.Fatal("removed on read-only grant")
669+ }
670+ if err := c.Mkdir("/dir"); err == nil {
671+ t.Fatal("mkdir on read-only grant")
672+ }
673+ other, err := os.Stat(t.TempDir())
674+ if err != nil || g.MatchesRoot(other) {
675+ t.Fatal("root identity accepted replacement", err)
676+ }
677+ if runtime.GOOS != "windows" {
678+ if err := os.Rename(original, original+"-old"); err != nil {
679+ t.Fatal(err)
680+ }
681+ t.Cleanup(func() { os.RemoveAll(original + "-old") })
682+ if err := os.Mkdir(original, 0700); err != nil {
683+ t.Fatal(err)
684+ }
685+ if _, err := c.Stat("/allowed"); err != nil {
686+ t.Fatal("lost pinned root", err)
687+ }
688+ if err := os.WriteFile(filepath.Join(original, "replacement"), []byte("private"), 0600); err != nil {
689+ t.Fatal(err)
690+ }
691+ if _, err := c.Open("/replacement"); err == nil {
692+ t.Fatal("followed replacement root")
693+ }
694+ }
695+}
696+
697+func TestCloudRefusesReusingRevokedGrant(t *testing.T) {
698+ dir, err := filepath.EvalSymlinks(t.TempDir())
699+ if err != nil {
700+ t.Fatal(err)
701+ }
702+ g, err := OpenCloudShare(dir, false)
703+ if err != nil {
704+ t.Fatal(err)
705+ }
706+ if err := g.Close(); err != nil {
707+ t.Fatal(err)
708+ }
709+ a, b := net.Pipe()
710+ defer b.Close()
711+ if !errors.Is(g.Serve(a), os.ErrClosed) {
712+ t.Fatal("accepted revoked grant")
713+ }
714+}
715+
716+func TestCloudOpenFilesBoundAcrossShares(t *testing.T) {
717+ root := t.TempDir()
718+ if err := os.WriteFile(filepath.Join(root, "f"), []byte("x"), 0600); err != nil {
719+ t.Fatal(err)
720+ }
721+ grants := make([]*CloudShare, 0, 3)
722+ clients := make([]*sftp.Client, 0, 3)
723+ for range 3 {
724+ g, c := cloudClient(t, root, true)
725+ grants = append(grants, g)
726+ clients = append(clients, c)
727+ }
728+ for _, client := range clients[:2] {
729+ for range 64 {
730+ if _, err := client.Open("/f"); err != nil {
731+ t.Fatal(err)
732+ }
733+ }
734+ if _, err := client.Open("/f"); err == nil {
735+ t.Fatal("per-stream handle cap bypassed")
736+ }
737+ }
738+ if _, err := clients[2].Open("/f"); err == nil {
739+ t.Fatal("process-wide handle cap bypassed")
740+ }
741+ if err := grants[0].Close(); err != nil {
742+ t.Fatal(err)
743+ }
744+ f, err := clients[2].Open("/f")
745+ if err != nil {
746+ t.Fatal("revocation leaked file handles", err)
747+ }
748+ f.Close()
749+}
750diff --git a/pkg/reversesshfs/cloud_unix.go b/pkg/reversesshfs/cloud_unix.go
751new file mode 100644
752index 0000000..15b9584
753--- /dev/null
754+++ b/pkg/reversesshfs/cloud_unix.go
755@@ -0,0 +1,52 @@
756+//go:build linux || darwin
757+
758+package reversesshfs
759+
760+import (
761+ "os"
762+ "path/filepath"
763+ "strings"
764+
765+ "golang.org/x/sys/unix"
766+)
767+
768+// Start at the volume root, so replacing any component of the picker result
769+// with a symlink while the grant is being opened cannot redirect it.
770+func openCloudRoot(directory string) (rootedSys, error) {
771+ const flags = unix.O_RDONLY | unix.O_DIRECTORY | unix.O_NOFOLLOW | unix.O_CLOEXEC | unix.O_NONBLOCK
772+ fd, err := unix.Open("/", flags, 0)
773+ if err != nil {
774+ return rootedSys{}, err
775+ }
776+ for _, c := range strings.Split(strings.TrimPrefix(filepath.Clean(directory), "/"), "/") {
777+ next, err := unix.Openat(fd, c, flags, 0)
778+ unix.Close(fd)
779+ if err != nil {
780+ return rootedSys{}, err
781+ }
782+ fd = next
783+ }
784+ return rootedSys{rootFD: fd}, nil
785+}
786+
787+func (h *rootedHandlers) cloudOpenRead(rel string) (*os.File, error) {
788+ parent, base, err := h.openParent(rel)
789+ if err != nil {
790+ return nil, err
791+ }
792+ defer unix.Close(parent)
793+ fd, err := cloudOpenat(parent, base, unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK|unix.O_RDONLY, 0)
794+ if err != nil {
795+ return nil, err
796+ }
797+ var st unix.Stat_t
798+ err = unix.Fstat(fd, &st)
799+ if err == nil && st.Mode&unix.S_IFMT != unix.S_IFDIR && (st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1) {
800+ err = errDenied
801+ }
802+ if err != nil {
803+ unix.Close(fd)
804+ return nil, err
805+ }
806+ return os.NewFile(uintptr(fd), rel), nil
807+}
808diff --git a/pkg/reversesshfs/cloud_unix_test.go b/pkg/reversesshfs/cloud_unix_test.go
809new file mode 100644
810index 0000000..848aadc
811--- /dev/null
812+++ b/pkg/reversesshfs/cloud_unix_test.go
813@@ -0,0 +1,115 @@
814+//go:build darwin || linux
815+
816+package reversesshfs
817+
818+import (
819+ "os"
820+ "path/filepath"
821+ "testing"
822+
823+ "golang.org/x/sys/unix"
824+)
825+
826+// Even when the client races normal file edits, neither the read nor the
827+// write path may follow the replacement symlink (including on truncation).
828+func TestCloudLinkSwapAndFifo(t *testing.T) {
829+ tmp := t.TempDir()
830+ outside, root := filepath.Join(tmp, "outside"), filepath.Join(tmp, "working")
831+ if err := os.Mkdir(root, 0700); err != nil {
832+ t.Fatal(err)
833+ }
834+ if err := os.WriteFile(outside, []byte("secret"), 0600); err != nil {
835+ t.Fatal(err)
836+ }
837+ if err := unix.Mkfifo(filepath.Join(root, "fifo"), 0600); err != nil {
838+ t.Fatal(err)
839+ }
840+ _, c := cloudClient(t, root, false)
841+ if _, err := c.Open("/fifo"); err == nil {
842+ t.Fatal("read FIFO opened")
843+ }
844+ if _, err := c.OpenFile("/fifo", os.O_WRONLY); err == nil {
845+ t.Fatal("write FIFO opened")
846+ }
847+
848+ swapped := filepath.Join(root, "swapped")
849+ done := make(chan struct{})
850+ raceErr := make(chan error, 1)
851+ go func() {
852+ for {
853+ select {
854+ case <-done:
855+ raceErr <- nil
856+ return
857+ default:
858+ }
859+ link, regular := filepath.Join(root, "link-temp"), filepath.Join(root, "regular-temp")
860+ if err := os.Symlink(outside, link); err != nil {
861+ raceErr <- err
862+ return
863+ }
864+ if err := os.Rename(link, swapped); err != nil {
865+ raceErr <- err
866+ return
867+ }
868+ if err := os.WriteFile(regular, []byte("public"), 0600); err != nil {
869+ raceErr <- err
870+ return
871+ }
872+ if err := os.Rename(regular, swapped); err != nil {
873+ raceErr <- err
874+ return
875+ }
876+ }
877+ }()
878+ defer func() {
879+ close(done)
880+ if err := <-raceErr; err != nil {
881+ t.Error(err)
882+ }
883+ }()
884+ for range 256 {
885+ f, err := c.Open("/swapped")
886+ if err == nil {
887+ buf := make([]byte, 7)
888+ n, _ := f.Read(buf)
889+ f.Close()
890+ if string(buf[:n]) == "secret" {
891+ t.Fatal("read outside the grant")
892+ }
893+ }
894+ if f, err := c.OpenFile("/swapped", os.O_WRONLY|os.O_TRUNC); err == nil {
895+ f.Close()
896+ }
897+ }
898+ b, err := os.ReadFile(outside)
899+ if err != nil || string(b) != "secret" {
900+ t.Fatalf("outside file changed, %q %v", b, err)
901+ }
902+}
903+
904+func TestCloudNeverSetsPrivilegeBits(t *testing.T) {
905+ dir := t.TempDir()
906+ _, c := cloudClient(t, dir, false)
907+ f, err := c.Create("/program")
908+ if err != nil {
909+ t.Fatal(err)
910+ }
911+ defer f.Close()
912+ mode := os.FileMode(0755) | os.ModeSetuid | os.ModeSetgid | os.ModeSticky
913+ check := func() {
914+ t.Helper()
915+ info, err := os.Stat(filepath.Join(dir, "program"))
916+ if err != nil || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 || info.Mode().Perm() != 0755 {
917+ t.Fatalf("unexpected host mode: %v %v", info, err)
918+ }
919+ }
920+ if err := f.Chmod(mode); err != nil {
921+ t.Fatal(err)
922+ }
923+ check()
924+ if err := c.Chmod("/program", mode); err != nil {
925+ t.Fatal(err)
926+ }
927+ check()
928+}
929diff --git a/pkg/reversesshfs/cloud_windows.go b/pkg/reversesshfs/cloud_windows.go
930new file mode 100644
931index 0000000..cab2ff7
932--- /dev/null
933+++ b/pkg/reversesshfs/cloud_windows.go
934@@ -0,0 +1,61 @@
935+package reversesshfs
936+
937+import (
938+ "os"
939+ "path/filepath"
940+ "strings"
941+
942+ "golang.org/x/sys/windows"
943+)
944+
945+// Open an absolute local drive path from its volume root. DONT_REPARSE applies
946+// to all remaining components, so junctions cannot redirect the grant.
947+func openCloudRoot(directory string) (rootedSys, error) {
948+ dir := filepath.Clean(directory)
949+ drive := filepath.VolumeName(dir)
950+ if len(drive) != 2 || drive[1] != ':' {
951+ return rootedSys{}, errDenied
952+ }
953+ base, err := openRootedSys(drive + `\`)
954+ if err != nil {
955+ return rootedSys{}, err
956+ }
957+ defer base.close()
958+ h, err := ntCreate(base.rootHandle, strings.TrimPrefix(dir[len(drive):], `\`), fileDirectoryAccess, 0, windows.FILE_OPEN, windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE)
959+ if err != nil {
960+ return rootedSys{}, err
961+ }
962+ name, err := normalizedName(h)
963+ if err != nil || CloudPathHidden(filepath.ToSlash(name)) {
964+ windows.CloseHandle(h)
965+ return rootedSys{}, errDenied
966+ }
967+ return rootedSys{localPath: dir, rootHandle: h, rootName: name}, nil
968+}
969+
970+func (h *rootedHandlers) cloudOpenRead(rel string) (*os.File, error) {
971+ var fh windows.Handle
972+ var err error
973+ if rel == "." {
974+ self := windows.CurrentProcess()
975+ err = windows.DuplicateHandle(self, h.rootHandle, self, &fh, 0, false, windows.DUPLICATE_SAME_ACCESS)
976+ } else {
977+ fh, err = ntCreate(h.rootHandle, filepath.FromSlash(rel), windows.FILE_GENERIC_READ, 0, windows.FILE_OPEN, 0, windows.OBJ_DONT_REPARSE)
978+ }
979+ if err != nil {
980+ return nil, err
981+ }
982+ err = h.checkHandle(fh)
983+ var fi windows.ByHandleFileInformation
984+ if err == nil {
985+ err = windows.GetFileInformationByHandle(fh, &fi)
986+ }
987+ if err == nil && (fi.FileAttributes&(windows.FILE_ATTRIBUTE_REPARSE_POINT|windows.FILE_ATTRIBUTE_DEVICE) != 0 || (fi.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY == 0 && fi.NumberOfLinks != 1)) {
988+ err = errDenied
989+ }
990+ if err != nil {
991+ windows.CloseHandle(fh)
992+ return nil, err
993+ }
994+ return os.NewFile(uintptr(fh), rel), nil
995+}