From 2db51e9385fa3ee95ebd7499165feb560be21d7f Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 23:21:41 +0300 Subject: [PATCH] feat(vfs): define the vfs.FS contract, sentinels, PathOps and ReadOnly wrapper (2.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Types and interfaces from design §2.1: FS, File, FileInfo, Caps, VolumeID, RenameMode, CreateMode, PathOps (posix and native), Location.Same, the optional Trasher/BirthTimer/Execer interfaces and ReadOnly(fs). Co-Authored-By: Claude Opus 5.5 --- internal/vfs/errors.go | 35 ++++++++ internal/vfs/fileinfo.go | 36 ++++++++ internal/vfs/fs.go | 138 ++++++++++++++++++++++++++++ internal/vfs/location.go | 28 ++++++ internal/vfs/paths.go | 55 ++++++++++++ internal/vfs/readonly.go | 84 +++++++++++++++++ internal/vfs/vfs_test.go | 189 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 565 insertions(+) create mode 100644 internal/vfs/errors.go create mode 100644 internal/vfs/fileinfo.go create mode 100644 internal/vfs/fs.go create mode 100644 internal/vfs/location.go create mode 100644 internal/vfs/paths.go create mode 100644 internal/vfs/readonly.go create mode 100644 internal/vfs/vfs_test.go diff --git a/internal/vfs/errors.go b/internal/vfs/errors.go new file mode 100644 index 0000000..e04aea5 --- /dev/null +++ b/internal/vfs/errors.go @@ -0,0 +1,35 @@ +package vfs + +import ( + "context" + "errors" + "io/fs" +) + +// Sentinel errors, checked with errors.Is. Implementations map their native +// errors (errno, SFTP status codes) onto these, so the UI and transfer never +// see *sftp.StatusError. +// +// ErrNotExist, ErrExist and ErrPermission are the io/fs sentinels and +// ErrUnsupported is errors.ErrUnsupported, so *os.PathError values from the +// local disk already match without wrapping. ErrCancelled is context.Canceled. +var ( + ErrNotExist = fs.ErrNotExist + ErrExist = fs.ErrExist + ErrPermission = fs.ErrPermission + ErrUnsupported = errors.ErrUnsupported + ErrCancelled = context.Canceled + + // ErrReadOnly: the FS (or the volume behind it) does not allow writes. + ErrReadOnly = errors.New("read-only file system") + // ErrConnLost: the connection died; the operation may be retried after + // a reconnect. + ErrConnLost = errors.New("connection lost") +) + +// SkipDir and SkipAll are returned by a WalkFunc to skip a directory's +// contents or stop the walk without an error. +var ( + SkipDir = fs.SkipDir + SkipAll = fs.SkipAll +) diff --git a/internal/vfs/fileinfo.go b/internal/vfs/fileinfo.go new file mode 100644 index 0000000..12db09f --- /dev/null +++ b/internal/vfs/fileinfo.go @@ -0,0 +1,36 @@ +package vfs + +import ( + "io/fs" + "time" +) + +// FileInfo describes one directory entry with lstat semantics. +type FileInfo struct { + Name string + Size int64 + Mode fs.FileMode // as from Lstat: ModeSymlink, ModeDir, ModeNamedPipe, ... + ModTime time.Time + // Target is the Stat of a symlink's target; nil if the link is broken or + // the target was not resolved. LinkErr says why it is nil. + Target *FileInfo + LinkErr error +} + +// IsDir reports whether the entry itself is a directory (not a link to one). +func (fi FileInfo) IsDir() bool { return fi.Mode.IsDir() } + +// IsSymlink reports whether the entry is a symbolic link. +func (fi FileInfo) IsSymlink() bool { return fi.Mode&fs.ModeSymlink != 0 } + +// NavigableDir reports whether a panel can enter the entry: a directory or a +// symlink whose target is a directory (U-P1-2). +func (fi FileInfo) NavigableDir() bool { + return fi.IsDir() || (fi.IsSymlink() && fi.Target != nil && fi.Target.IsDir()) +} + +// IsRegularLike reports whether the entry is a regular file or a symlink to +// one. FIFOs, devices and sockets are not. +func (fi FileInfo) IsRegularLike() bool { + return fi.Mode.IsRegular() || (fi.IsSymlink() && fi.Target != nil && fi.Target.Mode.IsRegular()) +} diff --git a/internal/vfs/fs.go b/internal/vfs/fs.go new file mode 100644 index 0000000..e782992 --- /dev/null +++ b/internal/vfs/fs.go @@ -0,0 +1,138 @@ +// Package vfs is the file-system abstraction every panel, transfer and preview +// works through (design §2). One interface covers the local disk (localfs), +// SFTP (sftpfs) and read-only archives (archivefs); the helpers in this package +// (Walk, RemoveTree, DirSize, SameFile, Within) are written once against it. +// +// All methods take a context. LocalFS mostly ignores it; SFTPFS uses it to stop +// waiting on a hung server. Paths are interpreted by FS.Paths(): posix for sftp +// and archives, the native separator for local. +package vfs + +import ( + "context" + "io" + "io/fs" + "time" +) + +// Kind identifies the implementation behind an FS. +type Kind uint8 + +const ( + KindLocal Kind = iota + KindSFTP + KindArchive +) + +func (k Kind) String() string { + switch k { + case KindLocal: + return "local" + case KindSFTP: + return "sftp" + case KindArchive: + return "archive" + } + return "unknown" +} + +// VolumeID: equal VolumeIDs mean "the same file namespace" (best effort). +// local: "local"; sftp: "ssh:" + SHA256 host-key fingerprint (not the HostName +// string — N-P0-5); archive: "archive:" + outer VolumeID + ":" + archive path. +type VolumeID string + +// Caps describes what an FS can do. Callers check Caps instead of Kind. +type Caps struct { + ReadOnly bool // all mutating methods return ErrReadOnly + AtomicReplace bool // Rename(..., Replace) is atomic (local: rename(2); sftp: posix-rename@openssh.com) + NoReplace bool // Rename(..., NoReplace) is atomic (local: renameat2 RENAME_NOREPLACE; sftp: SSH_FXP_RENAME v3) + Symlinks bool + Chmod bool + Chtimes bool + Fsync bool // File.Sync works (local: yes; sftp: fsync@openssh.com) + Trash bool // the FS implements Trasher + Exec bool // files can be executed (local only) +} + +// RenameMode selects what Rename does when the target exists. +type RenameMode uint8 + +const ( + // NoReplace fails with ErrExist if the target exists. + NoReplace RenameMode = iota + // Replace atomically replaces an existing target where Caps.AtomicReplace. + Replace +) + +// CreateMode selects what Create does when the file exists. +type CreateMode uint8 + +const ( + // CreateExcl fails with ErrExist if the file exists (the transfer engine + // only uses this, for its temp files). + CreateExcl CreateMode = iota + // CreateTrunc truncates an existing file. + CreateTrunc +) + +// File is an open file. Sync returns ErrUnsupported when !Caps.Fsync. +type File interface { + io.Reader + io.Writer + io.ReaderAt + io.Closer + Stat() (FileInfo, error) + Sync() error +} + +// FS is one file namespace. +type FS interface { + Kind() Kind + Volume() VolumeID + Caps() Caps + Label() string // for the UI: "local", "bob@prod", "foo.zip" + Paths() PathOps // path rules: posix (sftp, archive) or native (local) + + // Stat follows symlinks; Lstat does not. For a symlink Lstat also fills + // FileInfo.Target the same way ReadDir does. + Stat(ctx context.Context, p string) (FileInfo, error) + Lstat(ctx context.Context, p string) (FileInfo, error) + // ReadDir has lstat semantics; for symlinks the implementation fills + // Target (local: Stat; sftp: parallel Stat, at most 16 in flight). + // The order is unspecified; the panel sorts. + ReadDir(ctx context.Context, p string) ([]FileInfo, error) + ReadLink(ctx context.Context, p string) (string, error) + // RealPath returns the absolute path with all symlinks resolved. + RealPath(ctx context.Context, p string) (string, error) + + Open(ctx context.Context, p string) (File, error) + Create(ctx context.Context, p string, perm fs.FileMode, mode CreateMode) (File, error) + Mkdir(ctx context.Context, p string, perm fs.FileMode) error + // Remove deletes a file, a symlink or an EMPTY directory. It never + // follows symlinks. + Remove(ctx context.Context, p string) error + Rename(ctx context.Context, from, to string, mode RenameMode) error + Symlink(ctx context.Context, target, p string) error + Chmod(ctx context.Context, p string, mode fs.FileMode) error + Chtimes(ctx context.Context, p string, atime, mtime time.Time) error +} + +// Optional capabilities, discovered by type assertion. + +// Trasher moves p to the FS's trash (local: freedesktop trash). +type Trasher interface { + Trash(ctx context.Context, p string) error +} + +// BirthTimer reports the creation time of p, if the FS knows it. ReadDir does +// not compute it (it is expensive); callers ask only when a "created" column or +// sort is enabled. +type BirthTimer interface { + BirthTime(ctx context.Context, p string) (time.Time, bool) +} + +// Execer runs a command next to the files (sftpfs over a conn with exec), for +// server-side transfer optimisations. The implementation quotes arguments. +type Execer interface { + Exec(ctx context.Context, argv []string) (stdout []byte, err error) +} diff --git a/internal/vfs/location.go b/internal/vfs/location.go new file mode 100644 index 0000000..704d06d --- /dev/null +++ b/internal/vfs/location.go @@ -0,0 +1,28 @@ +package vfs + +// Location is "where a panel stands / where an operation writes". +type Location struct { + FS FS + Path string +} + +// Same reports whether both locations name the same path on the same volume +// (lexically: equal VolumeID and equal cleaned paths). It does not resolve +// symlinks; use SameFile or Within for identity. +func (l Location) Same(o Location) bool { + if l.FS == nil || o.FS == nil { + return l.FS == nil && o.FS == nil && l.Path == o.Path + } + if l.FS.Volume() != o.FS.Volume() { + return false + } + return l.FS.Paths().Clean(l.Path) == o.FS.Paths().Clean(o.Path) +} + +// String renders "label:path" for logs and messages. +func (l Location) String() string { + if l.FS == nil { + return l.Path + } + return l.FS.Label() + ":" + l.Path +} diff --git a/internal/vfs/paths.go b/internal/vfs/paths.go new file mode 100644 index 0000000..5a2a341 --- /dev/null +++ b/internal/vfs/paths.go @@ -0,0 +1,55 @@ +package vfs + +import ( + "path" + "path/filepath" + "strings" +) + +// PathOps are the path rules of an FS. +type PathOps interface { + Join(elem ...string) string + Dir(p string) string + Base(p string) string + Clean(p string) string + IsAbs(p string) bool + Sep() byte +} + +// PosixPaths are slash-separated paths (sftp, archives). +var PosixPaths PathOps = posixPaths{} + +// NativePaths follow the host OS (path/filepath); used by localfs. +var NativePaths PathOps = nativePaths{} + +type posixPaths struct{} + +func (posixPaths) Join(elem ...string) string { return path.Join(elem...) } +func (posixPaths) Dir(p string) string { return path.Dir(p) } +func (posixPaths) Base(p string) string { return path.Base(p) } +func (posixPaths) Clean(p string) string { return path.Clean(p) } +func (posixPaths) IsAbs(p string) bool { return path.IsAbs(p) } +func (posixPaths) Sep() byte { return '/' } + +type nativePaths struct{} + +func (nativePaths) Join(elem ...string) string { return filepath.Join(elem...) } +func (nativePaths) Dir(p string) string { return filepath.Dir(p) } +func (nativePaths) Base(p string) string { return filepath.Base(p) } +func (nativePaths) Clean(p string) string { return filepath.Clean(p) } +func (nativePaths) IsAbs(p string) bool { return filepath.IsAbs(p) } +func (nativePaths) Sep() byte { return filepath.Separator } + +// IsWithin reports whether child equals parent or lies under it, comparing +// cleaned paths lexically with ops (no symlink resolution; see Within). +func IsWithin(ops PathOps, child, parent string) bool { + child, parent = ops.Clean(child), ops.Clean(parent) + if child == parent { + return true + } + sep := string(ops.Sep()) + if !strings.HasSuffix(parent, sep) { + parent += sep + } + return strings.HasPrefix(child, parent) +} diff --git a/internal/vfs/readonly.go b/internal/vfs/readonly.go new file mode 100644 index 0000000..fa24fe5 --- /dev/null +++ b/internal/vfs/readonly.go @@ -0,0 +1,84 @@ +package vfs + +import ( + "context" + "io/fs" + "time" +) + +// ReadOnly wraps fsys so that Caps().ReadOnly is true and every mutating +// method returns ErrReadOnly without reaching fsys. Trash and Exec are hidden; +// BirthTime is passed through. +func ReadOnly(fsys FS) FS { + if ro, ok := fsys.(readOnlyFS); ok { + return ro + } + return readOnlyFS{fsys} +} + +type readOnlyFS struct{ inner FS } + +func (r readOnlyFS) Kind() Kind { return r.inner.Kind() } +func (r readOnlyFS) Volume() VolumeID { return r.inner.Volume() } +func (r readOnlyFS) Label() string { return r.inner.Label() } +func (r readOnlyFS) Paths() PathOps { return r.inner.Paths() } + +func (r readOnlyFS) Caps() Caps { + c := r.inner.Caps() + c.ReadOnly = true + c.Trash = false + c.Exec = false + return c +} + +func (r readOnlyFS) Stat(ctx context.Context, p string) (FileInfo, error) { + return r.inner.Stat(ctx, p) +} +func (r readOnlyFS) Lstat(ctx context.Context, p string) (FileInfo, error) { + return r.inner.Lstat(ctx, p) +} +func (r readOnlyFS) ReadDir(ctx context.Context, p string) ([]FileInfo, error) { + return r.inner.ReadDir(ctx, p) +} +func (r readOnlyFS) ReadLink(ctx context.Context, p string) (string, error) { + return r.inner.ReadLink(ctx, p) +} +func (r readOnlyFS) RealPath(ctx context.Context, p string) (string, error) { + return r.inner.RealPath(ctx, p) +} + +// Open returns a file whose Write fails with ErrReadOnly. +func (r readOnlyFS) Open(ctx context.Context, p string) (File, error) { + f, err := r.inner.Open(ctx, p) + if err != nil { + return nil, err + } + return readOnlyFile{f}, nil +} + +func (r readOnlyFS) BirthTime(ctx context.Context, p string) (time.Time, bool) { + if bt, ok := r.inner.(BirthTimer); ok { + return bt.BirthTime(ctx, p) + } + return time.Time{}, false +} + +func roErr(op, p string) error { return &fs.PathError{Op: op, Path: p, Err: ErrReadOnly} } + +func (readOnlyFS) Create(_ context.Context, p string, _ fs.FileMode, _ CreateMode) (File, error) { + return nil, roErr("create", p) +} +func (readOnlyFS) Mkdir(_ context.Context, p string, _ fs.FileMode) error { return roErr("mkdir", p) } +func (readOnlyFS) Remove(_ context.Context, p string) error { return roErr("remove", p) } +func (readOnlyFS) Rename(_ context.Context, from, _ string, _ RenameMode) error { + return roErr("rename", from) +} +func (readOnlyFS) Symlink(_ context.Context, _, p string) error { return roErr("symlink", p) } +func (readOnlyFS) Chmod(_ context.Context, p string, _ fs.FileMode) error { return roErr("chmod", p) } +func (readOnlyFS) Chtimes(_ context.Context, p string, _, _ time.Time) error { + return roErr("chtimes", p) +} + +type readOnlyFile struct{ File } + +func (readOnlyFile) Write([]byte) (int, error) { return 0, ErrReadOnly } diff --git a/internal/vfs/vfs_test.go b/internal/vfs/vfs_test.go new file mode 100644 index 0000000..a87f1c7 --- /dev/null +++ b/internal/vfs/vfs_test.go @@ -0,0 +1,189 @@ +package vfs + +import ( + "context" + "errors" + "io/fs" + "testing" + "time" +) + +// recFS is a fake FS that records which methods reached it. +type recFS struct{ calls []string } + +func (r *recFS) rec(op string) { r.calls = append(r.calls, op) } + +func (r *recFS) Kind() Kind { return KindLocal } +func (r *recFS) Volume() VolumeID { return "fake" } +func (r *recFS) Caps() Caps { return Caps{Trash: true, Exec: true, Chmod: true} } +func (r *recFS) Label() string { return "fake" } +func (r *recFS) Paths() PathOps { return PosixPaths } +func (r *recFS) Stat(context.Context, string) (FileInfo, error) { + r.rec("stat") + return FileInfo{}, nil +} +func (r *recFS) Lstat(context.Context, string) (FileInfo, error) { + r.rec("lstat") + return FileInfo{}, nil +} +func (r *recFS) ReadDir(context.Context, string) ([]FileInfo, error) { + r.rec("readdir") + return nil, nil +} +func (r *recFS) ReadLink(context.Context, string) (string, error) { r.rec("readlink"); return "", nil } +func (r *recFS) RealPath(context.Context, string) (string, error) { r.rec("realpath"); return "", nil } +func (r *recFS) Open(context.Context, string) (File, error) { r.rec("open"); return fakeFile{}, nil } +func (r *recFS) Create(context.Context, string, fs.FileMode, CreateMode) (File, error) { + r.rec("create") + return fakeFile{}, nil +} +func (r *recFS) Mkdir(context.Context, string, fs.FileMode) error { r.rec("mkdir"); return nil } +func (r *recFS) Remove(context.Context, string) error { r.rec("remove"); return nil } +func (r *recFS) Rename(context.Context, string, string, RenameMode) error { + r.rec("rename") + return nil +} +func (r *recFS) Symlink(context.Context, string, string) error { r.rec("symlink"); return nil } +func (r *recFS) Chmod(context.Context, string, fs.FileMode) error { r.rec("chmod"); return nil } +func (r *recFS) Chtimes(context.Context, string, time.Time, time.Time) error { + r.rec("chtimes") + return nil +} +func (r *recFS) Trash(context.Context, string) error { r.rec("trash"); return nil } + +type fakeFile struct{} + +func (fakeFile) Read([]byte) (int, error) { return 0, nil } +func (fakeFile) Write(b []byte) (int, error) { return len(b), nil } +func (fakeFile) ReadAt([]byte, int64) (int, error) { return 0, nil } +func (fakeFile) Close() error { return nil } +func (fakeFile) Stat() (FileInfo, error) { return FileInfo{}, nil } +func (fakeFile) Sync() error { return nil } + +func TestReadOnlyRejectsMutations(t *testing.T) { + ctx := context.Background() + inner := &recFS{} + ro := ReadOnly(inner) + + if !ro.Caps().ReadOnly || ro.Caps().Trash || ro.Caps().Exec { + t.Fatalf("caps = %+v, want ReadOnly and no Trash/Exec", ro.Caps()) + } + if !ro.Caps().Chmod { + t.Fatalf("other caps must pass through: %+v", ro.Caps()) + } + if _, ok := ro.(Trasher); ok { + t.Fatal("read-only wrapper must not expose Trasher") + } + + _, errCreate := ro.Create(ctx, "/a", 0o644, CreateExcl) + muts := map[string]error{ + "create": errCreate, + "mkdir": ro.Mkdir(ctx, "/a", 0o755), + "remove": ro.Remove(ctx, "/a"), + "rename": ro.Rename(ctx, "/a", "/b", Replace), + "symlink": ro.Symlink(ctx, "/a", "/b"), + "chmod": ro.Chmod(ctx, "/a", 0o600), + "chtimes": ro.Chtimes(ctx, "/a", time.Now(), time.Now()), + } + for op, err := range muts { + if !errors.Is(err, ErrReadOnly) { + t.Errorf("%s: err = %v, want ErrReadOnly", op, err) + } + } + if len(inner.calls) != 0 { + t.Fatalf("mutations reached the inner FS: %v", inner.calls) + } + + // Reads pass through; files opened through the wrapper refuse writes. + if _, err := ro.Stat(ctx, "/a"); err != nil { + t.Fatal(err) + } + if _, err := ro.ReadDir(ctx, "/"); err != nil { + t.Fatal(err) + } + f, err := ro.Open(ctx, "/a") + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte("x")); !errors.Is(err, ErrReadOnly) { + t.Fatalf("write through read-only open: %v", err) + } + if got := inner.calls; len(got) != 3 || got[0] != "stat" || got[1] != "readdir" || got[2] != "open" { + t.Fatalf("inner calls = %v", got) + } + if ReadOnly(ro) != ro { + t.Fatal("ReadOnly must not double-wrap") + } +} + +func TestPosixPathOps(t *testing.T) { + p := PosixPaths + if p.Sep() != '/' { + t.Fatal("sep") + } + cases := []struct{ got, want string }{ + {p.Join("/a", "b", "../c"), "/a/c"}, + {p.Join("a", "", "b"), "a/b"}, + {p.Dir("/a/b/c"), "/a/b"}, + {p.Dir("/"), "/"}, + {p.Dir("file"), "."}, + {p.Base("/a/b/"), "b"}, + {p.Base("/"), "/"}, + {p.Clean("/a//b/./c/.."), "/a/b"}, + {p.Clean(""), "."}, + {p.Join("/srv", `back\slash`), `/srv/back\slash`}, // backslash is a normal char in posix + } + for i, c := range cases { + if c.got != c.want { + t.Errorf("case %d: got %q, want %q", i, c.got, c.want) + } + } + if !p.IsAbs("/x") || p.IsAbs("x") { + t.Error("IsAbs") + } + within := []struct { + child, parent string + want bool + }{ + {"/a/b", "/a", true}, + {"/a", "/a/", true}, + {"/ab", "/a", false}, + {"/a/../b", "/a", false}, + {"/anything", "/", true}, + } + for _, c := range within { + if got := IsWithin(p, c.child, c.parent); got != c.want { + t.Errorf("IsWithin(%q, %q) = %v", c.child, c.parent, got) + } + } +} + +func TestLocationSame(t *testing.T) { + a := &recFS{} + l1 := Location{FS: a, Path: "/x/y/"} + l2 := Location{FS: ReadOnly(a), Path: "/x/./y"} + if !l1.Same(l2) { + t.Fatal("same volume and cleaned path must be Same") + } + if l1.Same(Location{FS: a, Path: "/x"}) { + t.Fatal("different paths") + } +} + +func TestFileInfoPredicates(t *testing.T) { + dir := FileInfo{Mode: fs.ModeDir | 0o755} + file := FileInfo{Mode: 0o644} + linkDir := FileInfo{Mode: fs.ModeSymlink, Target: &dir} + linkFile := FileInfo{Mode: fs.ModeSymlink, Target: &file} + broken := FileInfo{Mode: fs.ModeSymlink, LinkErr: ErrNotExist} + fifo := FileInfo{Mode: fs.ModeNamedPipe} + if !dir.NavigableDir() || !linkDir.NavigableDir() || linkFile.NavigableDir() || broken.NavigableDir() { + t.Error("NavigableDir") + } + if linkDir.IsDir() || !linkDir.IsSymlink() { + t.Error("a link to a dir is not itself a dir") + } + if !file.IsRegularLike() || !linkFile.IsRegularLike() || fifo.IsRegularLike() || broken.IsRegularLike() { + t.Error("IsRegularLike") + } +}