feat: add SSO workspace, named shares and Debian release tooling

This commit is contained in:
SantaSpeen committed 2026-10-21 20:57:44 +03:00
1 parent 833d908884
commit 87bc33e675
106 files changed
+4160 -5637

No files matched your search

+7 -247
View File
@@ -1,27 +1,8 @@
package fbhttp
import (
"encoding/json"
"errors"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/golang-jwt/jwt/v5/request"
fbAuth "github.com/filebrowser/filebrowser/v2/auth"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
)
const (
DefaultTokenExpirationTime = time.Hour * 2
maxAuthBodySize = 1 << 20 // 1 MiB
"net/http"
)
type userInfo struct {
@@ -39,248 +20,27 @@ type userInfo struct {
AceEditorTheme string `json:"aceEditorTheme"`
}
type authToken struct {
User userInfo `json:"user"`
jwt.RegisteredClaims
}
type extractor []string
func (e extractor) ExtractToken(r *http.Request) (string, error) {
token, _ := request.HeaderExtractor{"X-Auth"}.ExtractToken(r)
// Checks if the token isn't empty and if it contains two dots.
// The former prevents incompatibility with URLs that previously
// used basic auth.
if token != "" && strings.Count(token, ".") == 2 {
return token, nil
}
if r.Method == http.MethodGet {
cookie, _ := r.Cookie("auth")
if cookie != nil && strings.Count(cookie.Value, ".") == 2 {
return cookie.Value, nil
}
}
return "", request.ErrNoTokenInRequest
}
func renewableErr(err error, r *http.Request, d *data, tk *authToken) bool {
if d.settings.AuthMethod != fbAuth.MethodProxyAuth || err == nil {
return false
}
if d.settings.LogoutPage == settings.DefaultLogoutPage {
return false
}
if !errors.Is(err, jwt.ErrTokenExpired) {
return false
}
// The expiration is only waived because the trusted proxy, not the token,
// decides when the session ends. Require the proxy to still assert the same
// identity on this request, otherwise a token that leaked before it expired
// would authenticate on its own forever.
return proxyAsserts(r, d, tk.User.ID)
}
// proxyAsserts reports whether the proxy-auth header on r identifies the user
// the token was issued for. The username is resolved through the user store, so
// that it is matched exactly as a regular proxy login would match it.
func proxyAsserts(r *http.Request, d *data, id uint) bool {
auther, err := d.store.Auth.Get(fbAuth.MethodProxyAuth)
if err != nil {
return false
}
proxy, ok := auther.(*fbAuth.ProxyAuth)
if !ok || proxy.Header == "" {
return false
}
username := r.Header.Get(proxy.Header)
if username == "" {
return false
}
user, err := d.store.Users.Get(d.server.Root, d.server.FollowExternalSymlinks, username)
if err != nil {
return false
}
return user.ID == id
}
func withUser(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
keyFunc := func(_ *jwt.Token) (interface{}, error) {
return d.settings.Key, nil
}
var tk authToken
p := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), jwt.WithExpirationRequired())
token, err := request.ParseFromRequest(r, &extractor{}, keyFunc, request.WithClaims(&tk), request.WithParser(p))
if (err != nil || !token.Valid) && !renewableErr(err, r, d, &tk) {
identity, ok := r.Context().Value(identityKey{}).(sessionIdentity)
if !ok {
return http.StatusUnauthorized, nil
}
expiresSoon := tk.ExpiresAt != nil && time.Until(tk.ExpiresAt.Time) < time.Hour
updated := tk.IssuedAt != nil && tk.IssuedAt.Unix() < d.store.Users.LastUpdate(tk.User.ID)
if expiresSoon || updated {
w.Header().Add("X-Renew-Token", "true")
}
d.user, err = d.store.Users.Get(d.server.Root, d.server.FollowExternalSymlinks, tk.User.ID)
var err error
d.user, err = d.store.Users.Get(d.server.Root, d.server.FollowExternalSymlinks, identity.ID)
if err != nil {
return http.StatusInternalServerError, err
return http.StatusUnauthorized, nil
}
applySSOIdentity(d.user, identity)
canonicalizeRequestPath(r)
return fn(w, r, d)
}
}
func withAdmin(fn handleFunc) handleFunc {
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if !d.user.Perm.Admin {
return http.StatusForbidden, nil
}
return fn(w, r, d)
})
}
func loginHandler(tokenExpireTime time.Duration) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, maxAuthBodySize)
}
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
if err != nil {
return http.StatusInternalServerError, err
}
user, err := auther.Auth(r, d.store.Users, d.settings, d.server)
switch {
case errors.Is(err, os.ErrPermission):
return http.StatusForbidden, nil
case err != nil:
return http.StatusInternalServerError, err
}
return printToken(w, r, d, user, tokenExpireTime)
}
}
type signupBody struct {
Username string `json:"username"`
Password string `json:"password"`
}
var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
if !d.settings.Signup {
return http.StatusMethodNotAllowed, nil
}
if r.Body == nil {
return http.StatusBadRequest, nil
}
r.Body = http.MaxBytesReader(w, r.Body, maxAuthBodySize)
info := &signupBody{}
err := json.NewDecoder(r.Body).Decode(info)
if err != nil {
return http.StatusBadRequest, err
}
if info.Password == "" || info.Username == "" {
return http.StatusBadRequest, nil
}
user := &users.User{
Username: info.Username,
}
d.settings.Defaults.Apply(user)
// Users signed up via the signup handler should never become admins, even
// if that is the default permission.
user.Perm.Admin = false
// Self-registered users should not inherit execution capabilities from
// default settings, regardless of what the administrator has configured
// as the default. Execution rights must be explicitly granted by an admin.
user.Perm.Execute = false
user.Commands = []string{}
pwd, err := users.ValidateAndHashPwd(info.Password, d.settings.MinimumPasswordLength)
if err != nil {
return http.StatusBadRequest, err
}
user.Password = pwd
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.SaveProvisioned(user, derivedScope)
if errors.Is(err, fberrors.ErrExist) {
return http.StatusConflict, err
} else if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func renewHandler(tokenExpireTime time.Duration) handleFunc {
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
w.Header().Set("X-Renew-Token", "false")
return printToken(w, r, d, d.user, tokenExpireTime)
})
}
func printToken(w http.ResponseWriter, _ *http.Request, d *data, user *users.User, tokenExpirationTime time.Duration) (int, error) {
claims := &authToken{
User: userInfo{
ID: user.ID,
Locale: user.Locale,
ViewMode: user.ViewMode,
SingleClick: user.SingleClick,
RedirectAfterCopyMove: user.RedirectAfterCopyMove,
Perm: user.Perm,
LockPassword: user.LockPassword,
Commands: user.Commands,
HideDotfiles: user.HideDotfiles,
DateFormat: user.DateFormat,
Username: user.Username,
AceEditorTheme: user.AceEditorTheme,
},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(tokenExpirationTime)),
Issuer: "File Browser",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(d.settings.Key)
if err != nil {
return http.StatusInternalServerError, err
}
w.Header().Set("Content-Type", "text/plain")
if _, err := w.Write([]byte(signed)); err != nil {
return http.StatusInternalServerError, err
}
return 0, nil
}
-151
View File
@@ -1,151 +0,0 @@
package fbhttp
import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/asdine/storm/v3"
"github.com/golang-jwt/jwt/v5"
fbAuth "github.com/filebrowser/filebrowser/v2/auth"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage/bolt"
"github.com/filebrowser/filebrowser/v2/users"
)
// Regression for the username-normalization home-directory collision
// (GHSA-7rc3-g7h6-22m7): with Signup and CreateUserDir enabled, two distinct
// usernames that cleanUsername() normalizes to the same directory must not be
// handed the same home directory. The second registration is rejected.
func TestSignupRejectsCollidingNormalizedScope(t *testing.T) {
root := t.TempDir()
db, err := storm.Open(filepath.Join(t.TempDir(), "db"))
if err != nil {
t.Fatalf("failed to open db: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
st, err := bolt.NewStorage(db)
if err != nil {
t.Fatalf("failed to get storage: %v", err)
}
if err := st.Settings.Save(&settings.Settings{
Key: []byte("test-signing-key"),
Signup: true,
CreateUserDir: true,
UserHomeBasePath: "/users",
MinimumPasswordLength: 1,
}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
server := &settings.Server{Root: root}
signup := func(username string) *httptest.ResponseRecorder {
body := `{"username":"` + username + `","password":"CollidePw12345!"}`
req, _ := http.NewRequest(http.MethodPost, "/signup", strings.NewReader(body))
rec := httptest.NewRecorder()
handle(signupHandler, "", st, server).ServeHTTP(rec, req)
return rec
}
// Victim registers first and gets /users/teamone-x.
if rec := signup("teamone-x"); rec.Code != http.StatusOK {
t.Fatalf("first signup: expected 200, got %d body=%q", rec.Code, rec.Body.String())
}
// Attacker picks a distinct username that normalizes to the same scope.
if rec := signup("teamone/x"); rec.Code != http.StatusConflict {
t.Fatalf("VULNERABLE: colliding signup expected 409, got %d body=%q", rec.Code, rec.Body.String())
}
// The shared scope must still be owned solely by the first user.
owner, err := st.Users.GetByScope("/users/teamone-x")
if err != nil {
t.Fatalf("expected first user to own the scope: %v", err)
}
if owner.Username != "teamone-x" {
t.Fatalf("scope owner = %q, want teamone-x", owner.Username)
}
}
// Regression for GHSA-v3jv-rmh2-635j: under proxy auth with a non-default
// logout page the JWT expiration is waived, because the proxy owns the session
// lifetime. That exception used to apply to every route on the strength of the
// token alone, so a token stolen before it expired kept working — and could be
// renewed — indefinitely. The proxy must still assert the same identity.
func TestExpiredTokenNeedsProxyAssertion(t *testing.T) {
const proxyHeader = "X-Fb-User"
key := []byte("test-signing-key")
perm := users.Permissions{Download: true}
st := scopedUserStorage(t, t.TempDir(), perm, key)
if err := st.Settings.Save(&settings.Settings{
Key: key,
AuthMethod: fbAuth.MethodProxyAuth,
LogoutPage: "/logged-out",
}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
if err := st.Auth.Save(&fbAuth.ProxyAuth{Header: proxyHeader}); err != nil {
t.Fatalf("failed to save auther: %v", err)
}
expired := &authToken{
User: userInfo{ID: 1, Username: "u", Perm: perm},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now().Add(-2 * time.Hour)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
},
}
expiredToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, expired).SignedString(key)
if err != nil {
t.Fatalf("failed to sign token: %v", err)
}
protected := withUser(func(w http.ResponseWriter, _ *http.Request, _ *data) (int, error) {
_, writeErr := w.Write([]byte("protected"))
return 0, writeErr
})
get := func(token, proxyUser string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(http.MethodGet, "/", http.NoBody)
req.Header.Set("X-Auth", token)
if proxyUser != "" {
req.Header.Set(proxyHeader, proxyUser)
}
rec := httptest.NewRecorder()
handle(protected, "", st, &settings.Server{}).ServeHTTP(rec, req)
return rec
}
t.Run("expired token alone is rejected", func(t *testing.T) {
if rec := get(expiredToken, ""); rec.Code != http.StatusUnauthorized {
t.Errorf("VULNERABLE: expired token without the proxy header = %d, body=%q; want 401", rec.Code, rec.Body.String())
}
})
t.Run("expired token for another identity is rejected", func(t *testing.T) {
if rec := get(expiredToken, "someone-else"); rec.Code != http.StatusUnauthorized {
t.Errorf("VULNERABLE: expired token with a foreign proxy identity = %d; want 401", rec.Code)
}
})
t.Run("expired token the proxy still asserts is accepted", func(t *testing.T) {
if rec := get(expiredToken, "u"); rec.Code != http.StatusOK {
t.Errorf("expired token asserted by the proxy = %d, body=%q; want 200", rec.Code, rec.Body.String())
}
})
t.Run("valid token needs no assertion", func(t *testing.T) {
if rec := get(signToken(t, perm, key), ""); rec.Code != http.StatusOK {
t.Errorf("valid token = %d, body=%q; want 200", rec.Code, rec.Body.String())
}
})
}
+2 -1
View File
@@ -92,7 +92,8 @@ func handle(fn handleFunc, prefix string, store *storage.Storage, server *settin
settings, err := store.Settings.Get()
if err != nil {
log.Fatalf("ERROR: couldn't get settings: %v\n", err)
log.Printf("ERROR: couldn't get settings: %v", err)
http.Error(w, "Settings temporarily unavailable", http.StatusServiceUnavailable)
return
}
+3 -8
View File
@@ -26,13 +26,15 @@ func NewHandler(
server *settings.Server,
assetsFs fs.FS,
) (http.Handler, error) {
server.EnableExec = false
server.FollowExternalSymlinks = false
server.Clean()
server.CaseInsensitiveFs = files.CaseInsensitive(afero.NewOsFs(), server.Root)
r := mux.NewRouter()
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'unsafe-inline';`)
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'`)
next.ServeHTTP(w, r)
})
})
@@ -48,14 +50,8 @@ func NewHandler(
api := r.PathPrefix("/api").Subrouter()
tokenExpirationTime := server.GetTokenExpirationTime(DefaultTokenExpirationTime)
api.Handle("/login", monkey(loginHandler(tokenExpirationTime), ""))
api.Handle("/signup", monkey(signupHandler, ""))
api.Handle("/renew", monkey(renewHandler(tokenExpirationTime), ""))
users := api.PathPrefix("/users").Subrouter()
users.Handle("", monkey(usersGetHandler, "")).Methods("GET")
users.Handle("", monkey(userPostHandler, "")).Methods("POST")
users.Handle("/{id:[0-9]+}", monkey(userPutHandler, "")).Methods("PUT")
users.Handle("/{id:[0-9]+}", monkey(userGetHandler, "")).Methods("GET")
users.Handle("/{id:[0-9]+}", monkey(userDeleteHandler, "")).Methods("DELETE")
@@ -85,7 +81,6 @@ func NewHandler(
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
api.PathPrefix("/preview/{size}/{path:.*}").
Handler(monkey(previewHandler(imgSvc, fileCache, server.EnableThumbnails, server.ResizePreview), "/api/preview")).Methods("GET")
api.PathPrefix("/command").Handler(monkey(commandsHandler, "/api/command")).Methods("GET")
api.PathPrefix("/search").Handler(monkey(searchHandler, "/api/search")).Methods("GET")
api.PathPrefix("/subtitle").Handler(monkey(subtitleHandler, "/api/subtitle")).Methods("GET")
+5 -1
View File
@@ -9,6 +9,7 @@ import (
"os"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
@@ -23,6 +24,9 @@ import (
// path separator "/", which would manufacture an entry like "../../evil.sh" that
// escapes the extraction directory on the downloader's machine.
func TestRawArchiveDoesNotManufactureTraversal(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX filenames containing backslashes cannot be represented on Windows")
}
root := t.TempDir()
userScope := filepath.Join(root, "user")
if err := os.MkdirAll(filepath.Join(userScope, "ziptest"), 0o755); err != nil {
@@ -43,7 +47,7 @@ func TestRawArchiveDoesNotManufactureTraversal(t *testing.T) {
signed := signToken(t, perm, key)
req, _ := http.NewRequest(http.MethodGet, "/ziptest?algo=zip", http.NoBody)
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
+1 -1
View File
@@ -29,7 +29,7 @@ func TestResourceChecksumRequiresDownloadPermission(t *testing.T) {
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))
req = authorizeTestRequest(req, signToken(t, perm, key))
rec := httptest.NewRecorder()
handle(resourceGetHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
return rec
+2 -2
View File
@@ -35,7 +35,7 @@ func TestResourceRecursiveListsTree(t *testing.T) {
handler, token := recursiveTestHandler(t, userScope)
req, _ := http.NewRequest(http.MethodGet, "/api/resources/recursive/target", http.NoBody)
req.Header.Set("X-Auth", token)
req = authorizeTestRequest(req, token)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
@@ -71,7 +71,7 @@ func TestResourceRecursiveStopsWhenClientDisconnects(t *testing.T) {
cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "/api/resources/recursive/target", http.NoBody)
req.Header.Set("X-Auth", token)
req = authorizeTestRequest(req, token)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
+6 -19
View File
@@ -7,10 +7,8 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/asdine/storm/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/diskcache"
@@ -74,7 +72,7 @@ func TestResourceCopyDoesNotDereferenceEscapingSymlink(t *testing.T) {
t.Run("direct raw read is forbidden", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/srcdir/link.txt", http.NoBody)
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
if rec.Code == http.StatusOK {
@@ -88,7 +86,7 @@ func TestResourceCopyDoesNotDereferenceEscapingSymlink(t *testing.T) {
q.Set("action", "copy")
q.Set("destination", "/dstdir")
req.URL.RawQuery = q.Encode()
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(resourcePatchHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
@@ -104,18 +102,7 @@ func TestResourceCopyDoesNotDereferenceEscapingSymlink(t *testing.T) {
func signToken(t *testing.T, perm users.Permissions, key []byte) string {
t.Helper()
claims := &authToken{
User: userInfo{ID: 1, Username: "u", Perm: perm},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
t.Fatalf("failed to sign token: %v", err)
}
return signed
return testSession(1, "u", perm.Admin)
}
// scopedUserStorage returns a storage whose single user (ID 1) is scoped to
@@ -172,7 +159,7 @@ func TestResourcePostRejectsDanglingSymlinkWriteEscape(t *testing.T) {
signed := signToken(t, perm, key)
req, _ := http.NewRequest(http.MethodPost, "/evil?override=true", strings.NewReader("http-outside"))
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
@@ -214,7 +201,7 @@ func TestResourcePostCleanupDoesNotDeleteThroughSymlink(t *testing.T) {
signed := signToken(t, perm, key)
req, _ := http.NewRequest(http.MethodPost, "/link/victim.txt", strings.NewReader("x"))
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
@@ -243,7 +230,7 @@ func TestResourcePostRunsUploadHooksForDirectories(t *testing.T) {
}
req, _ := http.NewRequest(http.MethodPost, "/created/", http.NoBody)
req.Header.Set("X-Auth", signToken(t, perm, key))
req = authorizeTestRequest(req, signToken(t, perm, key))
rec := httptest.NewRecorder()
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{EnableExec: true}).ServeHTTP(rec, req)
+4 -4
View File
@@ -45,7 +45,7 @@ func TestRuleDeniesCaseVariantWhenFsIsCaseInsensitive(t *testing.T) {
get := func(path string, caseInsensitive bool) *httptest.ResponseRecorder {
req, _ := http.NewRequest(http.MethodGet, path, http.NoBody)
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{CaseInsensitiveFs: caseInsensitive}).ServeHTTP(rec, req)
return rec
@@ -91,7 +91,7 @@ func TestRuleDeniesTraversalToDeniedPath(t *testing.T) {
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))
req = authorizeTestRequest(req, signToken(t, perm, key))
rec := httptest.NewRecorder()
handle(rawHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
@@ -113,7 +113,7 @@ func TestCanonicalizeRequestPathKeepsTrailingSlash(t *testing.T) {
t.Run("post creates a directory", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/newdir/", http.NoBody)
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(resourcePostHandler(diskcache.NewNoOp()), "", st, &settings.Server{}).ServeHTTP(rec, req)
@@ -128,7 +128,7 @@ func TestCanonicalizeRequestPathKeepsTrailingSlash(t *testing.T) {
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)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(resourcePutHandler, "", st, &settings.Server{}).ServeHTTP(rec, req)
+1 -1
View File
@@ -47,7 +47,7 @@ func TestRecursiveOperationsEnforceDescendantRules(t *testing.T) {
do := func(t *testing.T, st *storage.Storage, handler handleFunc, method, target string) *httptest.ResponseRecorder {
t.Helper()
req, _ := http.NewRequest(method, target, http.NoBody)
req.Header.Set("X-Auth", signToken(t, perm, key))
req = authorizeTestRequest(req, signToken(t, perm, key))
rec := httptest.NewRecorder()
handle(handler, "", st, &settings.Server{}).ServeHTTP(rec, req)
return rec
+47
View File
@@ -0,0 +1,47 @@
package fbhttp
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
// Filesystem regression tests exercise authorization through the same identity
// context as the SSO middleware, without accepting test credentials in production.
func testSession(id uint, name string, admin bool) string {
b, _ := json.Marshal(sessionIdentity{ID: id, Name: name, Admin: admin})
return base64.RawURLEncoding.EncodeToString(b)
}
func authorizeTestRequest(r *http.Request, token string) *http.Request {
r.Header.Set("X-Test-Identity", token)
var i sessionIdentity
b, _ := base64.RawURLEncoding.DecodeString(token)
_ = json.Unmarshal(b, &i)
return r.WithContext(context.WithValue(r.Context(), identityKey{}, i))
}
func TestSSORoles(t *testing.T) {
for _, tc := range []struct {
roles []string
admin bool
}{{[]string{"Master Admin"}, true}, {[]string{"FS Admin"}, true}, {[]string{"User", "SSO Admin"}, false}, {[]string{"master admin"}, false}, {nil, false}} {
if ssoAdmin(tc.roles) != tc.admin {
t.Errorf("unexpected access for %v", tc.roles)
}
}
}
func TestLegacyTokenCannotAuthenticate(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("X-Auth", "old.jwt.token")
r.AddCookie(&http.Cookie{Name: "auth", Value: "old.jwt.token"})
code, _ := withUser(func(http.ResponseWriter, *http.Request, *data) (int, error) {
t.Fatal("legacy credential accepted")
return 0, nil
})(httptest.NewRecorder(), r, &data{})
if code != 401 {
t.Fatalf("got %d", code)
}
}
+8 -4
View File
@@ -42,23 +42,27 @@ var settingsGetHandler = withAdmin(func(w http.ResponseWriter, r *http.Request,
return renderJSON(w, r, data)
})
var settingsPutHandler = withAdmin(func(_ http.ResponseWriter, r *http.Request, d *data) (int, error) {
var settingsPutHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
req := &settingsData{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
return http.StatusBadRequest, err
}
d.settings.Signup = req.Signup
d.settings.Signup = false
d.settings.CreateUserDir = req.CreateUserDir
d.settings.MinimumPasswordLength = req.MinimumPasswordLength
d.settings.UserHomeBasePath = req.UserHomeBasePath
d.settings.Defaults = req.Defaults
d.settings.Defaults.Perm.Admin = false
d.settings.Defaults.Perm.Execute = false
d.settings.Defaults.Commands = nil
d.settings.Rules = req.Rules
d.settings.Branding = req.Branding
d.settings.Tus = req.Tus
d.settings.Shell = req.Shell
d.settings.Commands = req.Commands
d.settings.Shell = nil
d.settings.Commands = nil
d.settings.HideLoginButton = req.HideLoginButton
err = d.store.Settings.Save(d.settings)
+18 -4
View File
@@ -6,8 +6,10 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/asdine/storm/v3"
"net/http"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
@@ -155,6 +157,8 @@ var shareDeleteHandler = withPermShare(func(_ http.ResponseWriter, r *http.Reque
return errToStatus(err), err
})
var shareKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{1,63}$`)
var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
// Only allow sharing paths that currently exist. Otherwise a share could be
// created for a non-existent path and would silently start exposing
@@ -170,26 +174,33 @@ var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request
var s *share.Link
var body share.CreateBody
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err)
}
defer r.Body.Close()
}
bytes := make([]byte, 6)
bytes := make([]byte, 16)
_, err := rand.Read(bytes)
if err != nil {
return http.StatusInternalServerError, err
}
str := base64.URLEncoding.EncodeToString(bytes)
str := base64.RawURLEncoding.EncodeToString(bytes)
if body.Key != "" {
if !shareKeyPattern.MatchString(body.Key) {
return http.StatusBadRequest, errors.New("key must be 2–64 ASCII letters, digits, underscores or hyphens, starting with a letter or digit")
}
str = body.Key
}
var expire int64 = 0
if body.Expires != "" {
num, err := strconv.Atoi(body.Expires)
if err != nil {
return http.StatusInternalServerError, err
if err != nil || num < 0 || num > 36500 {
return http.StatusBadRequest, errors.New("invalid expiry: use 0–36500 units")
}
var add time.Duration
@@ -231,6 +242,9 @@ var sharePostHandler = withPermShare(func(w http.ResponseWriter, r *http.Request
}
if err := d.store.Share.Save(s); err != nil {
if errors.Is(err, storm.ErrAlreadyExists) {
return http.StatusConflict, errors.New("this short link name is already in use")
}
return http.StatusInternalServerError, err
}
+43
View File
@@ -0,0 +1,43 @@
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"
)
func TestCustomShareKey(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "report.txt"), []byte("report"), 0600); err != nil {
t.Fatal(err)
}
perm := users.Permissions{Share: true, Download: true}
st := scopedUserStorage(t, root, perm, []byte("test-key"))
create := func(key string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", "/report.txt", strings.NewReader(`{"key":"`+key+`"}`))
r = authorizeTestRequest(r, signToken(t, perm, nil))
w := httptest.NewRecorder()
handle(sharePostHandler, "", st, &settings.Server{}).ServeHTTP(w, r)
return w
}
if w := create("quarterly-report"); w.Code != 200 || !strings.Contains(w.Body.String(), `"hash":"quarterly-report"`) {
t.Fatalf("create: %d %s", w.Code, w.Body.String())
}
if w := create("quarterly-report"); w.Code != http.StatusConflict {
t.Fatalf("duplicate accepted: %d", w.Code)
}
for _, key := range []string{"..", "a/b", "x", "has space", "-start"} {
if w := create(key); w.Code != 400 {
t.Fatalf("invalid key %q accepted: %d", key, w.Code)
}
}
if w := create(""); w.Code != 200 {
t.Fatalf("random key: %d", w.Code)
}
}
+3 -17
View File
@@ -8,10 +8,8 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/asdine/storm/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/share"
@@ -75,7 +73,7 @@ func TestAdminShareGetsHandlerMatchesOwnerScope(t *testing.T) {
if err != nil {
t.Fatalf("failed to construct request: %v", err)
}
req.Header.Set("X-Auth", signShareTestToken(t, admin.ID, admin.Username, adminPerm, key))
req = authorizeTestRequest(req, signShareTestToken(t, admin.ID, admin.Username, adminPerm, key))
rec := httptest.NewRecorder()
handle(shareGetsHandler, "", st, &settings.Server{Root: root}).ServeHTTP(rec, req)
@@ -113,7 +111,7 @@ func TestSharePostHandlerDoesNotLeakSecrets(t *testing.T) {
body := `{"password":"ShareSecret123!","expires":"24","unit":"hours"}`
req, _ := http.NewRequest(http.MethodPost, "/file.txt", strings.NewReader(body))
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
rec := httptest.NewRecorder()
handle(sharePostHandler, "", st, &settings.Server{Root: root}).ServeHTTP(rec, req)
@@ -148,17 +146,5 @@ func TestSharePostHandlerDoesNotLeakSecrets(t *testing.T) {
func signShareTestToken(t *testing.T, id uint, username string, perm users.Permissions, key []byte) string {
t.Helper()
claims := &authToken{
User: userInfo{ID: id, Username: username, Perm: perm},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
t.Fatalf("failed to sign token: %v", err)
}
return signed
return testSession(id, username, perm.Admin)
}
+391
View File
@@ -0,0 +1,391 @@
package fbhttp
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coreos/go-oidc/v3/oidc"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/users"
"golang.org/x/oauth2"
)
type identityKey struct{}
type sessionIdentity struct {
ID uint
Admin bool
Name string
}
type ssoClaims struct {
Subject string `json:"sub"`
Username string `json:"preferred_username"`
Roles []string `json:"roles"`
}
type loginAttempt struct {
Nonce, Verifier, ReturnTo string
Expires time.Time
}
type ssoSession struct {
sync.Mutex
Identity sessionIdentity
Expires time.Time
Touched time.Time
}
// SSO owns opaque server-side sessions (8h absolute, 30m idle). Roles are
// captured at login. Provider tokens are discarded after OIDC verification.
type SSO struct {
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
oauth oauth2.Config
origin, base, cookiePath string
secure bool
issuer string
store *storage.Storage
server *settings.Server
mu sync.Mutex
provision sync.Mutex
attempts map[string]loginAttempt
sessions map[[32]byte]*ssoSession
}
type SSOConfig struct {
Issuer string `json:"issuer"`
ClientID string `json:"clientID"`
ClientSecret string `json:"clientSecret"`
PublicURL string `json:"publicURL"`
}
func NewSSO(ctx context.Context, store *storage.Storage, server *settings.Server, config SSOConfig) (*SSO, error) {
issuer, clientID, secret, publicURL := config.Issuer, config.ClientID, config.ClientSecret, config.PublicURL
if issuer == "" || clientID == "" || secret == "" || publicURL == "" {
return nil, errors.New("SSO is required: run filebrowser init first")
}
u, err := url.Parse(publicURL)
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"))) {
return nil, errors.New("sso.publicURL must be an HTTPS URL (HTTP allowed only on loopback)")
}
i, err := url.Parse(issuer)
if err != nil || i.Host == "" || i.User != nil || (i.Scheme != "https" && !(i.Scheme == "http" && (i.Hostname() == "localhost" || i.Hostname() == "127.0.0.1"))) {
return nil, errors.New("sso.issuer must use HTTPS (HTTP allowed only on loopback)")
}
base := strings.TrimRight(u.Path, "/")
if base != strings.TrimRight(server.BaseURL, "/") {
return nil, errors.New("sso.publicURL path must match baseURL")
}
client := &http.Client{Timeout: 15 * time.Second}
ctx = oidc.ClientContext(ctx, client)
provider, err := oidc.NewProvider(ctx, strings.TrimRight(issuer, "/"))
if err != nil {
return nil, fmt.Errorf("SSO discovery: %w", err)
}
endpoint := provider.Endpoint()
endpoint.AuthStyle = oauth2.AuthStyleInHeader
s := &SSO{provider: provider, verifier: provider.Verifier(&oidc.Config{ClientID: clientID, SupportedSigningAlgs: []string{oidc.RS256}}), origin: u.Scheme + "://" + u.Host, base: base, cookiePath: base + "/", secure: u.Scheme == "https", issuer: strings.TrimRight(issuer, "/"), store: store, server: server, attempts: map[string]loginAttempt{}, sessions: map[[32]byte]*ssoSession{}}
s.oauth = oauth2.Config{ClientID: clientID, ClientSecret: secret, Endpoint: endpoint, RedirectURL: strings.TrimRight(publicURL, "/") + "/auth/callback", Scopes: []string{oidc.ScopeOpenID, "profile", "email"}}
// Remove usable local credentials when migrating an existing installation.
legacy, err := store.Users.Gets(server.Root, false)
if err != nil && !errors.Is(err, fberrors.ErrNotExist) {
return nil, err
}
for _, u := range legacy {
if u.Password != "!sso-disabled" || !u.LockPassword || u.Perm.Execute || len(u.Commands) > 0 || u.Perm.Admin {
u.Password = "!sso-disabled"
u.LockPassword = true
u.Perm.Admin = false
u.Perm.Execute = false
u.Commands = []string{}
if err = store.Users.Update(u, "Password", "LockPassword", "Perm", "Commands"); err != nil {
return nil, err
}
}
}
return s, nil
}
func randomSecret() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func (s *SSO) cookie(w http.ResponseWriter, name, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: s.cookiePath, HttpOnly: true, Secure: s.secure, SameSite: http.SameSiteLaxMode, MaxAge: maxAge})
}
func ssoAdmin(roles []string) bool {
for _, role := range roles {
if role == "Master Admin" || role == "FS Admin" {
return true
}
}
return false
}
func (s *SSO) cleanupLocked() {
now := time.Now()
for k, a := range s.attempts {
if now.After(a.Expires) {
delete(s.attempts, k)
}
}
for k, v := range s.sessions {
if !now.Before(v.Expires) {
delete(s.sessions, k)
}
}
}
func (s *SSO) login(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(405)
return
}
state := randomSecret()
a := loginAttempt{Nonce: randomSecret(), Verifier: oauth2.GenerateVerifier(), Expires: time.Now().Add(10 * time.Minute), ReturnTo: s.base + "/files/"}
if target := r.URL.Query().Get("return"); strings.HasPrefix(target, s.base+"/") && !strings.HasPrefix(target, "//") && !strings.ContainsAny(target, "\\\r\n") && !strings.HasPrefix(target, s.base+"/auth/") && !strings.HasPrefix(target, s.base+"/login") {
a.ReturnTo = target
}
s.mu.Lock()
s.cleanupLocked()
if len(s.attempts) >= 1000 {
s.mu.Unlock()
http.Error(w, "Too many sign-in attempts", 429)
return
}
s.attempts[state] = a
s.mu.Unlock()
s.cookie(w, "fb_login", state, 600)
http.Redirect(w, r, s.oauth.AuthCodeURL(state, oidc.Nonce(a.Nonce), oauth2.S256ChallengeOption(a.Verifier)), http.StatusFound)
}
func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(405)
return
}
if len(r.URL.Query()["state"]) != 1 || len(r.URL.Query()["code"]) != 1 {
http.Error(w, "Invalid callback parameters", 400)
return
}
state := r.URL.Query().Get("state")
c, err := r.Cookie("fb_login")
if err != nil || state == "" || c.Value != state {
http.Error(w, "Invalid sign-in state", 400)
return
}
s.mu.Lock()
a, ok := s.attempts[state]
delete(s.attempts, state)
s.mu.Unlock()
s.cookie(w, "fb_login", "", -1)
if !ok || time.Now().After(a.Expires) {
http.Error(w, "Sign-in expired. Please try again.", 400)
return
}
ctx := oidc.ClientContext(r.Context(), &http.Client{Timeout: 15 * time.Second})
token, err := s.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(a.Verifier))
if err != nil {
http.Error(w, "SSO code exchange failed", 401)
return
}
raw, _ := token.Extra("id_token").(string)
id, err := s.verifier.Verify(ctx, raw)
if err != nil || id.Nonce != a.Nonce {
http.Error(w, "Invalid SSO identity", 401)
return
}
if err = id.VerifyAccessToken(token.AccessToken); err != nil {
http.Error(w, "Invalid SSO token binding", 401)
return
}
var claims ssoClaims
if err = id.Claims(&claims); err != nil || claims.Subject == "" {
http.Error(w, "Invalid SSO claims", 401)
return
}
if token.Expiry.IsZero() || time.Now().After(token.Expiry) {
http.Error(w, "Invalid SSO expiry", 401)
return
}
identity, err := s.provisionUser(claims)
if err != nil {
http.Error(w, "Cannot provision SSO user", 500)
return
}
sid := randomSecret()
key := sha256.Sum256([]byte(sid))
s.mu.Lock()
s.cleanupLocked()
if len(s.sessions) >= 10000 {
s.mu.Unlock()
http.Error(w, "Too many sessions", 503)
return
}
if old, e := r.Cookie("fb_session"); e == nil {
delete(s.sessions, sha256.Sum256([]byte(old.Value)))
}
expires := time.Now().Add(8 * time.Hour)
s.sessions[key] = &ssoSession{Identity: identity, Expires: expires, Touched: time.Now()}
s.mu.Unlock()
s.cookie(w, "fb_session", sid, int(time.Until(expires).Seconds()))
http.Redirect(w, r, a.ReturnTo, http.StatusSeeOther)
}
func (s *SSO) provisionUser(c ssoClaims) (sessionIdentity, error) {
s.provision.Lock()
defer s.provision.Unlock()
// Stable subject IDs cannot claim a pre-existing local username or administrator.
// Namespace by issuer and subject, never by a renameable login or email.
identityHash := sha256.Sum256([]byte(s.issuer + "\x00" + c.Subject))
username := "sso:" + base64.RawURLEncoding.EncodeToString(identityHash[:])
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, username)
if errors.Is(err, fberrors.ErrNotExist) {
st, err := s.store.Settings.Get()
if err != nil {
return sessionIdentity{}, err
}
u = &users.User{Username: username, DisplayName: c.Username, Password: "!sso-disabled", LockPassword: true}
st.Defaults.Apply(u)
u.Perm.Admin = false
u.Perm.Execute = false
u.Commands = []string{}
u.ViewMode = users.ListViewMode
derived, err := st.CreateUserHome(u, s.server.Root, false)
if err != nil {
return sessionIdentity{}, err
}
if err = s.store.Users.SaveProvisioned(u, derived); err != nil {
return sessionIdentity{}, err
}
} else if err != nil {
return sessionIdentity{}, err
}
if u.DisplayName != c.Username {
u.DisplayName = c.Username
if err = s.store.Users.Update(u, "DisplayName"); err != nil {
return sessionIdentity{}, err
}
}
name := c.Username
if name == "" {
name = c.Subject
}
return sessionIdentity{ID: u.ID, Name: name, Admin: ssoAdmin(c.Roles)}, nil
}
func (s *SSO) identify(r *http.Request) (sessionIdentity, bool) {
c, err := r.Cookie("fb_session")
if err != nil {
return sessionIdentity{}, false
}
key := sha256.Sum256([]byte(c.Value))
s.mu.Lock()
session := s.sessions[key]
s.mu.Unlock()
if session == nil {
return sessionIdentity{}, false
}
session.Lock()
defer session.Unlock()
valid := time.Now().Before(session.Expires) && time.Since(session.Touched) < 30*time.Minute
if !valid {
s.mu.Lock()
delete(s.sessions, key)
s.mu.Unlock()
return sessionIdentity{}, false
}
session.Touched = time.Now()
return session.Identity, true
}
func (s *SSO) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, s.base)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/auth/") {
w.Header().Set("Cache-Control", "no-store")
}
if r.Method != "GET" && r.Method != "HEAD" && r.Method != "OPTIONS" {
origin := r.Header.Get("Origin")
if (origin != "" && origin != s.origin) || (origin == "" && r.Header.Get("X-FB-Request") != "1") || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
http.Error(w, "Cross-origin request rejected", 403)
return
}
}
switch p {
case "/auth/login":
s.login(w, r)
return
case "/auth/callback":
s.callback(w, r)
return
case "/auth/logout":
if r.Method != "POST" {
w.WriteHeader(405)
return
}
if c, e := r.Cookie("fb_session"); e == nil {
s.mu.Lock()
delete(s.sessions, sha256.Sum256([]byte(c.Value)))
s.mu.Unlock()
}
s.cookie(w, "fb_session", "", -1)
w.WriteHeader(204)
return
case "/api/login", "/api/signup", "/api/renew", "/api/command":
http.NotFound(w, r)
return
}
identity, ok := s.identify(r)
if p == "/api/session" {
if r.Method != "GET" {
w.WriteHeader(405)
return
}
if !ok {
w.WriteHeader(401)
return
}
u, err := s.store.Users.Get(s.server.Root, s.server.FollowExternalSymlinks, identity.ID)
if err != nil {
w.WriteHeader(401)
return
}
applySSOIdentity(u, identity)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ssoUserInfo(u))
return
}
if ok {
r = r.WithContext(context.WithValue(r.Context(), identityKey{}, identity))
}
next.ServeHTTP(w, r)
})
}
func applySSOIdentity(u *users.User, i sessionIdentity) {
u.Perm.Admin = i.Admin
if i.Admin {
u.Perm = users.Permissions{Admin: true, Create: true, Rename: true, Modify: true, Delete: true, Share: true, Download: true}
}
u.Perm.Execute = false
u.LockPassword = true
u.Commands = []string{}
u.Username = i.Name
}
func ssoUserInfo(u *users.User) userInfo {
return userInfo{ID: u.ID, Username: u.Username, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
}
+58
View File
@@ -0,0 +1,58 @@
package fbhttp
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/gorilla/mux"
)
func TestLocalAdminCannotOverrideSSORole(t *testing.T) {
st := scopedUserStorage(t, t.TempDir(), users.Permissions{Admin: true}, []byte("key"))
r := authorizeTestRequest(httptest.NewRequest("GET", "/", nil), testSession(1, "u", false))
w := httptest.NewRecorder()
handle(withAdmin(func(http.ResponseWriter, *http.Request, *data) (int, error) {
t.Fatal("local admin bypassed SSO role")
return 0, nil
}), "", st, &settings.Server{}).ServeHTTP(w, r)
if w.Code != 403 {
t.Fatalf("got %d", w.Code)
}
}
func TestLocalPasswordMutationsRejected(t *testing.T) {
st := scopedUserStorage(t, t.TempDir(), users.Permissions{}, []byte("key"))
for _, body := range []string{`{"what":"user","which":["password"],"data":{"id":1,"password":"password"}}`, `{"what":"user","which":["all"],"data":{"id":1}}`, `{"what":"user","which":["locale"],"data":null}`} {
r := httptest.NewRequest("PUT", "/users/1", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"id": "1"})
r = authorizeTestRequest(r, testSession(1, "u", true))
w := httptest.NewRecorder()
handle(userPutHandler, "", st, &settings.Server{}).ServeHTTP(w, r)
if w.Code != 400 && w.Code != 403 {
t.Fatalf("mutation accepted: %d", w.Code)
}
}
}
func TestIndexNonceChangesPerResponse(t *testing.T) {
f := fstest.MapFS{"public/index.html": &fstest.MapFile{Data: []byte(`<script>window.FileBrowser=[{[ .Json ]}];</script>`)}}
d := &data{settings: &settings.Settings{}, server: &settings.Server{}}
var previous string
for i := 0; i < 2; i++ {
w := httptest.NewRecorder()
status, err := handleWithStaticData(w, httptest.NewRequest("GET", "/", nil), d, f, "public/index.html", "text/html")
if err != nil || status != 0 {
t.Fatal(status, err)
}
csp := w.Header().Get("Content-Security-Policy")
if !strings.Contains(csp, "'nonce-") || csp == previous || !strings.Contains(w.Body.String(), "<script nonce=") {
t.Fatal("missing or reused nonce")
}
previous = csp
}
}
+156
View File
@@ -0,0 +1,156 @@
package fbhttp
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
jose "github.com/go-jose/go-jose/v4"
)
func TestOIDCSessionLifecycle(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "test"))
if err != nil {
t.Fatal(err)
}
var issuer, nonce, challenge string
roles := []string{"FS Admin"}
enabled := true
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/.well-known/openid-configuration":
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "userinfo_endpoint": issuer + "/userinfo", "jwks_uri": issuer + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}})
case "/keys":
_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "test", Algorithm: "RS256", Use: "sig"}}})
case "/token":
if err := r.ParseForm(); err != nil {
t.Error(err)
}
verifier := sha256.Sum256([]byte(r.Form.Get("code_verifier")))
if base64.RawURLEncoding.EncodeToString(verifier[:]) != challenge {
t.Error("PKCE mismatch")
}
id, secret, ok := r.BasicAuth()
if !ok || id != "client" || secret != "secret" {
t.Error("client authentication mismatch")
}
hash := sha256.Sum256([]byte("access"))
claims := map[string]any{"iss": issuer, "aud": "client", "sub": "subject-123", "preferred_username": "alice", "roles": roles, "nonce": nonce, "exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(), "at_hash": base64.RawURLEncoding.EncodeToString(hash[:16])}
b, _ := json.Marshal(claims)
signed, _ := signer.Sign(b)
token, _ := signed.CompactSerialize()
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access", "id_token": token, "token_type": "Bearer", "expires_in": 300})
case "/userinfo":
if !enabled {
w.WriteHeader(401)
return
}
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: "subject-123", Username: "alice", Roles: roles})
default:
w.WriteHeader(404)
}
}))
defer provider.Close()
issuer = provider.URL
root := t.TempDir()
st := scopedUserStorage(t, root, users.Permissions{Download: true}, []byte("test-key"))
if err = st.Settings.Save(&settings.Settings{Key: []byte("test-key"), Defaults: settings.UserDefaults{Scope: ".", Perm: users.Permissions{Download: true}}}); err != nil {
t.Fatal(err)
}
s, err := NewSSO(context.Background(), st, &settings.Server{Root: root}, SSOConfig{Issuer: issuer, ClientID: "client", ClientSecret: "secret", PublicURL: "http://127.0.0.1:9111"})
if err != nil {
t.Fatal(err)
}
h := s.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
login := httptest.NewRecorder()
h.ServeHTTP(login, httptest.NewRequest("GET", "/auth/login?return=%2Ffiles%2Fdocs", nil))
u, _ := url.Parse(login.Header().Get("Location"))
nonce = u.Query().Get("nonce")
challenge = u.Query().Get("code_challenge")
if u.Query().Get("code_challenge_method") != "S256" || nonce == "" {
t.Fatal("missing PKCE or nonce")
}
callback := httptest.NewRequest("GET", "/auth/callback?code=test&state="+u.Query().Get("state"), nil)
callback.AddCookie(login.Result().Cookies()[0])
response := httptest.NewRecorder()
h.ServeHTTP(response, callback)
if response.Code != 303 || response.Header().Get("Location") != "/files/docs" {
t.Fatalf("callback: %d %s", response.Code, response.Body.String())
}
var sessionCookie *http.Cookie
for _, c := range response.Result().Cookies() {
if c.Name == "fb_session" {
sessionCookie = c
}
}
if sessionCookie == nil || !sessionCookie.HttpOnly {
t.Fatal("missing HttpOnly session")
}
request := func(method, path string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, nil)
r.AddCookie(sessionCookie)
if method == "POST" {
r.Header.Set("X-FB-Request", "1")
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
check := request("GET", "/api/session")
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
t.Fatalf("session: %d %s", check.Code, check.Body.String())
}
roles = []string{"User"}
check = request("GET", "/api/session")
if check.Code != 200 || !strings.Contains(check.Body.String(), `"admin":true`) {
t.Fatal("login role snapshot changed during local session")
}
for _, p := range []string{"/api/login", "/api/signup", "/api/renew", "/api/command"} {
if request("POST", p).Code != 404 {
t.Fatalf("legacy endpoint %s is reachable", p)
}
}
bad := httptest.NewRequest("POST", "/auth/logout", nil)
bad.AddCookie(sessionCookie)
bad.Header.Set("Origin", "https://evil.example")
w := httptest.NewRecorder()
h.ServeHTTP(w, bad)
if w.Code != 403 {
t.Fatal("cross-origin logout accepted")
}
if request("POST", "/auth/logout").Code != 204 || request("GET", "/api/session").Code != 401 {
t.Fatal("logout did not revoke session")
}
w = httptest.NewRecorder()
h.ServeHTTP(w, callback)
if w.Code != 400 {
t.Fatal("callback replay accepted")
}
// Expired/idle sessions are rejected, even with an otherwise valid cookie.
sessionKey := sha256.Sum256([]byte(sessionCookie.Value))
for _, tc := range []struct{ expires, touched time.Time }{{time.Now().Add(-time.Second), time.Now()}, {time.Now().Add(time.Hour), time.Now().Add(-31 * time.Minute)}} {
s.mu.Lock()
s.sessions[sessionKey] = &ssoSession{Identity: sessionIdentity{ID: 2, Name: "alice"}, Expires: tc.expires, Touched: tc.touched}
s.mu.Unlock()
if request("GET", "/api/session").Code != 401 {
t.Fatal("expired/idle session accepted")
}
}
}
+27 -28
View File
@@ -14,21 +14,18 @@ import (
"path"
"path/filepath"
"strings"
"sync"
"github.com/filebrowser/filebrowser/v2/auth"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/version"
)
var indexTemplates sync.Map
func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys fs.FS, file, contentType string) (int, error) {
w.Header().Set("Content-Type", contentType)
auther, err := d.store.Auth.Get(d.settings.AuthMethod)
if err != nil {
return http.StatusInternalServerError, err
}
data := map[string]interface{}{
"Name": d.settings.Branding.Name,
"DisableExternal": d.settings.Branding.DisableExternal,
@@ -37,19 +34,20 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
"BaseURL": d.server.BaseURL,
"Version": version.Version,
"StaticURL": path.Join(d.server.BaseURL, "/static"),
"Signup": d.settings.Signup,
"NoAuth": d.settings.AuthMethod == auth.MethodNoAuth,
"AuthMethod": d.settings.AuthMethod,
"LogoutPage": d.settings.LogoutPage,
"LoginPage": auther.LoginPage(),
"Signup": false,
"NoAuth": false,
"AuthMethod": "sso",
"LogoutPage": "/auth/logout",
"LoginPage": true,
"CSS": false,
"ReCaptcha": false,
"Theme": d.settings.Branding.Theme,
"EnableThumbs": d.server.EnableThumbnails,
"ResizePreview": d.server.ResizePreview,
"EnableExec": d.server.EnableExec,
"EnableExec": false,
"TusSettings": d.settings.Tus,
"HideLoginButton": d.settings.HideLoginButton,
"Nonce": randomSecret(),
}
if d.settings.Branding.Files != "" {
@@ -65,21 +63,6 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
}
}
if d.settings.AuthMethod == auth.MethodJSONAuth {
raw, err := d.store.Auth.Get(d.settings.AuthMethod)
if err != nil {
return http.StatusInternalServerError, err
}
auther := raw.(*auth.JSONAuth)
if auther.ReCaptcha != nil {
data["ReCaptcha"] = auther.ReCaptcha.Key != "" && auther.ReCaptcha.Secret != ""
data["ReCaptchaHost"] = auther.ReCaptcha.Host
data["ReCaptchaKey"] = auther.ReCaptcha.Key
}
}
b, err := json.Marshal(data)
if err != nil {
return http.StatusInternalServerError, err
@@ -94,7 +77,19 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
}
return http.StatusInternalServerError, err
}
index := template.Must(template.New("index").Delims("[{[", "]}]").Parse(string(fileContents)))
// Build templates once. A per-response nonce permits the bootstrap without
// enabling arbitrary inline scripts; the configuration JSON stays escaped.
contents := strings.ReplaceAll(string(fileContents), "<script", `<script nonce="[{[ .Nonce ]}]"`)
cached, ok := indexTemplates.Load(contents)
if !ok {
parsed, parseErr := template.New("index").Delims("[{[", "]}]").Parse(contents)
if parseErr != nil {
return http.StatusInternalServerError, parseErr
}
cached, _ = indexTemplates.LoadOrStore(contents, parsed)
}
index := cached.(*template.Template)
w.Header().Set("Content-Security-Policy", fmt.Sprintf("default-src 'self'; script-src 'self' 'nonce-%s' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self' blob:; worker-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", data["Nonce"]))
err = index.Execute(w, data)
if err != nil {
return http.StatusInternalServerError, err
@@ -125,6 +120,10 @@ 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))
if strings.HasPrefix(r.URL.Path, "assets/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
}
w.Header().Add("Vary", "Accept-Encoding")
w.Header().Set("X-Content-Type-Options", "nosniff")
if d.settings.Branding.Files != "" {
+3 -1
View File
@@ -242,7 +242,9 @@ func tusPatchUpload(w http.ResponseWriter, r *http.Request, d *data, cache Uploa
)
}
openFile, err := d.user.Fs.OpenFile(r.URL.Path, os.O_WRONLY|os.O_APPEND, d.settings.FileMode)
// Explicit seek makes rollback via Truncate work on Windows too. O_APPEND
// obtains append-only access there, which cannot truncate an oversized chunk.
openFile, err := d.user.Fs.OpenFile(r.URL.Path, os.O_WRONLY, d.settings.FileMode)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("could not open file: %w", err)
}
+6 -4
View File
@@ -41,7 +41,9 @@ func newTusTestServer(t *testing.T, st *storage.Storage, cache UploadCache) *htt
}
})
srv := httptest.NewServer(mux)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mux.ServeHTTP(w, authorizeTestRequest(r, r.Header.Get("X-Test-Identity")))
}))
t.Cleanup(srv.Close)
return srv
}
@@ -87,7 +89,7 @@ func (f *tusTestFixture) create(t *testing.T, name string, length int) string {
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Auth", f.token)
req = authorizeTestRequest(req, f.token)
req.Header.Set("Upload-Length", strconv.Itoa(length))
res, err := f.client.Do(req)
@@ -116,7 +118,7 @@ func (f *tusTestFixture) patch(t *testing.T, url string, offset int, chunk []byt
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Auth", f.token)
req = authorizeTestRequest(req, f.token)
req.Header.Set("Content-Type", "application/offset+octet-stream")
req.Header.Set("Upload-Offset", strconv.Itoa(offset))
@@ -200,7 +202,7 @@ func TestTusHeadReportsOffsetBetweenChunks(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Auth", f.token)
req = authorizeTestRequest(req, f.token)
headRes, err := f.client.Do(req)
if err != nil {
+2 -15
View File
@@ -6,10 +6,8 @@ import (
"os"
"path/filepath"
"testing"
"time"
"github.com/asdine/storm/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/files"
@@ -63,18 +61,7 @@ func TestTusHandlersRejectSymlinkScopeEscape(t *testing.T) {
}
// Forge a valid auth token for user ID 1.
claims := &authToken{
User: userInfo{ID: 1, Username: "u", Perm: users.Permissions{Create: true, Modify: true}},
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
t.Fatalf("failed to sign token: %v", err)
}
signed := testSession(1, "u", false)
cases := map[string]struct {
method string
handler handleFunc
@@ -99,7 +86,7 @@ func TestTusHandlersRejectSymlinkScopeEscape(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
for k, v := range tc.headers {
req.Header.Set(k, v)
}
+2 -2
View File
@@ -34,7 +34,7 @@ func TestTusPatchEnforcesUploadLength(t *testing.T) {
patchReq := func(body string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(http.MethodPatch, "/file.txt", strings.NewReader(body))
req.Header.Set("X-Auth", signed)
req = authorizeTestRequest(req, signed)
req.Header.Set("Content-Type", "application/offset+octet-stream")
req.Header.Set("Upload-Offset", "0")
rec := httptest.NewRecorder()
@@ -44,7 +44,7 @@ func TestTusPatchEnforcesUploadLength(t *testing.T) {
// Create an upload that declares only 5 bytes.
reqPost, _ := http.NewRequest(http.MethodPost, "/file.txt", http.NoBody)
reqPost.Header.Set("X-Auth", signed)
reqPost = authorizeTestRequest(reqPost, signed)
reqPost.Header.Set("Upload-Length", "5")
recPost := httptest.NewRecorder()
post.ServeHTTP(recPost, reqPost)
+15 -133
View File
@@ -3,17 +3,13 @@ package fbhttp
import (
"encoding/json"
"errors"
"log"
"net/http"
"sort"
"strconv"
"strings"
"github.com/gorilla/mux"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/filebrowser/filebrowser/v2/auth"
fberrors "github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/users"
)
@@ -36,11 +32,12 @@ func getUserID(r *http.Request) (uint, error) {
return uint(i), err
}
func getUser(_ http.ResponseWriter, r *http.Request) (*modifyUserRequest, error) {
func getUser(w http.ResponseWriter, r *http.Request) (*modifyUserRequest, error) {
if r.Body == nil {
return nil, fberrors.ErrEmptyRequest
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
req := &modifyUserRequest{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
@@ -117,12 +114,6 @@ var userDeleteHandler = withSelfOrAdmin(func(_ http.ResponseWriter, r *http.Requ
return http.StatusBadRequest, err
}
if d.settings.AuthMethod == auth.MethodJSONAuth {
if !users.CheckPwd(body.CurrentPassword, d.user.Password) {
return http.StatusBadRequest, fberrors.ErrCurrentPasswordIncorrect
}
}
err := d.store.Users.Delete(d.raw.(uint))
if err != nil {
return errToStatus(err), err
@@ -131,139 +122,30 @@ var userDeleteHandler = withSelfOrAdmin(func(_ http.ResponseWriter, r *http.Requ
return http.StatusOK, nil
})
var userPostHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
req, err := getUser(w, r)
if err != nil {
return http.StatusBadRequest, err
}
if d.settings.AuthMethod == auth.MethodJSONAuth {
if !users.CheckPwd(req.CurrentPassword, d.user.Password) {
return http.StatusBadRequest, fberrors.ErrCurrentPasswordIncorrect
}
}
if len(req.Which) != 0 {
return http.StatusBadRequest, nil
}
if req.Data.Password == "" {
return http.StatusBadRequest, fberrors.ErrEmptyPassword
}
req.Data.Password, err = users.ValidateAndHashPwd(req.Data.Password, d.settings.MinimumPasswordLength)
if err != nil {
return http.StatusBadRequest, err
}
if req.Data.Perm.Share && !req.Data.Perm.Download {
return http.StatusBadRequest, fberrors.ErrShareRequiresDownload
}
userHome, err := d.settings.MakeUserDir(req.Data.Username, req.Data.Scope, d.server.Root)
if err != nil {
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
return http.StatusInternalServerError, err
}
req.Data.Scope = userHome
log.Printf("user: %s, home dir: [%s].", req.Data.Username, userHome)
err = d.store.Users.Save(req.Data)
if err != nil {
return http.StatusInternalServerError, err
}
w.Header().Set("Location", "/settings/users/"+strconv.FormatUint(uint64(req.Data.ID), 10))
return http.StatusCreated, nil
})
var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
req, err := getUser(w, r)
if err != nil {
return http.StatusBadRequest, err
}
if d.settings.AuthMethod == auth.MethodJSONAuth {
var sensibleFields = map[string]struct{}{
"all": {},
"username": {},
"password": {},
"scope": {},
"lockPassword": {},
"commands": {},
"perm": {},
}
for _, field := range req.Which {
if _, ok := sensibleFields[strings.ToLower(field)]; ok {
if !users.CheckPwd(req.CurrentPassword, d.user.Password) {
return http.StatusBadRequest, fberrors.ErrCurrentPasswordIncorrect
}
break
}
}
}
if req.Data.ID != d.raw.(uint) {
if req.Data == nil || req.Data.ID != d.raw.(uint) || len(req.Which) == 0 || req.Data.Password != "" {
return http.StatusBadRequest, nil
}
for _, field := range req.Which {
if strings.ToLower(field) == "perm" || strings.ToLower(field) == "all" {
if req.Data.Perm.Share && !req.Data.Perm.Download {
return http.StatusBadRequest, fberrors.ErrShareRequiresDownload
}
}
}
if len(req.Which) == 0 || (len(req.Which) == 1 && req.Which[0] == "all") {
if !d.user.Perm.Admin {
allowed := map[string]string{"scope": "Scope", "perm": "Perm", "rules": "Rules", "locale": "Locale", "viewmode": "ViewMode", "singleclick": "SingleClick", "redirectaftercopymove": "RedirectAfterCopyMove", "hidedotfiles": "HideDotfiles", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
for i, field := range req.Which {
canonical, ok := allowed[strings.ToLower(field)]
if !ok {
return http.StatusForbidden, nil
}
if req.Data.Password != "" {
req.Data.Password, err = users.ValidateAndHashPwd(req.Data.Password, d.settings.MinimumPasswordLength)
if err != nil {
return http.StatusBadRequest, err
}
} else {
var suser *users.User
suser, err = d.store.Users.Get(d.server.Root, d.server.FollowExternalSymlinks, d.raw.(uint))
if err != nil {
return http.StatusInternalServerError, err
}
req.Data.Password = suser.Password
if !d.user.Perm.Admin && (canonical == "Scope" || canonical == "Perm" || canonical == "Rules") {
return http.StatusForbidden, nil
}
req.Which = []string{}
req.Which[i] = canonical
}
for k, v := range req.Which {
v = cases.Title(language.English, cases.NoLower).String(v)
req.Which[k] = v
if v == "Password" {
if !d.user.Perm.Admin && d.user.LockPassword {
return http.StatusForbidden, nil
}
req.Data.Password, err = users.ValidateAndHashPwd(req.Data.Password, d.settings.MinimumPasswordLength)
if err != nil {
return http.StatusBadRequest, err
}
}
for _, f := range NonModifiableFieldsForNonAdmin {
if !d.user.Perm.Admin && v == f {
return http.StatusForbidden, nil
}
}
if req.Data.Perm.Share && !req.Data.Perm.Download {
return http.StatusBadRequest, fberrors.ErrShareRequiresDownload
}
req.Data.Perm.Admin = false
req.Data.Perm.Execute = false
err = d.store.Users.Update(req.Data, req.Which...)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
return errToStatus(err), err
})