Compare commits

...
7 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
13 changed files with 386 additions and 85 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.
+6
View File
@@ -2,6 +2,12 @@
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
+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 }
@@ -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"
+3 -5
View File
@@ -192,16 +192,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 {
+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)
}
+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))
}
}