Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
328f629181 | ||
|
|
4c3cb4bc9b | ||
|
|
3213b605be | ||
|
|
610e0b09e9 | ||
|
|
7453c78c98 | ||
|
|
cd5749dff8 | ||
|
|
4daddec6f2 | ||
|
|
9bd79c3aae | ||
|
|
6c69b5cd89 | ||
|
|
4b8a8d72ce | ||
|
|
8ddd3d1db9 | ||
|
|
9fffee387f | ||
|
|
5a12cad548 | ||
|
|
6232686e22 | ||
|
|
b21b1245ae | ||
|
|
7361d91ea2 | ||
|
|
c05c668148 | ||
|
|
b7dc392838 | ||
|
|
ac46cf0671 | ||
|
|
f0785391bf | ||
|
|
9b78324d77 |
No files matched your search
@@ -2,6 +2,20 @@
|
||||
|
||||
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.19](https://github.com/filebrowser/filebrowser/compare/v2.63.18...v2.63.19) (2026-07-25)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* accessibility and security improvements ([#6033](https://github.com/filebrowser/filebrowser/issues/6033)) ([b21b124](https://github.com/filebrowser/filebrowser/commit/b21b1245ae1b57f031b2f5d787f32a17532402c0))
|
||||
* **auth:** isolate auto-provisioned proxy and hook users to their own home ([8ddd3d1](https://github.com/filebrowser/filebrowser/commit/8ddd3d1db9b9f5727d0bf96ea0e7d9a25a8692b4))
|
||||
* **http:** delete abandoned TUS uploads through the scoped filesystem ([9bd79c3](https://github.com/filebrowser/filebrowser/commit/9bd79c3aaeb4a55b0e69cf8976c4a258db2f5e06))
|
||||
* **http:** enforce declared Upload-Length on TUS uploads ([4daddec](https://github.com/filebrowser/filebrowser/commit/4daddec6f200b03a721197d8c0b4b652c994894e))
|
||||
* **http:** enforce download permission on the checksum branch ([6c69b5c](https://github.com/filebrowser/filebrowser/commit/6c69b5cd895e15b29e563200a9a6dfc27b06525e))
|
||||
* **http:** run upload hooks for directories ([#6034](https://github.com/filebrowser/filebrowser/issues/6034)) ([9b78324](https://github.com/filebrowser/filebrowser/commit/9b78324d773c790951cc6a97840c4b55f66b5f3d))
|
||||
* process --FollowExternalSymlinks ([c05c668](https://github.com/filebrowser/filebrowser/commit/c05c66814891c3cccef394162e428444b53394e4))
|
||||
* return error instead of panicking on an unreadable directory during copy ([#6020](https://github.com/filebrowser/filebrowser/issues/6020)) ([ac46cf0](https://github.com/filebrowser/filebrowser/commit/ac46cf06719575477d5125e7472037c204b3702d))
|
||||
* **storage:** reject case-folded home directory collisions ([4b8a8d7](https://github.com/filebrowser/filebrowser/commit/4b8a8d72ce554dde378b5091da74aa930ea18327))
|
||||
* **upload:** handle encoded path conflicts safely ([#6040](https://github.com/filebrowser/filebrowser/issues/6040)) ([7361d91](https://github.com/filebrowser/filebrowser/commit/7361d91ea2e8cc200a0f40ac84adcd02aedc9ed2))
|
||||
## [2.63.18](https://github.com/filebrowser/filebrowser/compare/v2.63.17...v2.63.18) (2026-07-04)
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
</p>
|
||||
|
||||
[](https://github.com/filebrowser/filebrowser/actions/workflows/ci.yaml)
|
||||
[](https://goreportcard.com/report/github.com/filebrowser/filebrowser/v2)
|
||||
[](https://github.com/filebrowser/filebrowser/releases/latest)
|
||||
|
||||
File Browser provides a file managing interface within a specified directory and it can be used to upload, delete, preview and edit your files. It is a **create-your-own-cloud**-kind of software where you can just install it on your server, direct it to a path and access your files through a nice web interface.
|
||||
@@ -19,7 +18,7 @@ This project is a finished product which fulfills its goal: be a single binary w
|
||||
- It can take a while until someone gets back to you. Please be patient.
|
||||
- [Issues](https://github.com/filebrowser/filebrowser/issues) are meant to track bugs. Unrelated issues will be converted into [discussions](https://github.com/filebrowser/filebrowser/discussions).
|
||||
- The priority is triaging issues, addressing security issues and reviewing pull requests meant to solve bugs.
|
||||
- No new features are planned. Pull requests for new features are not guaranteed to be reviewed.
|
||||
- No new features are planned. Pull requests for new features will not be reviewed.
|
||||
|
||||
Please read [@hacdias' personal reflection](https://hacdias.com/2026/03/11/filebrowser/) on the project status.
|
||||
|
||||
|
||||
+7
-7
@@ -157,15 +157,15 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
|
||||
}
|
||||
u = a.GetUser(d)
|
||||
|
||||
userHome, err := a.Settings.MakeUserDir(u.Username, u.Scope, a.Server.Root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user: failed to mkdir user home dir: [%s]", userHome)
|
||||
// A scope explicitly returned by the hook takes precedence over the
|
||||
// automatic per-user home directory derivation.
|
||||
_, explicitScope := a.Fields.Values["user.scope"]
|
||||
if err := a.Settings.CreateUserHome(u, a.Users, a.Server.Root, explicitScope); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.Scope = userHome
|
||||
log.Printf("user: %s, home dir: [%s].", u.Username, userHome)
|
||||
log.Printf("user: %s, home dir: [%s].", u.Username, u.Scope)
|
||||
|
||||
err = a.Users.Save(u)
|
||||
if err != nil {
|
||||
if err := a.Users.Save(u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if p := !users.CheckPwd(a.Cred.Password, u.Password); len(a.Fields.Values) > 1 || p {
|
||||
|
||||
@@ -5,6 +5,9 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// writeHookScript writes a POSIX shell script to a temp file and returns its
|
||||
@@ -86,3 +89,68 @@ fi
|
||||
t.Fatalf("expected action %q, got %q", "auth", action)
|
||||
}
|
||||
}
|
||||
|
||||
// newHookAuth builds a HookAuth for a freshly provisioned user with the given
|
||||
// parsed hook fields (hook.action=auth is added automatically).
|
||||
func newHookAuth(store *mockUserStore, s *settings.Settings, srv *settings.Server, username string, fields map[string]string) *HookAuth {
|
||||
fields["hook.action"] = "auth"
|
||||
return &HookAuth{
|
||||
Users: store,
|
||||
Settings: s,
|
||||
Server: srv,
|
||||
Cred: hookCred{Username: username, Password: "a-strong-password"},
|
||||
Fields: hookFields{Values: fields},
|
||||
}
|
||||
}
|
||||
|
||||
// With CreateUserDir enabled and no explicit scope from the hook, a provisioned
|
||||
// hook user must receive its own home directory rather than the server root.
|
||||
func TestHookSaveUserCreateUserDirIsolatesScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
u, err := newHookAuth(store, s, srv, "alice", map[string]string{}).SaveUser()
|
||||
if err != nil {
|
||||
t.Fatalf("SaveUser error: %v", err)
|
||||
}
|
||||
if u.Scope != "/users/alice" {
|
||||
t.Errorf("hook user without explicit scope: expected /users/alice, got %q", u.Scope)
|
||||
}
|
||||
}
|
||||
|
||||
// A scope explicitly returned by the hook takes precedence over the automatic
|
||||
// per-user home directory derivation.
|
||||
func TestHookSaveUserRespectsExplicitScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
u, err := newHookAuth(store, s, srv, "teamlead", map[string]string{"user.scope": "/shared/team"}).SaveUser()
|
||||
if err != nil {
|
||||
t.Fatalf("SaveUser error: %v", err)
|
||||
}
|
||||
if u.Scope != "/shared/team" {
|
||||
t.Errorf("explicit hook scope should win, got %q", u.Scope)
|
||||
}
|
||||
}
|
||||
+2
-6
@@ -50,15 +50,11 @@ func (a ProxyAuth) createUser(usr users.Store, setting *settings.Settings, srv *
|
||||
user.Perm.Execute = false
|
||||
user.Commands = []string{}
|
||||
|
||||
var userHome string
|
||||
userHome, err = setting.MakeUserDir(user.Username, user.Scope, srv.Root)
|
||||
if err != nil {
|
||||
if err = setting.CreateUserHome(user, usr, srv.Root, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.Scope = userHome
|
||||
|
||||
err = usr.Save(user)
|
||||
if err != nil {
|
||||
if err = usr.Save(user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -78,3 +78,46 @@ func TestProxyAuthCreateUserRestrictsDefaults(t *testing.T) {
|
||||
t.Error("auto-provisioned proxy user should retain Create permission from defaults")
|
||||
}
|
||||
}
|
||||
|
||||
// With CreateUserDir enabled, two distinct proxy-authenticated users must each
|
||||
// receive their own home directory instead of both inheriting the server root.
|
||||
func TestProxyAuthCreateUserDirIsolatesScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := &mockUserStore{users: make(map[string]*users.User)}
|
||||
srv := &settings.Server{Root: t.TempDir()}
|
||||
s := &settings.Settings{
|
||||
Key: []byte("key"),
|
||||
AuthMethod: MethodProxyAuth,
|
||||
CreateUserDir: true,
|
||||
UserHomeBasePath: "/users",
|
||||
Defaults: settings.UserDefaults{
|
||||
Scope: ".",
|
||||
Perm: users.Permissions{Create: true},
|
||||
},
|
||||
}
|
||||
|
||||
auth := ProxyAuth{Header: "X-Remote-User"}
|
||||
provision := func(name string) *users.User {
|
||||
req, _ := http.NewRequest(http.MethodGet, "/", http.NoBody)
|
||||
req.Header.Set("X-Remote-User", name)
|
||||
u, err := auth.Auth(req, store, s, srv)
|
||||
if err != nil {
|
||||
t.Fatalf("Auth(%q) error: %v", name, err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
alice := provision("alice")
|
||||
bob := provision("bob")
|
||||
|
||||
if alice.Scope == "/" || bob.Scope == "/" {
|
||||
t.Fatalf("provisioned users inherited the server root: alice=%q bob=%q", alice.Scope, bob.Scope)
|
||||
}
|
||||
if alice.Scope == bob.Scope {
|
||||
t.Fatalf("distinct users must get distinct scopes, both got %q", alice.Scope)
|
||||
}
|
||||
if alice.Scope != "/users/alice" {
|
||||
t.Errorf("expected /users/alice, got %q", alice.Scope)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ import (
|
||||
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/auth"
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
)
|
||||
|
||||
// TestEnvCollisions ensures that there are no collisions in the produced environment
|
||||
@@ -33,3 +37,25 @@ func testEnvCollisions(t *testing.T, cmd *cobra.Command) {
|
||||
t.Errorf("Found duplicate environment variable keys for command %q: %v", cmd.Name(), duplicates)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetSettingsFollowExternalSymlinks ensures that the followExternalSymlinks
|
||||
// flag is persisted to the server config when set via "config set".
|
||||
func TestGetSettingsFollowExternalSymlinks(t *testing.T) {
|
||||
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
||||
addConfigFlags(flags)
|
||||
|
||||
if err := flags.Parse([]string{"--followExternalSymlinks"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
set := &settings.Settings{AuthMethod: auth.MethodJSONAuth}
|
||||
ser := &settings.Server{}
|
||||
|
||||
if _, err := getSettings(flags, set, ser, &auth.JSONAuth{}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !ser.FollowExternalSymlinks {
|
||||
t.Error("expected FollowExternalSymlinks to be persisted as true")
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,8 @@ func getSettings(flags *pflag.FlagSet, set *settings.Settings, ser *settings.Ser
|
||||
case "disableImageResolutionCalc":
|
||||
ser.ImageResolutionCal, err = flags.GetBool(flag.Name)
|
||||
ser.ImageResolutionCal = !ser.ImageResolutionCal
|
||||
case "followExternalSymlinks":
|
||||
ser.FollowExternalSymlinks, err = flags.GetBool(flag.Name)
|
||||
|
||||
// Settings flags from [addConfigFlags]
|
||||
case "signup":
|
||||
|
||||
@@ -2,6 +2,7 @@ package fileutils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
@@ -9,6 +10,54 @@ import (
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// failingOpenFs wraps an afero.Fs and makes Open fail for one specific path,
|
||||
// while every other operation (including Stat) is delegated unchanged. It
|
||||
// simulates a directory that can be stat-ed but not opened/read — for example
|
||||
// an unreadable sub-directory, or one whose permissions changed or that was
|
||||
// removed after its parent was listed (a TOCTOU race) — encountered during a
|
||||
// recursive copy.
|
||||
type failingOpenFs struct {
|
||||
afero.Fs
|
||||
failOpen string
|
||||
}
|
||||
|
||||
func (f *failingOpenFs) Open(name string) (afero.File, error) {
|
||||
if path.Clean(name) == path.Clean(f.failOpen) {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
return f.Fs.Open(name)
|
||||
}
|
||||
|
||||
// CopyDir is documented to keep going when it hits an error and to report the
|
||||
// error afterwards. A sub-directory that cannot be opened must therefore yield
|
||||
// an error (and leave the other, readable entries copied) rather than
|
||||
// panicking on a nil directory handle.
|
||||
func TestCopyDirUnreadableSubdirReturnsError(t *testing.T) {
|
||||
mem := afero.NewMemMapFs()
|
||||
if err := mem.MkdirAll("/srcdir/sub", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := afero.WriteFile(mem, "/srcdir/ok.txt", []byte("readable"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
afs := &failingOpenFs{Fs: mem, failOpen: "/srcdir/sub"}
|
||||
|
||||
err := Copy(afs, "/srcdir", "/dstdir", 0o644, 0o755)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error when a sub-directory cannot be opened")
|
||||
}
|
||||
|
||||
// The readable sibling must still have been copied (continue-on-error).
|
||||
data, readErr := afero.ReadFile(afs, "/dstdir/ok.txt")
|
||||
if readErr != nil {
|
||||
t.Fatalf("readable sibling was not copied: %v", readErr)
|
||||
}
|
||||
if string(data) != "readable" {
|
||||
t.Fatalf("unexpected copied content: %q", string(data))
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
+6
-1
@@ -23,7 +23,12 @@ func CopyDir(afs afero.Fs, source, dest string, fileMode, dirMode fs.FileMode) e
|
||||
return err
|
||||
}
|
||||
|
||||
dir, _ := afs.Open(source)
|
||||
dir, err := afs.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dir.Close()
|
||||
|
||||
obs, err := dir.Readdir(-1)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, user-scalable=no"
|
||||
content="width=device-width, initial-scale=1"
|
||||
/>
|
||||
|
||||
[{[ if .ReCaptcha -]}]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="sr-only">{{ name }}</h1>
|
||||
<router-view></router-view>
|
||||
</div>
|
||||
</template>
|
||||
@@ -9,6 +10,7 @@ import { ref, onMounted, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { setHtmlLocale } from "./i18n";
|
||||
import { getMediaPreference, getTheme, setTheme } from "./utils/theme";
|
||||
import { name } from "./utils/constants";
|
||||
|
||||
const { locale } = useI18n();
|
||||
|
||||
@@ -31,3 +33,17 @@ watch(locale, (newValue) => {
|
||||
newValue && setHtmlLocale(newValue);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -57,6 +57,9 @@ const container = ref<HTMLDivElement | null>(null);
|
||||
onMounted(() => {
|
||||
if (!decodeUTIF() && imgex.value !== null) {
|
||||
imgex.value.src = props.src;
|
||||
imgex.value.alt = decodeURIComponent(
|
||||
props.src.split("/").pop() || "preview"
|
||||
);
|
||||
}
|
||||
|
||||
props.classList.forEach((className) =>
|
||||
@@ -88,6 +91,9 @@ watch(
|
||||
() => {
|
||||
if (!decodeUTIF() && imgex.value !== null) {
|
||||
imgex.value.src = props.src;
|
||||
imgex.value.alt = decodeURIComponent(
|
||||
props.src.split("/").pop() || "preview"
|
||||
);
|
||||
}
|
||||
|
||||
scale.value = 1;
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
:data-dir="isDir"
|
||||
:data-type="type"
|
||||
:aria-label="name"
|
||||
:aria-selected="isSelected"
|
||||
:aria-pressed="isSelected"
|
||||
:data-ext="getExtension(name).toLowerCase()"
|
||||
@contextmenu="contextMenu"
|
||||
>
|
||||
@@ -26,6 +26,7 @@
|
||||
<img
|
||||
v-if="!readOnly && type === 'image' && isThumbsEnabled"
|
||||
v-lazy="thumbnailUrl"
|
||||
:alt="name"
|
||||
/>
|
||||
<i v-else class="material-icons"></i>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<header>
|
||||
<img v-if="showLogo" :src="logoURL" />
|
||||
<img v-if="showLogo" :src="logoURL" alt="File Browser" />
|
||||
<Action
|
||||
v-if="showMenu"
|
||||
class="menu-button"
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-label="item.name"
|
||||
:aria-selected="selected == item.url"
|
||||
:aria-pressed="selected == item.url"
|
||||
:key="item.name"
|
||||
v-for="item in items"
|
||||
:data-url="item.url"
|
||||
|
||||
@@ -29,8 +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.",
|
||||
"resumeTransfer": "Vorherige Übertragung fortsetzen",
|
||||
"resumeTransferTooltip": "Alle Dateien mit Konflikten überspringen, außer denen, die auf dem Server kleiner sind, da wir davon ausgehen, dass deren Übertragung unterbrochen wurde.",
|
||||
"save": "Speichern",
|
||||
"schedule": "Planen",
|
||||
"search": "Suchen",
|
||||
@@ -283,7 +283,7 @@
|
||||
"currentPassword": "Dein aktuelles Passwort"
|
||||
},
|
||||
"sidebar": {
|
||||
"diskUsed": "{used} of {total} used",
|
||||
"diskUsed": "{used} von {total} belegt",
|
||||
"help": "Hilfe",
|
||||
"hugoNew": "Hugo Neu",
|
||||
"login": "Anmelden",
|
||||
|
||||
+25
-25
@@ -120,12 +120,12 @@
|
||||
"passwordsDontMatch": "Les mots de passe ne concordent pas",
|
||||
"signup": "S'inscrire",
|
||||
"submit": "Se connecter",
|
||||
"username": "Utilisateur",
|
||||
"usernameTaken": "Le nom d'utilisateur est déjà pris",
|
||||
"username": "Identifiant",
|
||||
"usernameTaken": "L'identifiant est déjà pris",
|
||||
"wrongCredentials": "Identifiants incorrects !",
|
||||
"passwordTooShort": "Le mot de passe doit contenir au moins {min} caractères",
|
||||
"logout_reasons": {
|
||||
"inactivity": "Vous avez été déconnecté(e) en raison d'une inactivité prolongée."
|
||||
"inactivity": "Vous avez été déconnecté'e en raison d'une inactivité prolongée."
|
||||
}
|
||||
},
|
||||
"permanent": "Permanent",
|
||||
@@ -194,12 +194,12 @@
|
||||
"settings": {
|
||||
"aceEditorTheme": "Éditeur de Thème Ace",
|
||||
"admin": "Admin",
|
||||
"administrator": "Administrateur",
|
||||
"administrator": "Administrateur'ice",
|
||||
"allowCommands": "Exécuter des commandes",
|
||||
"allowEdit": "Éditer, renommer et supprimer des fichiers ou des dossiers",
|
||||
"allowNew": "Créer de nouveaux fichiers et dossiers",
|
||||
"allowPublish": "Publier de nouveaux posts et pages",
|
||||
"allowSignup": "Autoriser les utilisateurs à s'inscrire",
|
||||
"allowSignup": "Autoriser les utilisateur'ices à s'inscrire",
|
||||
"hideLoginButton": "Cacher le bouton d’identification sur les pages publiques",
|
||||
"avoidChanges": "(Laisser vide pour conserver l'actuel)",
|
||||
"branding": "Image de marque",
|
||||
@@ -209,34 +209,34 @@
|
||||
"commandRunner": "Exécuteur de commandes",
|
||||
"commandRunnerHelp": "Ici, vous pouvez définir les commandes qui seront exécutées lors des événements nommés précédemments. Vous devez en écrire une par ligne. Les variables d'environnement {0} et {1} seront disponibles, {0} étant relatif à {1}. Pour plus d'informations sur cette fonctionnalité et les variables d'environnement disponibles, veuillez lire la {2}.",
|
||||
"commandsUpdated": "Commandes mises à jour !",
|
||||
"createUserDir": "Créer automatiquement un dossier pour l'utilisateur",
|
||||
"createUserDir": "Créer automatiquement un dossier pour l'utilisateur'ice",
|
||||
"minimumPasswordLength": "Taille minimale du mot de passe",
|
||||
"tusUploads": "Uploads segmentés",
|
||||
"tusUploadsHelp": "File Browser prend en charge les uploads segmentés afin de permettre une gestion efficace, fiable et reprenable sur des réseaux instables.",
|
||||
"tusUploadsChunkSize": "Taille maximale autorisée par segment (les uploads directs seront utilisés pour les fichiers plus petits). Vous pouvez entrer un entier en octets ou une chaîne telle que 10MB, 1GB, etc.",
|
||||
"tusUploadsRetryCount": "Nombre de tentatives en cas d'échec d'un segment.",
|
||||
"userHomeBasePath": "Chemin de base pour les dossiers personnels des utilisateurs",
|
||||
"userHomeBasePath": "Chemin de base pour les dossiers personnels des utilisateur'ices",
|
||||
"userScopeGenerationPlaceholder": "Le périmètre sera généré automatiquement",
|
||||
"createUserHomeDirectory": "Créer le dossier personnel de l'utilisateur",
|
||||
"createUserHomeDirectory": "Créer le dossier personnel de l'utilisateur'ice",
|
||||
"customStylesheet": "Feuille de style personnalisée",
|
||||
"defaultUserDescription": "Paramètres par défaut pour les nouveaux utilisateurs.",
|
||||
"defaultUserDescription": "Paramètres par défaut pour les nouveaux utilisateur'ices.",
|
||||
"disableExternalLinks": "Désactiver les liens externes (sauf la documentation)",
|
||||
"disableUsedDiskPercentage": "Désactiver le graphique de pourcentage d'utilisation du disque",
|
||||
"documentation": "documentation",
|
||||
"examples": "Exemples",
|
||||
"executeOnShell": "Exécuter dans le shell",
|
||||
"executeOnShellDescription": "Par défaut, File Browser exécute les commandes en appelant directement leurs binaires. Si vous voulez les exécuter sur un shell à la place (comme Bash ou PowerShell), vous pouvez le définir ici avec les arguments et les drapeaux requis. S'il est défini, la commande que vous exécutez sera ajoutée en tant qu'argument. Cela s'applique à la fois aux commandes utilisateur et aux crochets d'événements.",
|
||||
"globalRules": "Il s'agit d'un ensemble global de règles d'autorisation et d'interdiction. Elles s'appliquent à tous les utilisateurs. Vous pouvez définir des règles spécifiques sur les paramètres de chaque utilisateur pour remplacer celles-ci.",
|
||||
"executeOnShellDescription": "Par défaut, File Browser exécute les commandes en appelant directement leurs binaires. Si vous voulez les exécuter sur un shell à la place (comme Bash ou PowerShell), vous pouvez le définir ici avec les arguments et les drapeaux requis. S'il est défini, la commande que vous exécutez sera ajoutée en tant qu'argument. Cela s'applique à la fois aux commandes utilisateur'ice et aux crochets d'événements.",
|
||||
"globalRules": "Il s'agit d'un ensemble global de règles d'autorisation et d'interdiction. Elles s'appliquent à tous les utilisateur'ices. Vous pouvez définir des règles spécifiques sur les paramètres de chaque utilisateur'ice pour remplacer celles-ci.",
|
||||
"globalSettings": "Paramètres globaux",
|
||||
"hideDotfiles": "Cacher les fichiers de configuration commançant par un point",
|
||||
"insertPath": "Insérer le chemin",
|
||||
"insertRegex": "Insérer une expression régulière",
|
||||
"instanceName": "Nom de l'instance",
|
||||
"language": "Langue",
|
||||
"lockPassword": "Empêcher l'utilisateur de changer son mot de passe",
|
||||
"lockPassword": "Empêcher l'utilisateur'ice de changer son mot de passe",
|
||||
"newPassword": "Votre nouveau mot de passe",
|
||||
"newPasswordConfirm": "Confirmation du nouveau mot de passe",
|
||||
"newUser": "Nouvel utilisateur",
|
||||
"newUser": "Nouvel'le utilisateur'ice",
|
||||
"password": "Mot de passe",
|
||||
"passwordUpdated": "Mot de passe mis à jour !",
|
||||
"path": "Chemin",
|
||||
@@ -250,14 +250,14 @@
|
||||
"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",
|
||||
"permissionsHelp": "Vous pouvez définir l'utilisateur'ice comme étant un'e administrateur'ice ou encore choisir les permissions individuellement. Si vous sélectionnez \"Administrateur'ice\", toutes les autres options seront automatiquement activées. La gestion des utilisateur'ices est un privilège que seul l'administrateur'ice possède.\n",
|
||||
"profileSettings": "Paramètres du profil",
|
||||
"redirectAfterCopyMove": "Rediriger vers la destination après une copie/déplacement",
|
||||
"ruleExample1": "Bloque l'accès à tous les fichiers commençant par un point (comme par exemple .git, .gitignore) dans tous les dossiers.\n",
|
||||
"ruleExample2": "Bloque l'accès au fichier nommé \"Caddyfile\" à la racine du dossier utilisateur",
|
||||
"ruleExample2": "Bloque l'accès au fichier nommé \"Caddyfile\" à la racine du dossier utilisateur'ice",
|
||||
"rules": "Règles",
|
||||
"rulesHelp": "Vous pouvez définir ici un ensemble de règles pour cet utilisateur. Les fichiers bloqués ne seront pas affichés et ne seront pas accessibles par l'utilisateur. Les expressions régulières sont supportées et les chemins d'accès sont relatifs par rapport au dossier de l'utilisateur.\n",
|
||||
"scope": "Portée du dossier utilisateur",
|
||||
"rulesHelp": "Vous pouvez définir ici un ensemble de règles pour cet'te utilisateur'ice. Les fichiers bloqués ne seront pas affichés et ne seront pas accessibles par l'utilisateur'ice. Les expressions régulières sont supportées et les chemins d'accès sont relatifs par rapport au dossier de l'utilisateur'ice.\n",
|
||||
"scope": "Portée du dossier utilisateur'ice",
|
||||
"setDateFormat": "Définir le format de la date",
|
||||
"settingsUpdated": "Les paramètres ont été mis à jour !",
|
||||
"shareDuration": "Durée du partage",
|
||||
@@ -270,16 +270,16 @@
|
||||
"light": "Clair",
|
||||
"title": "Thème"
|
||||
},
|
||||
"user": "Utilisateur",
|
||||
"user": "Utilisateur'ice",
|
||||
"userCommands": "Commandes",
|
||||
"userCommandsHelp": "Une liste séparée par des espaces des commandes permises pour l'utilisateur. Exemple :\n",
|
||||
"userCreated": "Utilisateur créé !",
|
||||
"userDefaults": "Paramètres par défaut de l'utilisateur",
|
||||
"userDeleted": "Utilisateur supprimé !",
|
||||
"userManagement": "Gestion des utilisateurs",
|
||||
"userUpdated": "Utilisateur mis à jour !",
|
||||
"username": "Nom d'utilisateur",
|
||||
"users": "Utilisateurs",
|
||||
"userCreated": "Utilisateur'ice créé !",
|
||||
"userDefaults": "Paramètres par défaut de l'utilisateur'ice",
|
||||
"userDeleted": "Utilisateur'ice supprimé !",
|
||||
"userManagement": "Gestion des utilisateur'ices",
|
||||
"userUpdated": "Utilisateur'ice mis à jour !",
|
||||
"username": "Nom d'utilisateur'ice",
|
||||
"users": "Utilisateur'ices",
|
||||
"currentPassword": "Mot de Passe Actuel"
|
||||
},
|
||||
"sidebar": {
|
||||
|
||||
@@ -180,7 +180,7 @@ const router = createRouter({
|
||||
routes,
|
||||
});
|
||||
|
||||
router.beforeResolve(async (to, from, next) => {
|
||||
router.beforeResolve(async (to, from) => {
|
||||
const title = i18n.global.t(titles[to.name as keyof typeof titles]);
|
||||
document.title = title + " - " + name;
|
||||
|
||||
@@ -196,29 +196,25 @@ router.beforeResolve(async (to, from, next) => {
|
||||
}
|
||||
|
||||
if (to.path.endsWith("/login") && authStore.isLoggedIn) {
|
||||
next({ path: "/files/" });
|
||||
return;
|
||||
return { path: "/files/" };
|
||||
}
|
||||
|
||||
if (to.matched.some((record) => record.meta.requiresAuth)) {
|
||||
if (!authStore.isLoggedIn) {
|
||||
next({
|
||||
return {
|
||||
path: "/login",
|
||||
query: { redirect: to.fullPath },
|
||||
});
|
||||
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
if (to.matched.some((record) => record.meta.requiresAdmin)) {
|
||||
if (authStore.user === null || !authStore.user.perm.admin) {
|
||||
next({ path: "/403" });
|
||||
return;
|
||||
return { path: "/403" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
return;
|
||||
});
|
||||
|
||||
export { router, router as default };
|
||||
@@ -286,4 +286,102 @@ describe("checkConflict", () => {
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["forward slashes", "/target/My SubDir/file.txt"],
|
||||
["Windows backslashes", "\\target\\My SubDir\\file.txt"],
|
||||
])(
|
||||
"detects conflicts below an encoded destination path with %s",
|
||||
async (_label, serverPath) => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: serverPath,
|
||||
name: "file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("file.txt", "/files/target/My%20SubDir/")],
|
||||
"/files/target/My%20SubDir/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/My SubDir/file.txt");
|
||||
}
|
||||
);
|
||||
|
||||
it("detects nested folder-upload conflicts below an encoded destination path", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "\\target\\My SubDir\\folder\\nested file.txt",
|
||||
name: "nested file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[
|
||||
{
|
||||
name: "nested file.txt",
|
||||
size: 12,
|
||||
isDir: false,
|
||||
fullPath: "folder/nested file.txt",
|
||||
},
|
||||
],
|
||||
"/files/target/My%20SubDir/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
expect(conflicts[0].name).toBe("/target/My SubDir/folder/nested file.txt");
|
||||
});
|
||||
|
||||
it("leaves malformed destination path segments unchanged", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/bad%ZZ/file.txt",
|
||||
name: "file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("file.txt", "/files/target/bad%ZZ/")],
|
||||
"/files/target/bad%ZZ/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not match files outside the decoded destination path", async () => {
|
||||
vi.mocked(api.fetchAll).mockResolvedValue([
|
||||
{
|
||||
path: "/target/My SubDir/other.txt",
|
||||
name: "other.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
{
|
||||
path: "/target/My Other SubDir/file.txt",
|
||||
name: "file.txt",
|
||||
size: 10,
|
||||
modified: "2026-06-04T00:00:00Z",
|
||||
isDir: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const conflicts = await checkConflict(
|
||||
[moveItem("file.txt", "/files/target/My%20SubDir/")],
|
||||
"/files/target/My%20SubDir/"
|
||||
);
|
||||
|
||||
expect(conflicts).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -44,13 +44,26 @@ function conflictPath(entry: ServerConflictEntry): string {
|
||||
return entry.path.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
function decodePath(path: string): string {
|
||||
return path
|
||||
.split("/")
|
||||
.map((segment) => {
|
||||
try {
|
||||
return decodeURIComponent(segment);
|
||||
} catch {
|
||||
return segment;
|
||||
}
|
||||
})
|
||||
.join("/");
|
||||
}
|
||||
|
||||
function buildConflictMap(
|
||||
serverEntries: ServerConflictEntry[],
|
||||
basePath: string,
|
||||
includeDirectories: boolean
|
||||
): Map<string, ServerConflictEntry> {
|
||||
const serverMap = new Map<string, ServerConflictEntry>();
|
||||
const normBase = removePrefix(basePath).replace(/\/+$/, "");
|
||||
const normBase = decodePath(removePrefix(basePath)).replace(/\/+$/, "");
|
||||
for (const entry of serverEntries) {
|
||||
// A Windows server may return OS-native backslash separators; normalize to
|
||||
// forward slashes so the prefix strip and key lookup line up.
|
||||
|
||||
@@ -162,7 +162,11 @@
|
||||
"
|
||||
style="height: 12em; padding: 0; margin: 0"
|
||||
>
|
||||
<img style="height: 12em" :src="raw" />
|
||||
<img
|
||||
style="height: 12em"
|
||||
:src="raw"
|
||||
:alt="req.items[fileStore.selected[0]].name"
|
||||
/>
|
||||
</a>
|
||||
<div
|
||||
v-else-if="
|
||||
|
||||
@@ -846,7 +846,7 @@ const drop = async (event: DragEvent) => {
|
||||
}
|
||||
}
|
||||
if (files.length > 0) {
|
||||
upload.handleFiles(files, path, true);
|
||||
upload.handleFiles(files, path);
|
||||
fileStore.preselect = preselect;
|
||||
}
|
||||
},
|
||||
@@ -902,7 +902,7 @@ const uploadInput = async (event: Event) => {
|
||||
}
|
||||
}
|
||||
if (uploadFiles.length > 0) {
|
||||
upload.handleFiles(uploadFiles, path, true);
|
||||
upload.handleFiles(uploadFiles, path);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import FileListing from "@/views/files/FileListing.vue";
|
||||
import UploadPrompt from "@/components/prompts/Upload.vue";
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
checkConflict: vi.fn(),
|
||||
scanFiles: vi.fn(),
|
||||
handleFiles: vi.fn(),
|
||||
queueUpload: vi.fn(),
|
||||
showHover: vi.fn(),
|
||||
closeHovers: vi.fn(),
|
||||
fileStore: {
|
||||
req: { items: [] },
|
||||
selected: [] as number[],
|
||||
selectedCount: 0,
|
||||
multiple: false,
|
||||
preselect: "",
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/auth", () => ({
|
||||
useAuthStore: () => ({ user: null }),
|
||||
}));
|
||||
vi.mock("@/stores/clipboard", () => ({
|
||||
useClipboardStore: () => ({ items: [], $patch: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@/stores/file", () => ({
|
||||
useFileStore: () => harness.fileStore,
|
||||
}));
|
||||
vi.mock("@/stores/layout", () => ({
|
||||
useLayoutStore: () => ({
|
||||
currentPrompt: null,
|
||||
showHover: harness.showHover,
|
||||
closeHovers: harness.closeHovers,
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/stores/upload", () => ({
|
||||
useUploadStore: () => ({ upload: harness.queueUpload }),
|
||||
}));
|
||||
vi.mock("@/api", () => ({
|
||||
users: {},
|
||||
files: {},
|
||||
}));
|
||||
vi.mock("@/utils/constants", () => ({ enableExec: false }));
|
||||
vi.mock("@/utils/auth", () => ({}));
|
||||
vi.mock("@/router", () => ({ default: {} }));
|
||||
vi.mock("@/i18n", () => ({ default: {} }));
|
||||
vi.mock("@/utils/upload", () => ({
|
||||
checkConflict: harness.checkConflict,
|
||||
scanFiles: harness.scanFiles,
|
||||
handleFiles: harness.handleFiles,
|
||||
}));
|
||||
vi.mock("@/utils/css", () => ({ default: vi.fn() }));
|
||||
vi.mock("@/components/header/HeaderBar.vue", () => ({ default: {} }));
|
||||
vi.mock("@/components/header/Action.vue", () => ({ default: {} }));
|
||||
vi.mock("@/components/Search.vue", () => ({ default: {} }));
|
||||
vi.mock("@/components/files/ListingItem.vue", () => ({ default: {} }));
|
||||
vi.mock("@/components/ContextMenu.vue", () => ({ default: {} }));
|
||||
vi.mock("vue-router", () => ({
|
||||
useRoute: () => ({ path: "/files/target/" }),
|
||||
onBeforeRouteUpdate: vi.fn(),
|
||||
}));
|
||||
vi.mock("vue-i18n", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("vue-i18n")>()),
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("pinia", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("pinia")>()),
|
||||
storeToRefs: () => ({ req: { value: harness.fileStore.req } }),
|
||||
}));
|
||||
vi.mock("vue", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("vue")>()),
|
||||
inject: () => vi.fn(),
|
||||
watch: vi.fn(),
|
||||
onMounted: vi.fn(),
|
||||
onBeforeUnmount: vi.fn(),
|
||||
useSSRContext: () => ({ modules: new Set<string>() }),
|
||||
}));
|
||||
|
||||
const file = (name: string): UploadEntry => ({
|
||||
file: { name, size: 12, type: "text/plain" } as File,
|
||||
name,
|
||||
size: 12,
|
||||
isDir: false,
|
||||
});
|
||||
|
||||
const conflict = (
|
||||
index: number,
|
||||
checked: Array<"origin" | "dest">
|
||||
): ConflictingResource => ({
|
||||
index,
|
||||
name: `/target/file-${index}.txt`,
|
||||
origin: { size: 12 },
|
||||
dest: { size: 10 },
|
||||
checked,
|
||||
isSmallerOnServer: true,
|
||||
});
|
||||
|
||||
function setup(component: any) {
|
||||
return component.setup({}, { expose: vi.fn() });
|
||||
}
|
||||
|
||||
function confirmPrompt(result: ConflictingResource[]) {
|
||||
const prompt = harness.showHover.mock.calls[0][0];
|
||||
prompt.confirm({ preventDefault: vi.fn() }, result);
|
||||
}
|
||||
|
||||
async function runActualHandleFiles() {
|
||||
const [files, path, overwrite] = harness.handleFiles.mock.calls[0];
|
||||
const actual =
|
||||
await vi.importActual<typeof import("@/utils/upload")>("@/utils/upload");
|
||||
actual.handleFiles(files, path, overwrite);
|
||||
}
|
||||
|
||||
function uploadFlags() {
|
||||
return harness.queueUpload.mock.calls.map((call) => call[3]);
|
||||
}
|
||||
|
||||
describe("upload conflict resolution", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
harness.fileStore.preselect = "";
|
||||
vi.stubGlobal("window", {
|
||||
innerWidth: 1024,
|
||||
innerHeight: 768,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
getElementsByClassName: () => [],
|
||||
});
|
||||
});
|
||||
|
||||
it("authorizes an explicit drag/drop Replace choice", async () => {
|
||||
const upload = file("file-0.txt");
|
||||
harness.scanFiles.mockResolvedValue([upload]);
|
||||
harness.checkConflict.mockResolvedValue([conflict(0, ["origin"])]);
|
||||
const bindings = setup(FileListing);
|
||||
|
||||
await bindings.drop({
|
||||
preventDefault: vi.fn(),
|
||||
dataTransfer: { files: [upload.file], items: [] },
|
||||
target: {
|
||||
classList: { contains: () => false },
|
||||
parentElement: null,
|
||||
},
|
||||
});
|
||||
confirmPrompt([conflict(0, ["origin"])]);
|
||||
await runActualHandleFiles();
|
||||
|
||||
expect(uploadFlags()).toEqual([true]);
|
||||
});
|
||||
|
||||
it("keeps the forbidden both-selected upload overwrite-safe", async () => {
|
||||
const upload = file("file-0.txt");
|
||||
harness.scanFiles.mockResolvedValue([upload]);
|
||||
harness.checkConflict.mockResolvedValue([conflict(0, ["origin"])]);
|
||||
const bindings = setup(FileListing);
|
||||
|
||||
await bindings.drop({
|
||||
preventDefault: vi.fn(),
|
||||
dataTransfer: { files: [upload.file], items: [] },
|
||||
target: {
|
||||
classList: { contains: () => false },
|
||||
parentElement: null,
|
||||
},
|
||||
});
|
||||
confirmPrompt([conflict(0, ["origin", "dest"])]);
|
||||
await runActualHandleFiles();
|
||||
|
||||
expect(uploadFlags()).toEqual([false]);
|
||||
});
|
||||
|
||||
it("applies Replace only to the selected file in a mixed batch", async () => {
|
||||
const conflicting = file("file-0.txt");
|
||||
const nonconflicting = file("new-file.txt");
|
||||
harness.checkConflict.mockResolvedValue([conflict(0, ["origin"])]);
|
||||
const bindings = setup(FileListing);
|
||||
|
||||
await bindings.uploadInput({
|
||||
currentTarget: { files: [conflicting.file, nonconflicting.file] },
|
||||
});
|
||||
confirmPrompt([conflict(0, ["origin"])]);
|
||||
await runActualHandleFiles();
|
||||
|
||||
expect(uploadFlags()).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it("keeps a nonconflicting sibling protected after Skip", async () => {
|
||||
const conflicting = file("file-0.txt");
|
||||
const nonconflicting = file("late-file.txt");
|
||||
harness.checkConflict.mockResolvedValue([conflict(0, ["origin"])]);
|
||||
const bindings = setup(FileListing);
|
||||
|
||||
await bindings.uploadInput({
|
||||
currentTarget: { files: [conflicting.file, nonconflicting.file] },
|
||||
});
|
||||
confirmPrompt([conflict(0, ["dest"])]);
|
||||
await runActualHandleFiles();
|
||||
|
||||
expect(harness.queueUpload).toHaveBeenCalledTimes(1);
|
||||
expect(harness.queueUpload).toHaveBeenCalledWith(
|
||||
"/files/target/late-file.txt",
|
||||
"late-file.txt",
|
||||
nonconflicting.file,
|
||||
false,
|
||||
"text"
|
||||
);
|
||||
});
|
||||
|
||||
it("matches the Upload prompt per-file overwrite semantics", async () => {
|
||||
const conflicting = file("file-0.txt");
|
||||
const nonconflicting = file("new-file.txt");
|
||||
harness.checkConflict.mockResolvedValue([conflict(0, ["origin"])]);
|
||||
const bindings = setup(UploadPrompt);
|
||||
|
||||
await bindings.uploadInput({
|
||||
currentTarget: { files: [conflicting.file, nonconflicting.file] },
|
||||
});
|
||||
confirmPrompt([conflict(0, ["origin"])]);
|
||||
await runActualHandleFiles();
|
||||
|
||||
expect(uploadFlags()).toEqual([true, false]);
|
||||
});
|
||||
});
|
||||
+5
-23
@@ -191,33 +191,15 @@ var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int,
|
||||
}
|
||||
|
||||
user.Password = pwd
|
||||
if d.settings.CreateUserDir {
|
||||
user.Scope = ""
|
||||
}
|
||||
|
||||
userHome, err := d.settings.MakeUserDir(user.Username, user.Scope, d.server.Root)
|
||||
if err != nil {
|
||||
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
|
||||
switch err := d.settings.CreateUserHome(user, d.store.Users, d.server.Root, false); {
|
||||
case errors.Is(err, fberrors.ErrExist):
|
||||
return http.StatusConflict, fberrors.ErrExist
|
||||
case err != nil:
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
user.Scope = userHome
|
||||
|
||||
// When home directories are created from the username, distinct usernames
|
||||
// can normalize to the same scope (cleanUsername is many-to-one), which would
|
||||
// silently hand the new user another user's home directory. Reject the signup
|
||||
// if the derived scope is already taken. When CreateUserDir is off, all
|
||||
// signups intentionally share the configured default scope, so this check
|
||||
// does not apply.
|
||||
if d.settings.CreateUserDir {
|
||||
switch _, err := d.store.Users.GetByScope(user.Scope); {
|
||||
case err == nil:
|
||||
return http.StatusConflict, fberrors.ErrExist
|
||||
case !errors.Is(err, fberrors.ErrNotExist):
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("new user: %s, home dir: [%s].", user.Username, userHome)
|
||||
log.Printf("new user: %s, home dir: [%s].", user.Username, user.Scope)
|
||||
|
||||
err = d.store.Users.Save(user)
|
||||
if errors.Is(err, fberrors.ErrExist) {
|
||||
|
||||
+7
-1
@@ -67,6 +67,10 @@ var resourceGetHandler = withUser(func(w http.ResponseWriter, r *http.Request, d
|
||||
}
|
||||
|
||||
if checksum := r.URL.Query().Get("checksum"); checksum != "" {
|
||||
if !d.user.Perm.Download {
|
||||
return http.StatusAccepted, nil
|
||||
}
|
||||
|
||||
err := file.Checksum(checksum)
|
||||
if errors.Is(err, fberrors.ErrInvalidOption) {
|
||||
return http.StatusBadRequest, nil
|
||||
@@ -130,7 +134,9 @@ func resourcePostHandler(fileCache FileCache) handleFunc {
|
||||
|
||||
// Directories creation on POST.
|
||||
if strings.HasSuffix(r.URL.Path, "/") {
|
||||
err := d.user.Fs.MkdirAll(r.URL.Path, d.settings.DirMode)
|
||||
err := d.RunHook(func() error {
|
||||
return d.user.Fs.MkdirAll(r.URL.Path, d.settings.DirMode)
|
||||
}, "upload", r.URL.Path, "", d.user)
|
||||
return errToStatus(err), err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// The ?checksum= branch reads the whole file to compute a digest, so it must be
|
||||
// gated behind Perm.Download like the other read paths. A user without download
|
||||
// permission must not obtain a digest of a file they cannot download.
|
||||
func TestResourceChecksumRequiresDownloadPermission(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
userScope := filepath.Join(root, "user")
|
||||
if err := os.MkdirAll(userScope, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(userScope, "secret.txt"), []byte("classified"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := []byte("test-signing-key")
|
||||
|
||||
get := func(t *testing.T, perm users.Permissions) *httptest.ResponseRecorder {
|
||||
st := scopedUserStorage(t, userScope, perm, key)
|
||||
req, _ := http.NewRequest(http.MethodGet, "/secret.txt?checksum=sha256", http.NoBody)
|
||||
req.Header.Set("X-Auth", signToken(t, perm, key))
|
||||
rec := httptest.NewRecorder()
|
||||
handle(resourceGetHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
t.Run("denied without download permission", func(t *testing.T) {
|
||||
rec := get(t, users.Permissions{})
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("expected 202, got %d body=%q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if strings.Contains(strings.ToLower(rec.Body.String()), "checksum") {
|
||||
t.Fatalf("digest leaked without download permission: %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allowed with download permission", func(t *testing.T) {
|
||||
rec := get(t, users.Permissions{Download: true})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d body=%q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "checksums") {
|
||||
t.Fatalf("expected a checksum in the response, got %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -222,3 +222,38 @@ func TestResourcePostCleanupDoesNotDeleteThroughSymlink(t *testing.T) {
|
||||
t.Fatalf("VULNERABLE: out-of-scope victim.txt deleted by cleanup RemoveAll (status=%d): %v", rec.Code, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcePostRunsUploadHooksForDirectories(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
userScope := filepath.Join(root, "user")
|
||||
if err := os.MkdirAll(userScope, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
key := []byte("test-signing-key")
|
||||
perm := users.Permissions{Create: true}
|
||||
st := scopedUserStorage(t, userScope, perm, key)
|
||||
if err := st.Settings.Save(&settings.Settings{
|
||||
Key: key,
|
||||
Commands: map[string][]string{
|
||||
"after_upload": {"filebrowser-hook-command-that-does-not-exist"},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPost, "/created/", http.NoBody)
|
||||
req.Header.Set("X-Auth", signToken(t, perm, key))
|
||||
rec := httptest.NewRecorder()
|
||||
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{EnableExec: true}).ServeHTTP(rec, req)
|
||||
|
||||
// A missing after_upload command makes the request fail only if the hook ran.
|
||||
// It avoids a platform-specific helper executable while still exercising the
|
||||
// same path the web UI uses for directory uploads.
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected directory upload hook failure to return 500, got %d body=%q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(userScope, "created")); err != nil {
|
||||
t.Fatalf("expected directory to be created before its after hook, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,7 @@ func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs
|
||||
}
|
||||
|
||||
w.Header().Set("x-xss-protection", "1; mode=block")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
return handleWithStaticData(w, r, d, assetsFs, "public/index.html", "text/html; charset=utf-8")
|
||||
}, "", store, server)
|
||||
|
||||
@@ -124,6 +125,7 @@ func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs
|
||||
|
||||
const maxAge = 86400 // 1 day
|
||||
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", maxAge))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
||||
if d.settings.Branding.Files != "" {
|
||||
if strings.HasPrefix(r.URL.Path, "img/") {
|
||||
|
||||
+26
-3
@@ -109,8 +109,13 @@ func tusPostHandler(cache UploadCache) handleFunc {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid upload length: %w", err)
|
||||
}
|
||||
|
||||
// Enables the user to utilize the PATCH endpoint for uploading file data
|
||||
cache.Register(file.RealPath(), uploadLength)
|
||||
// Enables the user to utilize the PATCH endpoint for uploading file data.
|
||||
// The removal callback deletes an abandoned upload through the user's
|
||||
// scoped filesystem, so eviction cannot follow a symlink out of scope.
|
||||
uploadPath := r.URL.Path
|
||||
cache.Register(file.RealPath(), uploadLength, func() error {
|
||||
return d.user.Fs.Remove(uploadPath)
|
||||
})
|
||||
|
||||
basePath := "/" + strings.Trim(strings.TrimSpace(d.server.BaseURL), "/")
|
||||
if basePath == "/" {
|
||||
@@ -188,6 +193,10 @@ func tusPatchHandler(cache UploadCache) handleFunc {
|
||||
return http.StatusNotFound, err
|
||||
}
|
||||
|
||||
if uploadOffset > uploadLength {
|
||||
return http.StatusBadRequest, fmt.Errorf("upload offset %d exceeds declared length %d", uploadOffset, uploadLength)
|
||||
}
|
||||
|
||||
// Prevent the upload from being evicted during the transfer
|
||||
stop := keepUploadActive(cache, file.RealPath())
|
||||
defer stop()
|
||||
@@ -215,10 +224,24 @@ func tusPatchHandler(cache UploadCache) handleFunc {
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
bytesWritten, err := io.Copy(openFile, r.Body)
|
||||
// Enforce the declared Upload-Length: never write more than the bytes
|
||||
// still expected for this upload. Reading one byte past the remainder
|
||||
// lets an over-length body be detected and rejected. Without this bound a
|
||||
// PATCH could stream arbitrary data to disk regardless of the length the
|
||||
// client declared when the upload was created.
|
||||
remaining := uploadLength - uploadOffset
|
||||
bytesWritten, err := io.Copy(openFile, io.LimitReader(r.Body, remaining+1))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("could not write to file: %w", err)
|
||||
}
|
||||
if bytesWritten > remaining {
|
||||
// The client sent more than it declared; roll this chunk back so the
|
||||
// file stays consistent with the tracked offset, and reject it.
|
||||
if truncErr := openFile.Truncate(uploadOffset); truncErr != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("could not truncate file: %w", truncErr)
|
||||
}
|
||||
return http.StatusRequestEntityTooLarge, fmt.Errorf("upload exceeds declared length of %d bytes", uploadLength)
|
||||
}
|
||||
|
||||
// Sync the file to ensure all data is written to storage
|
||||
// to prevent file corruption.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// A TUS PATCH must not write more than the declared Upload-Length. A client that
|
||||
// declares a small length and then streams a large body must be rejected without
|
||||
// the excess being written to disk, while a correctly-sized upload still works.
|
||||
func TestTusPatchEnforcesUploadLength(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
userScope := filepath.Join(root, "user")
|
||||
if err := os.MkdirAll(userScope, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
key := []byte("test-signing-key")
|
||||
perm := users.Permissions{Create: true, Modify: true}
|
||||
st := scopedUserStorage(t, userScope, perm, key)
|
||||
signed := signToken(t, perm, key)
|
||||
|
||||
cache := newMemoryUploadCache()
|
||||
t.Cleanup(cache.Close)
|
||||
post := handle(tusPostHandler(cache), "", st, &settings.Server{})
|
||||
patch := handle(tusPatchHandler(cache), "", st, &settings.Server{})
|
||||
|
||||
patchReq := func(body string) *httptest.ResponseRecorder {
|
||||
req, _ := http.NewRequest(http.MethodPatch, "/file.txt", strings.NewReader(body))
|
||||
req.Header.Set("X-Auth", signed)
|
||||
req.Header.Set("Content-Type", "application/offset+octet-stream")
|
||||
req.Header.Set("Upload-Offset", "0")
|
||||
rec := httptest.NewRecorder()
|
||||
patch.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// Create an upload that declares only 5 bytes.
|
||||
reqPost, _ := http.NewRequest(http.MethodPost, "/file.txt", http.NoBody)
|
||||
reqPost.Header.Set("X-Auth", signed)
|
||||
reqPost.Header.Set("Upload-Length", "5")
|
||||
recPost := httptest.NewRecorder()
|
||||
post.ServeHTTP(recPost, reqPost)
|
||||
if recPost.Code != http.StatusCreated {
|
||||
t.Fatalf("POST expected 201, got %d body=%q", recPost.Code, recPost.Body.String())
|
||||
}
|
||||
|
||||
// A body far larger than the declared length must be rejected, and nothing
|
||||
// beyond the declared length may reach disk.
|
||||
if rec := patchReq(strings.Repeat("A", 5000)); rec.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("over-length PATCH expected 413, got %d body=%q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(userScope, "file.txt")); err != nil {
|
||||
t.Fatalf("stat file.txt: %v", err)
|
||||
} else if fi.Size() > 5 {
|
||||
t.Fatalf("wrote %d bytes despite Upload-Length 5", fi.Size())
|
||||
}
|
||||
|
||||
// A correctly-sized upload still completes.
|
||||
if rec := patchReq("hello"); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("valid PATCH expected 204, got %d body=%q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if data, _ := os.ReadFile(filepath.Join(userScope, "file.txt")); string(data) != "hello" {
|
||||
t.Fatalf("expected file content \"hello\", got %q", string(data))
|
||||
}
|
||||
}
|
||||
+26
-10
@@ -3,7 +3,6 @@ package fbhttp
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jellydator/ttlcache/v3"
|
||||
@@ -15,8 +14,11 @@ const uploadCacheTTL = 3 * time.Minute
|
||||
// Allows for different backends (e.g. in-memory or redis)
|
||||
// to support both single instance and multi replica deployments.
|
||||
type UploadCache interface {
|
||||
// Register stores an upload with its expected file size
|
||||
Register(filePath string, fileSize int64)
|
||||
// Register stores an upload with its expected file size. remove is called if
|
||||
// the upload expires before completion, to delete the partial file; it must
|
||||
// route through the uploading user's scoped filesystem so that eviction
|
||||
// cannot follow a symlink out of the user's scope.
|
||||
Register(filePath string, fileSize int64, remove func() error)
|
||||
|
||||
// Complete removes an upload from the cache
|
||||
Complete(filePath string)
|
||||
@@ -31,17 +33,31 @@ type UploadCache interface {
|
||||
Close()
|
||||
}
|
||||
|
||||
// memoryUploadEntry is the value stored for each active upload.
|
||||
type memoryUploadEntry struct {
|
||||
size int64
|
||||
remove func() error
|
||||
}
|
||||
|
||||
// memoryUploadCache is an upload cache for single replica deployments
|
||||
type memoryUploadCache struct {
|
||||
cache *ttlcache.Cache[string, int64]
|
||||
cache *ttlcache.Cache[string, memoryUploadEntry]
|
||||
}
|
||||
|
||||
func newMemoryUploadCache() *memoryUploadCache {
|
||||
cache := ttlcache.New[string, int64]()
|
||||
cache.OnEviction(func(_ context.Context, reason ttlcache.EvictionReason, item *ttlcache.Item[string, int64]) {
|
||||
cache := ttlcache.New[string, memoryUploadEntry]()
|
||||
cache.OnEviction(func(_ context.Context, reason ttlcache.EvictionReason, item *ttlcache.Item[string, memoryUploadEntry]) {
|
||||
if reason == ttlcache.EvictionReasonExpired {
|
||||
fmt.Printf("deleting incomplete upload file: \"%s\"\n", item.Key())
|
||||
os.Remove(item.Key())
|
||||
// Delete through the scoped removal callback rather than a raw
|
||||
// os.Remove on the cached path, so an ancestor directory swapped for
|
||||
// a symlink during the TTL window cannot redirect the delete outside
|
||||
// the user's scope.
|
||||
if remove := item.Value().remove; remove != nil {
|
||||
if err := remove(); err != nil {
|
||||
fmt.Printf("failed to delete incomplete upload file %q: %v\n", item.Key(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
go cache.Start()
|
||||
@@ -49,8 +65,8 @@ func newMemoryUploadCache() *memoryUploadCache {
|
||||
return &memoryUploadCache{cache: cache}
|
||||
}
|
||||
|
||||
func (c *memoryUploadCache) Register(filePath string, fileSize int64) {
|
||||
c.cache.Set(filePath, fileSize, uploadCacheTTL)
|
||||
func (c *memoryUploadCache) Register(filePath string, fileSize int64, remove func() error) {
|
||||
c.cache.Set(filePath, memoryUploadEntry{size: fileSize, remove: remove}, uploadCacheTTL)
|
||||
}
|
||||
|
||||
func (c *memoryUploadCache) Complete(filePath string) {
|
||||
@@ -62,7 +78,7 @@ func (c *memoryUploadCache) GetLength(filePath string) (int64, error) {
|
||||
if item == nil {
|
||||
return 0, fmt.Errorf("no active upload found for the given path")
|
||||
}
|
||||
return item.Value(), nil
|
||||
return item.Value().size, nil
|
||||
}
|
||||
|
||||
func (c *memoryUploadCache) Touch(filePath string) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// On expiry the memory upload cache must delete an abandoned upload through the
|
||||
// registered scoped removal callback, not with a raw os.Remove on the cached
|
||||
// path. This test registers an entry keyed by a real file's path whose callback
|
||||
// does not delete the file; if the old raw os.Remove behaviour were still in
|
||||
// place the file (whose path is the key) would be removed.
|
||||
func TestMemoryUploadCacheEvictionUsesRemovalCallback(t *testing.T) {
|
||||
c := newMemoryUploadCache()
|
||||
t.Cleanup(c.Close)
|
||||
|
||||
f := filepath.Join(t.TempDir(), "partial.upload")
|
||||
if err := os.WriteFile(f, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
var once sync.Once
|
||||
// Deliberately do NOT delete the file here.
|
||||
c.cache.Set(f, memoryUploadEntry{size: 1, remove: func() error {
|
||||
once.Do(func() { close(done) })
|
||||
return nil
|
||||
}}, time.Millisecond)
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("eviction did not invoke the removal callback")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(f); err != nil {
|
||||
t.Fatalf("file at the cache key was deleted, so eviction bypassed the callback (raw os.Remove?): %v", err)
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,9 @@ func (c *redisUploadCache) filePathKey(filePath string) string {
|
||||
return "filebrowser:upload:" + filePath
|
||||
}
|
||||
|
||||
func (c *redisUploadCache) Register(filePath string, fileSize int64) {
|
||||
// Register stores the upload length. The scoped removal callback is unused by
|
||||
// the redis backend, which does not delete partial files on eviction.
|
||||
func (c *redisUploadCache) Register(filePath string, fileSize int64, _ func() error) {
|
||||
err := c.client.Set(context.Background(), c.filePathKey(filePath), fileSize, uploadCacheTTL).Err()
|
||||
if err != nil {
|
||||
log.Printf("failed to register upload in redis cache: %v", err)
|
||||
|
||||
@@ -10,6 +10,9 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -39,6 +42,39 @@ func (s *Settings) MakeUserDir(username, userScope, serverRoot string) (string,
|
||||
return userScope, nil
|
||||
}
|
||||
|
||||
// CreateUserHome derives and creates the home directory for a user that is
|
||||
// being provisioned (via signup, proxy auth or hook auth) and sets user.Scope
|
||||
// to the resulting path. When CreateUserDir is enabled and the caller did not
|
||||
// supply an explicit scope, the scope is cleared so that MakeUserDir derives a
|
||||
// per-user home from the username instead of falling back to the default scope
|
||||
// (which normalizes to the server root, leaving every provisioned user sharing
|
||||
// it). When a home directory is derived, it also rejects a scope already owned
|
||||
// by another user, so that distinct usernames cannot silently share one home
|
||||
// directory.
|
||||
func (s *Settings) CreateUserHome(user *users.User, store users.Store, serverRoot string, explicitScope bool) error {
|
||||
derived := s.CreateUserDir && !explicitScope
|
||||
if derived {
|
||||
user.Scope = ""
|
||||
}
|
||||
|
||||
userHome, err := s.MakeUserDir(user.Username, user.Scope, serverRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user.Scope = userHome
|
||||
|
||||
if derived {
|
||||
switch _, err := store.GetByScope(user.Scope); {
|
||||
case err == nil:
|
||||
return fberrors.ErrExist
|
||||
case !errors.Is(err, fberrors.ErrNotExist):
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func cleanUsername(s string) string {
|
||||
// Remove any trailing space to avoid ending on -
|
||||
s = strings.Trim(s, " ")
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// stubStore is a minimal users.Store used to exercise CreateUserHome.
|
||||
type stubStore struct {
|
||||
byScope map[string]*users.User
|
||||
}
|
||||
|
||||
func (s *stubStore) Get(_ string, _ bool, _ interface{}) (*users.User, error) {
|
||||
return nil, fberrors.ErrNotExist
|
||||
}
|
||||
|
||||
func (s *stubStore) GetByScope(scope string) (*users.User, error) {
|
||||
if u, ok := s.byScope[scope]; ok {
|
||||
return u, nil
|
||||
}
|
||||
return nil, fberrors.ErrNotExist
|
||||
}
|
||||
|
||||
func (s *stubStore) Gets(_ string, _ bool) ([]*users.User, error) { return nil, nil }
|
||||
func (s *stubStore) Update(_ *users.User, _ ...string) error { return nil }
|
||||
func (s *stubStore) Save(_ *users.User) error { return nil }
|
||||
func (s *stubStore) Delete(_ interface{}) error { return nil }
|
||||
func (s *stubStore) LastUpdate(_ uint) int64 { return 0 }
|
||||
|
||||
// A user provisioned with CreateUserDir must receive a per-user home directory
|
||||
// derived from its username, not the default scope which normalizes to the
|
||||
// server root.
|
||||
func TestCreateUserHomeDerivesPerUserScope(t *testing.T) {
|
||||
s := &Settings{CreateUserDir: true, UserHomeBasePath: "/users"}
|
||||
store := &stubStore{byScope: map[string]*users.User{}}
|
||||
|
||||
user := &users.User{Username: "alice", Scope: "."}
|
||||
if err := s.CreateUserHome(user, store, t.TempDir(), false); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.Scope != "/users/alice" {
|
||||
t.Errorf("expected derived scope /users/alice, got %q", user.Scope)
|
||||
}
|
||||
}
|
||||
|
||||
// When the derived scope is already owned by another user, provisioning must be
|
||||
// rejected so distinct usernames cannot silently share one home directory.
|
||||
func TestCreateUserHomeRejectsCollision(t *testing.T) {
|
||||
s := &Settings{CreateUserDir: true, UserHomeBasePath: "/users"}
|
||||
store := &stubStore{byScope: map[string]*users.User{"/users/alice": {Username: "alice"}}}
|
||||
|
||||
user := &users.User{Username: "alice", Scope: "."}
|
||||
if err := s.CreateUserHome(user, store, t.TempDir(), false); !errors.Is(err, fberrors.ErrExist) {
|
||||
t.Fatalf("expected ErrExist on scope collision, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A scope explicitly supplied by the caller (e.g. returned by an auth hook) must
|
||||
// be preserved instead of being replaced by a derived home directory.
|
||||
func TestCreateUserHomePreservesExplicitScope(t *testing.T) {
|
||||
s := &Settings{CreateUserDir: true, UserHomeBasePath: "/users"}
|
||||
store := &stubStore{byScope: map[string]*users.User{"/users/alice": {Username: "alice"}}}
|
||||
|
||||
user := &users.User{Username: "alice", Scope: "/custom"}
|
||||
if err := s.CreateUserHome(user, store, t.TempDir(), true); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.Scope != "/custom" {
|
||||
t.Errorf("explicit scope should be preserved, got %q", user.Scope)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
"github.com/asdine/storm/v3/q"
|
||||
@@ -44,7 +45,11 @@ func (st usersBackend) GetBy(i interface{}) (user *users.User, err error) {
|
||||
|
||||
func (st usersBackend) GetByScope(scope string) (*users.User, error) {
|
||||
user := &users.User{}
|
||||
err := st.db.Select(q.Eq("Scope", scope)).First(user)
|
||||
// Match case-insensitively: on a case-insensitive filesystem two scopes
|
||||
// that differ only in case (e.g. /users/Alice and /users/alice) resolve to
|
||||
// the same home directory, so they must be treated as a collision.
|
||||
pattern := "(?i)^" + regexp.QuoteMeta(scope) + "$"
|
||||
err := st.db.Select(q.Re("Scope", pattern)).First(user)
|
||||
if err != nil {
|
||||
if errors.Is(err, storm.ErrNotFound) {
|
||||
return nil, fberrors.ErrNotExist
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package bolt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/asdine/storm/v3"
|
||||
|
||||
fberrors "github.com/filebrowser/filebrowser/v2/errors"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
// GetByScope must match case-insensitively: on a case-insensitive filesystem
|
||||
// two scopes that differ only in case resolve to the same home directory, so
|
||||
// the provisioning collision check has to treat them as the same scope.
|
||||
func TestGetByScopeCaseInsensitive(t *testing.T) {
|
||||
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
st, err := NewStorage(db)
|
||||
if err != nil {
|
||||
t.Fatalf("new storage: %v", err)
|
||||
}
|
||||
if err := st.Users.Save(&users.User{Username: "CaseVictim", Password: "pw", Scope: "/users/CaseVictim"}); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
|
||||
for _, scope := range []string{"/users/CaseVictim", "/users/casevictim", "/USERS/CASEVICTIM"} {
|
||||
u, err := st.Users.GetByScope(scope)
|
||||
if err != nil {
|
||||
t.Errorf("GetByScope(%q) unexpected error: %v", scope, err)
|
||||
continue
|
||||
}
|
||||
if u.Username != "CaseVictim" {
|
||||
t.Errorf("GetByScope(%q) returned %q, want CaseVictim", scope, u.Username)
|
||||
}
|
||||
}
|
||||
|
||||
// A genuinely different scope must still miss (and the regex-escaped query
|
||||
// must not match a superstring).
|
||||
for _, scope := range []string{"/users/other", "/users/CaseVictimX"} {
|
||||
if _, err := st.Users.GetByScope(scope); !errors.Is(err, fberrors.ErrNotExist) {
|
||||
t.Errorf("GetByScope(%q) expected ErrNotExist, got %v", scope, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ docker run \
|
||||
|
||||
Where `filebrowser_data`, `filebrowser_database` and `filebrowser_config` are Docker [volumes](https://docs.docker.com/engine/storage/volumes/), where the data, database and configuration will be stored, respectively. The default configuration and database will be automatically initialized.
|
||||
|
||||
The default user that runs File Browser inside the container has PID 1000 and GID 1000. If, for one reason or another, you want to run the Docker container with a different user, please consult Docker's [user documentation](https://docs.docker.com/engine/containers/run/#user).
|
||||
The default user that runs File Browser inside the container has UID 1000 and GID 1000. If, for one reason or another, you want to run the Docker container with a different user, please consult Docker's [user documentation](https://docs.docker.com/engine/containers/run/#user).
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
|
||||
Reference in new issue
Block a user