Compare commits

..
28 Commits
Author SHA1 Message Date
Henrique Dias 50125a5d21 chore(release): 2.63.20 2026-07-25 22:16:14 +02:00
Henrique Dias bc3d75a94a test(users): cover concurrent provisioning into one scope
Two usernames that normalize to the same home directory must not both be
provisioned when their requests are handled concurrently. Also cover that
an explicit, non-derived scope may still be legitimately shared.

Refs GHSA-j7jh-37pf-mf8h
2026-07-25 22:15:35 +02:00
Henrique Dias fb6aeba9ea fix(users): make the provisioned scope check atomic with the save
The check that stops two usernames normalizing to the same home directory
ran as a storage operation separate from the save, so two first-time users
provisioned concurrently could both observe a free scope and both be saved
into it, ending up sharing one home directory.

Move the check into users.Storage.SaveProvisioned, which holds a single
lock across the lookup and the save, and reduce CreateUserHome to deriving
and creating the directory. This covers all three provisioning paths:
signup, proxy auth and hook auth.

Refs GHSA-j7jh-37pf-mf8h
2026-07-25 22:15:27 +02:00
Henrique Dias 67e893eee7 fix: use aria-selected 2026-07-25 22:09:01 +02:00
Henrique Dias 4a4b0f8c84 docs: update CLAUDE instructions 2026-07-25 22:03:33 +02:00
Henrique Dias 660d84661d docs: update CLAUDE.md 2026-07-25 08:47:34 +02:00
Henrique Dias 392253c563 docs: update SECURITY.md and add CLAUDE.md 2026-07-25 08:42:52 +02:00
Henrique Dias 328f629181 chore(release): 2.63.19 2026-07-25 08:19:11 +02:00
Henrique Dias 4c3cb4bc9b test(http): cover TUS Upload-Length enforcement
Refs GHSA-ffv3-7h97-993q
2026-07-25 08:16:19 +02:00
Henrique Dias 3213b605be test(http): cover scope-safe removal on TUS upload eviction
Refs GHSA-m9f5-2232-frp6
2026-07-25 08:16:19 +02:00
Henrique Dias 610e0b09e9 test(http): cover download-permission gate on the checksum branch
Refs GHSA-7whw-q6gh-xr59
2026-07-25 08:16:19 +02:00
Henrique Dias 7453c78c98 test(storage): cover case-insensitive GetByScope matching
Refs GHSA-576v-w77m-gr84
2026-07-25 08:16:18 +02:00
Henrique Dias cd5749dff8 test(auth): cover per-user scope isolation for proxy and hook provisioning
Unit tests for Settings.CreateUserHome (derives a per-user home, rejects a
colliding scope, preserves an explicit scope) plus proxy and hook regression
tests asserting that with CreateUserDir enabled two provisioned users receive
distinct home directories instead of the server root.

Refs GHSA-j7jh-37pf-mf8h, GHSA-j2fc-28fx-hc8q
2026-07-25 08:16:18 +02:00
Henrique Dias 4daddec6f2 fix(http): enforce declared Upload-Length on TUS uploads
The TUS PATCH handler copied the whole request body to disk and used the
declared Upload-Length only to decide when the upload was complete. A client
could declare a tiny Upload-Length and then stream an arbitrarily large body
in a single PATCH, writing it all to disk, so any user with create permission
could exhaust the filesystem.

Bound each write to the bytes still expected (Upload-Length - Upload-Offset),
reject a PATCH whose offset already exceeds the declared length, and roll back
and reject a body that exceeds it. This complements the existing negative
Upload-Length handling.

Refs GHSA-ffv3-7h97-993q
2026-07-25 08:16:18 +02:00
Henrique Dias 9bd79c3aae fix(http): delete abandoned TUS uploads through the scoped filesystem
The in-memory upload cache deleted expired incomplete uploads with a raw
os.Remove on the absolute path it had stored, bypassing ScopedFs entirely.
Because the stored path is only lexically cleaned (no symlink evaluation) and
os.Remove resolves symlinked parent directories, a Create-only user could
register an upload and then, within the 3-minute TTL, swap an in-scope
ancestor directory for a symlink so the eviction deleted an arbitrary file
outside their scope.

