Compare commits

...
13 Commits
Author SHA1 Message Date
Henrique Dias f6fb8f6bf5 chore(release): 2.63.21 2026-07-26 10:02:11 +02:00
Henrique Dias e6d70cf24c fix(http): canonicalize paths before checking access rules (#6045) 2026-07-26 10:00:18 +02:00
Henrique Dias 41e2b1bbba docs: update CLAUDE.md 2026-07-26 09:58:40 +02:00
Henrique Dias 41b01a7404 chore: update Go deps 2026-07-26 08:01:32 +02:00
Henrique Dias 0dd8905886 Revert "chore(deps): update all non-major dependencies (#5946)"
This reverts commit 032271bafa.
2026-07-26 08:00:07 +02:00
renovate[bot] 032271bafa chore(deps): update all non-major dependencies (#5946) 2026-07-26 07:58:26 +02:00
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
29 changed files with 840 additions and 158 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 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.
+15
View File
@@ -2,6 +2,21 @@
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.21](https://github.com/filebrowser/filebrowser/compare/v2.63.20...v2.63.21) (2026-07-26)
### Bug Fixes
* **http:** canonicalize paths before checking access rules ([#6045](https://github.com/filebrowser/filebrowser/issues/6045)) ([e6d70cf](https://github.com/filebrowser/filebrowser/commit/e6d70cf24c0cd79a1787601dc99104ec7e7ca3ef))
### Reverts
* Revert "chore(deps): update all non-major dependencies (#5946)" ([0dd8905](https://github.com/filebrowser/filebrowser/commit/0dd89058867f87a7bc04aa7517d21528a280e27c)), references [#5946](https://github.com/filebrowser/filebrowser/issues/5946)
## [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
+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.
+3 -2
View File
@@ -160,12 +160,13 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
// 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 {
derivedScope, err := a.Settings.CreateUserHome(u, a.Server.Root, explicitScope)
if err != nil {
return nil, err
}
log.Printf("user: %s, home dir: [%s].", u.Username, u.Scope)
if err := a.Users.Save(u); 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 {
+3 -2
View File
@@ -50,11 +50,12 @@ func (a ProxyAuth) createUser(usr users.Store, setting *settings.Settings, srv *
user.Perm.Execute = false
user.Commands = []string{}
if err = setting.CreateUserHome(user, usr, srv.Root, false); err != nil {
var derivedScope bool
if derivedScope, err = setting.CreateUserHome(user, srv.Root, false); err != nil {
return nil, err
}
if err = usr.Save(user); err != nil {
if err = usr.SaveProvisioned(user, derivedScope); err != nil {
return nil, err
}
+20 -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 }
+34
View File
@@ -0,0 +1,34 @@
package files
import (
"path/filepath"
"runtime"
"strings"
"github.com/spf13/afero"
)
// CaseInsensitive reports whether the filesystem backing root treats file names
// case-insensitively, as NTFS, APFS, HFS+, exFAT and CIFS do. It creates a
// probe file and looks it up under a different case, mirroring how git detects
// core.ignoreCase.
//
// It probes rather than inferring from runtime.GOOS because neither direction
// holds: macOS can be formatted case-sensitively, and a Linux host commonly
// serves a case-insensitive mount. When the root cannot be written to, it falls
// back to the host's usual default rather than assuming case-sensitivity, since
// a read-only root is still exposed to the disclosure this guards against.
func CaseInsensitive(fs afero.Fs, root string) bool {
probe, err := afero.TempFile(fs, root, "fb-case-probe-")
if err != nil {
return runtime.GOOS == "windows" || runtime.GOOS == "darwin"
}
name := probe.Name()
probe.Close()
defer fs.Remove(name) //nolint:errcheck
dir, base := filepath.Split(name)
_, err = fs.Stat(filepath.Join(dir, strings.ToUpper(base)))
return err == nil
}
+44
View File
@@ -0,0 +1,44 @@
package files
import (
"strings"
"testing"
"github.com/spf13/afero"
)
// MemMapFs keys its entries by exact name, so it is case-sensitive.
func TestCaseInsensitiveReportsCaseSensitiveFs(t *testing.T) {
fs := afero.NewMemMapFs()
if err := fs.MkdirAll("/root", 0o755); err != nil {
t.Fatal(err)
}
if CaseInsensitive(fs, "/root") {
t.Error("CaseInsensitive() = true for a case-sensitive filesystem; want false")
}
assertNoProbeLeft(t, fs, "/root")
}
// Whatever the verdict, the probe file must not be left behind in the user's
// data directory.
func TestCaseInsensitiveRemovesProbe(t *testing.T) {
root := t.TempDir()
fs := afero.NewOsFs()
t.Logf("CaseInsensitive(%s) = %v", root, CaseInsensitive(fs, root))
assertNoProbeLeft(t, fs, root)
}
func assertNoProbeLeft(t *testing.T, fs afero.Fs, root string) {
t.Helper()
entries, err := afero.ReadDir(fs, root)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), "fb-case-probe-") {
t.Errorf("probe file left behind: %s", e.Name())
}
}
}
@@ -18,7 +18,7 @@
:data-dir="isDir"
:data-type="type"
:aria-label="name"
:aria-pressed="isSelected"
:aria-selected="isSelected"
:data-ext="getExtension(name).toLowerCase()"
@contextmenu="contextMenu"
>
+1 -1
View File
@@ -8,7 +8,7 @@
role="button"
tabindex="0"
:aria-label="item.name"
:aria-pressed="selected == item.url"
:aria-selected="selected == item.url"
:key="item.name"
v-for="item in items"
:data-url="item.url"
+14 -14
View File
@@ -4,7 +4,7 @@ go 1.25.0
require (
github.com/asdine/storm/v3 v3.2.1
github.com/asticode/go-astisub v0.41.0
github.com/asticode/go-astisub v0.42.0
github.com/disintegration/imaging v1.6.2
github.com/dsoprea/go-exif/v3 v3.0.1
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568
@@ -26,9 +26,9 @@ require (
github.com/stretchr/testify v1.11.1
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce
go.etcd.io/bbolt v1.5.0
golang.org/x/crypto v0.53.0
golang.org/x/image v0.43.0
golang.org/x/text v0.38.0
golang.org/x/crypto v0.54.0
golang.org/x/image v0.44.0
golang.org/x/text v0.40.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
)
@@ -39,7 +39,7 @@ require (
github.com/asticode/go-astikit v0.59.0 // indirect
github.com/asticode/go-astits v1.15.0 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.4 // indirect
github.com/bodgit/sevenzip v1.6.5 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
@@ -47,21 +47,21 @@ require (
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
github.com/ebitengine/purego v0.10.1 // indirect
github.com/ebitengine/purego v0.10.2 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/golang/geo v0.0.0-20260625163123-7c0e84413537 // indirect
github.com/golang/geo v0.0.0-20260713102120-857a528af641 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/klauspost/compress v1.19.0 // indirect
github.com/klauspost/compress v1.19.1 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/mikelolasagasti/xz v1.0.1 // indirect
github.com/minio/minlz v1.1.1 // indirect
github.com/minio/minlz v1.2.0 // indirect
github.com/nwaples/rardecode/v2 v2.2.5 // indirect
github.com/pelletier/go-toml/v2 v2.4.2 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pierrec/lz4/v4 v4.1.27 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
@@ -71,14 +71,14 @@ require (
github.com/spf13/cast v1.10.0 // indirect
github.com/stangelandcl/ppmd v0.1.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/ulikunitz/xz v0.5.16 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/net v0.57.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
+28 -28
View File
@@ -12,15 +12,15 @@ github.com/asticode/go-astikit v0.20.0/go.mod h1:h4ly7idim1tNhaVkdVBeXQZEE3L0xbl
github.com/asticode/go-astikit v0.30.0/go.mod h1:h4ly7idim1tNhaVkdVBeXQZEE3L0xblP7fCWbgwipF0=
github.com/asticode/go-astikit v0.59.0 h1:tjbwDym+MTSxqkAhJoHRZmHMXK6Jv4vGx+97FptKH6k=
github.com/asticode/go-astikit v0.59.0/go.mod h1:fV43j20UZYfXzP9oBn33udkvCvDvCDhzjVqoLFuuYZE=
github.com/asticode/go-astisub v0.41.0 h1:XFPIreVnpi9nPNVRmTdRuq4fr9XzGhgCRwpAaccnShM=
github.com/asticode/go-astisub v0.41.0/go.mod h1:WTkuSzFB+Bp7wezuSf2Oxulj5A8zu2zLRVFf6bIFQK8=
github.com/asticode/go-astisub v0.42.0 h1:IJuJJTQwCSFeY9bx1kTzdCwkIeG27wj4CAh6nHc+pvY=
github.com/asticode/go-astisub v0.42.0/go.mod h1:WTkuSzFB+Bp7wezuSf2Oxulj5A8zu2zLRVFf6bIFQK8=
github.com/asticode/go-astits v1.8.0/go.mod h1:DkOWmBNQpnr9mv24KfZjq4JawCFX1FCqjLVGvO0DygQ=
github.com/asticode/go-astits v1.15.0 h1:yRyCiUc8Jj4F7clt2GDxHghMpWuFL5rkaLuGUd2/0J4=
github.com/asticode/go-astits v1.15.0/go.mod h1:QSHmknZ51pf6KJdHKZHJTLlMegIrhega3LPWz3ND/iI=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
github.com/bodgit/sevenzip v1.6.4 h1:iHiVJfxbrB6RF4X+snI2MpVgNBKmVfGaTqZGNlMQIU0=
github.com/bodgit/sevenzip v1.6.4/go.mod h1:ZtNi5KNgHXeXg1G7WiF0IWSuFE2eG6lt/cTGlvuirO0=
github.com/bodgit/sevenzip v1.6.5 h1:7H7BxgmeX0j6UX42lH+KXQ92WgMQJ49DoocFdfHbCng=
github.com/bodgit/sevenzip v1.6.5/go.mod h1:GhuB6Lq1xCpP1sps+horjZ8lgiKPJcy2zUX3prla9wc=
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
@@ -58,8 +58,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003142440-7a1927d49d9d/go.mod h1:LV
github.com/dsoprea/go-utility/v2 v2.0.0-20221003160719-7bc88537c05e/go.mod h1:VZ7cB0pTjm1ADBWhJUOHESu4ZYy9JN+ZPqjfiW09EPU=
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje0z+3UQ5YjYiSRRzVdtamFpvBQXKwMglWqw=
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -82,8 +82,8 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20260625163123-7c0e84413537 h1:KeIaDS/+VEy/bhDYjG3Z78dOyLAU4HXcVxmd0WYHJTE=
github.com/golang/geo v0.0.0-20260625163123-7c0e84413537/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
github.com/golang/geo v0.0.0-20260713102120-857a528af641 h1:cpoobkgVGCE6bC5kJkOfwfM6hAtZuvoBjnCLECxG4AU=
github.com/golang/geo v0.0.0-20260713102120-857a528af641/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@@ -106,8 +106,8 @@ github.com/jellydator/ttlcache/v3 v3.4.1/go.mod h1:j7LO12PNghFg5+0v9budMAT4rDK4J
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid v1.2.0 h1:NMpwD2G9JSFOE1/TJjGSo5zG7Yb2bTe7eq1jH+irmeE=
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
@@ -130,14 +130,14 @@ github.com/mholt/archives v0.1.5 h1:Fh2hl1j7VEhc6DZs2DLMgiBNChUux154a1G+2esNvzQ=
github.com/mholt/archives v0.1.5/go.mod h1:3TPMmBLPsgszL+1As5zECTuKwKvIfj6YcwWPpeTAXF4=
github.com/mikelolasagasti/xz v1.0.1 h1:Q2F2jX0RYJUG3+WsM+FJknv+6eVjsjXNDV0KJXZzkD0=
github.com/mikelolasagasti/xz v1.0.1/go.mod h1:muAirjiOUxPRXwm9HdDtB3uoRPrGnL85XHtokL9Hcgc=
github.com/minio/minlz v1.1.1 h1:OGmft1V6AnI/Wme332U6bhG54nxEan+VFgkD7lat4KM=
github.com/minio/minlz v1.1.1/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec=
github.com/minio/minlz v1.2.0 h1:6IOBuiHg04QxvbFfgFLT/9sMaO/UhL7S+ApW1mK8q5A=
github.com/minio/minlz v1.2.0/go.mod h1:Ls9H7nlkASeCcdl5thjVD5Eraj6z+zGa7xtq57jIKD4=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/nwaples/rardecode/v2 v2.2.5 h1:L5doqgGfQwI7qADJMqnkrSB86rpPsqQDrHeO0HWa5JY=
github.com/nwaples/rardecode/v2 v2.2.5/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw=
github.com/pelletier/go-toml/v2 v2.4.2 h1:M2fKKbmyvI+hGId/D0W64qDBMVhJnNR10O5gIbMc//Q=
github.com/pelletier/go-toml/v2 v2.4.2/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pkg/profile v1.4.0/go.mod h1:NWz/XGvpEW1FyYQ7fCx4dqYBLlfTcE+A9FLAkNKqjFE=
@@ -190,8 +190,8 @@ github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSW
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce h1:fb190+cK2Xz/dvi9Hv8eCYJYvIGUTN2/KLq1pT6CjEc=
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4=
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.16 h1:ld6NyySjx5lowVKwJvMRLnW5nxKX/xnpSiFYZ/Lxur0=
github.com/ulikunitz/xz v0.5.16/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw=
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
@@ -213,11 +213,11 @@ go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH
go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -227,10 +227,10 @@ golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -242,14 +242,14 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
+5 -5
View File
@@ -106,6 +106,8 @@ func withUser(fn handleFunc) handleFunc {
if err != nil {
return http.StatusInternalServerError, err
}
canonicalizeRequestPath(r)
return fn(w, r, d)
}
}
@@ -192,16 +194,14 @@ var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int,
user.Password = pwd
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:
derivedScope, err := d.settings.CreateUserHome(user, d.server.Root, false)
if err != nil {
return http.StatusInternalServerError, err
}
log.Printf("new user: %s, home dir: [%s].", user.Username, user.Scope)
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 {
+9 -2
View File
@@ -35,6 +35,13 @@ type data struct {
// Check implements rules.Checker.
func (d *data) Check(path string) bool {
// Rules are written as "/"-separated virtual paths, but callers hand us
// paths built by the OS as well as ones taken from the request: afero.Walk
// and filepath.Join use "\" on Windows, where the filesystem also treats it
// as a separator. Canonicalize first so the authorization decision does not
// depend on which separator the caller happened to use.
path = slashClean(path)
// When the filesystem has been rebased (e.g. a public share rooted at a
// subdirectory), the incoming path is relative to that root. Resolve it
// back to the user's original scope before matching rules, otherwise rules
@@ -49,13 +56,13 @@ func (d *data) Check(path string) bool {
allow := true
for _, rule := range d.settings.Rules {
if rule.Matches(path) {
if rule.Matches(path, d.server.CaseInsensitiveFs) {
allow = rule.Allow
}
}
for _, rule := range d.user.Rules {
if rule.Matches(path) {
if rule.Matches(path, d.server.CaseInsensitiveFs) {
allow = rule.Allow
}
}
+3
View File
@@ -5,7 +5,9 @@ import (
"net/http"
"github.com/gorilla/mux"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
)
@@ -25,6 +27,7 @@ func NewHandler(
assetsFs fs.FS,
) (http.Handler, error) {
server.Clean()
server.CaseInsensitiveFs = files.CaseInsensitive(afero.NewOsFs(), server.Root)
r := mux.NewRouter()
r.Use(func(next http.Handler) http.Handler {
+4 -2
View File
@@ -47,8 +47,10 @@ func previewHandler(imgSvc ImgService, fileCache FileCache, enableThumbnails, re
}
file, err := files.NewFileInfo(&files.FileOptions{
Fs: d.user.Fs,
Path: "/" + vars["path"],
Fs: d.user.Fs,
// Preview reads its path from mux.Vars, not r.URL.Path, so it does
// not get the canonicalization withUser applies.
Path: slashClean(vars["path"]),
Modify: d.user.Perm.Modify,
Expand: true,
ReadHeader: d.server.TypeDetectionByHeader,
+7 -4
View File
@@ -52,14 +52,15 @@ var withHashFile = func(fn handleFunc) handleFunc {
return errToStatus(err), err
}
// share base path
basePath := link.Path
// share base path. Canonicalized because it roots both the rebased
// filesystem and checkerPrefix below, and a stored path that is not
// "/"-separated would make the two disagree on Windows.
basePath := slashClean(link.Path)
// file relative path
filePath := ""
if file.IsDir {
basePath = filepath.Clean(link.Path)
filePath = ifPath
}
@@ -109,7 +110,9 @@ func ifPathWithName(r *http.Request) (id, filePath string) {
case 1:
return r.URL.Path, "/"
default:
return pathElements[0], path.Join("/", path.Join(pathElements[1:]...))
// Public share routes do not pass through withUser, so canonicalize the
// share-relative path here instead.
return pathElements[0], slashClean(path.Join(pathElements[1:]...))
}
}
-7
View File
@@ -17,13 +17,6 @@ import (
"github.com/mholt/archives"
)
func slashClean(name string) string {
if name == "" || name[0] != '/' {
name = "/" + name
}
return gopath.Clean(name)
}
func parseQueryFiles(r *http.Request, f *files.FileInfo, _ *users.User) ([]string, error) {
var fileSlice []string
names := strings.Split(r.URL.Query().Get("files"), ",")
+2 -2
View File
@@ -221,8 +221,8 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
dst := r.URL.Query().Get("destination")
action := r.URL.Query().Get("action")
dst, err := url.QueryUnescape(dst)
dst = path.Clean("/" + dst)
src = path.Clean("/" + src)
dst = slashClean(dst)
src = slashClean(src)
if !d.Check(src) || !d.Check(dst) {
return http.StatusForbidden, nil
}
+139
View File
@@ -0,0 +1,139 @@
package fbhttp
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/filebrowser/filebrowser/v2/diskcache"
"github.com/filebrowser/filebrowser/v2/rules"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/users"
)
// denyRuleStorage builds a scoped storage whose global settings deny denyPath.
func denyRuleStorage(t *testing.T, userScope, denyPath string, perm users.Permissions, key []byte) *storage.Storage {
t.Helper()
st := scopedUserStorage(t, userScope, perm, key)
if err := st.Settings.Save(&settings.Settings{
Key: key,
Rules: []rules.Rule{{Path: denyPath, Allow: false}},
}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
return st
}
// Regression for GHSA-fgm5-pw99-w2p7: on a case-insensitive filesystem
// /Secret.txt and /secret.TXT name the same file, so a deny rule for one must
// cover the other. The rule check runs before any filesystem access, so the 403
// is asserted on every platform; the flag is what does the work, which the
// case-sensitive half of the test pins down.
func TestRuleDeniesCaseVariantWhenFsIsCaseInsensitive(t *testing.T) {
userScope := t.TempDir()
if err := os.WriteFile(filepath.Join(userScope, "Secret.txt"), []byte("SECRET"), 0o644); err != nil {
t.Fatal(err)
}
key := []byte("test-signing-key")
perm := users.Permissions{Download: true}
st := denyRuleStorage(t, userScope, "/Secret.txt", perm, key)
signed := signToken(t, perm, key)
get := func(path string, caseInsensitive bool) *httptest.ResponseRecorder {
req, _ := http.NewRequest(http.MethodGet, path, http.NoBody)
req.Header.Set("X-Auth", signed)
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{CaseInsensitiveFs: caseInsensitive}).ServeHTTP(rec, req)
return rec
}
t.Run("canonical path is denied either way", func(t *testing.T) {
for _, caseInsensitive := range []bool{false, true} {
if rec := get("/Secret.txt", caseInsensitive); rec.Code != http.StatusForbidden {
t.Errorf("GET /Secret.txt (caseInsensitive=%v) = %d; want 403", caseInsensitive, rec.Code)
}
}
})
t.Run("case variant is denied on a case-insensitive filesystem", func(t *testing.T) {
if rec := get("/secret.TXT", true); rec.Code != http.StatusForbidden {
t.Errorf("VULNERABLE: GET /secret.TXT = %d, body=%q; want 403", rec.Code, rec.Body.String())
}
})
t.Run("case variant is a distinct path on a case-sensitive filesystem", func(t *testing.T) {
if rec := get("/secret.TXT", false); rec.Code == http.StatusForbidden {
t.Error("GET /secret.TXT = 403 with folding off; the rule must not widen on a case-sensitive filesystem")
}
})
}
// Regression for GHSA-fgm5-pw99-w2p7: a path is canonicalized before it is
// matched against the rules, so a traversal sequence cannot reach a denied file
// by spelling its way there. gorilla/mux cleans forward-slash traversal before
// routing, so this is defense in depth on POSIX; on Windows the equivalent
// backslash form reaches the handler intact, which cleanSeparators covers.
func TestRuleDeniesTraversalToDeniedPath(t *testing.T) {
userScope := t.TempDir()
if err := os.MkdirAll(filepath.Join(userScope, "allow"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(userScope, "Secret.txt"), []byte("SECRET"), 0o644); err != nil {
t.Fatal(err)
}
key := []byte("test-signing-key")
perm := users.Permissions{Download: true}
st := denyRuleStorage(t, userScope, "/Secret.txt", perm, key)
req, _ := http.NewRequest(http.MethodGet, "/allow/../Secret.txt", http.NoBody)
req.Header.Set("X-Auth", signToken(t, perm, key))
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("VULNERABLE: GET /allow/../Secret.txt = %d, body=%q; want 403", rec.Code, rec.Body.String())
}
}
// Canonicalizing the request path must not drop a trailing separator: POST
// distinguishes "/dir/" (create a directory) from "/dir" (write a file), and
// PUT rejects the directory form outright.
func TestCanonicalizeRequestPathKeepsTrailingSlash(t *testing.T) {
userScope := t.TempDir()
key := []byte("test-signing-key")
perm := users.Permissions{Create: true, Modify: true}
st := scopedUserStorage(t, userScope, perm, key)
signed := signToken(t, perm, key)
t.Run("post creates a directory", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/newdir/", http.NoBody)
req.Header.Set("X-Auth", signed)
rec := httptest.NewRecorder()
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
info, err := os.Stat(filepath.Join(userScope, "newdir"))
if err != nil {
t.Fatalf("POST /newdir/ = %d, body=%q; directory not created: %v", rec.Code, rec.Body.String(), err)
}
if !info.IsDir() {
t.Error("POST /newdir/ created a file, not a directory")
}
})
t.Run("put rejects a directory path", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodPut, "/newdir/", http.NoBody)
req.Header.Set("X-Auth", signed)
rec := httptest.NewRecorder()
handle(resourcePutHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Errorf("PUT /newdir/ = %d; want 405", rec.Code)
}
})
}
+44
View File
@@ -6,12 +6,56 @@ import (
"net/http"
"net/url"
"os"
gopath "path"
"path/filepath"
"strings"
libErrors "github.com/filebrowser/filebrowser/v2/errors"
imgErrors "github.com/filebrowser/filebrowser/v2/img"
)
// slashClean canonicalizes a virtual path to the absolute, "/"-separated,
// lexically cleaned form that both the rule checker and the scoped filesystem
// expect.
//
// Paths reach us either verbatim from a request or built by the OS — afero.Walk
// and filepath.Join use "\" on Windows. There the filesystem resolves "\" as a
// separator while the rule checker treated it as an ordinary character, so
// "/allow\..\Secret.txt" evaded a rule for "/Secret.txt" and still opened it.
// Normalizing with the host's own separator makes both layers agree on which
// file a path names, and is a no-op on POSIX, where "\" is a legal character in
// a filename and must stay one.
func slashClean(name string) string {
return cleanSeparators(name, string(filepath.Separator))
}
// canonicalizeRequestPath rewrites the request path to its canonical virtual
// form, so that the filesystem operation, the hook, the stored share record and
// the thumbnail cache key all use the same string the rule check approved.
//
// A trailing separator is preserved: handlers distinguish "/dir/" from "/dir"
// to decide whether to create a directory, and gopath.Clean would drop it.
func canonicalizeRequestPath(r *http.Request) {
p := slashClean(r.URL.Path)
trailing := strings.HasSuffix(r.URL.Path, "/") || strings.HasSuffix(r.URL.Path, string(filepath.Separator))
if p != "/" && trailing {
p += "/"
}
r.URL.Path = p
}
// cleanSeparators is slashClean with the host separator passed in explicitly,
// so the Windows behaviour can be exercised on any platform.
func cleanSeparators(name, sep string) string {
if sep != "/" {
name = strings.ReplaceAll(name, sep, "/")
}
if name == "" || name[0] != '/' {
name = "/" + name
}
return gopath.Clean(name)
}
func renderJSON(w http.ResponseWriter, _ *http.Request, data interface{}) (int, error) {
marsh, err := json.Marshal(data)
+45
View File
@@ -0,0 +1,45 @@
package fbhttp
import "testing"
// cleanSeparators takes the host separator explicitly so the Windows behaviour
// can be asserted from any platform. See GHSA-fgm5-pw99-w2p7: on Windows a
// backslash is a path separator the filesystem resolves but the rule checker
// used to treat as an ordinary character, so "/allow\..\Secret.txt" evaded a
// rule for "/Secret.txt" and still opened it.
func TestCleanSeparators(t *testing.T) {
t.Parallel()
cases := []struct {
name string
in string
sep string
want string
}{
// Windows: a backslash is a separator and must be resolved before the
// path is matched against a rule.
{"windows traversal", `/allow\..\Secret.txt`, `\`, "/Secret.txt"},
{"windows leading backslash", `\Secret.txt`, `\`, "/Secret.txt"},
{"windows mixed separators", `/a/b\..\..\c`, `\`, "/c"},
{"windows already canonical", "/Secret.txt", `\`, "/Secret.txt"},
{"windows relative", `allow\..\Secret.txt`, `\`, "/Secret.txt"},
{"windows empty", "", `\`, "/"},
// POSIX: a backslash is a legal filename character and must survive, or
// files named with one become unreachable.
{"posix backslash is a filename character", `/a\b.txt`, "/", `/a\b.txt`},
{"posix traversal", "/allow/../Secret.txt", "/", "/Secret.txt"},
{"posix relative", "Secret.txt", "/", "/Secret.txt"},
{"posix multiple slashes", "//a///b", "/", "/a/b"},
{"posix empty", "", "/", "/"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := cleanSeparators(tc.in, tc.sep); got != tc.want {
t.Errorf("cleanSeparators(%q, %q) = %q; want %q", tc.in, tc.sep, got, tc.want)
}
})
}
}
+16 -4
View File
@@ -25,17 +25,29 @@ func MatchHidden(path string) bool {
return path != "" && strings.HasPrefix(filepath.Base(path), ".")
}
// Matches matches a path against a rule.
func (r *Rule) Matches(path string) bool {
// Matches matches a path against a rule. When fold is true the comparison is
// case-insensitive: on a case-insensitive filesystem two paths differing only
// in case name the same file, so a rule written for one spelling has to cover
// the others or it can be trivially evaded.
//
// Regex rules are never folded. An admin-authored pattern means what it says,
// and lowering its input would silently change it; use (?i) for those.
func (r *Rule) Matches(path string, fold bool) bool {
if r.Regex {
return r.Regexp.MatchString(path)
}
if path == r.Path {
rulePath := r.Path
if fold {
path = strings.ToLower(path)
rulePath = strings.ToLower(rulePath)
}
if path == rulePath {
return true
}
prefix := r.Path
prefix := rulePath
if prefix != "/" && !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
+49 -10
View File
@@ -9,30 +9,69 @@ func TestRuleMatches(t *testing.T) {
name string
rulePath string
testPath string
fold bool
want bool
}{
{"exact match", "/uploads", "/uploads", true},
{"child path", "/uploads", "/uploads/file.txt", true},
{"sibling prefix", "/uploads", "/uploads_backup/secret.txt", false},
{"root rule", "/", "/anything", true},
{"trailing slash rule", "/uploads/", "/uploads/file.txt", true},
{"trailing slash no sibling", "/uploads/", "/uploads_backup/file.txt", false},
{"nested child", "/data/shared", "/data/shared/docs/file.txt", true},
{"nested sibling", "/data/shared", "/data/shared_private/file.txt", false},
{"exact match", "/uploads", "/uploads", false, true},
{"child path", "/uploads", "/uploads/file.txt", false, true},
{"sibling prefix", "/uploads", "/uploads_backup/secret.txt", false, false},
{"root rule", "/", "/anything", false, true},
{"trailing slash rule", "/uploads/", "/uploads/file.txt", false, true},
{"trailing slash no sibling", "/uploads/", "/uploads_backup/file.txt", false, false},
{"nested child", "/data/shared", "/data/shared/docs/file.txt", false, true},
{"nested sibling", "/data/shared", "/data/shared_private/file.txt", false, false},
// On a case-insensitive filesystem /Secret.txt and /secret.TXT name the
// same file, so a rule for one must cover the other. See
// GHSA-fgm5-pw99-w2p7.
{"case variant not folded", "/Secret.txt", "/secret.TXT", false, false},
{"case variant folded", "/Secret.txt", "/secret.TXT", true, true},
{"case variant child folded", "/Private", "/private/notes.txt", true, true},
{"exact match folded", "/uploads", "/uploads", true, true},
// Folding must not widen a rule past its own path segment.
{"sibling prefix folded", "/uploads", "/UPLOADS_backup/secret.txt", true, false},
{"nested sibling folded", "/data/shared", "/data/SHARED_private/x", true, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
r := &Rule{Path: tc.rulePath}
got := r.Matches(tc.testPath)
got := r.Matches(tc.testPath, tc.fold)
if got != tc.want {
t.Errorf("Rule{Path: %q}.Matches(%q) = %v; want %v", tc.rulePath, tc.testPath, got, tc.want)
t.Errorf("Rule{Path: %q}.Matches(%q, fold=%v) = %v; want %v",
tc.rulePath, tc.testPath, tc.fold, got, tc.want)
}
})
}
}
// A regex rule is authored by an administrator and means exactly what it says,
// so folding must not reach it: the admin opts in with (?i) instead.
func TestRuleMatchesRegexIgnoresFold(t *testing.T) {
t.Parallel()
cases := []struct {
raw string
path string
want bool
}{
{`^/Secret\.txt$`, "/Secret.txt", true},
{`^/Secret\.txt$`, "/secret.TXT", false},
{`(?i)^/Secret\.txt$`, "/secret.TXT", true},
}
for _, tc := range cases {
for _, fold := range []bool{false, true} {
r := &Rule{Regex: true, Regexp: &Regexp{Raw: tc.raw}}
if got := r.Matches(tc.path, fold); got != tc.want {
t.Errorf("Rule{Regexp: %q}.Matches(%q, fold=%v) = %v; want %v",
tc.raw, tc.path, fold, got, tc.want)
}
}
}
}
func TestMatchHidden(t *testing.T) {
cases := map[string]bool{
"/": false,
+10 -17
View File
@@ -11,7 +11,6 @@ import (
"github.com/spf13/afero"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/users"
)
@@ -48,31 +47,25 @@ func (s *Settings) MakeUserDir(username, userScope, serverRoot string) (string,
// 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
// 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 err
return false, 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
return derived, nil
}
func cleanUsername(s string) string {
+12 -41
View File
@@ -1,73 +1,44 @@
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 {
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)
}
}
// 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.
// 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"}
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 {
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)
}
+5
View File
@@ -63,6 +63,11 @@ type Server struct {
AuthHook string `json:"authHook"`
TokenExpirationTime string `json:"tokenExpirationTime"`
FollowExternalSymlinks bool `json:"followExternalSymlinks"`
// CaseInsensitiveFs is detected from Root at startup rather than
// configured, and tells the rule checker to match paths case-insensitively.
// It is never persisted.
CaseInsensitiveFs bool `json:"-"`
}
// Clean cleans any variables that might need cleaning.
+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))
}
}