Compare commits

...
39 Commits
Author SHA1 Message Date
Henrique Dias 67ed670d92 chore(release): 2.63.13 2026-06-06 08:33:27 +02:00
Henrique Dias a1a514dcbb fix: copy/move allow overwrite 2026-06-06 08:28:31 +02:00
Henrique Dias 5f7311d324 refactor: cleanup and simplify upload.ts 2026-06-06 08:15:16 +02:00
Henrique Dias 998bd95bfa chore(release): 2.63.12 2026-06-04 17:17:38 +02:00
Puneet DixitandGitHub c1abe8f561 fix: await copy move conflict detection (#5978) 2026-06-04 17:16:30 +02:00
Puneet DixitandGitHub 0bb2768754 fix: keep mobile file sort controls visible (#5977) 2026-06-04 12:49:30 +02:00
Puneet DixitandGitHub 7b7ff8ae8f fix: skip inaccessible children when listing directories (#5958) 2026-06-04 12:49:07 +02:00
Henrique Dias 1086903c14 chore(release): 2.63.11 2026-06-04 11:03:17 +02:00
Henrique Dias 3471ec2c4b fix: incomplete fix for symlinked directories let scopes users and public-share recipients read and write files outside of scope 2026-06-04 11:02:18 +02:00
Henrique Dias 69c76d11cc chore(release): 2.63.10 2026-06-03 15:42:27 +02:00
Henrique Dias 6b04cbf5e9 fix: allow writes when user scope resolves to filesystem root
WithinScope compared targets against root+separator, which produced
"//" when the scope resolved to "/". No path matched, so every write
was rejected with os.ErrPermission (HTTP 403), breaking saves and
uploads for root-scoped installs. Skip the appended separator when root
already ends in one.
2026-06-03 15:40:26 +02:00
Henrique Dias 503fd6b01f chore(release): 2.63.9 2026-06-03 13:13:03 +02:00
Henrique Dias 35db07d015 fix: set X-Content-Type-Options: nosniff on raw file responses
Prevents browsers from MIME-sniffing uploaded files into a renderable type.
2026-06-03 12:21:23 +02:00
Henrique Dias 19514367ad fix: use constant-time comparison for share access token
Compare the share token with subtle.ConstantTimeCompare instead of ==.
2026-06-03 12:21:23 +02:00
Henrique Dias cdd666fc95 fix: prevent symlink scope escape in copy/move/rename
Check WithinScope for src and dst in resourcePatchHandler before
fileutils.Copy/MoveFile, which follow symlinks and bypassed the
stat()/writeFile() guards (GHSA-239w-m3h6-ch8v).
2026-06-03 12:21:23 +02:00
mehmet turacandGitHub 103acd15fe fix: force octet-stream for attachment downloads (#5942) 2026-06-03 11:59:17 +02:00
Henrique Dias f5e0c4e2e1 chore(release): 2.63.8 2026-06-03 11:57:30 +02:00
Henrique Dias ca019ae7d9 fix: check if share is within scope when creating 2026-06-03 11:57:10 +02:00
Henrique Dias 4488f5b131 chore(release): 2.63.7 2026-06-03 11:44:54 +02:00
Henrique Dias 166583db63 fix: disallow shares for non-existent paths 2026-06-03 11:43:22 +02:00
Henrique Dias 85b7d2762d chore(release): 2.63.6 2026-06-03 11:31:10 +02:00
Henrique Dias 4edabb9ccc chore(docs): update CLI documentation 2026-06-03 11:30:59 +02:00
transifex-integration[bot]andGitHub 103683069e chore: Updates for project File Browser (#5947) 2026-06-03 11:25:04 +02:00
Ariel LeyvaandGitHub 5328e80d2e fix: parse csv files with uneven columns in their rows (#5965) 2026-06-03 11:22:05 +02:00
Henrique DiasandClaude Opus 4.8 847d08bdd1 fix: address three security disclosures (archive traversal, login DoS, symlink escape)
- http/raw.go: strip Windows backslash separators from archive entry names
  on any host. filepath.ToSlash is a no-op for "\" on Linux, so a stored
  backslash filename was emitted verbatim and could escape the extraction
  directory on Windows extractors (zip-slip). (GHSA-gxjx-7m74-hcq8)

- http/auth.go: cap the login and signup request bodies with
  http.MaxBytesReader (1 MiB). The JSON decoder previously read an
  arbitrarily large password into memory before bcrypt truncated it,
  enabling unauthenticated memory-exhaustion DoS. (GHSA-w5fm-68j4-fpc4)

- files/file.go, http/resource.go: add files.WithinScope and refuse to
  follow a symlink whose on-disk target escapes the user's scoped root,
  on both the read path (stat) and the write path (writeFile). Prevents a
  scoped user from reading/overwriting/sharing files outside their scope
  via a pre-existing escaping symlink. (GHSA-239w-m3h6-ch8v)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:21:00 +02:00
Henrique Dias 0231b7ebdf fix: cross-user unauthorized share-link deletion 2026-06-03 10:31:44 +02:00
Henrique Dias e07c59df0b fix: incorrect access control in public directory shares via rule path rebasing 2026-06-03 10:24:05 +02:00
Henrique Dias 0d3eb9bea9 docs: clarify hide dotfiles 2026-06-03 10:20:12 +02:00
Henrique Dias 34ae34e764 fix: remove undocumented hook auth with shell replacement 2026-06-03 09:59:36 +02:00
Henrique Dias ca0108f070 chore: disable automatic major updates 2026-05-21 16:52:04 +02:00
Henrique Dias a1e442ef9e chore(release): 2.63.5 2026-05-21 15:42:07 +02:00
Jose OlceseandGitHub 6ad8160aa3 fix(router): handle undefined catchAll param on root redirect (#5955) 2026-05-21 15:39:45 +02:00
Henrique Dias 22b848f26e chore(release): 2.63.4 2026-05-17 15:11:55 +02:00
Henrique Dias a418dd6bb3 chore: revert node dependencies updates 2026-05-17 15:10:16 +02:00
transifex-integration[bot]andGitHub d978d1ecca chore: sync translations (#5945) 2026-05-17 15:05:08 +02:00
mehmet turacandGitHub 9cc18a81e3 fix: show item shares from all users to admins (#5941) 2026-05-17 15:01:02 +02:00
Henrique DiasandGitHub e38c28273a chore: fix typo 2026-05-17 15:00:44 +02:00
transifex-integration[bot]andGitHub da2dff0933 chore: sync translations 2026-05-17 14:59:45 +02:00
renovate[bot]andGitHub 261bca67bc chore(deps): update all non-major dependencies (#5929) 2026-05-17 14:59:19 +02:00
52 changed files with 2358 additions and 813 deletions
+84
View File
@@ -2,6 +2,90 @@
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.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)
### Bug Fixes
* allow writes when user scope resolves to filesystem root ([6b04cbf](https://github.com/filebrowser/filebrowser/commit/6b04cbf5e9db1f5b9c0b1624843607ce2881cfc4))
## [2.63.9](https://github.com/filebrowser/filebrowser/compare/v2.63.8...v2.63.9) (2026-06-03)
### Bug Fixes
* force octet-stream for attachment downloads ([#5942](https://github.com/filebrowser/filebrowser/issues/5942)) ([103acd1](https://github.com/filebrowser/filebrowser/commit/103acd15fe57554fe0246bfe70a49b6cb4ae0c51))
* prevent symlink scope escape in copy/move/rename ([cdd666f](https://github.com/filebrowser/filebrowser/commit/cdd666fc95f569ad583c32391e45646fed676dfd))
* set X-Content-Type-Options: nosniff on raw file responses ([35db07d](https://github.com/filebrowser/filebrowser/commit/35db07d0159c520a6b3c969ac52033593914fadd))
* use constant-time comparison for share access token ([1951436](https://github.com/filebrowser/filebrowser/commit/19514367adf2d9fe5be2b7666e397979ea679b94))
## [2.63.8](https://github.com/filebrowser/filebrowser/compare/v2.63.7...v2.63.8) (2026-06-03)
### Bug Fixes
* check if share is within scope when creating ([ca019ae](https://github.com/filebrowser/filebrowser/commit/ca019ae7d966a7c28de2b2341271cd13e3458ae6))
## [2.63.7](https://github.com/filebrowser/filebrowser/compare/v2.63.6...v2.63.7) (2026-06-03)
### Bug Fixes
* disallow shares for non-existent paths ([166583d](https://github.com/filebrowser/filebrowser/commit/166583db632e088e9f0adce30aec43bb9d9019f4))
## [2.63.6](https://github.com/filebrowser/filebrowser/compare/v2.63.5...v2.63.6) (2026-06-03)
### Bug Fixes
* address three security disclosures (archive traversal, login DoS, symlink escape) ([847d08b](https://github.com/filebrowser/filebrowser/commit/847d08bdd135e5c3659f2e6dea2f0cd36617af9b))
* cross-user unauthorized share-link deletion ([0231b7e](https://github.com/filebrowser/filebrowser/commit/0231b7ebdfbe77a6c54027d30c4856c3fd81ee4d))
* incorrect access control in public directory shares via rule path rebasing ([e07c59d](https://github.com/filebrowser/filebrowser/commit/e07c59df0b850f5924d5b1683e8609661ddcf534))
* parse csv files with uneven columns in their rows ([#5965](https://github.com/filebrowser/filebrowser/issues/5965)) ([5328e80](https://github.com/filebrowser/filebrowser/commit/5328e80d2e88d1c279a1250a7dfee4fc96f703ec))
* remove undocumented hook auth with shell replacement ([34ae34e](https://github.com/filebrowser/filebrowser/commit/34ae34e764d72540c039f1f5ea2ec4c974168c1f))
## [2.63.5](https://github.com/filebrowser/filebrowser/compare/v2.63.4...v2.63.5) (2026-05-21)
### Bug Fixes
* **router:** handle undefined catchAll param on root redirect ([#5955](https://github.com/filebrowser/filebrowser/issues/5955)) ([6ad8160](https://github.com/filebrowser/filebrowser/commit/6ad8160aa3309314c1b471c5090b67c824464396))
## [2.63.4](https://github.com/filebrowser/filebrowser/compare/v2.63.3...v2.63.4) (2026-05-17)
### Bug Fixes
* show item shares from all users to admins ([#5941](https://github.com/filebrowser/filebrowser/issues/5941)) ([9cc18a8](https://github.com/filebrowser/filebrowser/commit/9cc18a81e3e1b8bf96795bfbe3d83ced294ecfd7))
## [2.63.3](https://github.com/filebrowser/filebrowser/compare/v2.63.2...v2.63.3) (2026-05-05)
-16
View File
@@ -86,22 +86,6 @@ func (a *HookAuth) LoginPage() bool {
// RunCommand starts the hook command and returns the action
func (a *HookAuth) RunCommand() (string, error) {
command := strings.Split(a.Command, " ")
envMapping := func(key string) string {
switch key {
case "USERNAME":
return a.Cred.Username
case "PASSWORD":
return a.Cred.Password
default:
return os.Getenv(key)
}
}
for i, arg := range command {
if i == 0 {
continue
}
command[i] = os.Expand(arg, envMapping)
}
cmd := exec.Command(command[0], command[1:]...)
cmd.Env = append(os.Environ(), fmt.Sprintf("USERNAME=%s", a.Cred.Username))
+88
View File
@@ -0,0 +1,88 @@
package auth
import (
"os"
"path/filepath"
"runtime"
"testing"
)
// writeHookScript writes a POSIX shell script to a temp file and returns its
// path, marking it executable.
func writeHookScript(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "hook.sh")
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o700); err != nil {
t.Fatalf("failed to write hook script: %v", err)
}
return path
}
// TestRunCommandNoCredentialInjection ensures that attacker-controlled
// credentials submitted at the unauthenticated login endpoint cannot be
// injected into the hook command string. Credentials must only ever reach the
// hook through the USERNAME/PASSWORD environment variables, never via string
// substitution into the command itself (CWE-78/CWE-88).
func TestRunCommandNoCredentialInjection(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses POSIX shell")
}
marker := filepath.Join(t.TempDir(), "pwned")
// The hook simply blocks. If the credential were ever interpolated into the
// command string and evaluated by a shell, the embedded `touch` would
// create the marker file.
script := writeHookScript(t, "echo hook.action=block\n")
a := &HookAuth{
Command: script,
Cred: hookCred{
Username: `"; touch ` + marker + `; #`,
Password: `$(touch ` + marker + `)`,
},
}
action, err := a.RunCommand()
if err != nil {
t.Fatalf("RunCommand returned error: %v", err)
}
if action != "block" {
t.Fatalf("expected action %q, got %q", "block", action)
}
if _, err := os.Stat(marker); err == nil {
t.Fatalf("credential injection executed: marker file %q was created", marker)
}
}
// TestRunCommandReceivesCredentialsViaEnv verifies the supported contract: the
// hook receives credentials through the USERNAME and PASSWORD environment
// variables.
func TestRunCommandReceivesCredentialsViaEnv(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses POSIX shell")
}
script := writeHookScript(t, `if [ "$USERNAME" = alice ] && [ "$PASSWORD" = secret ]; then
echo hook.action=auth
else
echo hook.action=block
fi
`)
a := &HookAuth{
Command: script,
Cred: hookCred{
Username: "alice",
Password: "secret",
},
}
action, err := a.RunCommand()
if err != nil {
t.Fatalf("RunCommand returned error: %v", err)
}
if action != "auth" {
t.Fatalf("expected action %q, got %q", "auth", action)
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ func addUserFlags(flags *pflag.FlagSet) {
flags.Bool("singleClick", false, "use single clicks only")
flags.Bool("redirectAfterCopyMove", false, "redirect to destination after copy/move")
flags.Bool("dateFormat", false, "use date format (true for absolute time, false for relative)")
flags.Bool("hideDotfiles", false, "hide dotfiles")
flags.Bool("hideDotfiles", false, "hide dotfiles in file listings")
flags.String("aceEditorTheme", "", "ace editor's syntax highlighting theme for users")
}
+123 -2
View File
@@ -18,6 +18,7 @@ import (
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
@@ -128,6 +129,13 @@ func stat(opts *FileOptions) (*FileInfo, error) {
}
}
if file != nil {
ok, scopeErr := WithinScope(opts.Fs, opts.Path)
if scopeErr != nil || !ok {
return nil, os.ErrPermission
}
}
// regular file
if file != nil && !file.IsSymlink {
return file, nil
@@ -165,6 +173,60 @@ 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 {
@@ -391,8 +453,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
}
@@ -414,6 +475,13 @@ func (i *FileInfo) readListing(checker rules.Checker, readHeader bool, calcImgRe
isSymlink, isInvalidLink := false, false
if IsSymlink(f.Mode()) {
isSymlink = true
// A symlink whose on-disk target escapes the scoped root must not be
// followed, otherwise the listing would leak the target's metadata
// (and downstream access) for files outside the user's scope or the
// shared subtree.
if ok, scopeErr := WithinScope(i.Fs, fPath); scopeErr != nil || !ok {
continue
}
// 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.
info, err := i.Fs.Stat(fPath)
@@ -467,3 +535,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)
}
+222
View File
@@ -0,0 +1,222 @@
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) {
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)
ok, err := WithinScope(bfs, "/file.txt")
if err != nil || !ok {
t.Fatalf("expected (true, nil), got (%v, %v)", ok, err)
}
})
t.Run("new file inside scope is allowed", func(t *testing.T) {
scope := t.TempDir()
bfs := afero.NewBasePathFs(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)
}
})
// 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) {
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(), "/")
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)
}
})
t.Run("sibling of a nested scope is rejected", func(t *testing.T) {
base := t.TempDir()
scope := filepath.Join(base, "srv")
sibling := filepath.Join(base, "srvother")
for _, d := range []string{scope, sibling} {
if err := os.MkdirAll(d, 0o755); err != nil {
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 {
t.Fatal(err)
}
bfs := afero.NewBasePathFs(afero.NewOsFs(), scope)
ok, err := WithinScope(bfs, "/escape")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ok {
t.Fatal("expected escaping symlink to a sibling directory to be rejected")
}
})
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)
}
bfs := afero.NewBasePathFs(afero.NewOsFs(), scope)
ok, err := WithinScope(bfs, "/link/f.txt")
if err != nil || !ok {
t.Fatalf("expected (true, nil) for an in-scope symlink target, got (%v, %v)", ok, 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 := afero.NewBasePathFs(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)
}
}
+1 -1
View File
@@ -74,5 +74,5 @@
"vitest": "^4.1.0",
"vue-tsc": "^3.1.3"
},
"packageManager": "pnpm@10.33.3+sha512.a19744364a7e248b92657a4ca5973f9354d21caf982579674b1c539f32c7420c47138ad8b1254df07aba9bc782d9b3029e3db34d5dbff974326eb74dac8ff489"
"packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"
}
+608 -636
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -138,7 +138,11 @@ watchEffect(() => {
: props.content;
parse(
content as string,
{ delimiter: columnSeparator.value, skip_empty_lines: true },
{
delimiter: columnSeparator.value,
skip_empty_lines: true,
relax_column_count: true,
},
(error, output) => {
if (error) {
console.error("Failed to parse CSV:", error);
@@ -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({
+2 -1
View File
@@ -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({
+2 -1
View File
@@ -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();
});
});
+22
View File
@@ -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;/
);
});
});
+31 -4
View File
@@ -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%;
}
}
+2
View File
@@ -29,6 +29,8 @@
"rename": "Umbenennen",
"replace": "Ersetzen",
"reportIssue": "Problem melden",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Speichern",
"schedule": "Planen",
"search": "Suchen",
+1 -1
View File
@@ -29,7 +29,7 @@
"rename": "Rename",
"replace": "Replace",
"reportIssue": "Report Issue",
"resumeTransfer": "Resume previous transfert",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Save",
"schedule": "Schedule",
+4 -4
View File
@@ -29,8 +29,8 @@
"rename": "Renommer",
"replace": "Remplacer",
"reportIssue": "Signaler un problème",
"resumeTransfer": "Reprendre un transfert précedement interrompu",
"resumeTransferTooltip": "Ignorer tous les fichiers en conflit, sauf ceux qui sont plus petits sur le serveur, car nous supposons que leur transfert a été interrompu.",
"resumeTransfer": "Reprendre le transfert précédent",
"resumeTransferTooltip": "Ignorez tous les fichiers en conflit, à l'exception de ceux dont la taille est inférieure sur le serveur, car nous supposons que leur transfert a été interrompu.",
"save": "Enregistrer",
"schedule": "Planifier",
"search": "Rechercher",
@@ -247,7 +247,7 @@
"execute": "Exécuter des commandes",
"modify": "Modifier des fichiers",
"rename": "Renommer ou déplacer des fichiers ou des dossiers",
"share": "Share files (require download permission)"
"share": "Partager des fichiers (autorisation de téléchargement requise)"
},
"permissions": "Permissions",
"permissionsHelp": "Vous pouvez définir l'utilisateur comme étant un administrateur ou encore choisir les permissions individuellement. Si vous sélectionnez \"Administrateur\", toutes les autres options seront automatiquement activées. La gestion des utilisateurs est un privilège que seul l'administrateur possède.\n",
@@ -283,7 +283,7 @@
"currentPassword": "Mot de Passe Actuel"
},
"sidebar": {
"diskUsed": "{used} of {total} used",
"diskUsed": "{used} sur {total} utilisés",
"help": "Aide",
"hugoNew": "Nouveau Hugo",
"login": "Login",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Preimenuj",
"replace": "Zamijeni",
"reportIssue": "Prijavi grešku",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Spremi",
"schedule": "Zakaži",
"search": "Pretraži",
+2
View File
@@ -29,6 +29,8 @@
"rename": "이름 바꾸기",
"replace": "대체",
"reportIssue": "문제 보고",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "저장",
"schedule": "일정",
"search": "검색",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Pārdēvēt",
"replace": "Aizstāt",
"reportIssue": "Ziņot par problēmu",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Saglabāt",
"schedule": "Grafiks",
"search": "Meklēt",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Hernoemen",
"replace": "Vervangen",
"reportIssue": "Probleem melden",
"resumeTransfer": "Vorige overdracht hervatten",
"resumeTransferTooltip": "Alle conflicterende bestanden overslaan, behalve de bestanden die kleiner zijn op de server, omdat we veronderstellen dat hun overdracht is onderbroken.",
"save": "Opslaan",
"schedule": "Plannen",
"search": "Zoeken",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Zmień nazwę",
"replace": "Zamień",
"reportIssue": "Zgłoś problem",
"resumeTransfer": "Wznów poprzedni transfer",
"resumeTransferTooltip": "Pomiń wszystkie pliki powodujące konflikty, z wyjątkiem tych, które są mniejsze na serwerze, ponieważ podejrzewamy, że ich transfer został przerwany.",
"save": "Zapisz",
"schedule": "Harmonogram",
"search": "Szukaj",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Mudar o nome",
"replace": "Substituir",
"reportIssue": "Reportar problema",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Guardar",
"schedule": "Agendar",
"search": "Pesquisar",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Alterar nome",
"replace": "Substituir",
"reportIssue": "Reportar erro",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Guardar",
"schedule": "Agendar",
"search": "Pesquisar",
+2
View File
@@ -29,6 +29,8 @@
"rename": "Переименовать",
"replace": "Перезаписать",
"reportIssue": "Сообщить о проблеме",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "Сохранить",
"schedule": "Планировка",
"search": "Поиск",
+2
View File
@@ -29,6 +29,8 @@
"rename": "重命名",
"replace": "替换",
"reportIssue": "报告问题",
"resumeTransfer": "Resume previous transfer",
"resumeTransferTooltip": "Skip all conflicting files, except the ones that are smaller on the server as we suppose that their transfert has been interrupted.",
"save": "保存",
"schedule": "计划",
"search": "搜索",
+5 -2
View File
@@ -145,8 +145,11 @@ const routes = [
},
{
path: "/:catchAll(.*)*",
redirect: (to: RouteLocation) =>
`/files/${[...to.params.catchAll].join("/")}`,
redirect: (to: RouteLocation) => {
const catchAll = to.params.catchAll;
if (!catchAll) return "/files/";
return `/files/${Array.isArray(catchAll) ? catchAll.join("/") : catchAll}`;
},
},
];
+1
View File
@@ -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
View File
@@ -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;
}
+3 -1
View File
@@ -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({
+9 -1
View File
@@ -20,6 +20,8 @@ import (
const (
DefaultTokenExpirationTime = time.Hour * 2
maxAuthBodySize = 1 << 20 // 1 MiB
)
type userInfo struct {
@@ -120,6 +122,10 @@ func withAdmin(fn handleFunc) handleFunc {
func loginHandler(tokenExpireTime time.Duration) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, maxAuthBodySize)
}
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
if err != nil {
return http.StatusInternalServerError, err
@@ -142,7 +148,7 @@ type signupBody struct {
Password string `json:"password"`
}
var signupHandler = func(_ http.ResponseWriter, r *http.Request, d *data) (int, error) {
var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if !d.settings.Signup {
return http.StatusMethodNotAllowed, nil
}
@@ -151,6 +157,8 @@ var signupHandler = func(_ http.ResponseWriter, r *http.Request, d *data) (int,
return http.StatusBadRequest, nil
}
r.Body = http.MaxBytesReader(w, r.Body, maxAuthBodySize)
info := &signupBody{}
err := json.NewDecoder(r.Body).Decode(info)
if err != nil {
+16
View File
@@ -3,6 +3,7 @@ package fbhttp
import (
"log"
"net/http"
gopath "path"
"strconv"
"github.com/tomasen/realip"
@@ -23,10 +24,25 @@ type data struct {
store *storage.Storage
user *users.User
raw interface{}
// checkerPrefix is prepended to every path before evaluating rules. It is
// set when the user's filesystem has been rebased onto a subdirectory (as
// done for public shares), so that rules — which are relative to the user's
// original scope — are still matched against the real path instead of the
// rebased one. Empty for regular requests.
checkerPrefix string
}
// Check implements rules.Checker.
func (d *data) Check(path string) bool {
// When the filesystem has been rebased (e.g. a public share rooted at a
// subdirectory), the incoming path is relative to that root. Resolve it
// back to the user's original scope before matching rules, otherwise rules
// targeting paths below the share root would be silently bypassed.
if d.checkerPrefix != "" {
path = gopath.Join(d.checkerPrefix, path)
}
if d.user.HideDotfiles && rules.MatchHidden(path) {
return false
}
+7 -1
View File
@@ -1,6 +1,7 @@
package fbhttp
import (
"crypto/subtle"
"errors"
"net/http"
"net/url"
@@ -67,6 +68,11 @@ var withHashFile = func(fn handleFunc) handleFunc {
// set fs root to the shared file/folder
d.user.Fs = afero.NewBasePathFs(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
// original scope so deny rules below the share root keep applying.
d.checkerPrefix = basePath
file, err = files.NewFileInfo(&files.FileOptions{
Fs: d.user.Fs,
Path: filePath,
@@ -131,7 +137,7 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
return 0, nil
}
if r.URL.Query().Get("token") == l.Token {
if subtle.ConstantTimeCompare([]byte(r.URL.Query().Get("token")), []byte(l.Token)) == 1 {
return 0, nil
}
+166
View File
@@ -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/spf13/afero"
"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"
)
// 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: afero.NewBasePathFs(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)
}
}
}
+111
View File
@@ -10,6 +10,7 @@ import (
"github.com/asdine/storm/v3"
"github.com/spf13/afero"
"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"
@@ -143,6 +144,116 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
}
}
// TestPublicShareHandlerRules ensures that owner rules keep applying to paths
// below a shared directory, even though the share rebases the filesystem onto
// that directory. A deny rule relative to the owner's scope must not be
// bypassable by requesting the blocked path through the public share.
func TestPublicShareHandlerRules(t *testing.T) {
t.Parallel()
testCases := map[string]struct {
handler handleFunc
path string
expectedStatusCode int
}{
"blocked file via dl handler, 403": {
handler: publicDlHandler,
path: "h/private/secret.txt",
expectedStatusCode: 403,
},
"blocked dir listing via share handler, 403": {
handler: publicShareHandler,
path: "h/private/",
expectedStatusCode: 403,
},
"blocked dir download via dl handler, 403": {
handler: publicDlHandler,
path: "h/private/",
expectedStatusCode: 403,
},
"allowed file via dl handler, 200": {
handler: publicDlHandler,
path: "h/public/readme.txt",
expectedStatusCode: 200,
},
"allowed dir listing via share handler, 200": {
handler: publicShareHandler,
path: "h/public/",
expectedStatusCode: 200,
},
}
for name, tc := range testCases {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
t.Parallel()
dbPath := filepath.Join(t.TempDir(), "db")
db, err := storm.Open(dbPath)
if err != nil {
t.Fatalf("failed to open db: %v", err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil {
t.Errorf("failed to close db: %v", err)
}
})
storage, err := bolt.NewStorage(db)
if err != nil {
t.Fatalf("failed to get storage: %v", err)
}
if err := storage.Share.Save(&share.Link{Hash: "h", UserID: 1, Path: "/projects"}); err != nil {
t.Fatalf("failed to save share: %v", err)
}
if err := storage.Users.Save(&users.User{
Username: "username",
Password: "pw",
Perm: users.Permissions{Share: true, Download: true},
Rules: []rules.Rule{
{Allow: false, Path: "/projects/private"},
},
}); err != nil {
t.Fatalf("failed to save user: %v", err)
}
if err := storage.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
fs := afero.NewBasePathFs(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)
}
if err := afero.WriteFile(fs, "/projects/public/readme.txt", []byte("hello"), 0o600); err != nil {
t.Fatalf("failed to write public file: %v", err)
}
storage.Users = &customFSUser{
Store: storage.Users,
fs: fs,
}
req := newHTTPRequest(t, func(r *http.Request) { r.URL.Path = tc.path })
recorder := httptest.NewRecorder()
handler := handle(tc.handler, "", storage, &settings.Server{})
handler.ServeHTTP(recorder, req)
result := recorder.Result()
defer result.Body.Close()
if result.StatusCode != tc.expectedStatusCode {
t.Errorf("expected status code %d, got status code %d", tc.expectedStatusCode, result.StatusCode)
}
})
}
}
func newHTTPRequest(t *testing.T, requestModifiers ...func(*http.Request)) *http.Request {
t.Helper()
r, err := http.NewRequest(http.MethodGet, "h", http.NoBody)
+12
View File
@@ -77,6 +77,7 @@ func setContentDisposition(w http.ResponseWriter, r *http.Request, file *files.F
} else {
// As per RFC6266 section 4.3
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(file.Name))
w.Header().Set("Content-Type", "application/octet-stream")
}
}
@@ -114,6 +115,10 @@ func getFiles(d *data, path, commonPath string) ([]archives.FileInfo, error) {
return nil, nil
}
if ok, err := files.WithinScope(d.user.Fs, path); err != nil || !ok {
return nil, nil
}
info, err := d.user.Fs.Stat(path)
if err != nil {
return nil, err
@@ -125,6 +130,12 @@ func getFiles(d *data, path, commonPath string) ([]archives.FileInfo, error) {
nameInArchive := strings.TrimPrefix(path, commonPath)
nameInArchive = strings.TrimPrefix(nameInArchive, string(filepath.Separator))
nameInArchive = filepath.ToSlash(nameInArchive)
// filepath.ToSlash only rewrites the host separator, so on a Linux
// host a stored backslash survives and is emitted verbatim into the
// archive. Windows extractors then treat "\" as a path separator,
// allowing the entry to escape the extraction directory (zip-slip).
// Strip Windows separators regardless of host OS.
nameInArchive = strings.ReplaceAll(nameInArchive, "\\", "/")
archiveFiles = append(archiveFiles, archives.FileInfo{
FileInfo: info,
@@ -218,6 +229,7 @@ func rawFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo
setContentDisposition(w, r, file)
w.Header().Add("Content-Security-Policy", `script-src 'none';`)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private")
http.ServeContent(w, r, file.Name, file.ModTime, fd)
return 0, nil
+8
View File
@@ -70,6 +70,14 @@ func TestSetContentDisposition(t *testing.T) {
if got != tc.expected {
t.Errorf("Content-Disposition = %q, want %q", got, tc.expected)
}
contentType := recorder.Header().Get("Content-Type")
if tc.inline && contentType != "" {
t.Errorf("Content-Type = %q, want empty", contentType)
}
if !tc.inline && contentType != "application/octet-stream" {
t.Errorf("Content-Type = %q, want application/octet-stream", contentType)
}
})
}
}
+21 -1
View File
@@ -100,7 +100,7 @@ func resourceDeleteHandler(fileCache FileCache) handleFunc {
return errToStatus(err), err
}
err = d.store.Share.DeleteWithPathPrefix(file.Path)
err = d.store.Share.DeleteWithPathPrefix(file.Path, d.user.ID)
if err != nil {
log.Printf("WARNING: Error(s) occurred while deleting associated shares with file: %s", err)
}
@@ -228,6 +228,19 @@ 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
@@ -295,6 +308,13 @@ 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 {
+27 -1
View File
@@ -15,6 +15,7 @@ import (
"golang.org/x/crypto/bcrypt"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/share"
)
@@ -57,7 +58,15 @@ var shareListHandler = withPermShare(func(w http.ResponseWriter, r *http.Request
})
var shareGetsHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
s, err := d.store.Share.Gets(r.URL.Path, d.user.ID)
var (
s []*share.Link
err error
)
if d.user.Perm.Admin {
s, err = d.store.Share.GetsByPath(r.URL.Path)
} else {
s, err = d.store.Share.Gets(r.URL.Path, d.user.ID)
}
if errors.Is(err, fberrors.ErrNotExist) {
return renderJSON(w, r, []*share.Link{})
}
@@ -91,6 +100,23 @@ var shareDeleteHandler = withPermShare(func(_ http.ResponseWriter, r *http.Reque
})
var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
// 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.
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 {
+10
View File
@@ -44,6 +44,11 @@ func tusPostHandler(cache UploadCache) handleFunc {
if !d.user.Perm.Create || !d.Check(r.URL.Path) {
return http.StatusForbidden, nil
}
if ok, scopeErr := files.WithinScope(d.user.Fs, r.URL.Path); scopeErr != nil || !ok {
return http.StatusForbidden, nil
}
file, err := files.NewFileInfo(&files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
@@ -161,6 +166,11 @@ func tusPatchHandler(cache UploadCache) handleFunc {
if r.Header.Get("Content-Type") != "application/offset+octet-stream" {
return http.StatusUnsupportedMediaType, nil
}
// Defense in depth: refuse to write through a symlink that escapes the
// scope, in case the target path is (or sits behind) an escaping link.
if ok, scopeErr := files.WithinScope(d.user.Fs, r.URL.Path); scopeErr != nil || !ok {
return http.StatusForbidden, nil
}
uploadOffset, err := getUploadOffset(r)
if err != nil {
+118
View File
@@ -0,0 +1,118 @@
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/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: afero.NewBasePathFs(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")
}
})
}
}
+1
View File
@@ -5,6 +5,7 @@
"group:allNonMajor",
"group:allDigest",
":disableDependencyDashboard",
":disableMajorUpdates",
":semanticCommitTypeAll(chore)"
],
"postUpdateOptions": [
+20 -3
View File
@@ -15,7 +15,7 @@ type StorageBackend interface {
Gets(path string, id uint) ([]*Link, error)
Save(s *Link) error
Delete(hash string) error
DeleteWithPathPrefix(path string) error
DeleteWithPathPrefix(path string, userID uint) error
}
// Storage is a storage.
@@ -110,6 +110,23 @@ func (s *Storage) Gets(path string, id uint) ([]*Link, error) {
return links, nil
}
// GetsByPath returns all non-expired links for a path.
func (s *Storage) GetsByPath(path string) ([]*Link, error) {
links, err := s.All()
if err != nil {
return nil, err
}
filtered := make([]*Link, 0, len(links))
for _, link := range links {
if link.Path == path {
filtered = append(filtered, link)
}
}
return filtered, nil
}
// Save wraps a StorageBackend.Save
func (s *Storage) Save(l *Link) error {
return s.back.Save(l)
@@ -120,6 +137,6 @@ func (s *Storage) Delete(hash string) error {
return s.back.Delete(hash)
}
func (s *Storage) DeleteWithPathPrefix(path string) error {
return s.back.DeleteWithPathPrefix(path)
func (s *Storage) DeleteWithPathPrefix(path string, userID uint) error {
return s.back.DeleteWithPathPrefix(path, userID)
}
+85
View File
@@ -0,0 +1,85 @@
package share
import (
"reflect"
"testing"
)
type fakeBackend struct {
links []*Link
}
func (f fakeBackend) All() ([]*Link, error) {
return f.links, nil
}
func (f fakeBackend) FindByUserID(id uint) ([]*Link, error) {
var links []*Link
for _, link := range f.links {
if link.UserID == id {
links = append(links, link)
}
}
return links, nil
}
func (f fakeBackend) GetByHash(hash string) (*Link, error) {
for _, link := range f.links {
if link.Hash == hash {
return link, nil
}
}
return nil, nil
}
func (f fakeBackend) GetPermanent(path string, id uint) (*Link, error) {
for _, link := range f.links {
if link.Path == path && link.UserID == id && link.Expire == 0 {
return link, nil
}
}
return nil, nil
}
func (f fakeBackend) Gets(path string, id uint) ([]*Link, error) {
var links []*Link
for _, link := range f.links {
if link.Path == path && link.UserID == id {
links = append(links, link)
}
}
return links, nil
}
func (f fakeBackend) Save(_ *Link) error {
return nil
}
func (f fakeBackend) Delete(_ string) error {
return nil
}
func (f fakeBackend) DeleteWithPathPrefix(_ string, _ uint) error {
return nil
}
func TestGetsByPathReturnsLinksFromAllUsers(t *testing.T) {
t.Parallel()
expected := []*Link{
{Hash: "a", Path: "/file.txt", UserID: 1},
{Hash: "b", Path: "/file.txt", UserID: 2},
}
store := NewStorage(fakeBackend{
links: append(expected, &Link{Hash: "c", Path: "/other.txt", UserID: 3}),
})
links, err := store.GetsByPath("/file.txt")
if err != nil {
t.Fatalf("GetsByPath returned error: %v", err)
}
if !reflect.DeepEqual(links, expected) {
t.Fatalf("GetsByPath returned %#v, want %#v", links, expected)
}
}
+15 -1
View File
@@ -2,6 +2,7 @@ package bolt
import (
"errors"
"strings"
"github.com/asdine/storm/v3"
"github.com/asdine/storm/v3/q"
@@ -76,14 +77,27 @@ func (s shareBackend) Delete(hash string) error {
return err
}
func (s shareBackend) DeleteWithPathPrefix(pathPrefix string) error {
func (s shareBackend) DeleteWithPathPrefix(pathPrefix string, userID uint) error {
var links []share.Link
if err := s.db.Prefix("Path", pathPrefix, &links); err != nil {
if errors.Is(err, storm.ErrNotFound) {
return nil
}
return err
}
prefix := strings.TrimRight(pathPrefix, "/")
var err error
for _, link := range links {
if link.UserID != userID {
continue
}
if link.Path != prefix && !strings.HasPrefix(link.Path, prefix+"/") {
continue
}
err = errors.Join(err, s.db.DeleteStruct(&share.Link{Hash: link.Hash}))
}
return err
+97
View File
@@ -0,0 +1,97 @@
package bolt
import (
"os"
"sort"
"testing"
"github.com/asdine/storm/v3"
"github.com/filebrowser/filebrowser/v2/share"
)
func newTestShareBackend(t *testing.T) shareBackend {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "shares-*.db")
if err != nil {
t.Fatalf("failed to create temp db: %v", err)
}
_ = f.Close()
db, err := storm.Open(f.Name())
if err != nil {
t.Fatalf("failed to open db: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
return shareBackend{db: db}
}
func remainingHashes(t *testing.T, s shareBackend) []string {
t.Helper()
links, err := s.All()
if err != nil {
t.Fatalf("All returned error: %v", err)
}
hashes := make([]string, 0, len(links))
for _, link := range links {
hashes = append(hashes, link.Hash)
}
sort.Strings(hashes)
return hashes
}
func TestDeleteWithPathPrefix(t *testing.T) {
t.Parallel()
s := newTestShareBackend(t)
links := []*share.Link{
// user 1's links
{Hash: "u1-a", Path: "/a", UserID: 1},
{Hash: "u1-a-child", Path: "/a/child.txt", UserID: 1},
{Hash: "u1-abc", Path: "/abc", UserID: 1}, // not a descendant of /a
{Hash: "u1-other", Path: "/other", UserID: 1},
// user 2's links — must never be touched when user 1 deletes
{Hash: "u2-a", Path: "/a", UserID: 2},
{Hash: "u2-a-child", Path: "/a/child.txt", UserID: 2},
}
for _, l := range links {
if err := s.Save(l); err != nil {
t.Fatalf("failed to save link %s: %v", l.Hash, err)
}
}
// User 1 deletes their directory /a. Only user 1's /a and its descendants
// should be removed; /abc (sibling sharing a byte prefix) and all of user
// 2's links must remain.
if err := s.DeleteWithPathPrefix("/a", 1); err != nil {
t.Fatalf("DeleteWithPathPrefix returned error: %v", err)
}
got := remainingHashes(t, s)
want := []string{"u1-abc", "u1-other", "u2-a", "u2-a-child"}
if len(got) != len(want) {
t.Fatalf("remaining hashes = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("remaining hashes = %v, want %v", got, want)
}
}
}
func TestDeleteWithPathPrefixNoMatch(t *testing.T) {
t.Parallel()
s := newTestShareBackend(t)
// No links exist at all: the storm Prefix query returns ErrNotFound, which
// must be treated as a no-op rather than surfaced as an error.
if err := s.DeleteWithPathPrefix("/a", 1); err != nil {
t.Fatalf("DeleteWithPathPrefix on empty store returned error: %v", err)
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ filebrowser config init [flags]
--disableTypeDetectionByHeader disables type detection by reading file headers
--fileMode string mode bits that new files are created with (default "0o640")
-h, --help help for init
--hideDotfiles hide dotfiles
--hideDotfiles hide dotfiles in file listings
--hideLoginButton hide login button from public pages
-k, --key string tls key
--locale string locale for users (default "en")
+1 -1
View File
@@ -39,7 +39,7 @@ filebrowser config set [flags]
--disableTypeDetectionByHeader disables type detection by reading file headers
--fileMode string mode bits that new files are created with (default "0o640")
-h, --help help for set
--hideDotfiles hide dotfiles
--hideDotfiles hide dotfiles in file listings
--hideLoginButton hide login button from public pages
-k, --key string tls key
--locale string locale for users (default "en")
+1 -1
View File
@@ -17,7 +17,7 @@ filebrowser users add <username> <password> [flags]
--commands strings a list of the commands a user can execute
--dateFormat use date format (true for absolute time, false for relative)
-h, --help help for add
--hideDotfiles hide dotfiles
--hideDotfiles hide dotfiles in file listings
--locale string locale for users (default "en")
--lockPassword lock password
--perm.admin admin perm for users
+1 -1
View File
@@ -18,7 +18,7 @@ filebrowser users update <id|username> [flags]
--commands strings a list of the commands a user can execute
--dateFormat use date format (true for absolute time, false for relative)
-h, --help help for update
--hideDotfiles hide dotfiles
--hideDotfiles hide dotfiles in file listings
--locale string locale for users (default "en")
--lockPassword lock password
-p, --password string new password