Carry a removal callback with each cache entry and invoke it on eviction
instead of os.Remove. For TUS uploads the callback deletes via the uploading
user's scoped filesystem, whose Remove is guarded by the same within() check
that CVE-2026-55667 added, so eviction can no longer follow a symlink out of
scope. The redis backend ignores the callback (it never deleted partial files).

Refs GHSA-m9f5-2232-frp6
2026-07-25 08:16:18 +02:00
Henrique Dias 6c69b5cd89 fix(http): enforce download permission on the checksum branch
The ?checksum= branch of the resource GET handler read the whole file to
compute its digest and returned it without checking Perm.Download, unlike the
sibling raw, preview, subtitle and X-Encoding paths. A user provisioned with
Perm.Download=false could therefore obtain md5/sha1/sha256/sha512 digests of
files they are not allowed to download, giving a file-content hash oracle, and
force a full-file read.

Return 202 Accepted before computing the checksum when the user lacks
Perm.Download, matching the other read paths. This completes the fix for
CVE-2026-35606, whose original patch gated only the content-returning paths.

Refs GHSA-7whw-q6gh-xr59
2026-07-25 08:16:18 +02:00
Henrique Dias 4b8a8d72ce fix(storage): reject case-folded home directory collisions
GetByScope compared scopes with a case-sensitive exact match, so on a
case-insensitive filesystem two accounts whose scopes differ only in case
(e.g. /users/CaseVictim and /users/casevictim) were treated as distinct even
though both resolve to the same physical home directory. The second account
could then read, overwrite and delete the first account's files.

Match the scope case-insensitively so the collision check performed during
signup, proxy and hook provisioning catches these aliases and rejects the
duplicate.

Refs GHSA-576v-w77m-gr84
2026-07-25 08:16:18 +02:00
Henrique Dias 8ddd3d1db9 fix(auth): isolate auto-provisioned proxy and hook users to their own home
Proxy- and hook-authenticated users were auto-provisioned by applying the
default scope (".") and passing it straight to MakeUserDir, which normalizes
"." to "/". With CreateUserDir enabled, every provisioned user therefore
received the server root as its scope instead of a per-user home directory,
letting one user read, overwrite and delete another user's files.

The signup handler already cleared the scope before deriving the home
directory. Centralize that logic into Settings.CreateUserHome (clear the
scope when CreateUserDir is on and no explicit scope was supplied, derive the
home dir, then reject a scope already owned by another user) and use it from
signup, proxy and hook auth so the three provisioning paths cannot diverge.

