Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfe6e5b333 | ||
|
|
d9816b1531 | ||
|
|
7c2c0a11b3 | ||
|
|
3406d3d7f9 | ||
|
|
67ed670d92 | ||
|
|
a1a514dcbb | ||
|
|
5f7311d324 | ||
|
|
998bd95bfa | ||
|
|
c1abe8f561 | ||
|
|
0bb2768754 | ||
|
|
7b7ff8ae8f | ||
|
|
1086903c14 | ||
|
|
3471ec2c4b |
@@ -2,6 +2,46 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
|
||||
|
||||
## [2.63.14](https://github.com/filebrowser/filebrowser/compare/v2.63.13...v2.63.14) (2026-06-07)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* recursive check ([3406d3d](https://github.com/filebrowser/filebrowser/commit/3406d3d7f98dfc3c16e4ff7ff4a87e3bdfe221dd))
|
||||
|
||||
|
||||
### Refactorings
|
||||
|
||||
* ScopedFs to avoid escaping symlinks ([7c2c0a1](https://github.com/filebrowser/filebrowser/commit/7c2c0a11b31b2bb214d741005a0b02b1764208b3))
|
||||
|
||||
## [2.63.13](https://github.com/filebrowser/filebrowser/compare/v2.63.12...v2.63.13) (2026-06-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* copy/move allow overwrite ([a1a514d](https://github.com/filebrowser/filebrowser/commit/a1a514dcbb216d2080412c5354eea1e1fb033050))
|
||||
|
||||
|
||||
### Refactorings
|
||||
|
||||
* cleanup and simplify upload.ts ([5f7311d](https://github.com/filebrowser/filebrowser/commit/5f7311d32437e98d7c14c7b307a4f68109275535))
|
||||
|
||||
## [2.63.12](https://github.com/filebrowser/filebrowser/compare/v2.63.11...v2.63.12) (2026-06-04)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* await copy move conflict detection ([#5978](https://github.com/filebrowser/filebrowser/issues/5978)) ([c1abe8f](https://github.com/filebrowser/filebrowser/commit/c1abe8f561208bf36bde70879d1a15ef9de998fa))
|
||||
* keep mobile file sort controls visible ([#5977](https://github.com/filebrowser/filebrowser/issues/5977)) ([0bb2768](https://github.com/filebrowser/filebrowser/commit/0bb2768754d11b865d68e72dcd7cebb232a6308a))
|
||||
* skip inaccessible children when listing directories ([#5958](https://github.com/filebrowser/filebrowser/issues/5958)) ([7b7ff8a](https://github.com/filebrowser/filebrowser/commit/7b7ff8ae8f97393b2e6ae6e061c1f780077c32b6))
|
||||
|
||||
## [2.63.11](https://github.com/filebrowser/filebrowser/compare/v2.63.10...v2.63.11) (2026-06-04)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* incomplete fix for symlinked directories let scopes users and public-share recipients read and write files outside of scope ([3471ec2](https://github.com/filebrowser/filebrowser/commit/3471ec2c4b6473831c72ee889cb3c1a6849a1fb1))
|
||||
|
||||
## [2.63.10](https://github.com/filebrowser/filebrowser/compare/v2.63.9...v2.63.10) (2026-06-03)
|
||||
|
||||
|
||||
|
||||
+67
-73
@@ -18,13 +18,13 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -133,17 +133,6 @@ func stat(opts *FileOptions) (*FileInfo, error) {
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// The path is a symlink. Refuse to follow it if its on-disk target escapes
|
||||
// the user's scoped root; otherwise a symlink that lives lexically inside
|
||||
// the scope but points outside it would let a restricted user read, write,
|
||||
// or share files beyond their boundary.
|
||||
if file != nil && file.IsSymlink {
|
||||
ok, scopeErr := WithinScope(opts.Fs, opts.Path)
|
||||
if scopeErr != nil || !ok {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
}
|
||||
|
||||
// fs doesn't support afero.Lstater interface or the file is a symlink
|
||||
info, err := opts.Fs.Stat(opts.Path)
|
||||
if err != nil {
|
||||
@@ -176,60 +165,6 @@ func stat(opts *FileOptions) (*FileInfo, error) {
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// WithinScope reports whether the on-disk target of p — after resolving any
|
||||
// symbolic links — stays within the scoped root of fsys. It exists to stop a
|
||||
// symlink that lives lexically inside a user's scope but points outside it
|
||||
// from being followed for reads, writes, or shares.
|
||||
//
|
||||
// Paths that do not exist yet (e.g. a brand-new file being created) are
|
||||
// validated against their nearest existing ancestor, so legitimate new files
|
||||
// are always allowed. For a filesystem that is not scoped with BasePathFs the
|
||||
// check is a no-op and returns true.
|
||||
//
|
||||
// Note: a dangling symlink whose target does not yet exist resolves to its
|
||||
// containing directory and is therefore allowed; writing through such a link
|
||||
// could still create a file outside the scope. Callers that create files
|
||||
// should treat this as best-effort and rely on rejecting existing escaping
|
||||
// symlinks, which covers the disclosure and overwrite vectors.
|
||||
func WithinScope(fsys afero.Fs, p string) (bool, error) {
|
||||
bfs, ok := fsys.(*afero.BasePathFs)
|
||||
if !ok {
|
||||
// Not a scoped filesystem; nothing to enforce.
|
||||
return true, nil
|
||||
}
|
||||
|
||||
root, err := filepath.EvalSymlinks(afero.FullBaseFsPath(bfs, "/"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
target := afero.FullBaseFsPath(bfs, p)
|
||||
resolved, err := filepath.EvalSymlinks(target)
|
||||
for errors.Is(err, fs.ErrNotExist) {
|
||||
parent := filepath.Dir(target)
|
||||
if parent == target {
|
||||
break
|
||||
}
|
||||
target = parent
|
||||
resolved, err = filepath.EvalSymlinks(target)
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Compare against root with a trailing separator so a sibling like
|
||||
// "/srvother" is not treated as being inside "/srv". When root is itself
|
||||
// the filesystem boundary (e.g. "/"), it already ends in a separator, so
|
||||
// avoid producing "//" — which no path would match — and accept any path
|
||||
// under it.
|
||||
prefix := root
|
||||
if !strings.HasSuffix(prefix, string(filepath.Separator)) {
|
||||
prefix += string(filepath.Separator)
|
||||
}
|
||||
|
||||
return resolved == root || strings.HasPrefix(resolved, prefix), nil
|
||||
}
|
||||
|
||||
// Checksum checksums a given File for a given User, using a specific
|
||||
// algorithm. The checksums data is saved on File object.
|
||||
func (i *FileInfo) Checksum(algo string) error {
|
||||
@@ -456,8 +391,7 @@ func (i *FileInfo) addSubtitle(fPath string) {
|
||||
}
|
||||
|
||||
func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRes bool) error {
|
||||
afs := &afero.Afero{Fs: i.Fs}
|
||||
dir, err := afs.ReadDir(i.Path)
|
||||
dir, err := readDir(i.Fs, i.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -479,12 +413,19 @@ func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRe
|
||||
isSymlink, isInvalidLink := false, false
|
||||
if IsSymlink(f.Mode()) {
|
||||
isSymlink = true
|
||||
// It's a symbolic link. We try to follow it. If it doesn't work,
|
||||
// we stay with the link information instead of the target's.
|
||||
// It's a symbolic link. We try to follow it. The scoped filesystem
|
||||
// refuses to dereference a link whose target escapes the scope
|
||||
// (permission error); such a link is omitted from the listing
|
||||
// entirely so it cannot leak the target's metadata. Any other
|
||||
// failure means a broken link, which we surface as an invalid link
|
||||
// rather than the target's information.
|
||||
info, err := i.Fs.Stat(fPath)
|
||||
if err == nil {
|
||||
switch {
|
||||
case err == nil:
|
||||
f = info
|
||||
} else {
|
||||
case errors.Is(err, os.ErrPermission):
|
||||
continue
|
||||
default:
|
||||
isInvalidLink = true
|
||||
}
|
||||
}
|
||||
@@ -532,3 +473,56 @@ func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRe
|
||||
i.Listing = listing
|
||||
return nil
|
||||
}
|
||||
|
||||
func readDir(afs afero.Fs, dirname string) ([]os.FileInfo, error) {
|
||||
dir, err := afero.ReadDir(afs, dirname)
|
||||
if err == nil {
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
dir, fallbackErr := readDirNames(afs, dirname)
|
||||
if fallbackErr != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func readDirNames(afs afero.Fs, dirname string) ([]os.FileInfo, error) {
|
||||
file, err := afs.Open(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names, err := file.Readdirnames(-1)
|
||||
if closeErr := file.Close(); err == nil && closeErr != nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sort.Strings(names)
|
||||
dir := make([]os.FileInfo, 0, len(names))
|
||||
for _, name := range names {
|
||||
fPath := path.Join(dirname, name)
|
||||
info, err := lstatIfPossible(afs, fPath)
|
||||
if err != nil {
|
||||
log.Printf("Skipping inaccessible file %s: %v", fPath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
dir = append(dir, info)
|
||||
}
|
||||
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func lstatIfPossible(afs afero.Fs, name string) (os.FileInfo, error) {
|
||||
if lstaterFs, ok := afs.(afero.Lstater); ok {
|
||||
info, _, err := lstaterFs.LstatIfPossible(name)
|
||||
return info, err
|
||||
}
|
||||
|
||||
return afs.Stat(name)
|
||||
}
|
||||
|
||||
+166
-35
@@ -2,60 +2,53 @@ package files
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
func TestWithinScope(t *testing.T) {
|
||||
t.Run("non-scoped filesystem is a no-op", func(t *testing.T) {
|
||||
ok, err := WithinScope(afero.NewOsFs(), "/anything")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("expected (true, nil), got (%v, %v)", ok, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("path inside a nested scope is allowed", func(t *testing.T) {
|
||||
func TestScopedFs(t *testing.T) {
|
||||
t.Run("path inside scope is allowed", func(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(scope, "file.txt"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bfs := afero.NewBasePathFs(afero.NewOsFs(), scope)
|
||||
fs := NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
ok, err := WithinScope(bfs, "/file.txt")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("expected (true, nil), got (%v, %v)", ok, err)
|
||||
if _, err := fs.Stat("/file.txt"); err != nil {
|
||||
t.Fatalf("expected in-scope file to be accessible, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("new file inside scope is allowed", func(t *testing.T) {
|
||||
t.Run("new file inside scope can be created", func(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
bfs := afero.NewBasePathFs(afero.NewOsFs(), scope)
|
||||
fs := NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
ok, err := WithinScope(bfs, "/does-not-exist-yet.txt")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("expected (true, nil), got (%v, %v)", ok, err)
|
||||
f, err := fs.OpenFile("/does-not-exist-yet.txt", os.O_RDWR|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
t.Fatalf("expected to create a new in-scope file, got %v", err)
|
||||
}
|
||||
_ = f.Close()
|
||||
})
|
||||
|
||||
// Regression for #5975: when the scope resolves to the filesystem root,
|
||||
// root+separator used to be "//", which no path matched, so every write
|
||||
// was rejected with os.ErrPermission (HTTP 403).
|
||||
t.Run("filesystem root scope allows writes", func(t *testing.T) {
|
||||
t.Run("filesystem root scope allows access", func(t *testing.T) {
|
||||
f := filepath.Join(t.TempDir(), "file.txt")
|
||||
if err := os.WriteFile(f, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bfs := afero.NewBasePathFs(afero.NewOsFs(), "/")
|
||||
fs := NewScopedFs(afero.NewOsFs(), "/")
|
||||
|
||||
ok, err := WithinScope(bfs, f)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("expected (true, nil) for a path under root scope, got (%v, %v)", ok, err)
|
||||
if _, err := fs.Stat(f); err != nil {
|
||||
t.Fatalf("expected a path under root scope to be accessible, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sibling of a nested scope is rejected", func(t *testing.T) {
|
||||
t.Run("escaping symlink to a sibling is rejected", func(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
scope := filepath.Join(base, "srv")
|
||||
sibling := filepath.Join(base, "srvother")
|
||||
@@ -64,20 +57,158 @@ func TestWithinScope(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// A symlink lexically inside the scope pointing at a sibling directory
|
||||
// must not be followed.
|
||||
link := filepath.Join(scope, "escape")
|
||||
if err := os.Symlink(sibling, link); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(sibling, "secret.txt"), []byte("secret"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bfs := afero.NewBasePathFs(afero.NewOsFs(), scope)
|
||||
|
||||
ok, err := WithinScope(bfs, "/escape")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
// A symlink lexically inside the scope pointing at a sibling directory
|
||||
// must not be followed for reads or stats.
|
||||
if err := os.Symlink(sibling, filepath.Join(scope, "escape")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
if ok {
|
||||
t.Fatal("expected escaping symlink to a sibling directory to be rejected")
|
||||
fs := NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
if _, err := fs.Stat("/escape"); !os.IsPermission(err) {
|
||||
t.Fatalf("expected stat of escaping symlink to be rejected, got %v", err)
|
||||
}
|
||||
if _, err := fs.Open("/escape/secret.txt"); !os.IsPermission(err) {
|
||||
t.Fatalf("expected read through escaping symlink to be rejected, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("symlink whose target stays within scope is allowed", func(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "real"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "real", "f.txt"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(scope, "real"), filepath.Join(scope, "link")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
fs := NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
if _, err := fs.Stat("/link/f.txt"); err != nil {
|
||||
t.Fatalf("expected in-scope symlink target to be accessible, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// stat must reject a regular file reached through a symlinked ancestor that
|
||||
// escapes the scope (GHSA-hf77-9m7w-fq8q), while still serving in-scope files.
|
||||
func TestStatRejectsLinkedAncestorEscape(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "shared"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(scope, "private"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "private", "secret.txt"), []byte("secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "shared", "ok.txt"), []byte("ok"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(scope, "private"), filepath.Join(scope, "shared", "link")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
// Filesystem scoped to the shared directory, as a public share would be.
|
||||
bfs := NewScopedFs(afero.NewOsFs(), filepath.Join(scope, "shared"))
|
||||
|
||||
if _, err := stat(&FileOptions{Fs: bfs, Path: "/link/secret.txt"}); !os.IsPermission(err) {
|
||||
t.Fatalf("expected permission error for linked-ancestor escape, got %v", err)
|
||||
}
|
||||
if _, err := stat(&FileOptions{Fs: bfs, Path: "/ok.txt"}); err != nil {
|
||||
t.Fatalf("expected in-scope file to be served, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type allowAllChecker struct{}
|
||||
|
||||
func (allowAllChecker) Check(string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type inaccessibleChildFs struct {
|
||||
afero.Fs
|
||||
child string
|
||||
}
|
||||
|
||||
func (fs inaccessibleChildFs) Open(name string) (afero.File, error) {
|
||||
file, err := fs.Fs.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if path.Clean(name) == "/" {
|
||||
return inaccessibleChildDir{File: file}, nil
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func (fs inaccessibleChildFs) Stat(name string) (os.FileInfo, error) {
|
||||
if path.Clean(name) == fs.child {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
return fs.Fs.Stat(name)
|
||||
}
|
||||
|
||||
func (fs inaccessibleChildFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
if path.Clean(name) == fs.child {
|
||||
return nil, false, os.ErrPermission
|
||||
}
|
||||
|
||||
if lstater, ok := fs.Fs.(afero.Lstater); ok {
|
||||
return lstater.LstatIfPossible(name)
|
||||
}
|
||||
|
||||
info, err := fs.Fs.Stat(name)
|
||||
return info, false, err
|
||||
}
|
||||
|
||||
type inaccessibleChildDir struct {
|
||||
afero.File
|
||||
}
|
||||
|
||||
func (dir inaccessibleChildDir) Readdir(int) ([]os.FileInfo, error) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
func TestReadListingSkipsInaccessibleChildren(t *testing.T) {
|
||||
memFs := afero.NewMemMapFs()
|
||||
for _, dir := range []string{"/media", "/proton-mount"} {
|
||||
if err := memFs.Mkdir(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
file, err := NewFileInfo(&FileOptions{
|
||||
Fs: inaccessibleChildFs{Fs: memFs, child: "/proton-mount"},
|
||||
Path: "/",
|
||||
Expand: true,
|
||||
Checker: allowAllChecker{},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if file.Listing == nil {
|
||||
t.Fatal("expected root listing")
|
||||
}
|
||||
|
||||
if got := len(file.Items); got != 1 {
|
||||
t.Fatalf("expected one accessible child, got %d", got)
|
||||
}
|
||||
|
||||
if got := file.Items[0].Name; got != "media" {
|
||||
t.Fatalf("expected accessible child to be listed, got %q", got)
|
||||
}
|
||||
|
||||
if got := file.NumDirs; got != 1 {
|
||||
t.Fatalf("expected one listed directory, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// ScopedFs is an afero.Fs that confines every operation to a base directory and
|
||||
// refuses to follow a symbolic link whose on-disk target resolves outside that
|
||||
// base. It wraps an *afero.BasePathFs — which already provides the lexical
|
||||
// confinement — and adds a per-operation scope check on every call that would
|
||||
// dereference a symlink at the OS layer (open, stat, lstat, chmod, …).
|
||||
type ScopedFs struct {
|
||||
base *afero.BasePathFs
|
||||
}
|
||||
|
||||
var (
|
||||
_ afero.Fs = (*ScopedFs)(nil)
|
||||
_ afero.Lstater = (*ScopedFs)(nil)
|
||||
)
|
||||
|
||||
func NewScopedFs(source afero.Fs, path string) *ScopedFs {
|
||||
if s, ok := source.(*ScopedFs); ok {
|
||||
source = s.base
|
||||
}
|
||||
return &ScopedFs{base: afero.NewBasePathFs(source, path).(*afero.BasePathFs)}
|
||||
}
|
||||
|
||||
// Base returns the underlying *afero.BasePathFs.
|
||||
func (s *ScopedFs) Base() *afero.BasePathFs { return s.base }
|
||||
|
||||
// guard returns an error if name's on-disk target resolves outside the scope.
|
||||
func (s *ScopedFs) guard(name string) error {
|
||||
ok, err := s.within(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return os.ErrPermission
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// within reports whether the on-disk target of p — after resolving any symbolic
|
||||
// links — stays within the scoped root. It exists to stop a symlink that lives
|
||||
// lexically inside the scope but points outside it from being followed for
|
||||
// reads, writes, or shares.
|
||||
//
|
||||
// Paths that do not exist yet (e.g. a brand-new file being created) are
|
||||
// validated against their nearest existing ancestor, so legitimate new files
|
||||
// are always allowed.
|
||||
//
|
||||
// Note: a dangling symlink whose target does not yet exist resolves to its
|
||||
// containing directory and is therefore allowed; writing through such a link
|
||||
// could still create a file outside the scope. This is treated as best-effort
|
||||
// and relies on rejecting existing escaping symlinks, which covers the
|
||||
// disclosure and overwrite vectors.
|
||||
func (s *ScopedFs) within(p string) (bool, error) {
|
||||
root, err := filepath.EvalSymlinks(afero.FullBaseFsPath(s.base, "/"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
target := afero.FullBaseFsPath(s.base, p)
|
||||
resolved, err := filepath.EvalSymlinks(target)
|
||||
for errors.Is(err, fs.ErrNotExist) {
|
||||
parent := filepath.Dir(target)
|
||||
if parent == target {
|
||||
break
|
||||
}
|
||||
target = parent
|
||||
resolved, err = filepath.EvalSymlinks(target)
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Compare against root with a trailing separator so a sibling like
|
||||
// "/srvother" is not treated as being inside "/srv". When root is itself the
|
||||
// filesystem boundary (e.g. "/"), it already ends in a separator, so avoid
|
||||
// producing "//" — which no path would match — and accept any path under it.
|
||||
prefix := root
|
||||
if !strings.HasSuffix(prefix, string(filepath.Separator)) {
|
||||
prefix += string(filepath.Separator)
|
||||
}
|
||||
|
||||
return resolved == root || strings.HasPrefix(resolved, prefix), nil
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Create(name string) (afero.File, error) {
|
||||
if err := s.guard(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.base.Create(name)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Mkdir(name string, perm os.FileMode) error {
|
||||
if err := s.guard(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.Mkdir(name, perm)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) MkdirAll(path string, perm os.FileMode) error {
|
||||
if err := s.guard(path); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.MkdirAll(path, perm)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Open(name string) (afero.File, error) {
|
||||
if err := s.guard(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.base.Open(name)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
|
||||
if err := s.guard(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.base.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Remove(name string) error {
|
||||
return s.base.Remove(name)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) RemoveAll(path string) error {
|
||||
return s.base.RemoveAll(path)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Rename(oldname, newname string) error {
|
||||
if err := s.guard(oldname); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.guard(newname); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Stat(name string) (os.FileInfo, error) {
|
||||
if err := s.guard(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.base.Stat(name)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Name() string { return "ScopedFs" }
|
||||
|
||||
func (s *ScopedFs) Chmod(name string, mode os.FileMode) error {
|
||||
if err := s.guard(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Chown(name string, uid, gid int) error {
|
||||
if err := s.guard(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.Chown(name, uid, gid)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) Chtimes(name string, atime, mtime time.Time) error {
|
||||
if err := s.guard(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.base.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (s *ScopedFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
if err := s.guard(name); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return s.base.LstatIfPossible(name)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package fileutils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// Copying an in-scope directory that contains a symlink whose target escapes
|
||||
// the user's scope must not dereference that symlink into the destination.
|
||||
// Otherwise a scoped user could exfiltrate out-of-scope file content via the
|
||||
// recursive copy path (GHSA-c2gv-wf5f-hjhh, an incomplete fix of
|
||||
// GHSA-239w-m3h6-ch8v).
|
||||
func TestCopyDoesNotDereferenceEscapingSymlink(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
scope := filepath.Join(base, "scope")
|
||||
if err := os.MkdirAll(filepath.Join(scope, "srcdir"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A secret living outside the scope.
|
||||
secret := filepath.Join(base, "secret.txt")
|
||||
if err := os.WriteFile(secret, []byte("OUT-OF-SCOPE-SECRET"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An escaping symlink planted inside the user's scope.
|
||||
if err := os.Symlink(secret, filepath.Join(scope, "srcdir", "link.txt")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
afs := files.NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
err := Copy(afs, "/srcdir", "/dstdir", 0o644, 0o755)
|
||||
if err == nil {
|
||||
t.Fatal("expected copy of a directory containing an escaping symlink to fail")
|
||||
}
|
||||
|
||||
// The escaping symlink's target content must not have landed in scope.
|
||||
if data, readErr := afero.ReadFile(afs, "/dstdir/link.txt"); readErr == nil {
|
||||
t.Fatalf("escaping symlink was dereferenced into scope: got %q", string(data))
|
||||
}
|
||||
}
|
||||
|
||||
// A symlink whose target stays within scope is legitimate and must still be
|
||||
// copied (dereferenced) so the fix does not over-block normal usage.
|
||||
func TestCopyAllowsInScopeSymlink(t *testing.T) {
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "srcdir", "real"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "srcdir", "real", "f.txt"), []byte("in-scope"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(scope, "srcdir", "real", "f.txt"), filepath.Join(scope, "srcdir", "link.txt")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
afs := files.NewScopedFs(afero.NewOsFs(), scope)
|
||||
|
||||
if err := Copy(afs, "/srcdir", "/dstdir", 0o644, 0o755); err != nil {
|
||||
t.Fatalf("expected copy of an in-scope symlink to succeed, got: %v", err)
|
||||
}
|
||||
|
||||
data, err := afero.ReadFile(afs, "/dstdir/link.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("expected in-scope symlink to be copied, got: %v", err)
|
||||
}
|
||||
if string(data) != "in-scope" {
|
||||
t.Fatalf("unexpected copied content: %q", string(data))
|
||||
}
|
||||
}
|
||||
@@ -179,6 +179,7 @@ const drop = async (event: Event) => {
|
||||
to: props.url + encodeURIComponent(fileStore.req?.items[i].name),
|
||||
name: fileStore.req?.items[i].name,
|
||||
size: fileStore.req?.items[i].size,
|
||||
isDir: fileStore.req?.items[i].isDir,
|
||||
modified: fileStore.req?.items[i].modified,
|
||||
overwrite: false,
|
||||
rename: false,
|
||||
@@ -204,7 +205,7 @@ const drop = async (event: Event) => {
|
||||
.catch($showError);
|
||||
};
|
||||
|
||||
const conflict = await upload.checkConflict(items, path);
|
||||
const conflict = await upload.checkConflict(items, path, true);
|
||||
|
||||
if (conflict.length > 0) {
|
||||
layoutStore.showHover({
|
||||
|
||||
@@ -92,6 +92,7 @@ export default {
|
||||
to: this.dest + encodeURIComponent(this.req.items[item].name),
|
||||
name: this.req.items[item].name,
|
||||
size: this.req.items[item].size,
|
||||
isDir: this.req.items[item].isDir,
|
||||
modified: this.req.items[item].modified,
|
||||
overwrite: false,
|
||||
rename: this.$route.path === this.dest,
|
||||
@@ -122,7 +123,7 @@ export default {
|
||||
});
|
||||
};
|
||||
|
||||
const conflict = upload.checkConflict(items, this.dest);
|
||||
const conflict = await upload.checkConflict(items, this.dest, true);
|
||||
|
||||
if (conflict.length > 0) {
|
||||
this.showHover({
|
||||
|
||||
@@ -98,6 +98,7 @@ export default {
|
||||
to: this.dest + encodeURIComponent(this.req.items[item].name),
|
||||
name: this.req.items[item].name,
|
||||
size: this.req.items[item].size,
|
||||
isDir: this.req.items[item].isDir,
|
||||
modified: this.req.items[item].modified,
|
||||
overwrite: false,
|
||||
rename: false,
|
||||
@@ -122,7 +123,7 @@ export default {
|
||||
});
|
||||
};
|
||||
|
||||
const conflict = upload.checkConflict(items, this.dest);
|
||||
const conflict = await upload.checkConflict(items, this.dest, true);
|
||||
|
||||
if (conflict.length > 0) {
|
||||
this.showHover({
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import CopyPrompt from "@/components/prompts/Copy.vue";
|
||||
import MovePrompt from "@/components/prompts/Move.vue";
|
||||
import { files as api } from "@/api";
|
||||
import { checkConflict } from "@/utils/upload";
|
||||
|
||||
vi.mock("@/api", () => ({
|
||||
files: {
|
||||
copy: vi.fn().mockResolvedValue(undefined),
|
||||
move: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/api/utils", () => ({
|
||||
removePrefix: (value: string) => value.replace(/^\/files/, ""),
|
||||
}));
|
||||
|
||||
vi.mock("@/utils/buttons", () => ({
|
||||
default: {
|
||||
loading: vi.fn(),
|
||||
success: vi.fn(),
|
||||
done: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/utils/upload", () => ({
|
||||
checkConflict: vi.fn(),
|
||||
}));
|
||||
|
||||
const conflict = [
|
||||
{
|
||||
index: 0,
|
||||
name: "/target/file.txt",
|
||||
origin: { size: 12 },
|
||||
dest: { size: 10 },
|
||||
checked: ["origin"],
|
||||
isSmallerOnServer: true,
|
||||
},
|
||||
];
|
||||
|
||||
function makeContext() {
|
||||
return {
|
||||
selected: [0],
|
||||
req: {
|
||||
items: [
|
||||
{
|
||||
url: "/files/source/file.txt",
|
||||
name: "file.txt",
|
||||
size: 12,
|
||||
isDir: false,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
dest: "/files/target/",
|
||||
user: { redirectAfterCopyMove: false },
|
||||
$route: { path: "/files/source/" },
|
||||
$router: { push: vi.fn() },
|
||||
reload: false,
|
||||
preselect: "",
|
||||
showHover: vi.fn(),
|
||||
closeHovers: vi.fn(),
|
||||
$showError: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
const event = {
|
||||
preventDefault: vi.fn(),
|
||||
};
|
||||
|
||||
describe("copy and move conflict prompts", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(checkConflict).mockResolvedValue(conflict);
|
||||
});
|
||||
|
||||
it("waits for copy conflict detection before calling the copy API", async () => {
|
||||
const context = makeContext();
|
||||
|
||||
await (CopyPrompt as any).methods.copy.call(context, event);
|
||||
|
||||
expect(checkConflict).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({
|
||||
to: "/files/target/file.txt",
|
||||
isDir: false,
|
||||
}),
|
||||
],
|
||||
"/files/target/",
|
||||
true
|
||||
);
|
||||
expect(context.showHover).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
prompt: "resolve-conflict",
|
||||
props: { conflict },
|
||||
})
|
||||
);
|
||||
expect(api.copy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits for move conflict detection before calling the move API", async () => {
|
||||
const context = makeContext();
|
||||
|
||||
await (MovePrompt as any).methods.move.call(context, event);
|
||||
|
||||
expect(checkConflict).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({
|
||||
to: "/files/target/file.txt",
|
||||
isDir: false,
|
||||
}),
|
||||
],
|
||||
"/files/target/",
|
||||
true
|
||||
);
|
||||
expect(context.showHover).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
prompt: "resolve-conflict",
|
||||
props: expect.objectContaining({
|
||||
conflict,
|
||||
files: expect.any(Array),
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(api.move).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
const mobileCss = readFileSync(resolve(__dirname, "../mobile.css"), "utf8");
|
||||
|
||||
const normalizedCss = mobileCss.replace(/\s+/g, " ");
|
||||
|
||||
describe("mobile file listing styles", () => {
|
||||
it("hides file row metadata without hiding list header sort controls", () => {
|
||||
expect(normalizedCss).toContain(
|
||||
"#listing.list .item:not(.header) .size { display: none;"
|
||||
);
|
||||
expect(normalizedCss).toContain(
|
||||
"#listing.list .item:not(.header) .modified { display: none;"
|
||||
);
|
||||
|
||||
expect(normalizedCss).not.toMatch(
|
||||
/#listing\.list \.item \.(size|modified) \{ display: none;/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,12 +14,27 @@
|
||||
body {
|
||||
padding-bottom: 5em;
|
||||
}
|
||||
#listing.list .item .size {
|
||||
#listing.list .item:not(.header) .size {
|
||||
display: none;
|
||||
}
|
||||
#listing.list .item .name {
|
||||
#listing.list .item:not(.header) .name {
|
||||
width: 60%;
|
||||
}
|
||||
#listing.list .item.header .name {
|
||||
margin-right: 0;
|
||||
width: 45%;
|
||||
}
|
||||
#listing.list .item.header .size {
|
||||
width: 25%;
|
||||
}
|
||||
#listing.list .item.header .modified {
|
||||
width: 30%;
|
||||
}
|
||||
#listing.list .item.header p {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
#more {
|
||||
display: inherit;
|
||||
}
|
||||
@@ -162,10 +177,22 @@
|
||||
}
|
||||
|
||||
@media (max-width: 450px) {
|
||||
#listing.list .item .modified {
|
||||
#listing.list .item:not(.header) .modified {
|
||||
display: none;
|
||||
}
|
||||
#listing.list .item .name {
|
||||
#listing.list .item:not(.header) .name {
|
||||
width: 100%;
|
||||
}
|
||||
#listing.list .item.header {
|
||||
padding: 0.75em 0.5em;
|
||||
}
|
||||
#listing.list .item.header .name {
|
||||
width: 34%;
|
||||
}
|
||||
#listing.list .item.header .size {
|
||||
width: 24%;
|
||||
}
|
||||
#listing.list .item.header .modified {
|
||||
width: 42%;
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
@@ -53,6 +53,7 @@ interface ClipItem {
|
||||
from: string;
|
||||
name: string;
|
||||
size?: number;
|
||||
isDir?: boolean;
|
||||
modified?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { checkConflict } from "@/utils/upload";
|
||||
import { files as api } from "@/api";
|
||||
|
||||
vi.mock("@/api", () => ({
|
||||
files: {
|
||||
fetchAll: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/api/utils", () => ({
|
||||
removePrefix: (value: string) => value.replace(/^\/files/, ""),
|
||||
}));
|
||||
|
||||
// upload.ts imports these at module load; they reach window-bound constants
|
||||
// which don't exist in the node test environment. checkConflict never uses
|
||||
// them, so empty stubs keep the import graph from blowing up.
|
||||
vi.mock("@/stores/layout", () => ({ useLayoutStore: vi.fn() }));
|
||||
vi.mock("@/stores/upload", () => ({ useUploadStore: vi.fn() }));
|
||||
vi.mock("@/utils/url", () => ({ default: {} }));
|
||||
|
||||
// A move/copy/drag item carries `name` (raw) and `to` (URL-encoded) but no
|
||||
// `fullPath` — mirroring what Move.vue / Copy.vue / ListingItem.vue build.
|
||||
function moveItem(name: string, dest: string, size = 12) {
|
||||
return {
|
||||
from: `/files/source/${encodeURIComponent(name)}`,
|
||||
to: dest + encodeURIComponent(name),
|
||||
name,
|
||||
size,
|
||||
isDir: false,
|
||||
overwrite: false,
|
||||
rename: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("checkConflict", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("detects a conflict for a plain filename", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/file.txt",
|
||||
name: "file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("file.txt", "/files/target/")],
|
||||
"/files/target/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/file.txt");
|
||||
});
|
||||
|
||||
// Regression for #5957: names with encodable characters (spaces, "#",
|
||||
// non-ASCII) were keyed by the URL-encoded `to` value and never matched the
|
||||
// server's raw path, so the conflict modal was skipped and the backend
|
||||
// returned a bare 409 instead.
|
||||
it.each(["my file.txt", "résumé.pdf", "a#b.txt"])(
|
||||
"detects a conflict for %s (encodable characters)",
|
||||
async (name) => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: `/target/${name}`,
|
||||
name,
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem(name, "/files/target/")],
|
||||
"/files/target/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe(`/target/${name}`);
|
||||
}
|
||||
);
|
||||
|
||||
it("reports no conflict when the destination has no matching name", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/other.txt",
|
||||
name: "other.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("my file.txt", "/files/target/")],
|
||||
"/files/target/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("detects nested conflicts for folder uploads via fullPath", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/folder",
|
||||
name: "folder",
|
||||
size: 0,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: true,
|
||||
},
|
||||
{
|
||||
path: "/target/folder/nested file.txt",
|
||||
name: "nested file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const files = [
|
||||
{ name: "folder", size: 0, isDir: true, fullPath: "folder" },
|
||||
{
|
||||
name: "nested file.txt",
|
||||
size: 12,
|
||||
isDir: false,
|
||||
fullPath: "folder/nested file.txt",
|
||||
},
|
||||
];
|
||||
|
||||
const conflicts = await checkConflict(files, "/files/target/");
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/folder/nested file.txt");
|
||||
});
|
||||
|
||||
// The "upload folder" file input pushes only files (with a relative
|
||||
// fullPath) and no directory entries. Conflict detection must still find a
|
||||
// nested file even though its parent folder is not in the upload list.
|
||||
it("detects nested conflicts when no directory entries are present", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/folder/deep/file.txt",
|
||||
name: "file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const files = [
|
||||
{
|
||||
name: "file.txt",
|
||||
size: 12,
|
||||
isDir: false,
|
||||
fullPath: "folder/deep/file.txt",
|
||||
},
|
||||
];
|
||||
|
||||
const conflicts = await checkConflict(files, "/files/target/");
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/folder/deep/file.txt");
|
||||
});
|
||||
|
||||
// Copy/move stats the whole destination, so a same-named directory is a
|
||||
// conflict in its own right (regression for the directory case of #5957).
|
||||
it("reports a directory conflict for copy/move (includeDirectories)", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/folder",
|
||||
name: "folder",
|
||||
size: 0,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const items = [{ ...moveItem("folder", "/files/target/", 0), isDir: true }];
|
||||
|
||||
const conflicts = await checkConflict(items, "/files/target/", true);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/folder");
|
||||
});
|
||||
|
||||
// Uploads merge into an existing folder, so the directory itself must not be
|
||||
// reported — only the files inside it can conflict.
|
||||
it("ignores a directory conflict for uploads (default)", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/folder",
|
||||
name: "folder",
|
||||
size: 0,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: true,
|
||||
},
|
||||
]);
|
||||
|
||||
const files = [
|
||||
{ name: "folder", size: 0, isDir: true, fullPath: "folder" },
|
||||
];
|
||||
|
||||
const conflicts = await checkConflict(files, "/files/target/");
|
||||
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns no conflicts when the recursive listing fails", async () => {
|
||||
vi.mocked(api.fetchAll).mockRejectedValue(new Error("404"));
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("file.txt", "/files/target/")],
|
||||
"/files/target/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+56
-129
@@ -4,159 +4,86 @@ import url from "@/utils/url";
|
||||
import { files as api } from "@/api";
|
||||
import { removePrefix } from "@/api/utils";
|
||||
|
||||
interface UploadEntryWithChild extends UploadEntry {
|
||||
children?: UploadEntryWithChild[];
|
||||
originalIndex: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert UploadList into a forest (array of root nodes).
|
||||
* This properly handles uploads with multiple top-level files/folders
|
||||
* instead of assuming a single root.
|
||||
* @param flatArray
|
||||
* @param basePath
|
||||
* The path used to detect conflicts against the server's recursive listing.
|
||||
*
|
||||
* It MUST be the raw, un-encoded path relative to the destination:
|
||||
* - `fullPath` is set for folder uploads and drag & drop (e.g. "sub/file.txt").
|
||||
* - `name` is the leaf for every other case (copy/move/paste/single upload),
|
||||
* which is always a flat top-level entry.
|
||||
*
|
||||
* We never key on `item.to`: it is URL-encoded (`dest + encodeURIComponent(name)`)
|
||||
* and would miss conflicts for any name with encodable characters (spaces, "#",
|
||||
* non-ASCII, ...), surfacing a raw 409 error instead of the conflict modal.
|
||||
* @param item
|
||||
*/
|
||||
function flatToForest(
|
||||
flatArray: UploadList,
|
||||
basePath: string
|
||||
): UploadEntryWithChild[] {
|
||||
const nodeMap: Record<string, UploadEntryWithChild> = {};
|
||||
|
||||
// First pass: create all nodes
|
||||
flatArray.forEach((item, index) => {
|
||||
// File list is created from very different action and info available are not always the same.
|
||||
// By doing a drag and drop or upload a folder (both from the browser or from the OS) we have the fullPath property available
|
||||
// By uploading a single file using the file input, we only have the "name" property
|
||||
// By doing drag and drop from filebrowser to filebrowser, we have the "to" property available but not the fullPath
|
||||
const fullPathOrTo =
|
||||
item.fullPath || item.to?.replace(basePath, "") || item.name;
|
||||
nodeMap[fullPathOrTo!] = {
|
||||
fullPath: fullPathOrTo,
|
||||
isDir: item.isDir,
|
||||
name: item.name,
|
||||
size: item.size,
|
||||
originalIndex: index,
|
||||
...(item.isDir && { children: [] }),
|
||||
...(item.file && { file: item.file }),
|
||||
};
|
||||
});
|
||||
|
||||
const roots: UploadEntryWithChild[] = [];
|
||||
|
||||
// Second pass: build hierarchy
|
||||
flatArray.forEach((item) => {
|
||||
// see comment before to explanation
|
||||
const fullPathOrTo =
|
||||
item.fullPath || item.to?.replace(basePath, "") || item.name;
|
||||
|
||||
const node = nodeMap[fullPathOrTo!];
|
||||
const lastSlash = fullPathOrTo!.lastIndexOf("/");
|
||||
|
||||
if (lastSlash === -1) {
|
||||
roots.push(node);
|
||||
} else {
|
||||
const parentPath = fullPathOrTo!.substring(0, lastSlash);
|
||||
const parent = nodeMap[parentPath];
|
||||
if (parent?.children) {
|
||||
parent.children.push(node);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return roots;
|
||||
function conflictKey(item: UploadEntry): string {
|
||||
return (item.fullPath || item.name).replace(/^\/+/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Return conflict files from
|
||||
* @param files - flat upload list to check
|
||||
* @param basePath - server destination path (e.g. "/files/uploads/")
|
||||
* Return the entries from `files` that already exist under `basePath` on the
|
||||
* server, so the caller can prompt the user to overwrite/rename/skip.
|
||||
*
|
||||
* The whole destination tree is fetched once and indexed by path relative to
|
||||
* the destination, then every entry is looked up directly — no need to mirror
|
||||
* the upload's folder structure.
|
||||
*
|
||||
* Directory handling differs by action, hence `includeDirectories`:
|
||||
* - Upload (false): an existing folder is silently merged, so only the
|
||||
* individual files inside it can conflict.
|
||||
* - Copy/move (true): the server stats the destination and rejects it whole if
|
||||
* a same-named entry exists, so the directory itself is a conflict. The list
|
||||
* only holds the top-level items being moved, so each is reported once.
|
||||
*
|
||||
* @param files - flat upload list to check
|
||||
* @param basePath - server destination path (e.g. "/files/uploads/")
|
||||
* @param includeDirectories - report directories as conflicts (copy/move)
|
||||
*/
|
||||
export async function checkConflict(
|
||||
files: UploadList,
|
||||
basePath: string
|
||||
basePath: string,
|
||||
includeDirectories = false
|
||||
): Promise<ConflictingResource[]> {
|
||||
console.log(
|
||||
"Starting conflict check, " + files.length + " possible conflict found."
|
||||
);
|
||||
if (files.length === 0) return [];
|
||||
|
||||
const forest = flatToForest(files, basePath);
|
||||
if (forest.length === 0) return [];
|
||||
|
||||
// Single API call: fetch the entire server tree under basePath.
|
||||
let serverEntries: RecursiveEntry[] = [];
|
||||
let serverEntries: RecursiveEntry[];
|
||||
try {
|
||||
// Single API call: fetch the entire server tree under basePath.
|
||||
serverEntries = await api.fetchAll(basePath);
|
||||
} catch {
|
||||
console.error(
|
||||
`Failed to fetch recursive server listing for ${basePath}. ` +
|
||||
`Assuming directory doesn't exist and skipping conflict check.`
|
||||
);
|
||||
// The destination doesn't exist yet, so nothing can conflict.
|
||||
return [];
|
||||
}
|
||||
|
||||
// Build a lookup map keyed by the normalised server path for O(1) access.
|
||||
// The server returns paths relative to the user's scope (e.g. "/uploads/foo.txt").
|
||||
// We strip the basePath prefix so the key matches the upload entry's fullPath.
|
||||
// The server returns paths absolute within the user's scope
|
||||
// (e.g. "/uploads/sub/file.txt"). Strip the basePath prefix so the keys line
|
||||
// up with each entry's conflictKey, which is relative to the destination.
|
||||
const normBase = removePrefix(basePath).replace(/\/+$/, "");
|
||||
const serverMap = new Map<string, RecursiveEntry>();
|
||||
for (const entry of serverEntries) {
|
||||
// entry.path is absolute from server root, e.g. "/uploads/sub/file.txt"
|
||||
// We need the relative part after normBase, e.g. "sub/file.txt"
|
||||
let rel = entry.path;
|
||||
if (rel.startsWith(normBase)) {
|
||||
rel = rel.slice(normBase.length);
|
||||
}
|
||||
// Strip leading slash so it matches fullPath format ("sub/file.txt")
|
||||
rel = rel.replace(/^\/+/, "");
|
||||
serverMap.set(rel, entry);
|
||||
const rel = entry.path.startsWith(normBase)
|
||||
? entry.path.slice(normBase.length)
|
||||
: entry.path;
|
||||
serverMap.set(rel.replace(/^\/+/, ""), entry);
|
||||
}
|
||||
|
||||
const conflicts: ConflictingResource[] = [];
|
||||
files.forEach((file, index) => {
|
||||
if (file.isDir && !includeDirectories) return; // see directory note above
|
||||
|
||||
/**
|
||||
* Walk the upload tree and compare each file node against the
|
||||
* pre-fetched server map. Directories only need to be recursed
|
||||
* when they appear in the map (otherwise no child can conflict).
|
||||
*/
|
||||
function recursiveCheckConflict(nodes: UploadEntryWithChild[]): void {
|
||||
for (const node of nodes) {
|
||||
if (node.isDir && node.children) {
|
||||
// Only recurse if this directory exists on the server
|
||||
const dirKey = node.fullPath!.replace(/^\/+/, "");
|
||||
if (serverMap.has(dirKey)) {
|
||||
recursiveCheckConflict(node.children);
|
||||
}
|
||||
} else {
|
||||
// File – check for a conflict against the server map
|
||||
const fileKey = node.fullPath!.replace(/^\/+/, "");
|
||||
const serverEntry = serverMap.get(fileKey);
|
||||
const server = serverMap.get(conflictKey(file));
|
||||
if (!server) return;
|
||||
|
||||
if (serverEntry) {
|
||||
conflicts.push({
|
||||
index: node.originalIndex,
|
||||
name: serverEntry.path,
|
||||
origin: {
|
||||
lastModified: node.file?.lastModified,
|
||||
size: node.size,
|
||||
},
|
||||
dest: {
|
||||
lastModified: serverEntry.modified,
|
||||
size: serverEntry.size,
|
||||
},
|
||||
checked: ["origin"],
|
||||
isSmallerOnServer: node.size > serverEntry.size,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Walk all root nodes synchronously against the pre-fetched data
|
||||
recursiveCheckConflict(forest);
|
||||
|
||||
console.log(conflicts.length + " conflicts found.");
|
||||
|
||||
conflicts.sort((a, b) => a.index - b.index);
|
||||
conflicts.push({
|
||||
index,
|
||||
name: server.path,
|
||||
origin: { lastModified: file.file?.lastModified, size: file.size },
|
||||
dest: { lastModified: server.modified, size: server.size },
|
||||
checked: ["origin"],
|
||||
isSmallerOnServer: file.size > server.size,
|
||||
});
|
||||
});
|
||||
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
@@ -632,6 +632,7 @@ const copyCut = (event: Event | KeyboardEvent): void => {
|
||||
from: fileStore.req.items[i].url,
|
||||
name: fileStore.req.items[i].name,
|
||||
size: fileStore.req.items[i].size,
|
||||
isDir: fileStore.req.items[i].isDir,
|
||||
modified: fileStore.req.items[i].modified,
|
||||
});
|
||||
}
|
||||
@@ -661,6 +662,7 @@ const paste = async (event: Event) => {
|
||||
to,
|
||||
name: item.name,
|
||||
size: item.size,
|
||||
isDir: item.isDir,
|
||||
modified: item.modified,
|
||||
overwrite: false,
|
||||
rename: clipboardStore.path == route.path,
|
||||
@@ -697,7 +699,7 @@ const paste = async (event: Event) => {
|
||||
}
|
||||
|
||||
const path = route.path.endsWith("/") ? route.path : route.path + "/";
|
||||
const conflict = await upload.checkConflict(items, path);
|
||||
const conflict = await upload.checkConflict(items, path, true);
|
||||
|
||||
if (conflict.length > 0) {
|
||||
layoutStore.showHover({
|
||||
|
||||
+6
-5
@@ -9,11 +9,9 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var withHashFile = func(fn handleFunc) handleFunc {
|
||||
@@ -65,8 +63,11 @@ var withHashFile = func(fn handleFunc) handleFunc {
|
||||
filePath = ifPath
|
||||
}
|
||||
|
||||
// set fs root to the shared file/folder
|
||||
d.user.Fs = afero.NewBasePathFs(d.user.Fs, basePath)
|
||||
// set fs root to the shared file/folder. ScopedFs (not a bare
|
||||
// BasePathFs) so the share is also symlink-confined: a link inside the
|
||||
// shared subtree that points elsewhere in the owner's scope — outside
|
||||
// the share — must not be followed.
|
||||
d.user.Fs = files.NewScopedFs(d.user.Fs, basePath)
|
||||
|
||||
// the filesystem is now rebased onto basePath, so paths handed to the
|
||||
// rule checker are relative to it. Resolve them back to the user's
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
"github.com/filebrowser/filebrowser/v2/storage"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// symlinkShareStorage builds a storage whose single user is rooted at a real
|
||||
// on-disk scope containing a public share "/shared" with a symlinked
|
||||
// descendant "link -> ../private". Skips the test if symlinks are unavailable.
|
||||
func symlinkShareStorage(t *testing.T) *storage.Storage {
|
||||
t.Helper()
|
||||
scope := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(scope, "shared"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(scope, "private"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(scope, "private", "secret.txt"), []byte("symlink-secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(scope, "private"), filepath.Join(scope, "shared", "link")); err != nil {
|
||||
t.Skipf("cannot create symlink on this platform: %v", err)
|
||||
}
|
||||
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
st, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get storage: %v", err)
|
||||
}
|
||||
if err := st.Share.Save(&share.Link{Hash: "h", UserID: 1, Path: "/shared"}); err != nil {
|
||||
t.Fatalf("failed to save share: %v", err)
|
||||
}
|
||||
if err := st.Users.Save(&users.User{
|
||||
Username: "username",
|
||||
Password: "pw",
|
||||
Perm: users.Permissions{Share: true, Download: true},
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to save user: %v", err)
|
||||
}
|
||||
if err := st.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
|
||||
t.Fatalf("failed to save settings: %v", err)
|
||||
}
|
||||
st.Users = &customFSUser{
|
||||
Store: st.Users,
|
||||
fs: files.NewScopedFs(afero.NewOsFs(), scope),
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Reproduces GHSA-hf77-9m7w-fq8q: a public directory share whose subtree
|
||||
// contains a symlink to a directory outside the share. Requesting a regular
|
||||
// file behind that linked ancestor must NOT disclose its contents.
|
||||
func TestPublicShareSymlinkDescendantDisclosure(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
handler handleFunc
|
||||
path string
|
||||
}{
|
||||
"direct file download via dl handler": {handler: publicDlHandler, path: "h/link/secret.txt"},
|
||||
"share info via share handler": {handler: publicShareHandler, path: "h/link/secret.txt"},
|
||||
"listing of linked dir": {handler: publicShareHandler, path: "h/link/"},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(name, func(t *testing.T) {
|
||||
st := symlinkShareStorage(t)
|
||||
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = tc.path })
|
||||
recorder := httptest.NewRecorder()
|
||||
handler := handle(tc.handler, "", st, &settings.Server{})
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
result := recorder.Result()
|
||||
defer result.Body.Close()
|
||||
body, _ := io.ReadAll(result.Body)
|
||||
|
||||
t.Logf("status=%d body=%q", result.StatusCode, string(body))
|
||||
if result.StatusCode == http.StatusOK {
|
||||
t.Errorf("VULNERABLE: leaked path outside share (status 200, body=%q)", string(body))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The listing of the public share root must omit the escaping symlink "link"
|
||||
// entirely (no target metadata leak).
|
||||
func TestPublicShareSymlinkListingOmitsEscapingLink(t *testing.T) {
|
||||
st := symlinkShareStorage(t)
|
||||
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/" })
|
||||
recorder := httptest.NewRecorder()
|
||||
handler := handle(publicShareHandler, "", st, &settings.Server{})
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
result := recorder.Result()
|
||||
defer result.Body.Close()
|
||||
body, _ := io.ReadAll(result.Body)
|
||||
if result.StatusCode != http.StatusOK {
|
||||
t.Fatalf("share root listing failed: status=%d body=%q", result.StatusCode, string(body))
|
||||
}
|
||||
if strings.Contains(string(body), "\"link\"") {
|
||||
t.Errorf("VULNERABLE: listing exposes escaping symlink: %s", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduces the archive variant of GHSA-hf77-9m7w-fq8q: downloading the whole
|
||||
// public share as a zip must not pull in files reached through a symlinked
|
||||
// descendant.
|
||||
func TestPublicShareSymlinkArchiveDisclosure(t *testing.T) {
|
||||
st := symlinkShareStorage(t)
|
||||
|
||||
// Request the whole share root as an archive.
|
||||
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = "h/" })
|
||||
recorder := httptest.NewRecorder()
|
||||
handler := handle(publicDlHandler, "", st, &settings.Server{})
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
result := recorder.Result()
|
||||
defer result.Body.Close()
|
||||
body, _ := io.ReadAll(result.Body)
|
||||
if result.StatusCode != http.StatusOK {
|
||||
t.Fatalf("archive request failed: status=%d body=%q", result.StatusCode, string(body))
|
||||
}
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read zip: %v", err)
|
||||
}
|
||||
for _, f := range zr.File {
|
||||
if strings.Contains(f.Name, "secret.txt") {
|
||||
t.Errorf("VULNERABLE: archive includes file behind symlinked descendant: %q", f.Name)
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
content, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
if bytes.Contains(content, []byte("symlink-secret")) {
|
||||
t.Errorf("VULNERABLE: archive entry %q leaks out-of-scope content", f.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -8,13 +8,13 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
func TestPublicShareHandlerAuthentication(t *testing.T) {
|
||||
@@ -220,7 +220,13 @@ func TestPublicShareHandlerRules(t *testing.T) {
|
||||
t.Fatalf("failed to save settings: %v", err)
|
||||
}
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
fs := files.NewScopedFs(afero.NewOsFs(), t.TempDir())
|
||||
if err := fs.MkdirAll("/projects/private", 0o755); err != nil {
|
||||
t.Fatalf("failed to create private dir: %v", err)
|
||||
}
|
||||
if err := fs.MkdirAll("/projects/public", 0o755); err != nil {
|
||||
t.Fatalf("failed to create public dir: %v", err)
|
||||
}
|
||||
if err := afero.WriteFile(fs, "/projects/private/secret.txt", []byte("top secret"), 0o600); err != nil {
|
||||
t.Fatalf("failed to write secret file: %v", err)
|
||||
}
|
||||
@@ -270,7 +276,9 @@ func (cu *customFSUser) Get(baseScope string, id interface{}) (*users.User, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.Fs = cu.fs
|
||||
// Mirror production (users.User init), where a user's filesystem is always a
|
||||
// scoped, symlink-confining ScopedFs rather than a bare afero.Fs.
|
||||
user.Fs = files.NewScopedFs(cu.fs, "/")
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
+1
-2
@@ -10,11 +10,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/archives"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/fileutils"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/mholt/archives"
|
||||
)
|
||||
|
||||
func slashClean(name string) string {
|
||||
|
||||
+2
-23
@@ -15,12 +15,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/fileutils"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
var resourceGetHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
@@ -228,19 +227,6 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
// Refuse to copy/move through a symlink that escapes the user's scope,
|
||||
// for either the source (read escape) or the destination (write
|
||||
// escape). fileutils.Copy/MoveFile operate on the raw afero FS and
|
||||
// follow symlinks, so they bypass the guards in stat()/writeFile().
|
||||
for _, p := range []string{src, dst} {
|
||||
if ok, scopeErr := files.WithinScope(d.user.Fs, p); scopeErr != nil || !ok {
|
||||
if scopeErr != nil {
|
||||
return errToStatus(scopeErr), scopeErr
|
||||
}
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
}
|
||||
|
||||
err = checkParent(src, dst)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, err
|
||||
@@ -308,13 +294,6 @@ func addVersionSuffix(source string, afs afero.Fs) string {
|
||||
}
|
||||
|
||||
func writeFile(afs afero.Fs, dst string, in io.Reader, fileMode, dirMode fs.FileMode) (os.FileInfo, error) {
|
||||
// Refuse to write through a symlink that escapes the user's scope, so an
|
||||
// overwrite of an existing escaping symlink cannot modify a file outside
|
||||
// the boundary.
|
||||
if ok, err := files.WithinScope(afs, dst); err != nil || !ok {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
dir, _ := path.Split(dst)
|
||||
err := afs.MkdirAll(dir, dirMode)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/diskcache"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
func TestResourceCopyDoesNotDereferenceEscapingSymlink(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
userScope := filepath.Join(root, "user")
|
||||
if err := os.MkdirAll(filepath.Join(userScope, "srcdir"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An ordinary in-scope file, to prove a normal copy still works.
|
||||
if err := os.WriteFile(filepath.Join(userScope, "srcdir", "normal.txt"), []byte("in-scope"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The secret living outside the user's scope.
|
||||
secret := filepath.Join(root, "secret.txt")
|
||||
if err := os.WriteFile(secret, []byte("OUT-OF-SCOPE-SECRET"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// An escaping symlink planted inside the user's scope (out-of-band, as the
|
||||
// advisory's preconditions describe).
|
||||
if err := os.Symlink(secret, filepath.Join(userScope, "srcdir", "link.txt")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
key := []byte("test-signing-key")
|
||||
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
st, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get storage: %v", err)
|
||||
}
|
||||
perm := users.Permissions{Create: true, Modify: true, Download: true, Rename: true}
|
||||
if err := st.Users.Save(&users.User{Username: "u", Password: "pw", Perm: perm}); err != nil {
|
||||
t.Fatalf("failed to save user: %v", err)
|
||||
}
|
||||
if err := st.Settings.Save(&settings.Settings{Key: key}); err != nil {
|
||||
t.Fatalf("failed to save settings: %v", err)
|
||||
}
|
||||
// The user's scope is the real on-disk userScope. customFSUser.Get wraps it
|
||||
// in a ScopedFs, mirroring production (users.User init).
|
||||
st.Users = &customFSUser{
|
||||
Store: st.Users,
|
||||
fs: afero.NewBasePathFs(afero.NewOsFs(), userScope),
|
||||
}
|
||||
|
||||
signed := signToken(t, perm, key)
|
||||
|
||||
t.Run("direct raw read is forbidden", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, "/srcdir/link.txt", http.NoBody)
|
||||
req.Header.Set("X-Auth", signed)
|
||||
rec := httptest.NewRecorder()
|
||||
handle(rawHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Fatalf("VULNERABLE: direct raw read of escaping symlink returned 200, body=%q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("recursive copy does not exfiltrate", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPatch, "/srcdir/", http.NoBody)
|
||||
q := req.URL.Query()
|
||||
q.Set("action", "copy")
|
||||
q.Set("destination", "/dstdir")
|
||||
req.URL.RawQuery = q.Encode()
|
||||
req.Header.Set("X-Auth", signed)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handle(resourcePatchHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
|
||||
t.Logf("copy status=%d body=%q", rec.Code, rec.Body.String())
|
||||
|
||||
// The escaping symlink's target content must never appear in scope.
|
||||
leaked := filepath.Join(userScope, "dstdir", "link.txt")
|
||||
if data, readErr := os.ReadFile(leaked); readErr == nil {
|
||||
t.Fatalf("VULNERABLE: out-of-scope content landed in scope at %s: %q", leaked, string(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func signToken(t *testing.T, perm users.Permissions, key []byte) string {
|
||||
t.Helper()
|
||||
claims := &authToken{
|
||||
User: userInfo{ID: 1, Username: "u", Perm: perm},
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
},
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to sign token: %v", err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
+5
-13
@@ -12,11 +12,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/share"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func withPermShare(fn handleFunc) handleFunc {
|
||||
@@ -103,20 +101,14 @@ var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request
|
||||
// Only allow sharing paths that currently exist. Otherwise a share could be
|
||||
// created for a non-existent path and would silently start exposing
|
||||
// whatever file later appears there.
|
||||
//
|
||||
// d.user.Fs is scoped, so Stat also refuses to follow a symlink whose target
|
||||
// escapes the user's scope: that returns a permission error here and so
|
||||
// blocks creating a share that points out of scope.
|
||||
if _, err := d.user.Fs.Stat(r.URL.Path); err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
// Refuse to create a share whose on-disk target escapes the user's scope
|
||||
// (e.g. via a symlink), mirroring the read/write guards. The public serve
|
||||
// path already rejects these, but blocking creation avoids dangling shares.
|
||||
if ok, err := files.WithinScope(d.user.Fs, r.URL.Path); err != nil || !ok {
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
var s *share.Link
|
||||
var body share.CreateBody
|
||||
if r.Body != nil {
|
||||
|
||||
@@ -11,9 +11,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// keepUploadActive periodically touches the cache entry to prevent eviction during transfer
|
||||
@@ -44,6 +43,7 @@ func tusPostHandler(cache UploadCache) handleFunc {
|
||||
if !d.user.Perm.Create || !d.Check(r.URL.Path) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
|
||||
file, err := files.NewFileInfo(&files.FileOptions{
|
||||
Fs: d.user.Fs,
|
||||
Path: r.URL.Path,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/storage/bolt"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// Reproduces the TUS write vector of GHSA-v9g6-9pp4-3w22: a scoped user must
|
||||
// not be able to create or write files through a symlinked directory that
|
||||
// escapes their scope.
|
||||
func TestTusHandlersRejectSymlinkScopeEscape(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
userScope := filepath.Join(root, "user")
|
||||
outside := filepath.Join(root, "otheruser")
|
||||
for _, d := range []string{userScope, outside} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// A directory symlink inside the user's scope pointing outside it.
|
||||
if err := os.Symlink(outside, filepath.Join(userScope, "escape_link")); err != nil {
|
||||
t.Skipf("cannot create symlink: %v", err)
|
||||
}
|
||||
|
||||
key := []byte("test-signing-key")
|
||||
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
st, err := bolt.NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get storage: %v", err)
|
||||
}
|
||||
if err := st.Users.Save(&users.User{
|
||||
Username: "u",
|
||||
Password: "pw",
|
||||
Perm: users.Permissions{Create: true, Modify: true},
|
||||
}); err != nil {
|
||||
t.Fatalf("failed to save user: %v", err)
|
||||
}
|
||||
if err := st.Settings.Save(&settings.Settings{Key: key}); err != nil {
|
||||
t.Fatalf("failed to save settings: %v", err)
|
||||
}
|
||||
st.Users = &customFSUser{
|
||||
Store: st.Users,
|
||||
fs: files.NewScopedFs(afero.NewOsFs(), userScope),
|
||||
}
|
||||
|
||||
// Forge a valid auth token for user ID 1.
|
||||
claims := &authToken{
|
||||
User: userInfo{ID: 1, Username: "u", Perm: users.Permissions{Create: true, Modify: true}},
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
},
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to sign token: %v", err)
|
||||
}
|
||||
|
||||
cases := map[string]struct {
|
||||
method string
|
||||
handler handleFunc
|
||||
headers map[string]string
|
||||
}{
|
||||
"POST create through symlinked dir": {
|
||||
method: http.MethodPost,
|
||||
handler: tusPostHandler(newMemoryUploadCache()),
|
||||
headers: map[string]string{"Upload-Length": "20"},
|
||||
},
|
||||
"PATCH write through symlinked dir": {
|
||||
method: http.MethodPatch,
|
||||
handler: tusPatchHandler(newMemoryUploadCache()),
|
||||
headers: map[string]string{"Content-Type": "application/offset+octet-stream", "Upload-Offset": "0"},
|
||||
},
|
||||
}
|
||||
|
||||
for name, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(name, func(t *testing.T) {
|
||||
req, err := http.NewRequest(tc.method, "escape_link/injected.txt", http.NoBody)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("X-Auth", signed)
|
||||
for k, v := range tc.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
handler := handle(tc.handler, "", st, &settings.Server{})
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Errorf("expected 403, got %d", recorder.Code)
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(outside, "injected.txt")); statErr == nil {
|
||||
t.Errorf("VULNERABLE: file was created outside the user's scope")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+20
-21
@@ -3,11 +3,10 @@ package users
|
||||
import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/files"
|
||||
"github.com/filebrowser/filebrowser/v2/rules"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// ViewMode describes a view mode.
|
||||
@@ -20,23 +19,23 @@ const (
|
||||
|
||||
// User describes a user.
|
||||
type User struct {
|
||||
ID uint `storm:"id,increment" json:"id"`
|
||||
Username string `storm:"unique" json:"username"`
|
||||
Password string `json:"password"`
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
ViewMode ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
Sorting files.Sorting `json:"sorting"`
|
||||
Fs afero.Fs `json:"-" yaml:"-"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
HideDotfiles bool `json:"hideDotfiles"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
ID uint `storm:"id,increment" json:"id"`
|
||||
Username string `storm:"unique" json:"username"`
|
||||
Password string `json:"password"`
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
ViewMode ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
Sorting files.Sorting `json:"sorting"`
|
||||
Fs *files.ScopedFs `json:"-" yaml:"-"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
HideDotfiles bool `json:"hideDotfiles"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
}
|
||||
|
||||
// GetRules implements rules.Provider.
|
||||
@@ -93,7 +92,7 @@ func (u *User) Clean(baseScope string, fields ...string) error {
|
||||
if u.Fs == nil {
|
||||
scope := u.Scope
|
||||
scope = filepath.Join(baseScope, filepath.Join("/", scope))
|
||||
u.Fs = afero.NewBasePathFs(afero.NewOsFs(), scope)
|
||||
u.Fs = files.NewScopedFs(afero.NewOsFs(), scope)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -101,5 +100,5 @@ func (u *User) Clean(baseScope string, fields ...string) error {
|
||||
|
||||
// FullPath gets the full path for a user's relative path.
|
||||
func (u *User) FullPath(path string) string {
|
||||
return afero.FullBaseFsPath(u.Fs.(*afero.BasePathFs), path)
|
||||
return afero.FullBaseFsPath(u.Fs.Base(), path)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user