Refs GHSA-j7jh-37pf-mf8h, GHSA-j2fc-28fx-hc8q
2026-07-25 08:16:15 +02:00
Henrique Dias 9fffee387f docs: remove go report 2026-07-25 08:00:00 +02:00
Henrique Dias 5a12cad548 docs: update readme 2026-07-25 07:52:21 +02:00
transifex-integration[bot] 6232686e22 chore: update translations 2026-07-25 07:30:18 +02:00
superafun b21b1245ae fix: accessibility and security improvements (#6033) 2026-07-25 07:30:02 +02:00
Archit Goyal 7361d91ea2 fix(upload): handle encoded path conflicts safely (#6040) 2026-07-25 07:29:49 +02:00
Henrique Dias c05c668148 fix: process --FollowExternalSymlinks 2026-07-25 07:25:26 +02:00
Henrique Dias b7dc392838 docs: fix typo 2026-07-21 19:18:51 +02:00
TowyTowyandClaude Fable 5 ac46cf0671 fix: return error instead of panicking on an unreadable directory during copy (#6020)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 07:21:44 +02:00
transifex-integration[bot] f0785391bf chore: update translations (#6019)
Co-authored-by: transifex-integration[bot] <43880903+transifex-integration[bot]@users.noreply.github.com>
2026-07-18 07:20:43 +02:00
tianrking 9b78324d77 fix(http): run upload hooks for directories (#6034) 2026-07-17 20:14:41 +02:00
42 changed files with 1380 additions and 115 deletions

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
# CLAUDE.md
Guidance for Claude when working in this repository (File Browser, `filebrowser/filebrowser`).
## Repo orientation
- Go backend (`github.com/filebrowser/filebrowser/v2`, ecosystem `go`) + Vue frontend under `frontend/`.
- The project is in **maintenance-only mode** (see `SECURITY.md`). Prefer small, surgical, well-tested changes.
- Version scheme: `v2.63.x`. Conventional-commit messages (`fix(scope): …`, `feat: …`, `chore: …`).
- Verify with `go build ./...`, `go vet ./...`, `go test ./...`. Reuse existing test harnesses (e.g. `signToken`, `scopedUserStorage`, `handle`, `customFSUser`, `mockUserStore`).
---
# Handling security advisories
Use this playbook when asked to triage, verify, fix, or manage GitHub security advisories.
All advisory state lives on GitHub and is driven with the `gh` CLI. States are
`triage → draft → published`, plus `closed`.
## 1. Fetch
```bash
# List by state (also: published, draft, closed)
gh api '/repos/filebrowser/filebrowser/security-advisories?state=triage&per_page=100' \
--jq '.[] | {ghsa_id, severity, summary, state}'
# Full report for one advisory (read .summary and .description)
gh api /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
--jq '.summary, "---", .description'
```
Always pull the **published** set too — you need it to dedup against.
## 2. Verify each report — do NOT trust the report text
Read the actual source **at HEAD** and reach one verdict per advisory:
- **CONFIRMED** — defect exists at HEAD. Quote the exact `file:line`.
- **FIXED** — already patched (find the fix commit).
- **FALSE / NOT APPLICABLE** — claim is wrong, or targets a different project.
- **NOT EXPLOITABLE** — pattern exists but no code path can reach the precondition.
- **DUPLICATE** — of a published advisory, or of another triage advisory.
Common traps — check each before accepting a report:
- **"Incomplete fix of a prior advisory."** Read the original fix commit and confirm the *specific*
sibling code path is actually still unguarded — a prior fix may already cover a related path.
- **Wrong project.** Confirm the referenced files, symbols, and endpoints exist in this repo; reports
sometimes describe a fork. If the cited code isn't here, close as not applicable.
- **"Legacy / upgraded / imported records are affected."** Trace the field's git history and confirm that
some released version could actually produce such a record before believing it
(`git log -S'Field' -- path`, `git show <commit>`, `git tag --contains <commit>`).
- **Overlapping reports.** Two triage advisories may share one root cause — consolidate and fix once.
- **Known, intentionally-unaddressed classes.** Some areas are known and tracked but not fixed (see
`SECURITY.md`'s Known Issues); matching reports are duplicates.
Record, per advisory: verdict, the `file:line` evidence, exploitability preconditions
(default config? platform-specific? auth required?), and the disposition.
## 3. Fix (one commit per advisory)
- Branch off `master` first; never commit fixes directly to `master`.
- **One commit per fix**, each referencing the GHSA in the body (`Refs GHSA-xxxx-xxxx-xxxx`).
- When several advisories share a root cause because parallel code paths diverged, **centralize** the logic
(e.g. `settings.CreateUserHome` used by signup, proxy, and hook provisioning) so they cannot drift again.
- Keep it surgical; match surrounding style.
## 4. Add a regression test per fix
- Reuse the existing harnesses; add a focused test asserting the fixed behavior (and that the legitimate
path still works). Commit tests alongside or right after the fixes (`test(scope): …`, `Refs GHSA-…`).
- Run `go test ./... && go vet ./...` before finishing.
## 5. Severity — set a CVSS vector, don't hand-assert
Set a CVSS v3.1 vector; GitHub derives the score **and** severity from it (overriding the plain `severity`
field). Encode the real preconditions in the vector so the band is defensible:
- Requires a specific target configuration/platform (e.g. case-insensitive FS) → **AC:H**.
- Unauthenticated vs needs an account → **PR:N / PR:L**.
- Keep it consistent with the **predecessor CVE's** rating (an incomplete-fix follow-up should not outrank
its parent). Bands: `0.1–3.9` low, `4.0–6.9` medium, `7.0–8.9` high, `9.0–10.0` critical.
```bash
gh api -X PATCH /repos/filebrowser/filebrowser/security-advisories/GHSA-xxxx-xxxx-xxxx \
-f cvss_vector_string='CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H' \
--jq '{ghsa_id, severity, score: .cvss.score, vector: .cvss.vector_string}'
```
## 6. Clean up the title
Rewrite reporter titles to the concise, sentence-case, backtick-free style of the published advisories
(state the vuln; drop "Incomplete fix of…" prefixes and jargon). The title is the `summary` field:
```bash
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx \
-f summary='Proxy-auth auto-provisioning ignores createUserDir and grants the server root scope'
```
## 7. Rewrite the body into the standard structure
Reporter reports arrive in whatever shape the reporter used. Before drafting, rewrite the
`description` into the sections below — **reusing the reporter's own wording wherever it is
accurate**, rather than paraphrasing it. Drop the greeting, the offer to help, and any claim the
verification in step 2 disproved. Keep sections in this order and omit the ones that don't apply:
| Section | Contents |
| --- | --- |
| `## Summary` | What the defect is, in two or three sentences. Note the version it was reported against and the range it was verified over. |
| `## Details` | Root cause, naming `file.go`, the function, and a short quote of the **pre-fix** code. |
| `## PoC` | The reporter's reproduction steps and observed result, trimmed to the essentials. |
| `## Impact` | Who can exploit it (privilege level, preconditions) and what they get. |
| `## Patches` | Fixed version plus a link to the fix commit, and one sentence on what the fix does. Mention it if the reporter re-tested and confirmed. |
| `## Workarounds` | Real mitigations, or `None. Upgrade to vX.Y.Z.` |
| `## Out of scope` | Anything in the original report deliberately **not** treated as a vulnerability, with the reasoning. Needed whenever the advisory is narrower than the report. |
| `## References` | Fix and regression-test commit links. |
Use `##` headings (matching the published advisories) and keep the body in the maintainer's voice —
first person ("I reproduced…") belongs only inside quoted PoC steps.
Send it as a file so the Markdown survives shell quoting:
```bash
jq -Rs '{description: .}' desc.md \
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
```
## 8. Set affected & patched versions
The package is always `{ecosystem: "go", name: "github.com/filebrowser/filebrowser/v2"}`.
- `vulnerable_version_range` — `<= <latest released version>` (the newest tag; find it with
`git tag --list 'v2.*' --sort=-version:refname | head -1`).
- `patched_versions` — the **next** release that will actually ship the fix. It doesn't exist just
because the branch does; it still has to be cut. **When unsure which version that will be, ask.**
Replace the placeholder versions below before sending:
```bash
printf '%s' '{"vulnerabilities":[{"package":{"ecosystem":"go","name":"github.com/filebrowser/filebrowser/v2"},"vulnerable_version_range":"<= <latest>","patched_versions":"<next>","vulnerable_functions":[]}]}' \
| gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx --input -
```
## 9. Move state / close, by disposition
```bash
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=draft # fixed, awaiting release
gh api -X PATCH .../security-advisories/GHSA-xxxx-xxxx-xxxx -f state=closed # duplicate / N-A / not-exploitable
```
- **CONFIRMED & fixed** → metadata done → **draft**. Publish after the patched release ships.
- **DUPLICATE / NOT APPLICABLE / NOT EXPLOITABLE** → **closed**.
- **DEFERRED** (confirmed but not yet fixed) → leave in **triage** with a note.
- The REST API **cannot post advisory comments** — replies to reporters (dup notice, evidence, links to
the relevant tracking issue) must be posted manually in the advisory UI. Draft the text for the maintainer.
## 10. Release & publish
Push the branch, open a PR, merge, tag/release the `patched_versions` you set, then publish the drafts.
Confirm outward-facing/irreversible advisory actions (close, publish) with the maintainer before doing them.
+20
View File
@@ -2,6 +2,26 @@
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.20](https://github.com/filebrowser/filebrowser/compare/v2.63.19...v2.63.20) (2026-07-25)
### Bug Fixes
* use aria-selected ([67e893e](https://github.com/filebrowser/filebrowser/commit/67e893eee7ee411e166d3fcd759a87b6f0971277))
* **users:** make the provisioned scope check atomic with the save ([fb6aeba](https://github.com/filebrowser/filebrowser/commit/fb6aeba9eae7b8eb401e0db325973781e1ffd08b))
## [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)
+1 -2
View File
@@ -3,7 +3,6 @@
</p>
[![Build](https://github.com/filebrowser/filebrowser/actions/workflows/ci.yaml/badge.svg)](https://github.com/filebrowser/filebrowser/actions/workflows/ci.yaml)
[![Go Report Card](https://goreportcard.com/badge/github.com/filebrowser/filebrowser/v2)](https://goreportcard.com/report/github.com/filebrowser/filebrowser/v2)
[![Version](https://img.shields.io/github/release/filebrowser/filebrowser.svg)](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.
+22 -15
View File
@@ -2,25 +2,32 @@
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | --------- |
| 2.x | ✅ |
| < 2.0 | ❌ |
| Version | Supported |
| ------- | ------------------ |
| 2.x | :white_check_mark: |
| < 2.0 | :x: |
## Before Reporting
This project is in maintenance-only mode. To avoid duplicates, first check the [existing advisories](https://github.com/filebrowser/filebrowser/security/advisories) and open issues, and confirm:
- **It concerns this project, not a fork.** Reports about code, features, or endpoints that don't exist here belong to the relevant fork.
- **It isn't an already-known class** that remains unaddressed:
- Command execution, runner, and hooks (opt-in, disabled by default) — [#5199](https://github.com/filebrowser/filebrowser/issues/5199)
- Session and JWT handling — [#5216](https://github.com/filebrowser/filebrowser/issues/5216)
Reports covering these are likely to be closed as duplicates.
## Reporting a Vulnerability
Vulnerabilities with critical impact should be reported on the [Security](https://github.com/filebrowser/filebrowser/security) page of this repository, which is a private way of communicating vulnerabilities to maintainers. This project is in maintenance-only mode and it can take a while until someone gets back to you.
- **Critical:** report privately via the [Security](https://github.com/filebrowser/filebrowser/security) page.
- **Non-critical:** open a public issue so the community can help; we'll label it as a security issue.
If it is not a critical vulnerability, please open an issue and we will categorize it as a security issue. By giving visibility, we can get more help from the community at fixing such issues.
Please include, where possible:
When reporting an issue, where possible, please provide at least:
- The commit the issue was found at
- A plaintext proof of concept (no binaries)
- Steps to reproduce
- Recommended remediation, if any
* The commit version the issue was identified at
* A proof of concept (plaintext; no binaries)
* Steps to reproduce
* Your recommended remediation(s), if any.
The File Browser team is a volunteer-only effort, and may reach back out for clarification.
We're a volunteer effort, so responses can take a while, and we may reach out for clarification.
+7 -6
View File
@@ -157,15 +157,16 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
}
u = a.GetUser(d)
userHome, err := a.Settings.MakeUserDir(u.Username, u.Scope, a.Server.Root)
// A scope explicitly returned by the hook takes precedence over the
// automatic per-user home directory derivation.
_, explicitScope := a.Fields.Values["user.scope"]
derivedScope, err := a.Settings.CreateUserHome(u, a.Server.Root, explicitScope)
if err != nil {
return nil, fmt.Errorf("user: failed to mkdir user home dir: [%s]", userHome)
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.SaveProvisioned(u, derivedScope); err != nil {
return nil, err
}
} else if p := !users.CheckPwd(a.Cred.Password, u.Password); len(a.Fields.Values) > 1 || p {
+68
View File
@@ -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)
}
}
+3 -6
View File
@@ -50,15 +50,12 @@ 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 {
var derivedScope bool
if derivedScope, err = setting.CreateUserHome(user, srv.Root, false); err != nil {
return nil, err
}
user.Scope = userHome
err = usr.Save(user)
if err != nil {
if err = usr.SaveProvisioned(user, derivedScope); err != nil {
return nil, err
}
+63 -1
View File
@@ -2,6 +2,7 @@ package auth
import (
"net/http"
"strings"
"testing"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
@@ -22,13 +23,31 @@ func (m *mockUserStore) Get(_ string, _ bool, id interface{}) (*users.User, erro
return nil, fberrors.ErrNotExist
}
func (m *mockUserStore) GetByScope(_ string) (*users.User, error) { return nil, fberrors.ErrNotExist }
func (m *mockUserStore) GetByScope(scope string) (*users.User, error) {
for _, u := range m.users {
if strings.EqualFold(u.Scope, scope) {
return u, nil
}
}
return nil, fberrors.ErrNotExist
}
func (m *mockUserStore) Gets(_ string, _ bool) ([]*users.User, error) { return nil, nil }
func (m *mockUserStore) Update(_ *users.User, _ ...string) error { return nil }
func (m *mockUserStore) Save(user *users.User) error {
m.users[user.Username] = user
return nil
}
func (m *mockUserStore) SaveProvisioned(user *users.User, derivedScope bool) error {
if derivedScope {
if _, err := m.GetByScope(user.Scope); err == nil {
return fberrors.ErrExist
}
}
return m.Save(user)
}
func (m *mockUserStore) Delete(_ interface{}) error { return nil }
func (m *mockUserStore) LastUpdate(_ uint) int64 { return 0 }
@@ -78,3 +97,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)
}
}
+26
View File
@@ -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")
}
}
+2
View File
@@ -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":
+49
View File
@@ -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
View File
@@ -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
+1 -1
View File
@@ -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 -]}]
+16
View File
@@ -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;
@@ -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 -1
View File
@@ -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"
+3 -3
View File
@@ -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
View File
@@ -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": {
+6 -10
View File
@@ -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);
});
});
+14 -1
View File
@@ -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.
+5 -1
View File
@@ -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="
+2 -2
View File
@@ -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]);
});
});
+3 -23
View File
@@ -191,35 +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)
derivedScope, err := d.settings.CreateUserHome(user, d.server.Root, false)
if err != nil {
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
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, user.Scope)
log.Printf("new user: %s, home dir: [%s].", user.Username, userHome)
err = d.store.Users.Save(user)
err = d.store.Users.SaveProvisioned(user, derivedScope)
if errors.Is(err, fberrors.ErrExist) {
return http.StatusConflict, err
} else if err != nil {
+7 -1
View File
@@ -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
}
+57
View File
@@ -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())
}
})
}
+35
View File
@@ -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)
}
}
+2
View File
@@ -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
View File
@@ -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.
+73
View File
@@ -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
View File
@@ -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) {
+42
View File
@@ -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)
}
}
+3 -1
View File
@@ -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)
+29
View File
@@ -10,6 +10,8 @@ import (
"strings"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/users"
)
var (
@@ -39,6 +41,33 @@ 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).
//
// It reports whether the scope was derived from the username. A derived scope
// must be persisted with users.Storage.SaveProvisioned, which 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, serverRoot string, explicitScope bool) (derived bool, err error) {
derived = s.CreateUserDir && !explicitScope
if derived {
user.Scope = ""
}
userHome, err := s.MakeUserDir(user.Username, user.Scope, serverRoot)
if err != nil {
return false, err
}
user.Scope = userHome
return derived, nil
}
func cleanUsername(s string) string {
// Remove any trailing space to avoid ending on -
s = strings.Trim(s, " ")
+45
View File
@@ -0,0 +1,45 @@
package settings
import (
"testing"
"github.com/filebrowser/filebrowser/v2/users"
)
// 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"}
user := &users.User{Username: "alice", Scope: "."}
derived, err := s.CreateUserHome(user, t.TempDir(), false)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !derived {
t.Error("expected the scope to be reported as derived")
}
if user.Scope != "/users/alice" {
t.Errorf("expected derived scope /users/alice, got %q", user.Scope)
}
}
// 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, and must
// not be reported as derived: it is legitimate for several users to share it.
func TestCreateUserHomePreservesExplicitScope(t *testing.T) {
s := &Settings{CreateUserDir: true, UserHomeBasePath: "/users"}
user := &users.User{Username: "alice", Scope: "/custom"}
derived, err := s.CreateUserHome(user, t.TempDir(), true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if derived {
t.Error("an explicit scope must not be reported as derived")
}
if user.Scope != "/custom" {
t.Errorf("explicit scope should be preserved, got %q", user.Scope)
}
}
+6 -1
View File
@@ -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
+50
View File
@@ -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)
}
}
}
+32
View File
@@ -1,6 +1,7 @@
package users
import (
"errors"
"sync"
"time"
@@ -25,6 +26,7 @@ type Store interface {
Gets(baseScope string, followExternalSymlinks bool) ([]*User, error)
Update(user *User, fields ...string) error
Save(user *User) error
SaveProvisioned(user *User, derivedScope bool) error
Delete(id interface{}) error
LastUpdate(id uint) int64
}
@@ -34,6 +36,10 @@ type Storage struct {
back StorageBackend
updated map[uint]int64
mux sync.RWMutex
// provision serializes the scope-collision check and the save of newly
// provisioned users, which must not interleave. See SaveProvisioned.
provision sync.Mutex
}
// NewStorage creates a users storage from a backend.
@@ -108,6 +114,32 @@ func (s *Storage) Save(user *User) error {
return s.back.Save(user)
}
// SaveProvisioned saves a user that is being provisioned (via signup, proxy
// auth or hook auth). When its scope was derived from the username, it first
// rejects the save if another user already owns that scope, so that distinct
// usernames cannot silently share one home directory.
//
// The check and the save are held under a single lock. Performing them as two
// independent operations lets two concurrent provisioning requests both observe
// a free scope and both save, leaving two users sharing one home directory.
func (s *Storage) SaveProvisioned(user *User, derivedScope bool) error {
if !derivedScope {
return s.Save(user)
}
s.provision.Lock()
defer s.provision.Unlock()
switch _, err := s.back.GetByScope(user.Scope); {
case err == nil:
return fberrors.ErrExist
case !errors.Is(err, fberrors.ErrNotExist):
return err
}
return s.Save(user)
}
// Delete allows you to delete a user by its name or username. The provided
// id must be a string for username lookup or a uint for id lookup. If id
// is neither, a ErrInvalidDataType will be returned.
+113
View File
@@ -1,4 +1,117 @@
package users
import (
"errors"
"strings"
"sync"
"testing"
"time"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
)
// Interface is implemented by storage
var _ Store = &Storage{}
// slowBackend is a minimal StorageBackend whose scope lookup is deliberately
// slow, so that an unsynchronized check-then-save reliably interleaves.
type slowBackend struct {
mu sync.Mutex
users []*User
delay time.Duration
}
func (b *slowBackend) GetByScope(scope string) (*User, error) {
time.Sleep(b.delay)
b.mu.Lock()
defer b.mu.Unlock()
for _, u := range b.users {
if strings.EqualFold(u.Scope, scope) {
return u, nil
}
}
return nil, fberrors.ErrNotExist
}
func (b *slowBackend) Save(u *User) error {
b.mu.Lock()
defer b.mu.Unlock()
b.users = append(b.users, u)
return nil
}
func (b *slowBackend) GetBy(interface{}) (*User, error) { return nil, fberrors.ErrNotExist }
func (b *slowBackend) Gets() ([]*User, error) { return b.users, nil }
func (b *slowBackend) Update(*User, ...string) error { return nil }
func (b *slowBackend) DeleteByID(uint) error { return nil }
func (b *slowBackend) DeleteByUsername(string) error { return nil }
func (b *slowBackend) CountAdmins() (int, error) { return 0, nil }
// Two usernames that normalize to the same home directory must not both be
// provisioned, even when their requests are handled concurrently: checking the
// scope and saving the user has to be a single atomic step.
func TestSaveProvisionedRejectsConcurrentScopeCollision(t *testing.T) {
back := &slowBackend{delay: 50 * time.Millisecond}
store := NewStorage(back)
errs := make([]error, 2)
var wg, ready sync.WaitGroup
ready.Add(2)
for i, username := range []string{"teamone-x", "teamone/x"} {
wg.Add(1)
go func(i int, username string) {
defer wg.Done()
// Only start once both goroutines are actually running, so that an
// unsynchronized implementation is guaranteed to interleave rather
// than to pass by scheduling luck.
ready.Done()
ready.Wait()
errs[i] = store.SaveProvisioned(&User{
Username: username,
Password: "pw",
Scope: "/users/teamone-x",
}, true)
}(i, username)
}
wg.Wait()
saved := 0
for _, err := range errs {
switch {
case err == nil:
saved++
case !errors.Is(err, fberrors.ErrExist):
t.Fatalf("unexpected error: %v", err)
}
}
if saved != 1 {
t.Fatalf("VULNERABLE: %d users provisioned into /users/teamone-x, want 1", saved)
}
if len(back.users) != 1 {
t.Fatalf("%d users stored, want 1", len(back.users))
}
}
// A scope that was not derived from the username (explicitly configured by an
// administrator or returned by an auth hook) may legitimately be shared, so it
// must not be subject to the collision check.
func TestSaveProvisionedAllowsSharedExplicitScope(t *testing.T) {
back := &slowBackend{}
store := NewStorage(back)
for _, username := range []string{"alice", "bob"} {
if err := store.SaveProvisioned(&User{
Username: username,
Password: "pw",
Scope: "/shared/team",
}, false); err != nil {
t.Fatalf("saving %q with an explicit shared scope: %v", username, err)
}
}
if len(back.users) != 2 {
t.Fatalf("%d users stored, want 2", len(back.users))
}
}
+1 -1
View File
@@ -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]
>