mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-26 08:29:41 -05:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79552f8adb | ||
|
|
951debcd87 | ||
|
|
cd8519c8aa |
No files matched your search
+1
-2
@@ -1,6 +1,6 @@
|
||||
*.db
|
||||
*.db.old
|
||||
*.sqlite**
|
||||
*.sqlite
|
||||
*.bak
|
||||
*.log
|
||||
*.mjs
|
||||
@@ -8,7 +8,6 @@ _old
|
||||
rice-box.go
|
||||
.idea/
|
||||
/backend/backend
|
||||
/backend/internal
|
||||
/backend/filebrowser
|
||||
/backend/filebrowser.exe
|
||||
frontend/tsconfig.tsbuildinfo
|
||||
|
||||
@@ -2,39 +2,6 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. For commit guidelines, please refer to [Standard Version](https://github.com/conventional-changelog/standard-version).
|
||||
|
||||
## v1.5.2-stable
|
||||
|
||||
**Security**:
|
||||
- [High] Symlink following on read paths no longer escapes source or user/share scope (GHSA-mgqf-5mf5-prfj) -- thanks @je-lv @KasperBuilds
|
||||
- [High] Share create/update could set delete/modify/create flags beyond the owner's permissions; POST /api/share with hash could update another user's share (GHSA-x79q-5hqm-x839) -- thanks @pant0m
|
||||
- [High] PATCH /api/share could re-point a share outside the owner's scope (GHSA-wfjp-qhvc-69wp) -- thanks @maximeborges
|
||||
- [High] Public upload ACL check used scope-stripped path, bypassing per-folder DENY rules (GHSA-qv53-4557-m65h) -- thanks @hypnguyen1209
|
||||
- [Moderate] Absolute paths in API path/file parameters could bypass user scope and read files outside the source mount (GHSA-rqqq-wv83-rp74) -- thanks @Wei-Leo
|
||||
- [Moderate] Authenticated upload and pause endpoints checked access rules on scope-relative paths, bypassing per-folder DENY rules (GHSA-cw65-p35p-633w) -- thanks @5ud0er
|
||||
- [Moderate] Logout did not invalidate session JWTs with equivalent Base64URL spellings (GHSA-8m35-wcjh-95q7) -- thanks @corbanvilla @soh3e @dderpym (This vulnerability was discovered as part of a U.C. Berkeley security research project by: Corban Villa, Sohee Kim, and Austin Chu)
|
||||
- [Moderate] Stored XSS via unsanitized DOCX hyperlink in DocViewer (GHSA-9wm6-jcjh-3m8c) -- thanks @karen93shieh @je-lv @EclipsSec
|
||||
- [Moderate] Revoked JWTs could still authenticate on public-share and withOrWithoutUser routes until natural expiry, bypassing logout and Api-permission revocation on that surface (GHSA-4wmj-rq3c-m65v) -- thanks @hypnguyen1209
|
||||
|
||||
## v1.5.5
|
||||
|
||||
**BugFixes**:
|
||||
- fix uncustomized (minimal) API tokens creation needed by webdav clients (#2503)
|
||||
|
||||
## v1.5.4
|
||||
|
||||
**Notes**:
|
||||
- PWA installation name now capped at 30 characters instead of 12 (#2699)
|
||||
|
||||
**BugFixes**:
|
||||
- fix forward slash blocked in text fields when the search shortcut listener intercepts `/` (#2696)
|
||||
|
||||
## v1.5.3
|
||||
|
||||
**BugFixes**:
|
||||
- fix probe canShare with the real file, not a fixed text/plain stand-in (#2664)
|
||||
- When the logout button is pressed, the user is redirected to an invalid URL that does not honor baseURL / externalUrl (#2657)
|
||||
- fix redirect to login when an authenticated request returns 401 (expired session)
|
||||
|
||||
## v1.5.2
|
||||
|
||||
**Notes**:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||
[](https://goreportcard.com/report/github.com/gtsteffaniak/filebrowser/backend)
|
||||
[](https://app.codacy.com/gh/gtsteffaniak/filebrowser/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
|
||||
[](https://github.com/gtsteffaniak/filebrowser/releases)
|
||||
[](https://hub.docker.com/r/gtstef/filebrowser)
|
||||
|
||||
@@ -143,7 +143,7 @@ func checkPermissionsImpl(opts utils.FileOptions, access *access.Storage, user *
|
||||
}
|
||||
|
||||
// Combine scope + sanitized path
|
||||
indexPath := utils.JoinScopedIndexPath(userScope, safePath)
|
||||
indexPath := utils.JoinPathAsUnix(userScope, safePath)
|
||||
// Layer 1: USER ACCESS CONTROL
|
||||
// Quick check: Does THIS user have permission?
|
||||
if !access.Permitted(idx.Path, indexPath, user.Username) {
|
||||
@@ -173,7 +173,7 @@ func filterFilesByExt(files []iteminfo.ExtendedItemInfo, hideFileExt string) []i
|
||||
|
||||
func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.User) (Items, error) {
|
||||
items := Items{}
|
||||
indexPath, userScope, topLevelErr := CheckPermissions(opts, access, user)
|
||||
indexPath, _, topLevelErr := CheckPermissions(opts, access, user)
|
||||
accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != ""
|
||||
if topLevelErr != nil && !accessRulesErr {
|
||||
return items, topLevelErr
|
||||
@@ -183,18 +183,14 @@ func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.Use
|
||||
if idx == nil {
|
||||
return items, fmt.Errorf("could not get index: %v ", opts.Source)
|
||||
}
|
||||
infoReq := indexing.FileInfoRequest{
|
||||
info, err := idx.GetFileInfo(indexing.FileInfoRequest{
|
||||
IndexPath: indexPath,
|
||||
FollowSymlinks: opts.FollowSymlinks,
|
||||
ShowHidden: opts.ShowHidden,
|
||||
HideFileExt: opts.HideFileExt,
|
||||
Expand: true,
|
||||
SkipExtendedAttrs: true,
|
||||
}
|
||||
if opts.FollowSymlinks {
|
||||
infoReq.BoundIndexPath = userScope
|
||||
}
|
||||
info, err := idx.GetFileInfo(infoReq)
|
||||
})
|
||||
if err != nil {
|
||||
return items, err // Path excluded by index rules OR doesn't exist
|
||||
}
|
||||
@@ -246,18 +242,14 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us
|
||||
}
|
||||
// Layer 2: INDEX RULES (global)
|
||||
// Get file info using unified entry point (applies IsViewable/ShouldSkip)
|
||||
fileInfoReq := indexing.FileInfoRequest{
|
||||
info, err := idx.GetFileInfo(indexing.FileInfoRequest{
|
||||
IndexPath: indexPath,
|
||||
FollowSymlinks: opts.FollowSymlinks,
|
||||
ShowHidden: opts.ShowHidden,
|
||||
HideFileExt: opts.HideFileExt,
|
||||
Expand: opts.Expand,
|
||||
SkipExtendedAttrs: opts.SkipExtendedAttrs,
|
||||
}
|
||||
if opts.FollowSymlinks {
|
||||
fileInfoReq.BoundIndexPath = userScope
|
||||
}
|
||||
info, err := idx.GetFileInfo(fileInfoReq)
|
||||
})
|
||||
if err != nil {
|
||||
return response, err // Path excluded by index rules OR doesn't exist
|
||||
}
|
||||
@@ -274,15 +266,7 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us
|
||||
|
||||
// Build response
|
||||
response.FileInfo = *info
|
||||
if opts.FollowSymlinks && info.Type != "directory" {
|
||||
realPath, _, err := idx.GetRealPathScoped(userScope, indexPath)
|
||||
if err != nil {
|
||||
return response, err
|
||||
}
|
||||
response.RealPath = realPath
|
||||
} else {
|
||||
response.RealPath = utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
}
|
||||
response.RealPath = filepath.Join(idx.Path, indexPath)
|
||||
response.Source = opts.Source
|
||||
if shareStore != nil && user.Permissions.Share && opts.ShowSharedAttr {
|
||||
for i := range response.Files {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
liberrors "github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/access"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
)
|
||||
|
||||
func setupSymlinkDirEscapeFixture(t *testing.T) (sourceRoot, userScope string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
sourceRoot = filepath.Join(root, "srv")
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.MkdirAll(userDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherDir := filepath.Join(sourceRoot, "otheruser")
|
||||
if err := os.MkdirAll(otherDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(otherDir, "leaked.txt"), []byte("leaked"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(otherDir, filepath.Join(userDir, "escape_dir")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sourceRoot, "/user1"
|
||||
}
|
||||
|
||||
func TestGetDirItems_RejectsDirectorySymlinkOutsideUserScope(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkDirEscapeFixture(t)
|
||||
sourceName := "test_getdiritems_scope"
|
||||
indexing.SetTestIndex(sourceName, sourceRoot)
|
||||
t.Cleanup(indexing.ClearTestIndices)
|
||||
|
||||
origCheck := CheckPermissionsFunc
|
||||
t.Cleanup(func() { CheckPermissionsFunc = origCheck })
|
||||
CheckPermissionsFunc = func(opts utils.FileOptions, _ *access.Storage, _ *users.User) (string, string, error) {
|
||||
return utils.JoinPathAsUnix(userScope, opts.Path), userScope, nil
|
||||
}
|
||||
|
||||
_, err := GetDirItems(utils.FileOptions{
|
||||
Source: sourceName,
|
||||
Path: "/escape_dir",
|
||||
FollowSymlinks: true,
|
||||
}, nil, &users.User{})
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -55,13 +55,7 @@ func MakeSignedTokenAPI(user *users.User, name string, duration time.Duration, p
|
||||
claim.Permissions = perms
|
||||
claim.BelongsTo = user.ID
|
||||
}
|
||||
signedClaims := jwt.Claims(claim)
|
||||
if minimal {
|
||||
// Sign only standard JWT claims. The full AuthToken struct always JSON-marshals
|
||||
// a zero Permissions object, which bloats the token past WebDAV client limits.
|
||||
signedClaims = claim.MinimalAuthToken
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, signedClaims)
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
|
||||
tokenString, err := token.SignedString([]byte(settings.Config.Auth.Key))
|
||||
if err != nil {
|
||||
return "", users.AuthToken{}, err
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
)
|
||||
|
||||
const base64URLAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
|
||||
func decodeJWTBase64URL(s string) ([]byte, error) {
|
||||
switch len(s) % 4 {
|
||||
case 2:
|
||||
s += "=="
|
||||
case 3:
|
||||
s += "="
|
||||
}
|
||||
return base64.URLEncoding.DecodeString(s)
|
||||
}
|
||||
|
||||
// equivalentSpelling returns a different compact JWT string with the same decoded signature bytes.
|
||||
func equivalentSpelling(token string) string {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
panic("equivalentSpelling: invalid JWT")
|
||||
}
|
||||
header, payload, signature := parts[0], parts[1], parts[2]
|
||||
orig, err := decodeJWTBase64URL(signature)
|
||||
if err != nil {
|
||||
panic("equivalentSpelling: decode canonical signature: " + err.Error())
|
||||
}
|
||||
|
||||
last := signature[len(signature)-1]
|
||||
for _, c := range base64URLAlphabet {
|
||||
if byte(c) == last {
|
||||
continue
|
||||
}
|
||||
trial := signature[:len(signature)-1] + string(c)
|
||||
dec, err := decodeJWTBase64URL(trial)
|
||||
if err != nil || !bytes.Equal(dec, orig) {
|
||||
continue
|
||||
}
|
||||
respelled := header + "." + payload + "." + trial
|
||||
if respelled != token {
|
||||
return respelled
|
||||
}
|
||||
}
|
||||
panic("equivalentSpelling: no alternate spelling found")
|
||||
}
|
||||
|
||||
func invalidSignatureSpelling(token string) string {
|
||||
parts := strings.Split(token, ".")
|
||||
header, payload, signature := parts[0], parts[1], parts[2]
|
||||
idx := strings.IndexByte(base64URLAlphabet, signature[len(signature)-1])
|
||||
replacement := base64URLAlphabet[((idx&0b110000)+16)%64]
|
||||
return header + "." + payload + "." + signature[:len(signature)-1] + string(replacement)
|
||||
}
|
||||
|
||||
func parseSessionToken(tokenString string) error {
|
||||
keyFunc := func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(settings.Config.Auth.Key), nil
|
||||
}
|
||||
var tk users.AuthToken
|
||||
_, err := jwt.ParseWithClaims(tokenString, &tk, keyFunc)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestDecodeStrictRejectsEquivalentSpelling(t *testing.T) {
|
||||
origKey := settings.Config.Auth.Key
|
||||
origStrict := jwt.DecodeStrict
|
||||
settings.Config.Auth.Key = "test-signing-key-strict-decode"
|
||||
jwt.DecodeStrict = true
|
||||
t.Cleanup(func() {
|
||||
settings.Config.Auth.Key = origKey
|
||||
jwt.DecodeStrict = origStrict
|
||||
})
|
||||
|
||||
user := &users.User{ID: 1, Username: "alice"}
|
||||
canonical, _, err := MakeSignedTokenAPI(user, "WEB_TOKEN_test", time.Hour, user.Permissions, false)
|
||||
if err != nil {
|
||||
t.Fatalf("MakeSignedTokenAPI: %v", err)
|
||||
}
|
||||
|
||||
if err := parseSessionToken(canonical); err != nil {
|
||||
t.Fatalf("canonical token should parse under strict mode: %v", err)
|
||||
}
|
||||
|
||||
respelled := equivalentSpelling(canonical)
|
||||
if err := parseSessionToken(respelled); err == nil {
|
||||
t.Fatal("equivalent spelling should be rejected when jwt.DecodeStrict is true")
|
||||
}
|
||||
|
||||
tampered := invalidSignatureSpelling(canonical)
|
||||
if err := parseSessionToken(tampered); err == nil {
|
||||
t.Fatal("tampered signature should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEquivalentSpellingParsesWithoutStrictMode(t *testing.T) {
|
||||
origKey := settings.Config.Auth.Key
|
||||
origStrict := jwt.DecodeStrict
|
||||
settings.Config.Auth.Key = "test-signing-key-strict-decode"
|
||||
jwt.DecodeStrict = false
|
||||
t.Cleanup(func() {
|
||||
settings.Config.Auth.Key = origKey
|
||||
jwt.DecodeStrict = origStrict
|
||||
})
|
||||
|
||||
user := &users.User{ID: 1, Username: "alice"}
|
||||
canonical, _, err := MakeSignedTokenAPI(user, "WEB_TOKEN_test", time.Hour, user.Permissions, false)
|
||||
if err != nil {
|
||||
t.Fatalf("MakeSignedTokenAPI: %v", err)
|
||||
}
|
||||
respelled := equivalentSpelling(canonical)
|
||||
if err := parseSessionToken(respelled); err != nil {
|
||||
t.Fatalf("equivalent spelling should parse without strict mode (documents pre-fix behavior): %v", err)
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,6 @@ var (
|
||||
ErrUnauthorized = errors.New("user unauthorized")
|
||||
ErrNotIndexed = errors.New("directory or item excluded from indexing")
|
||||
ErrNotViewable = errors.New("directory or item is not viewable")
|
||||
ErrPathEscapesScope = errors.New("resolved path escapes scope")
|
||||
ErrWrongLoginMethod = errors.New("user attempted to login with wrong login method")
|
||||
ErrDownloadNotAllowed = errors.New("downloads are not allowed for this share")
|
||||
ErrUploadNotAllowed = errors.New("upload permission not allowed for this share")
|
||||
|
||||
@@ -280,7 +280,7 @@ type ResolvedRulesConfig struct {
|
||||
}
|
||||
|
||||
type Frontend struct {
|
||||
Name string `json:"name"` // display name, PWA installation name is capped at 30 characters
|
||||
Name string `json:"name"` // display name
|
||||
DisableDefaultLinks bool `json:"disableDefaultLinks"` // disable default links in the sidebar
|
||||
DisableUsedPercentage bool `json:"disableUsedPercentage"` // disable used percentage for the sources in the sidebar
|
||||
ExternalLinks []ExternalLink `json:"externalLinks"`
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CleanIndexPathSegment normalizes a path segment as if it were rooted, so relative
|
||||
// ".." components cannot escape via path.Clean on an unrooted input.
|
||||
func CleanIndexPathSegment(segment string) string {
|
||||
return strings.TrimPrefix(path.Clean("/"+segment), "/")
|
||||
}
|
||||
|
||||
// JoinIndexPathComponents combines index path segments into a single rooted Unix path.
|
||||
func JoinIndexPathComponents(relativePath ...string) string {
|
||||
if len(relativePath) == 0 {
|
||||
return "/"
|
||||
}
|
||||
cleaned := CleanIndexPathSegment(relativePath[0])
|
||||
for _, p := range relativePath[1:] {
|
||||
segment := CleanIndexPathSegment(p)
|
||||
if segment == "" {
|
||||
continue
|
||||
}
|
||||
if cleaned == "" {
|
||||
cleaned = segment
|
||||
continue
|
||||
}
|
||||
cleaned = cleaned + "/" + segment
|
||||
}
|
||||
if cleaned == "" {
|
||||
return "/"
|
||||
}
|
||||
return "/" + cleaned
|
||||
}
|
||||
|
||||
// JoinScopedIndexPath joins a user's index scope with a sanitized path segment.
|
||||
// Unlike filepath.Join, a leading slash on rel does not discard scope (avoids absolute-path scope bypass).
|
||||
func JoinScopedIndexPath(scope, rel string) string {
|
||||
rel = CleanIndexPathSegment(rel)
|
||||
scope = strings.TrimRight(scope, "/")
|
||||
if rel == "" {
|
||||
if scope == "" || scope == "/" {
|
||||
return "/"
|
||||
}
|
||||
return scope
|
||||
}
|
||||
if scope == "" || scope == "/" {
|
||||
return "/" + rel
|
||||
}
|
||||
return scope + "/" + rel
|
||||
}
|
||||
|
||||
// JoinUnderSourceRoot maps an index path onto a source filesystem root without treating
|
||||
// indexPath as a host-absolute path (filepath.Join would discard sourceRoot when indexPath starts with "/").
|
||||
func JoinUnderSourceRoot(sourceRoot, indexPath string) string {
|
||||
rel := CleanIndexPathSegment(indexPath)
|
||||
if rel == "" {
|
||||
return sourceRoot
|
||||
}
|
||||
return filepath.Join(sourceRoot, rel)
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestJoinScopedIndexPath_absoluteRelDoesNotDropScope(t *testing.T) {
|
||||
const scope = "/home/alice"
|
||||
got := JoinScopedIndexPath(scope, "/etc/passwd")
|
||||
want := "/home/alice/etc/passwd"
|
||||
if got != want {
|
||||
t.Fatalf("JoinScopedIndexPath(%q, /etc/passwd) = %q, want %q", scope, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinScopedIndexPath_traversalResolvedUnderScope(t *testing.T) {
|
||||
const scope = "/home/alice"
|
||||
got := JoinScopedIndexPath(scope, "/../../../etc/passwd")
|
||||
want := "/home/alice/etc/passwd"
|
||||
if got != want {
|
||||
t.Fatalf("JoinScopedIndexPath(%q, /../../../etc/passwd) = %q, want %q", scope, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinScopedIndexPath_unrootedTraversalResolvedUnderScope(t *testing.T) {
|
||||
const scope = "/home/alice"
|
||||
got := JoinScopedIndexPath(scope, "../../etc/passwd")
|
||||
want := "/home/alice/etc/passwd"
|
||||
if got != want {
|
||||
t.Fatalf("JoinScopedIndexPath(%q, ../../etc/passwd) = %q, want %q", scope, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinScopedIndexPath_rootScope(t *testing.T) {
|
||||
got := JoinScopedIndexPath("/", "projects/acme/file.txt")
|
||||
if got != "/projects/acme/file.txt" {
|
||||
t.Fatalf("got %q want /projects/acme/file.txt", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinUnderSourceRoot_absoluteIndexPathStaysUnderSource(t *testing.T) {
|
||||
const sourceRoot = "/srv/mount"
|
||||
got := JoinUnderSourceRoot(sourceRoot, "/etc/passwd")
|
||||
want := filepath.Join(sourceRoot, "etc/passwd")
|
||||
if got != want {
|
||||
t.Fatalf("JoinUnderSourceRoot = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinUnderSourceRoot_relativeIndexPath(t *testing.T) {
|
||||
const sourceRoot = "/srv/mount"
|
||||
got := JoinUnderSourceRoot(sourceRoot, "/home/alice/projects/foo")
|
||||
want := filepath.Join(sourceRoot, "home/alice/projects/foo")
|
||||
if got != want {
|
||||
t.Fatalf("JoinUnderSourceRoot = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinUnderSourceRoot_unrootedTraversalStaysUnderSource(t *testing.T) {
|
||||
const sourceRoot = "/srv/mount"
|
||||
got := JoinUnderSourceRoot(sourceRoot, "../../etc/passwd")
|
||||
want := filepath.Join(sourceRoot, "etc/passwd")
|
||||
if got != want {
|
||||
t.Fatalf("JoinUnderSourceRoot(%q, ../../etc/passwd) = %q, want %q", sourceRoot, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinScopedIndexPath_authorizationMustUseScopedPath(t *testing.T) {
|
||||
const userScope = "/home/alice"
|
||||
requestPath := "/etc/passwd"
|
||||
scoped := JoinScopedIndexPath(userScope, requestPath)
|
||||
if scoped == requestPath {
|
||||
t.Fatalf("access checks must use scoped path %q, not raw request path %q", scoped, requestPath)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package share
|
||||
|
||||
import "github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
|
||||
// ClampShareEditable limits client-requested share flags to what the owner is allowed.
|
||||
func ClampShareEditable(ownerPerms users.Permissions, cs *CommonShare) {
|
||||
if cs == nil {
|
||||
return
|
||||
}
|
||||
if !ownerPerms.Modify {
|
||||
cs.AllowModify = false
|
||||
}
|
||||
if !ownerPerms.Create {
|
||||
cs.AllowCreate = false
|
||||
}
|
||||
if !ownerPerms.Delete {
|
||||
cs.AllowDelete = false
|
||||
}
|
||||
if !ownerPerms.Download {
|
||||
cs.DisableDownload = true
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package share
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
)
|
||||
|
||||
func TestClampShareEditable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ownerPerms := users.Permissions{
|
||||
Modify: false,
|
||||
Create: true,
|
||||
Delete: false,
|
||||
Download: false,
|
||||
}
|
||||
cs := &CommonShare{
|
||||
AllowModify: true,
|
||||
AllowCreate: true,
|
||||
AllowDelete: true,
|
||||
DisableDownload: false,
|
||||
}
|
||||
|
||||
ClampShareEditable(ownerPerms, cs)
|
||||
|
||||
if cs.AllowModify {
|
||||
t.Fatal("expected AllowModify clamped to false")
|
||||
}
|
||||
if !cs.AllowCreate {
|
||||
t.Fatal("expected AllowCreate to remain true")
|
||||
}
|
||||
if cs.AllowDelete {
|
||||
t.Fatal("expected AllowDelete clamped to false")
|
||||
}
|
||||
if !cs.DisableDownload {
|
||||
t.Fatal("expected DisableDownload forced true when owner lacks download")
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -18,7 +18,7 @@ require (
|
||||
github.com/gtsteffaniak/go-cache v1.1.0
|
||||
github.com/gtsteffaniak/go-logger v1.1.0
|
||||
github.com/kovidgoyal/imaging v1.8.23
|
||||
github.com/mattn/go-sqlite3 v1.14.49
|
||||
github.com/mattn/go-sqlite3 v1.14.48
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/spf13/afero v1.15.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
@@ -33,7 +33,7 @@ require (
|
||||
golang.org/x/time v0.15.0
|
||||
golang.org/x/tools v0.48.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.55.0
|
||||
modernc.org/sqlite v1.54.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -106,7 +106,7 @@ require (
|
||||
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/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/ebitengine/purego v0.10.2 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/ettle/strcase v0.2.0 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fatih/structtag v1.2.0 // indirect
|
||||
@@ -114,7 +114,7 @@ require (
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.9.2 // indirect
|
||||
github.com/fzipp/gocyclo v0.6.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/ghostiam/protogetter v0.3.20 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
|
||||
github.com/go-critic/go-critic v0.14.3 // indirect
|
||||
@@ -122,14 +122,14 @@ require (
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-openapi/jsonpointer v1.0.0 // indirect
|
||||
github.com/go-openapi/jsonreference v1.0.0 // indirect
|
||||
github.com/go-openapi/spec v0.22.9 // indirect
|
||||
github.com/go-openapi/swag/conv v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/jsonutils v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/loading v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/pools v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.28.0 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.28.0 // indirect
|
||||
github.com/go-openapi/spec v0.22.6 // indirect
|
||||
github.com/go-openapi/swag/conv v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/loading v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-toolsmith/astcast v1.1.0 // indirect
|
||||
@@ -192,7 +192,7 @@ require (
|
||||
github.com/ldez/structtags v0.6.1 // indirect
|
||||
github.com/ldez/tagliatelle v0.7.2 // indirect
|
||||
github.com/ldez/usetesting v0.5.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/leonklingele/grouper v1.1.2 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
|
||||
github.com/macabu/inamedparam v0.2.0 // indirect
|
||||
@@ -204,7 +204,7 @@ require (
|
||||
github.com/maratori/testpackage v1.1.2 // indirect
|
||||
github.com/matoous/godox v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mattn/go-isatty v0.0.23 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mgechev/revive v1.15.0 // indirect
|
||||
@@ -284,7 +284,7 @@ require (
|
||||
go.etcd.io/bbolt v1.5.0 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
@@ -293,7 +293,7 @@ require (
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
honnef.co/go/tools v0.7.0 // indirect
|
||||
modernc.org/libc v1.74.4 // indirect
|
||||
modernc.org/libc v1.74.2 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
mvdan.cc/gofumpt v0.9.2 // indirect
|
||||
|
||||
+33
-34
@@ -256,8 +256,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje
|
||||
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
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/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -281,8 +281,8 @@ github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh
|
||||
github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||
github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=
|
||||
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gen2brain/go-fitz v1.28.2 h1:845G85N5TUgnq5oDqyYrW0JvehAkeo35UkkK2dJtW1M=
|
||||
github.com/gen2brain/go-fitz v1.28.2/go.mod h1:pY2hqAjp9Zy7qfPI2gwbJMHBFAdZpVXOLrRxD82l3Bs=
|
||||
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
|
||||
@@ -320,25 +320,25 @@ github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxg
|
||||
github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y=
|
||||
github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY=
|
||||
github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0=
|
||||
github.com/go-openapi/spec v0.22.9 h1:/vKIFDcGKp0ktZWGbym/tJEWbk6/XOEmAVU0kqKMH+w=
|
||||
github.com/go-openapi/spec v0.22.9/go.mod h1:b/mNUYIOQOyIiUzUzXEE8xzyZqf93KvM9hQGP91yfl0=
|
||||
github.com/go-openapi/spec v0.22.6 h1:Tyy1pLaNCM8GBCFLoGYLonjJi6zykqyLCjXLc19ZPic=
|
||||
github.com/go-openapi/spec v0.22.6/go.mod h1:HZvTHat+iH0PALQRWhrqIHtU/PEqxqd89fu0MxGlMeM=
|
||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8=
|
||||
github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k=
|
||||
github.com/go-openapi/swag/jsonutils v0.28.0 h1:YIch6FwO7RXzeAnbO8Tu7dWBZeUEH+4nA0HXltVTnv4=
|
||||
github.com/go-openapi/swag/jsonutils v0.28.0/go.mod h1:CYM3WlTUcagR2ZoHdz54di/cbBqt82tuxuXgAjxw+mg=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0 h1:qV+VVUAx5Oro8WjVWpZeql7YReTKhT4smR4zhcOQZr0=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY=
|
||||
github.com/go-openapi/swag/loading v0.28.0 h1:td8QZdZC9MIYGGSnSPKShKiK22I2tU5UQvuUhIBPRLU=
|
||||
github.com/go-openapi/swag/loading v0.28.0/go.mod h1:rXB0QiQX5mMveXEA7ouM4KiiM9jVJe4K6BVbwhD1M4k=
|
||||
github.com/go-openapi/swag/pools v0.28.0 h1:HPMZWSAfce3rdVTFcjFiCIBtDg9h4x2QlRrHipwhxeU=
|
||||
github.com/go-openapi/swag/pools v0.28.0/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE=
|
||||
github.com/go-openapi/swag/stringutils v0.28.0 h1:ixsc9iYgDPubHL/8nSkbnryEHpD2VRlBMLKpQyPXcDU=
|
||||
github.com/go-openapi/swag/stringutils v0.28.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM=
|
||||
github.com/go-openapi/swag/typeutils v0.28.0 h1:nRBKSBXjDgf01VDPB3fWeD9nQuhCOVeIYAkUx2tbkyY=
|
||||
github.com/go-openapi/swag/typeutils v0.28.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ=
|
||||
github.com/go-openapi/swag/yamlutils v0.28.0 h1:TV3JXH6DS46KUroDtMLAYHGkdWf5VDq3wVWFirmzROY=
|
||||
github.com/go-openapi/swag/yamlutils v0.28.0/go.mod h1:x0q/yndZHEgk9Rx3DyDqzFUmHy55KTvIZldvF2dTJXs=
|
||||
github.com/go-openapi/swag/conv v0.27.0 h1:EKOH4feXrvdo8DbSsXSAqRT8fz1epEnS5O2IfXUOzE8=
|
||||
github.com/go-openapi/swag/conv v0.27.0/go.mod h1:pfiv0uKQTbaGApk8Zs/lZV3uSjmSpa2FO1y183YngN8=
|
||||
github.com/go-openapi/swag/jsonname v0.27.0 h1:4QVB//CKOdE8IOiBg19JNY2wfDS48MhesIquYBy2rUE=
|
||||
github.com/go-openapi/swag/jsonname v0.27.0/go.mod h1:I1YsyvvhBuZsFXSW6I7ODfdyq13p7hDil//1T9/pFFk=
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0 h1:VYtd9jEQYeU4j8q5vdn5KWotF4vKywhGdMBrALtAsfE=
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0/go.mod h1:U7pb8AGuwhok3RDicHeHwSG4L3PXSq6PAL98Aon632g=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.0 h1:+d7C7Ur/SsGg/UZ9G0JEovnfRqtMNZCJQGKc2h/ojoE=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY=
|
||||
github.com/go-openapi/swag/loading v0.27.0 h1:s8DA9aPEdFH6OluHUYUn3DnIuoTdyWs9RwffXBUfyeI=
|
||||
github.com/go-openapi/swag/loading v0.27.0/go.mod h1:VOz+Jg6UGGywcmRvYsI4fvtp+bd7NfioseGEPleYdA4=
|
||||
github.com/go-openapi/swag/stringutils v0.27.0 h1:Of7w/HljWsNZvuxsUAnw3n+hCOyI6HLJOxW2kQRAxio=
|
||||
github.com/go-openapi/swag/stringutils v0.27.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM=
|
||||
github.com/go-openapi/swag/typeutils v0.27.0 h1:aCf4MSGo8NLwZP8Q6t32DWLJSvl/WwNqgmEG+xJ6v2o=
|
||||
github.com/go-openapi/swag/typeutils v0.27.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ=
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0 h1:bQ6eAMil5X9tdcf7dMn4t15alzG6jddnrKPuKa/zxKM=
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0/go.mod h1:yRfIo7qqVkmJRQjX8exjA3AfcI8rH1KDNPsTparoCv4=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo=
|
||||
github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug=
|
||||
@@ -628,8 +628,8 @@ github.com/ldez/tagliatelle v0.7.2 h1:KuOlL70/fu9paxuxbeqlicJnCspCRjH0x8FW+NfgYU
|
||||
github.com/ldez/tagliatelle v0.7.2/go.mod h1:PtGgm163ZplJfZMZ2sf5nhUT170rSuPgBimoyYtdaSI=
|
||||
github.com/ldez/usetesting v0.5.0 h1:3/QtzZObBKLy1F4F8jLuKJiKBjjVFi1IavpoWbmqLwc=
|
||||
github.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3iRrzvDQ=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY=
|
||||
github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
@@ -658,12 +658,12 @@ github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
|
||||
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-sqlite3 v1.14.49 h1:B8jBHC3xhxZgxztrgruTuLucebnULQnx4W7cF7SAE9w=
|
||||
github.com/mattn/go-sqlite3 v1.14.49/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/mattn/go-sqlite3 v1.14.48 h1:7XHIgl0a8HwOaiK4E47ozLkST78rR9+OtNGx27D/TFs=
|
||||
github.com/mattn/go-sqlite3 v1.14.48/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/mgechev/revive v1.15.0 h1:vJ0HzSBzfNyPbHKolgiFjHxLek9KUijhqh42yGoqZ8Q=
|
||||
@@ -941,9 +941,8 @@ go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
@@ -1303,8 +1302,8 @@ modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
|
||||
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
|
||||
modernc.org/libc v1.74.2 h1:r94QPC+Mh3WN1lSCDxQxFdIxcI+zdQROo+1pTEZGqkk=
|
||||
modernc.org/libc v1.74.2/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
@@ -1313,8 +1312,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
|
||||
modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
|
||||
+2
-6
@@ -45,8 +45,8 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
return http.StatusBadRequest, fmt.Errorf("api token duration must be valid")
|
||||
}
|
||||
|
||||
// For full tokens (minimal=false), permissions are embedded in the JWT claim.
|
||||
// For minimal tokens (minimal=true), only standard JWT claims are included.
|
||||
// For full tokens (minimal=false), permissions are required in the claim
|
||||
// For minimal tokens (minimal=true), permissions are not in the token
|
||||
var permissions users.Permissions
|
||||
if !minimal {
|
||||
// Parse permissions from the query parameter
|
||||
@@ -60,10 +60,6 @@ func createApiTokenHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
Realtime: strings.Contains(permissionsStr, "realtime") && d.user.Permissions.Realtime,
|
||||
Download: strings.Contains(permissionsStr, "download") && d.user.Permissions.Download,
|
||||
}
|
||||
if !permissions.Api && !permissions.Admin && !permissions.Modify && !permissions.Delete &&
|
||||
!permissions.Create && !permissions.Share && !permissions.Realtime && !permissions.Download {
|
||||
minimal = true
|
||||
}
|
||||
}
|
||||
|
||||
// Convert the duration string to an int64
|
||||
|
||||
+45
-38
@@ -2,15 +2,14 @@ package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
liberrors "github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
@@ -174,13 +173,13 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
// modify all filepaths for user scope
|
||||
if d.share == nil {
|
||||
userscope, err = d.user.GetScopeForSourceName(source)
|
||||
if err != nil || userscope == "" {
|
||||
if err != nil {
|
||||
// Send OnlyOffice error log if this was an OnlyOffice file
|
||||
if isOnlyOffice {
|
||||
// Try to get document ID for error logging
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx != nil {
|
||||
tempPath := utils.JoinScopedIndexPath(userscope, firstFilePath)
|
||||
tempPath := utils.JoinPathAsUnix(userscope, firstFilePath)
|
||||
if realPath, _, realErr := idx.GetRealPath(tempPath); realErr == nil {
|
||||
if docId, _ := getOnlyOfficeId(realPath); docId != "" {
|
||||
if ctx := getOnlyOfficeLogContext(docId); ctx != nil {
|
||||
@@ -191,10 +190,10 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
}
|
||||
}
|
||||
}
|
||||
return http.StatusForbidden, fmt.Errorf("user has no access to source: %s", source)
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
for i, filePath := range fileList {
|
||||
fileList[i] = utils.JoinScopedIndexPath(userscope, filePath)
|
||||
fileList[i] = utils.JoinPathAsUnix(userscope, filePath)
|
||||
}
|
||||
}
|
||||
firstFilePath = fileList[0]
|
||||
@@ -208,41 +207,22 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
}
|
||||
return http.StatusInternalServerError, fmt.Errorf("source %s is not available", source)
|
||||
}
|
||||
|
||||
var bound string
|
||||
if d.share != nil {
|
||||
if d.share.Path == "" {
|
||||
return http.StatusForbidden, fmt.Errorf("share has no path scope")
|
||||
realPath, isDir, err := idx.GetRealPath(firstFilePath)
|
||||
if err != nil {
|
||||
// Send OnlyOffice error log if this was an OnlyOffice file
|
||||
if isOnlyOffice {
|
||||
if docId, _ := getOnlyOfficeId(realPath); docId != "" {
|
||||
if ctx := getOnlyOfficeLogContext(docId); ctx != nil {
|
||||
sendOnlyOfficeLogEvent(ctx, "ERROR", "download",
|
||||
fmt.Sprintf("OnlyOffice download failed - could not resolve path: %s - %v", firstFilePath, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
bound = d.share.Path
|
||||
} else {
|
||||
bound = userscope
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
|
||||
// ** Single file download with Content-Length **
|
||||
if len(fileList) == 1 {
|
||||
fd, fileInfo, openErr := idx.OpenScopedPath(bound, firstFilePath)
|
||||
if openErr != nil {
|
||||
if errors.Is(openErr, liberrors.ErrPathEscapesScope) {
|
||||
return http.StatusForbidden, openErr
|
||||
}
|
||||
if isOnlyOffice {
|
||||
if docId, _ := getOnlyOfficeId(filepath.Join(idx.Path, firstFilePath)); docId != "" {
|
||||
if ctx := getOnlyOfficeLogContext(docId); ctx != nil {
|
||||
sendOnlyOfficeLogEvent(ctx, "ERROR", "download",
|
||||
fmt.Sprintf("OnlyOffice download failed - could not open file: %s - %v", firstFilePath, openErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
return http.StatusInternalServerError, openErr
|
||||
}
|
||||
defer fd.Close()
|
||||
realPath := fd.Name()
|
||||
|
||||
if fileInfo.IsDir() {
|
||||
return BuildAndStreamArchive(w, r, d, source, fileList)
|
||||
}
|
||||
|
||||
if len(fileList) == 1 && !isDir {
|
||||
// Get document ID and log context for OnlyOffice downloads
|
||||
if isOnlyOffice {
|
||||
documentId, _ = getOnlyOfficeId(realPath)
|
||||
@@ -251,10 +231,11 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
}
|
||||
}
|
||||
|
||||
// Verify access control before serving the file (direct rule check)
|
||||
// Verify access control before opening the file (direct rule check)
|
||||
if d.share == nil && store.Access != nil {
|
||||
if !store.Access.Permitted(idx.Path, firstFilePath, d.user.Username) {
|
||||
logger.Debugf("user %s denied access to path %s", d.user.Username, firstFilePath)
|
||||
// Send OnlyOffice error log if this was an OnlyOffice download
|
||||
if isOnlyOffice && logContext != nil {
|
||||
sendOnlyOfficeLogEvent(logContext, "ERROR", "download",
|
||||
fmt.Sprintf("OnlyOffice download failed - access denied by rule: %s", firstFilePath))
|
||||
@@ -263,6 +244,28 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
}
|
||||
}
|
||||
|
||||
fd, err2 := os.Open(realPath)
|
||||
if err2 != nil {
|
||||
// Send OnlyOffice error log if this was an OnlyOffice download
|
||||
if isOnlyOffice && logContext != nil {
|
||||
sendOnlyOfficeLogEvent(logContext, "ERROR", "download",
|
||||
fmt.Sprintf("OnlyOffice download failed - could not open file: %s - %v", firstFilePath, err2))
|
||||
}
|
||||
return http.StatusInternalServerError, err2
|
||||
}
|
||||
defer fd.Close()
|
||||
|
||||
// Get file size
|
||||
fileInfo, err2 := fd.Stat()
|
||||
if err2 != nil {
|
||||
// Send OnlyOffice error log if this was an OnlyOffice download
|
||||
if isOnlyOffice && logContext != nil {
|
||||
sendOnlyOfficeLogEvent(logContext, "ERROR", "download",
|
||||
fmt.Sprintf("OnlyOffice download failed - could not get file info: %s - %v", firstFilePath, err2))
|
||||
}
|
||||
return http.StatusInternalServerError, err2
|
||||
}
|
||||
|
||||
// Send success log for OnlyOffice downloads
|
||||
if isOnlyOffice && logContext != nil {
|
||||
logger.Infof("OnlyOffice Server is downloading file: %s (documentId: %s)",
|
||||
@@ -276,9 +279,13 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
|
||||
setContentDisposition(w, r, fileName)
|
||||
w.Header().Set("Cache-Control", "private")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
// video scrubbing, etc.
|
||||
// Note: http.ServeContent will respect our already-set Content-Disposition header
|
||||
var reader io.ReadSeeker = fd
|
||||
if d.share != nil && d.share.MaxBandwidth > 0 {
|
||||
// convert KB/s to B/s
|
||||
limit := rate.Limit(d.share.MaxBandwidth * 1024)
|
||||
// burst size can be the same as limit
|
||||
burst := d.share.MaxBandwidth * 1024
|
||||
reader = newThrottledReadSeeker(fd, limit, burst, r.Context())
|
||||
}
|
||||
|
||||
@@ -201,10 +201,7 @@ func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.U
|
||||
|
||||
data.token = tokenString
|
||||
var tk users.AuthToken
|
||||
// Validate signature without enforcing exp/iat so expired session JWTs can still yield
|
||||
// user context on public-share routes; revocation is checked explicitly below.
|
||||
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
|
||||
token, err := parser.ParseWithClaims(tokenString, &tk, keyFunc)
|
||||
token, err := jwt.ParseWithClaims(tokenString, &tk, keyFunc)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -213,18 +210,8 @@ func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.U
|
||||
return nil
|
||||
}
|
||||
|
||||
if auth.IsRevokedApiToken(store.Access, tokenString) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tk.BelongsTo == 0 {
|
||||
userID, found := store.Access.GetUserIDFromToken(tokenString)
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
tk.BelongsTo = userID
|
||||
}
|
||||
|
||||
// Token is valid (but might be expired or revoked)
|
||||
// Try to get the user regardless of expiration status
|
||||
user, err := store.Users.Get(tk.BelongsTo)
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to get user with ID %v: %v", tk.BelongsTo, err)
|
||||
|
||||
@@ -46,18 +46,6 @@ func setupTestEnv(t *testing.T) {
|
||||
mockFileInfoFaster(t) // Mock FileInfoFasterFunc for this test
|
||||
}
|
||||
|
||||
func saveTestUser(t *testing.T, user *users.User) *users.User {
|
||||
t.Helper()
|
||||
if err := store.Users.Save(user, false, false); err != nil {
|
||||
t.Fatalf("Save(%s): %v", user.Username, err)
|
||||
}
|
||||
got, err := store.Users.Get(user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func mockFileInfoFaster(t *testing.T) {
|
||||
// Backup the original function
|
||||
originalFileInfoFaster := FileInfoFasterFunc
|
||||
@@ -92,10 +80,10 @@ func TestWithAdminHelper(t *testing.T) {
|
||||
Permissions: users.Permissions{Admin: false}, // Non-admin user
|
||||
}
|
||||
// Save the users to the mock database
|
||||
if err := store.Users.Save(adminUser, false, false); err != nil {
|
||||
if err := store.Users.Save(adminUser, true, true); err != nil {
|
||||
t.Fatal("failed to save admin user:", err)
|
||||
}
|
||||
if err := store.Users.Save(nonAdminUser, false, false); err != nil {
|
||||
if err := store.Users.Save(nonAdminUser, true, true); err != nil {
|
||||
t.Fatal("failed to save non-admin user:", err)
|
||||
}
|
||||
// Test cases for different scenarios
|
||||
@@ -156,162 +144,6 @@ func TestWithAdminHelper(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicShare_RejectsRevokedJWT(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
victim := &users.User{
|
||||
Username: "victim",
|
||||
Permissions: users.Permissions{Api: true},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: "srv", Scope: "/"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(victim, false, false); err != nil {
|
||||
t.Fatal("failed to create victim user:", err)
|
||||
}
|
||||
|
||||
originalAuthKey := settings.Config.Auth.Key
|
||||
settings.Config.Auth.Key = "key"
|
||||
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
|
||||
if err := store.Settings.Save(&settings.Settings{Auth: settings.Auth{Key: "key"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tokenString, _, err := auth.MakeSignedTokenAPI(victim, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*2, victim.Permissions, false)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to issue token: %v", err)
|
||||
}
|
||||
|
||||
shareLink := &share.Link{
|
||||
Hash: "revoked_jwt_hash",
|
||||
UserID: victim.ID,
|
||||
CommonShare: share.CommonShare{
|
||||
Source: "/srv",
|
||||
Path: "/",
|
||||
AllowedUsernames: []string{"victim"},
|
||||
},
|
||||
}
|
||||
if err := store.Share.Save(shareLink); err != nil {
|
||||
t.Fatal("failed to create share:", err)
|
||||
}
|
||||
|
||||
handler := withHashFile(publicGetResourceHandler)
|
||||
|
||||
makeRequest := func(jwt string) *httptest.ResponseRecorder {
|
||||
recorder := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/public/api/resources?hash=revoked_jwt_hash&path=/", http.NoBody)
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "filebrowser_quantum_jwt",
|
||||
Value: jwt,
|
||||
})
|
||||
handler.ServeHTTP(recorder, req)
|
||||
return recorder
|
||||
}
|
||||
|
||||
rec := makeRequest(tokenString)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("valid token: expected status %d, got %d", http.StatusOK, rec.Code)
|
||||
}
|
||||
|
||||
if err := auth.RevokeApiToken(store.Access, tokenString); err != nil {
|
||||
t.Fatalf("failed to revoke token: %v", err)
|
||||
}
|
||||
|
||||
rec = makeRequest(tokenString)
|
||||
if rec.Code == http.StatusOK {
|
||||
t.Fatalf("revoked token: expected non-200 status, got %d (JWT resurrection bypass)", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractUserFromExpiredToken_RejectsRevokedJWT(t *testing.T) {
|
||||
_, tokenString := issueExtractUserTestToken(t, time.Hour*2)
|
||||
if err := auth.RevokeApiToken(store.Access, tokenString); err != nil {
|
||||
t.Fatalf("failed to revoke token: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/public/api/resources", http.NoBody)
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "filebrowser_quantum_jwt",
|
||||
Value: tokenString,
|
||||
})
|
||||
|
||||
data := &requestContext{}
|
||||
if got := extractUserFromExpiredToken(req, data); got != nil {
|
||||
t.Fatalf("extractUserFromExpiredToken() = user %q, want nil for revoked token", got.Username)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractUserFromExpiredToken_AcceptsExpiredNonRevoked(t *testing.T) {
|
||||
user, tokenString := issueExtractUserTestToken(t, -time.Hour)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/public/api/resources", http.NoBody)
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "filebrowser_quantum_jwt",
|
||||
Value: tokenString,
|
||||
})
|
||||
|
||||
data := &requestContext{}
|
||||
got := extractUserFromExpiredToken(req, data)
|
||||
if got == nil {
|
||||
t.Fatal("extractUserFromExpiredToken() = nil, want user for expired non-revoked token")
|
||||
}
|
||||
if got.Username != user.Username {
|
||||
t.Fatalf("extractUserFromExpiredToken() username = %q, want %q", got.Username, user.Username)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractUserFromExpiredToken_RejectsRevokedExpired(t *testing.T) {
|
||||
_, tokenString := issueExtractUserTestToken(t, -time.Hour)
|
||||
if err := auth.RevokeApiToken(store.Access, tokenString); err != nil {
|
||||
t.Fatalf("failed to revoke token: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/public/api/resources", http.NoBody)
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "filebrowser_quantum_jwt",
|
||||
Value: tokenString,
|
||||
})
|
||||
|
||||
data := &requestContext{}
|
||||
if got := extractUserFromExpiredToken(req, data); got != nil {
|
||||
t.Fatalf("extractUserFromExpiredToken() = user %q, want nil for revoked expired token", got.Username)
|
||||
}
|
||||
}
|
||||
|
||||
func issueExtractUserTestToken(t *testing.T, duration time.Duration) (*users.User, string) {
|
||||
t.Helper()
|
||||
setupTestEnv(t)
|
||||
|
||||
user := &users.User{
|
||||
Username: "victim",
|
||||
Permissions: users.Permissions{Api: true},
|
||||
}
|
||||
if err := store.Users.Save(user, false, false); err != nil {
|
||||
t.Fatal("failed to create user:", err)
|
||||
}
|
||||
got, err := store.Users.Get(user.ID)
|
||||
if err != nil {
|
||||
t.Fatal("failed to load user:", err)
|
||||
}
|
||||
got.Permissions = users.Permissions{Api: true}
|
||||
if err = store.Users.Save(got, false, false); err != nil {
|
||||
t.Fatal("failed to set user permissions:", err)
|
||||
}
|
||||
|
||||
originalAuthKey := settings.Config.Auth.Key
|
||||
settings.Config.Auth.Key = "key"
|
||||
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
|
||||
if err = store.Settings.Save(&settings.Settings{Auth: settings.Auth{Key: "key"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tokenString, _, err := auth.MakeSignedTokenAPI(got, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), duration, got.Permissions, false)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to issue token: %v", err)
|
||||
}
|
||||
return got, tokenString
|
||||
}
|
||||
|
||||
func TestPublicShareHandlerAuthentication(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
@@ -326,7 +158,7 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
|
||||
{Name: "srv", Scope: "/"}, // Root scope on srv source
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(dummyUser, false, false); err != nil {
|
||||
if err := store.Users.Save(dummyUser, true, true); err != nil {
|
||||
t.Fatal("failed to save dummy user:", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ func publicDownloadHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
}
|
||||
|
||||
// Join the share path with the requested path
|
||||
filePath := utils.JoinScopedIndexPath(d.share.Path, cleanFile)
|
||||
filePath := utils.JoinPathAsUnix(d.share.Path, cleanFile)
|
||||
fileList = append(fileList, filePath)
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ func publicPutHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
resolvedPath := utils.JoinScopedIndexPath(d.share.Path, cleanPath)
|
||||
resolvedPath := utils.JoinPathAsUnix(d.share.Path, cleanPath)
|
||||
err = files.WriteFile(sourceName, resolvedPath, r.Body)
|
||||
// hide the error
|
||||
if err != nil {
|
||||
@@ -373,13 +373,13 @@ func publicPatchHandler(w http.ResponseWriter, r *http.Request, d *requestContex
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid from path: %w", err)
|
||||
}
|
||||
req.Items[i].FromSource = sourceName
|
||||
req.Items[i].FromPath = utils.JoinScopedIndexPath(d.share.Path, sanitizedPath)
|
||||
req.Items[i].FromPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath)
|
||||
sanitizedPath, err = utils.SanitizeUserPath(req.Items[i].ToPath)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid to path: %w", err)
|
||||
}
|
||||
req.Items[i].ToSource = sourceName
|
||||
req.Items[i].ToPath = utils.JoinScopedIndexPath(d.share.Path, sanitizedPath)
|
||||
req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath)
|
||||
}
|
||||
d.Data = req
|
||||
|
||||
|
||||
+16
-16
@@ -333,7 +333,7 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques
|
||||
continue
|
||||
}
|
||||
withoutUserScope := strings.TrimPrefix(d.share.Path, userScope)
|
||||
indexPath := utils.JoinScopedIndexPath(withoutUserScope, sanitizedPath)
|
||||
indexPath := utils.JoinPathAsUnix(withoutUserScope, sanitizedPath)
|
||||
|
||||
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
|
||||
FollowSymlinks: true,
|
||||
@@ -471,15 +471,13 @@ func resourcePauseHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
logger.Debugf("source %s not found", source)
|
||||
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
|
||||
}
|
||||
userscope, err := d.user.GetScopeForSourceName(source)
|
||||
if err != nil {
|
||||
if _, err := d.user.GetScopeForSourceName(source); err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
fullIndexPath := utils.JoinScopedIndexPath(userscope, path)
|
||||
if !store.Access.Permitted(idx.Path, fullIndexPath, d.user.Username) {
|
||||
return http.StatusForbidden, fmt.Errorf("access denied to path %s", fullIndexPath)
|
||||
if !store.Access.Permitted(idx.Path, path, d.user.Username) {
|
||||
return http.StatusForbidden, fmt.Errorf("access denied to path %s", path)
|
||||
}
|
||||
pauseCache.Set(pauseUploadCacheKey(source, fullIndexPath), "1")
|
||||
pauseCache.Set(pauseUploadCacheKey(source, path), "1")
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
@@ -568,14 +566,14 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
|
||||
}
|
||||
userscope = strings.TrimRight(userscope, "/")
|
||||
|
||||
fullIndexPath := utils.JoinScopedIndexPath(userscope, path)
|
||||
fullIndexPath := utils.JoinPathAsUnix(userscope, path)
|
||||
|
||||
// get scoped path
|
||||
realPath, _, _ := idx.GetRealPath(fullIndexPath)
|
||||
|
||||
// Check access control for the target path
|
||||
if !store.Access.Permitted(idx.Path, fullIndexPath, filePermUser.Username) {
|
||||
return http.StatusForbidden, fmt.Errorf("access denied to path %s", fullIndexPath)
|
||||
if !store.Access.Permitted(idx.Path, path, filePermUser.Username) {
|
||||
return http.StatusForbidden, fmt.Errorf("access denied to path %s", path)
|
||||
}
|
||||
|
||||
// Check for file/folder conflicts before creation
|
||||
@@ -692,7 +690,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
|
||||
publicPauseCache.Delete(k)
|
||||
}
|
||||
} else {
|
||||
k := pauseUploadCacheKey(source, fullIndexPath)
|
||||
k := pauseUploadCacheKey(source, path)
|
||||
if _, ok := pauseCache.Get(k); ok {
|
||||
gracefulPause = true
|
||||
pauseCache.Delete(k)
|
||||
@@ -767,7 +765,7 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex
|
||||
if err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
fullIndexPath := utils.JoinScopedIndexPath(userScope, path)
|
||||
fullIndexPath := utils.JoinPathAsUnix(userScope, path)
|
||||
// Check access control for the target path
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx == nil {
|
||||
@@ -932,8 +930,8 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
}
|
||||
|
||||
// Build full index paths for access control
|
||||
fullSrcIndexPath := utils.JoinScopedIndexPath(userscopeSrc, item.FromPath)
|
||||
fullDstIndexPath := utils.JoinScopedIndexPath(userscopeDst, item.ToPath)
|
||||
fullSrcIndexPath := utils.JoinPathAsUnix(userscopeSrc, item.FromPath)
|
||||
fullDstIndexPath := utils.JoinPathAsUnix(userscopeDst, item.ToPath)
|
||||
if fullDstIndexPath == "/" || fullSrcIndexPath == "/" {
|
||||
item.Message = "source or destination is the root or unautharized directory"
|
||||
response.Failed = append(response.Failed, item)
|
||||
@@ -965,7 +963,9 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
}
|
||||
|
||||
// Get real paths
|
||||
realSrc, isSrcDir, err := srcIdx.GetRealPath(fullSrcIndexPath)
|
||||
// Combine user scope with item paths BEFORE calling GetRealPath to avoid double scope application
|
||||
fullSrcPath := utils.JoinPathAsUnix(userscopeSrc, item.FromPath)
|
||||
realSrc, isSrcDir, err := srcIdx.GetRealPath(fullSrcPath)
|
||||
if err != nil {
|
||||
logger.Errorf("could not resolve source path: %v, item.FromPath: %v", err, item.FromPath)
|
||||
item.Message = "could not resolve source path"
|
||||
@@ -981,7 +981,7 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
|
||||
// Check destination parent directory exists
|
||||
dstParentPath := filepath.Dir(item.ToPath)
|
||||
fullDstParentPath := utils.JoinScopedIndexPath(userscopeDst, dstParentPath)
|
||||
fullDstParentPath := utils.JoinPathAsUnix(userscopeDst, dstParentPath)
|
||||
parentDir, _, err := dstIdx.GetRealPath(fullDstParentPath)
|
||||
if err != nil {
|
||||
item.Message = "destination directory does not exist"
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
)
|
||||
|
||||
func setupResourceACLTestSource(t *testing.T) string {
|
||||
t.Helper()
|
||||
srvRoot := t.TempDir()
|
||||
settings.Config.Server.SourceMap = map[string]*settings.Source{
|
||||
srvRoot: {Path: srvRoot, Name: "srv"},
|
||||
}
|
||||
settings.Config.Server.NameToSource = map[string]*settings.Source{
|
||||
"srv": {Path: srvRoot, Name: "srv"},
|
||||
}
|
||||
indexing.SetTestIndex("srv", srvRoot)
|
||||
t.Cleanup(indexing.ClearTestIndices)
|
||||
return srvRoot
|
||||
}
|
||||
|
||||
func TestResourcePostACLUsesFullIndexPathKey(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
const (
|
||||
sourcePath = "/srv"
|
||||
userScope = "/home/alice"
|
||||
deniedFolder = "/home/alice/projects/acme/private"
|
||||
relPath = "/projects/acme/private/poison.docx"
|
||||
)
|
||||
fullIndexPath := utils.JoinScopedIndexPath(userScope, relPath)
|
||||
|
||||
alice := &users.User{
|
||||
ID: 1,
|
||||
Username: "alice",
|
||||
}
|
||||
if err := store.Users.Save(alice, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := store.Access.DenyUser(sourcePath, deniedFolder, "alice"); err != nil {
|
||||
t.Fatalf("DenyUser: %v", err)
|
||||
}
|
||||
|
||||
if !store.Access.Permitted(sourcePath, relPath, "alice") {
|
||||
t.Fatal("scope-stripped path does not match deny rule keyed at full index path (documents pre-fix ACL miss)")
|
||||
}
|
||||
if store.Access.Permitted(sourcePath, fullIndexPath, "alice") {
|
||||
t.Fatalf("full index path %q should be denied for alice", fullIndexPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcePostHandler_DeniesAuthenticatedUploadToDeniedPath(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
sourcePath := setupResourceACLTestSource(t)
|
||||
|
||||
alice := &users.User{
|
||||
ID: 1,
|
||||
Username: "alice",
|
||||
Permissions: users.Permissions{Create: true},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: sourcePath, Scope: "/home/alice"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(alice, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deniedFolder := "/home/alice/projects/acme/private"
|
||||
if err := store.Access.DenyUser(sourcePath, deniedFolder, "alice"); err != nil {
|
||||
t.Fatalf("DenyUser: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/resources?source=srv&path=/projects/acme/private/evil.txt",
|
||||
strings.NewReader("payload"),
|
||||
)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
status, err := resourcePostHandler(rec, req, &requestContext{user: alice})
|
||||
if status != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 for denied upload path, got status=%d err=%v", status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourcePauseHandler_DeniesAuthenticatedPauseOnDeniedPath(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
sourcePath := setupResourceACLTestSource(t)
|
||||
|
||||
alice := &users.User{
|
||||
ID: 1,
|
||||
Username: "alice",
|
||||
Permissions: users.Permissions{Create: true},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: sourcePath, Scope: "/home/alice"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(alice, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := store.Access.DenyUser(sourcePath, "/home/alice/projects/acme/private", "alice"); err != nil {
|
||||
t.Fatalf("DenyUser: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/resources/pause?source=srv&path=/projects/acme/private/evil.txt",
|
||||
http.NoBody,
|
||||
)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
status, err := resourcePauseHandler(rec, req, &requestContext{user: alice})
|
||||
if status != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 for denied pause path, got status=%d err=%v", status, err)
|
||||
}
|
||||
}
|
||||
+3
-33
@@ -220,32 +220,8 @@ func sharePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext
|
||||
if thisShare.UserID != d.user.ID && !d.user.Permissions.Admin {
|
||||
return http.StatusForbidden, fmt.Errorf("you are not allowed to update this share")
|
||||
}
|
||||
|
||||
sourceName := thisShare.GetSourceName()
|
||||
if sourceName == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("source not available for share")
|
||||
}
|
||||
shareOwner, err := store.Users.Get(thisShare.UserID)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("share owner not found")
|
||||
}
|
||||
userscope, err := shareOwner.GetScopeForSourceName(sourceName)
|
||||
if err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
storedPath := utils.JoinPathAsUnix(userscope, body.Path)
|
||||
storedPath = utils.AddTrailingSlashIfNotExists(storedPath)
|
||||
|
||||
idx := indexing.GetIndex(sourceName)
|
||||
if idx == nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("index not found for source: %s", sourceName)
|
||||
}
|
||||
_, _, err = idx.GetRealPath(storedPath)
|
||||
if err != nil {
|
||||
return http.StatusForbidden, fmt.Errorf("path not found: %s", body.Path)
|
||||
}
|
||||
|
||||
err = store.Share.UpdateSharePath(body.Hash, storedPath)
|
||||
// Update the share path
|
||||
err = store.Share.UpdateSharePath(body.Hash, sanitizedPath)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
@@ -344,11 +320,6 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
stringHash = string(hash)
|
||||
}
|
||||
if s != nil {
|
||||
if !s.UserCanEdit(d.user) {
|
||||
return http.StatusForbidden, fmt.Errorf("you are not allowed to update this share")
|
||||
}
|
||||
share.ClampShareEditable(d.user.Permissions, &body.CommonShare)
|
||||
|
||||
// Check if downloads limit or per-user limit changed - reset counts if so
|
||||
shouldResetCounts := s.DownloadsLimit != body.DownloadsLimit || s.PerUserDownloadLimit != body.PerUserDownloadLimit
|
||||
|
||||
@@ -418,7 +389,7 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
|
||||
body.Path = utils.JoinScopedIndexPath(userscope, cleanPath)
|
||||
body.Path = utils.JoinPathAsUnix(userscope, cleanPath)
|
||||
body.Path = utils.AddTrailingSlashIfNotExists(body.Path)
|
||||
// validate path exists as file or folder
|
||||
_, _, err = idx.GetRealPath(body.Path)
|
||||
@@ -429,7 +400,6 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
if body.ShareType == "upload" && !body.AllowCreate {
|
||||
body.AllowCreate = true
|
||||
}
|
||||
share.ClampShareEditable(d.user.Permissions, &body.CommonShare)
|
||||
body.Source = source.Path // backend source is path
|
||||
s = &share.Link{
|
||||
Expire: expire,
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
)
|
||||
|
||||
const victimShareHashX79q = "victim_share_x79q_01"
|
||||
|
||||
func setupShareAuthUsers(t *testing.T) (owner, attacker, admin *users.User) {
|
||||
t.Helper()
|
||||
setupTestEnv(t)
|
||||
|
||||
owner = &users.User{
|
||||
ID: 1,
|
||||
Username: "share_owner",
|
||||
Permissions: users.Permissions{Share: true, Delete: true, Create: true, Modify: true},
|
||||
Scopes: []users.SourceScope{{Name: "/srv", Scope: "/"}},
|
||||
}
|
||||
attacker = &users.User{
|
||||
ID: 2,
|
||||
Username: "share_attacker",
|
||||
Permissions: users.Permissions{Share: true, Delete: true, Create: true, Modify: true},
|
||||
Scopes: []users.SourceScope{{Name: "/srv", Scope: "/"}},
|
||||
}
|
||||
noDelete := &users.User{
|
||||
ID: 3,
|
||||
Username: "share_no_delete",
|
||||
Permissions: users.Permissions{Share: true, Delete: false, Create: true, Modify: true},
|
||||
Scopes: []users.SourceScope{{Name: "/srv", Scope: "/"}},
|
||||
}
|
||||
admin = &users.User{
|
||||
ID: 4,
|
||||
Username: "share_admin",
|
||||
Permissions: users.Permissions{Admin: true, Share: true, Delete: true},
|
||||
Scopes: []users.SourceScope{{Name: "/srv", Scope: "/"}},
|
||||
}
|
||||
|
||||
for _, u := range []*users.User{owner, attacker, noDelete, admin} {
|
||||
if err := store.Users.Save(u, false, false); err != nil {
|
||||
t.Fatalf("Save(%s): %v", u.Username, err)
|
||||
}
|
||||
}
|
||||
gotOwner, err := store.Users.Get(owner.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotAttacker, err := store.Users.Get(attacker.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotAdmin, err := store.Users.Get(admin.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return gotOwner, gotAttacker, gotAdmin
|
||||
}
|
||||
|
||||
func createVictimShareLink(t *testing.T, ownerID uint) {
|
||||
t.Helper()
|
||||
link := &share.Link{
|
||||
Hash: victimShareHashX79q,
|
||||
UserID: ownerID,
|
||||
Version: 1,
|
||||
CommonShare: share.CommonShare{
|
||||
Path: "/",
|
||||
Source: "/srv",
|
||||
ShareType: "normal",
|
||||
AllowDelete: false,
|
||||
},
|
||||
}
|
||||
if err := store.Share.Save(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func postShareUpdate(t *testing.T, user *users.User, hash string, allowDelete bool) (int, error) {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(map[string]interface{}{
|
||||
"hash": hash,
|
||||
"allowDelete": allowDelete,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/share", bytes.NewReader(raw))
|
||||
rec := httptest.NewRecorder()
|
||||
return sharePostHandler(rec, req, &requestContext{user: user})
|
||||
}
|
||||
|
||||
func postShareCreate(t *testing.T, user *users.User, allowDelete bool) (int, error) {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(map[string]interface{}{
|
||||
"path": "/",
|
||||
"source": "srv",
|
||||
"allowDelete": allowDelete,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/share", bytes.NewReader(raw))
|
||||
rec := httptest.NewRecorder()
|
||||
return sharePostHandler(rec, req, &requestContext{user: user})
|
||||
}
|
||||
|
||||
func TestSharePostUpdate_RejectNonOwner(t *testing.T) {
|
||||
owner, attacker, _ := setupShareAuthUsers(t)
|
||||
createVictimShareLink(t, owner.ID)
|
||||
|
||||
status, err := postShareUpdate(t, attacker, victimShareHashX79q, true)
|
||||
if status != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got status=%d err=%v", status, err)
|
||||
}
|
||||
|
||||
got, err := store.Share.GetByHash(victimShareHashX79q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.AllowDelete {
|
||||
t.Fatal("non-owner update should not enable allowDelete")
|
||||
}
|
||||
if got.UserID != owner.ID {
|
||||
t.Fatalf("UserID changed to %d, want owner %d", got.UserID, owner.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePostUpdate_AllowsOwner(t *testing.T) {
|
||||
owner, _, _ := setupShareAuthUsers(t)
|
||||
createVictimShareLink(t, owner.ID)
|
||||
|
||||
status, err := postShareUpdate(t, owner, victimShareHashX79q, true)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("expected 200, got status=%d err=%v", status, err)
|
||||
}
|
||||
|
||||
got, err := store.Share.GetByHash(victimShareHashX79q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !got.AllowDelete {
|
||||
t.Fatal("owner update should enable allowDelete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePostCreate_ClampsAllowDeleteWithoutUserDeletePerm(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
indexing.SetTestIndex("srv", t.TempDir())
|
||||
t.Cleanup(indexing.ClearTestIndices)
|
||||
|
||||
user := &users.User{
|
||||
ID: 5,
|
||||
Username: "share_no_delete_create",
|
||||
Permissions: users.Permissions{Share: true, Delete: false, Create: true},
|
||||
Scopes: []users.SourceScope{{Name: "/srv", Scope: "/"}},
|
||||
}
|
||||
if err := store.Users.Save(user, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := store.Users.Get(user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
status, handlerErr := postShareCreate(t, got, true)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("expected 200, got status=%d err=%v", status, handlerErr)
|
||||
}
|
||||
|
||||
links, err := store.Share.GetBySourcePath("/", "/srv")
|
||||
if err != nil || len(links) == 0 {
|
||||
t.Fatalf("expected created share, err=%v len=%d", err, len(links))
|
||||
}
|
||||
created := links[len(links)-1]
|
||||
if created.AllowDelete {
|
||||
t.Fatal("user without delete permission should not persist allowDelete=true")
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
)
|
||||
|
||||
func TestSharePatchHandler_AnchorsPathToOwnerScope(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
srvRoot := t.TempDir()
|
||||
publicDir := filepath.Join(srvRoot, "public")
|
||||
if err := os.MkdirAll(publicDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(publicDir, "marker.txt"), []byte("ok"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
settings.Config.Server.SourceMap = map[string]*settings.Source{
|
||||
"/srv": {Path: "/srv", Name: "srv"},
|
||||
}
|
||||
settings.Config.Server.NameToSource = map[string]*settings.Source{
|
||||
"srv": {Path: "/srv", Name: "srv"},
|
||||
}
|
||||
indexing.SetTestIndex("srv", srvRoot)
|
||||
t.Cleanup(indexing.ClearTestIndices)
|
||||
|
||||
guest := &users.User{
|
||||
ID: 2,
|
||||
Username: "guest",
|
||||
Permissions: users.Permissions{
|
||||
Share: true,
|
||||
},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: "/srv", Scope: "/public"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(guest, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
initialPath := "/public/"
|
||||
link := &share.Link{
|
||||
Hash: "patch_scope_hash",
|
||||
UserID: guest.ID,
|
||||
Version: 1,
|
||||
CommonShare: share.CommonShare{
|
||||
Path: initialPath,
|
||||
Source: "/srv",
|
||||
},
|
||||
}
|
||||
if err := store.Share.Save(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"hash": link.Hash,
|
||||
"path": "/",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/share", bytes.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
status, handlerErr := sharePatchHandler(rec, req, &requestContext{user: guest})
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("sharePatchHandler status=%d err=%v", status, handlerErr)
|
||||
}
|
||||
|
||||
updated, err := store.Share.GetByHash(link.Hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated.Path == "/" {
|
||||
t.Fatalf("share path escaped to source root: %q", updated.Path)
|
||||
}
|
||||
if updated.Path != initialPath {
|
||||
t.Fatalf("share path = %q, want %q", updated.Path, initialPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePatchHandler_AdminUpdateUsesOwnerScope(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
srvRoot := t.TempDir()
|
||||
publicDir := filepath.Join(srvRoot, "public")
|
||||
if err := os.MkdirAll(publicDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(publicDir, "marker.txt"), []byte("ok"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
settings.Config.Server.SourceMap = map[string]*settings.Source{
|
||||
"/srv": {Path: "/srv", Name: "srv"},
|
||||
}
|
||||
settings.Config.Server.NameToSource = map[string]*settings.Source{
|
||||
"srv": {Path: "/srv", Name: "srv"},
|
||||
}
|
||||
indexing.SetTestIndex("srv", srvRoot)
|
||||
t.Cleanup(indexing.ClearTestIndices)
|
||||
|
||||
owner := &users.User{
|
||||
ID: 2,
|
||||
Username: "guest",
|
||||
Permissions: users.Permissions{
|
||||
Share: true,
|
||||
},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: "/srv", Scope: "/public"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(owner, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
admin := &users.User{
|
||||
ID: 1,
|
||||
Username: "admin",
|
||||
Permissions: users.Permissions{
|
||||
Admin: true,
|
||||
Share: true,
|
||||
},
|
||||
Scopes: []users.SourceScope{
|
||||
{Name: "/srv", Scope: "/"},
|
||||
},
|
||||
}
|
||||
if err := store.Users.Save(admin, false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
initialPath := "/public/"
|
||||
link := &share.Link{
|
||||
Hash: "patch_admin_scope_hash",
|
||||
UserID: owner.ID,
|
||||
Version: 1,
|
||||
CommonShare: share.CommonShare{
|
||||
Path: initialPath,
|
||||
Source: "/srv",
|
||||
},
|
||||
}
|
||||
if err := store.Share.Save(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"hash": link.Hash,
|
||||
"path": "/",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/share", bytes.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
status, handlerErr := sharePatchHandler(rec, req, &requestContext{user: admin})
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("sharePatchHandler status=%d err=%v", status, handlerErr)
|
||||
}
|
||||
|
||||
updated, err := store.Share.GetByHash(link.Hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated.Path == "/" {
|
||||
t.Fatalf("admin update escaped to source root using admin scope: %q", updated.Path)
|
||||
}
|
||||
if updated.Path != initialPath {
|
||||
t.Fatalf("share path = %q, want %q", updated.Path, initialPath)
|
||||
}
|
||||
}
|
||||
@@ -322,13 +322,13 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) {
|
||||
}
|
||||
|
||||
// Save users
|
||||
if err := store.Users.Save(adminUser, false, false); err != nil {
|
||||
if err := store.Users.Save(adminUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Users.Save(scopedUser, false, false); err != nil {
|
||||
if err := store.Users.Save(scopedUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Users.Save(restrictedUser, false, false); err != nil {
|
||||
if err := store.Users.Save(restrictedUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -464,13 +464,13 @@ func TestWebDAV_WriteOperations(t *testing.T) {
|
||||
}
|
||||
|
||||
// Save users
|
||||
if err := store.Users.Save(fullAccessUser, false, false); err != nil {
|
||||
if err := store.Users.Save(fullAccessUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Users.Save(readOnlyUser, false, false); err != nil {
|
||||
if err := store.Users.Save(readOnlyUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Users.Save(scopedUser, false, false); err != nil {
|
||||
if err := store.Users.Save(scopedUser, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -602,10 +602,10 @@ func TestWebDAV_AccessControl(t *testing.T) {
|
||||
}
|
||||
|
||||
// Save users
|
||||
if err := store.Users.Save(user1, false, false); err != nil {
|
||||
if err := store.Users.Save(user1, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Users.Save(user2, false, false); err != nil {
|
||||
if err := store.Users.Save(user2, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -708,7 +708,7 @@ func TestWebDAV_IndexingStates(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
if err := store.Users.Save(user, false, false); err != nil {
|
||||
if err := store.Users.Save(user, true, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
+12
-17
@@ -1,14 +1,13 @@
|
||||
package icons
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
)
|
||||
|
||||
// PWAManifest represents the web app manifest structure
|
||||
type PWAManifest struct {
|
||||
Name string `json:"name"`
|
||||
ShortName string `json:"short_name"`
|
||||
ID string `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Icons []PWAIcon `json:"icons"`
|
||||
@@ -30,23 +29,19 @@ type PWAIcon struct {
|
||||
// CachedManifest holds the generated PWA manifest at startup
|
||||
var CachedManifest PWAManifest
|
||||
|
||||
const pwaManifestNameMaxLen = 30
|
||||
|
||||
// pwaManifestName returns the app title for the web app manifest.
|
||||
// Names longer than 30 characters are truncated to fit common mobile launcher limits.
|
||||
func pwaManifestName(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
runes := []rune(name)
|
||||
if len(runes) > pwaManifestNameMaxLen {
|
||||
return string(runes[:pwaManifestNameMaxLen])
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// generatePWAManifest creates the PWA manifest structure.
|
||||
// generatePWAManifest creates the PWA manifest structure
|
||||
func generatePWAManifest(name, description, baseURL, themeColor, pwaIcon192, pwaIcon256, pwaIcon512 string) PWAManifest {
|
||||
shortName := name
|
||||
if len(name) > 12 {
|
||||
shortName = name[:12]
|
||||
}
|
||||
if name == "FileBrowser Quantum" {
|
||||
shortName = "FBQ"
|
||||
}
|
||||
|
||||
return PWAManifest{
|
||||
Name: pwaManifestName(name),
|
||||
Name: name,
|
||||
ShortName: shortName,
|
||||
ID: baseURL,
|
||||
Scope: baseURL,
|
||||
StartURL: baseURL,
|
||||
|
||||
@@ -93,7 +93,12 @@ func ManifestForShare(baseURL, startURL, name, description string) (PWAManifest,
|
||||
manifest.ID = shareRoot
|
||||
|
||||
if name = sanitizeManifestText(strings.TrimSpace(name)); name != "" {
|
||||
manifest.Name = pwaManifestName(name)
|
||||
manifest.Name = name
|
||||
shortName := name
|
||||
if len(shortName) > 12 {
|
||||
shortName = shortName[:12]
|
||||
}
|
||||
manifest.ShortName = shortName
|
||||
}
|
||||
if description = sanitizeManifestText(strings.TrimSpace(description)); description != "" {
|
||||
manifest.Description = description
|
||||
|
||||
@@ -52,10 +52,11 @@ func TestShareHashFromHTTPPathRejectsEmbeddedPrefix(t *testing.T) {
|
||||
|
||||
func TestManifestForShare(t *testing.T) {
|
||||
CachedManifest = PWAManifest{
|
||||
Name: "FileBrowser Quantum",
|
||||
StartURL: "/testing/",
|
||||
Scope: "/testing/",
|
||||
ID: "/testing/",
|
||||
Name: "FileBrowser Quantum",
|
||||
ShortName: "FBQ",
|
||||
StartURL: "/testing/",
|
||||
Scope: "/testing/",
|
||||
ID: "/testing/",
|
||||
}
|
||||
|
||||
manifest, ok := ManifestForShare(
|
||||
@@ -77,27 +78,3 @@ func TestManifestForShare(t *testing.T) {
|
||||
t.Fatalf("unexpected name: %q", manifest.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestForShareTruncatesLongName(t *testing.T) {
|
||||
CachedManifest = PWAManifest{
|
||||
Name: "FileBrowser Quantum",
|
||||
StartURL: "/testing/",
|
||||
Scope: "/testing/",
|
||||
ID: "/testing/",
|
||||
}
|
||||
|
||||
longName := "Shared files - quarterly backup archive 2026"
|
||||
want := "Shared files - quarterly backu"
|
||||
manifest, ok := ManifestForShare(
|
||||
"/testing/",
|
||||
"/testing/public/share/hash1234567890abcdef/",
|
||||
longName,
|
||||
"",
|
||||
)
|
||||
if !ok {
|
||||
t.Fatal("expected share manifest")
|
||||
}
|
||||
if manifest.Name != want {
|
||||
t.Fatalf("expected name %q, got %q", want, manifest.Name)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package indexing
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -433,7 +432,6 @@ type PathContext struct {
|
||||
type FileInfoRequest struct {
|
||||
IndexPath string
|
||||
FollowSymlinks bool
|
||||
BoundIndexPath string // index prefix for symlink containment (e.g. user scope)
|
||||
ShowHidden bool
|
||||
HideFileExt string // Hide files based on their extension
|
||||
Expand bool // get child items for directories
|
||||
@@ -441,61 +439,10 @@ type FileInfoRequest struct {
|
||||
SkipExtendedAttrs bool // whether to skip extended attributes
|
||||
}
|
||||
|
||||
// filesystemBound resolves the filesystem path for an index prefix under this source.
|
||||
func (idx *Index) filesystemBound(boundIndexPath string) (string, error) {
|
||||
bound := boundIndexPath
|
||||
if bound == "" {
|
||||
bound = "/"
|
||||
}
|
||||
fsPath := utils.JoinUnderSourceRoot(idx.Path, bound)
|
||||
abs, err := filepath.Abs(fsPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.EvalSymlinks(abs)
|
||||
}
|
||||
|
||||
// ensureResolvedContained rejects resolved filesystem paths outside the source or scope prefix.
|
||||
func (idx *Index) ensureResolvedContained(realPath, boundIndexPath string) error {
|
||||
sourceRoot, err := idx.filesystemBound("/")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := iteminfo.PathWithinRoot(sourceRoot, realPath); err != nil {
|
||||
return errors.ErrPathEscapesScope
|
||||
}
|
||||
bound := boundIndexPath
|
||||
if bound == "" {
|
||||
bound = "/"
|
||||
}
|
||||
if bound != "/" {
|
||||
scopeRoot, err := idx.filesystemBound(bound)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := iteminfo.PathWithinRoot(scopeRoot, realPath); err != nil {
|
||||
return errors.ErrPathEscapesScope
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveSymlinksContained resolves symlinks and ensures the target stays within bounds.
|
||||
func (idx *Index) resolveSymlinksContained(fsPath, boundIndexPath string) (string, error) {
|
||||
resolved, err := filepath.EvalSymlinks(fsPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := idx.ensureResolvedContained(resolved, boundIndexPath); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
// resolvePathContext resolves all path characteristics in a SINGLE stat call
|
||||
// This eliminates duplicate stat/lstat calls and redundant isHidden/isSymlink checks
|
||||
func (idx *Index) resolvePathContext(indexPath string, followSymlinks bool, boundIndexPath string) (*PathContext, error) {
|
||||
realPath := utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
func (idx *Index) resolvePathContext(indexPath string, followSymlinks bool) (*PathContext, error) {
|
||||
realPath := filepath.Join(idx.Path, indexPath)
|
||||
|
||||
// ONE filesystem stat call
|
||||
fileInfo, err := os.Lstat(realPath)
|
||||
@@ -507,7 +454,7 @@ func (idx *Index) resolvePathContext(indexPath string, followSymlinks bool, boun
|
||||
|
||||
// Resolve symlink if requested
|
||||
if isSymlink && followSymlinks {
|
||||
realPath, err = idx.resolveSymlinksContained(realPath, boundIndexPath)
|
||||
realPath, err = filepath.EvalSymlinks(realPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -563,7 +510,7 @@ func (idx *Index) evaluateIndexRules(ctx *PathContext, isRoutineScan bool) (isVi
|
||||
// User permission checking happens in the API layer (FileInfoFaster)
|
||||
func (idx *Index) GetFileInfo(req FileInfoRequest) (*iteminfo.FileInfo, error) {
|
||||
// 1. Resolve path context (single stat call)
|
||||
ctx, err := idx.resolvePathContext(req.IndexPath, req.FollowSymlinks, req.BoundIndexPath)
|
||||
ctx, err := idx.resolvePathContext(req.IndexPath, req.FollowSymlinks)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -651,7 +598,7 @@ func (idx *Index) indexDirectory(indexPath string, opts Options, scanner *Scanne
|
||||
if !strings.HasSuffix(indexPath, "/") {
|
||||
indexPath = indexPath + "/"
|
||||
}
|
||||
realPath := utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
realPath := filepath.Join(idx.Path, indexPath)
|
||||
|
||||
// Open the directory
|
||||
dir, err := os.Open(realPath)
|
||||
@@ -689,10 +636,10 @@ func (idx *Index) indexDirectory(indexPath string, opts Options, scanner *Scanne
|
||||
// GetFsInfoCore is the consolidated implementation for both GetFsInfo and GetFsInfoViewableOnly
|
||||
func (idx *Index) GetFsInfoCore(indexPath string, opts Options) (*iteminfo.FileInfo, error) {
|
||||
// Handle symlinks if not following them
|
||||
realPath := utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
realPath := filepath.Join(idx.Path, indexPath)
|
||||
if opts.FollowSymlinks {
|
||||
var err error
|
||||
realPath, err = idx.resolveSymlinksContained(realPath, "/")
|
||||
realPath, err = filepath.EvalSymlinks(realPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1048,24 +995,10 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, indexPath strin
|
||||
}
|
||||
|
||||
func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) {
|
||||
return idx.getRealPathInternal("/", false, relativePath...)
|
||||
}
|
||||
|
||||
// GetRealPathScoped resolves an index path and rejects symlink targets outside the source and bound prefix.
|
||||
func (idx *Index) GetRealPathScoped(boundIndexPath string, relativePath ...string) (string, bool, error) {
|
||||
return idx.getRealPathInternal(boundIndexPath, true, relativePath...)
|
||||
}
|
||||
|
||||
func (idx *Index) getRealPathInternal(boundIndexPath string, enforceScope bool, relativePath ...string) (string, bool, error) {
|
||||
indexPath := utils.JoinIndexPathComponents(relativePath...)
|
||||
joinedPath := utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
bound := boundIndexPath
|
||||
if enforceScope && bound == "" {
|
||||
bound = "/"
|
||||
}
|
||||
cacheKey := fmt.Sprintf("realpath|scoped=%t|bound=%q|path=%q", enforceScope, bound, joinedPath)
|
||||
isDir, _ := IsDirCache.Get(cacheKey + ":isdir")
|
||||
cached, ok := RealPathCache.Get(cacheKey)
|
||||
combined := append([]string{idx.Path}, relativePath...)
|
||||
joinedPath := filepath.Join(combined...)
|
||||
isDir, _ := IsDirCache.Get(joinedPath + ":isdir")
|
||||
cached, ok := RealPathCache.Get(joinedPath)
|
||||
if ok && cached != "" {
|
||||
return cached, isDir, nil
|
||||
}
|
||||
@@ -1074,53 +1007,11 @@ func (idx *Index) getRealPathInternal(boundIndexPath string, enforceScope bool,
|
||||
return absolutePath, false, fmt.Errorf("could not get real path: %v, %s", joinedPath, err)
|
||||
}
|
||||
realPath, isDir, err := iteminfo.ResolveSymlinks(absolutePath)
|
||||
if err != nil {
|
||||
return realPath, isDir, err
|
||||
if err == nil {
|
||||
RealPathCache.Set(joinedPath, realPath)
|
||||
IsDirCache.Set(joinedPath+":isdir", isDir)
|
||||
}
|
||||
if enforceScope {
|
||||
if err := idx.ensureResolvedContained(realPath, boundIndexPath); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
} else if err := idx.ensureResolvedContained(realPath, "/"); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
RealPathCache.Set(cacheKey, realPath)
|
||||
IsDirCache.Set(cacheKey+":isdir", isDir)
|
||||
return realPath, isDir, nil
|
||||
}
|
||||
|
||||
func scopedIndexRel(boundIndexPath, indexPath string) string {
|
||||
bound := boundIndexPath
|
||||
if bound == "" {
|
||||
bound = "/"
|
||||
}
|
||||
rel := indexPath
|
||||
if bound != "/" {
|
||||
rel = strings.TrimPrefix(indexPath, bound)
|
||||
}
|
||||
rel = strings.TrimPrefix(rel, "/")
|
||||
return filepath.FromSlash(rel)
|
||||
}
|
||||
|
||||
// OpenScopedPath opens indexPath relative to boundIndexPath using traversal-resistant APIs.
|
||||
func (idx *Index) OpenScopedPath(boundIndexPath, indexPath string) (*os.File, os.FileInfo, error) {
|
||||
scopeRoot, err := idx.filesystemBound(boundIndexPath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
file, err := iteminfo.OpenContained(scopeRoot, scopedIndexRel(boundIndexPath, indexPath))
|
||||
if err != nil {
|
||||
if _, _, scopeErr := idx.GetRealPathScoped(boundIndexPath, indexPath); stderrors.Is(scopeErr, errors.ErrPathEscapesScope) {
|
||||
return nil, nil, scopeErr
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return file, info, nil
|
||||
return realPath, isDir, err
|
||||
}
|
||||
|
||||
func (idx *Index) RefreshFileInfo(opts utils.FileOptions) error {
|
||||
@@ -1147,7 +1038,7 @@ func (idx *Index) RefreshDirectory(indexPath string, recursive bool) error {
|
||||
indexPath = indexPath + "/"
|
||||
}
|
||||
|
||||
realPath := utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
realPath := filepath.Join(idx.Path, indexPath)
|
||||
|
||||
// Check if directory exists
|
||||
dirInfo, err := os.Stat(realPath)
|
||||
|
||||
@@ -105,51 +105,6 @@ func (info *FileInfo) SortItems() {
|
||||
})
|
||||
}
|
||||
|
||||
// PathWithinRoot reports whether path is equal to or under root after resolving symlinks.
|
||||
// It is intended for validation only; use OpenContained for atomic file opens within a root.
|
||||
func PathWithinRoot(root, path string) error {
|
||||
rootAbs, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid root path: %w", err)
|
||||
}
|
||||
rootReal, err := filepath.EvalSymlinks(rootAbs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not resolve root path: %w", err)
|
||||
}
|
||||
pathAbs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid path: %w", err)
|
||||
}
|
||||
pathReal, err := filepath.EvalSymlinks(pathAbs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not resolve path: %w", err)
|
||||
}
|
||||
rel, err := filepath.Rel(rootReal, pathReal)
|
||||
if err != nil {
|
||||
return fmt.Errorf("path outside root: %w", err)
|
||||
}
|
||||
sep := string(filepath.Separator)
|
||||
if rel == ".." || strings.HasPrefix(rel, ".."+sep) {
|
||||
return fmt.Errorf("path escapes root")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OpenContained opens relPath relative to rootDir without following symlinks that escape rootDir.
|
||||
// Prefer this over PathWithinRoot followed by os.Open to avoid TOCTOU races.
|
||||
func OpenContained(rootDir, relPath string) (*os.File, error) {
|
||||
rel := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(relPath, "/")))
|
||||
if rel == "." || rel == "" || strings.HasPrefix(rel, "..") {
|
||||
return nil, fmt.Errorf("path escapes root")
|
||||
}
|
||||
root, err := os.OpenRoot(rootDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
return root.Open(rel)
|
||||
}
|
||||
|
||||
// ResolveSymlinks resolves symlinks in the given path and returns
|
||||
// Uses Go's filepath.EvalSymlinks which properly detects circular symlinks.
|
||||
func ResolveSymlinks(path string) (string, bool, error) {
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package iteminfo
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOpenContained_RejectsSymlinkEscape(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
scopeDir := filepath.Join(root, "scope")
|
||||
if err := os.MkdirAll(scopeDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(root, "outside.txt")
|
||||
if err := os.WriteFile(outside, []byte("secret"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(scopeDir, "escape")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := OpenContained(scopeDir, "escape")
|
||||
if err == nil {
|
||||
t.Fatal("expected symlink escape to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenContained_OpensInScopeFile(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
inside := filepath.Join(root, "allowed.txt")
|
||||
if err := os.WriteFile(inside, []byte("ok"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
file, err := OpenContained(root, "allowed.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("expected in-scope open to succeed: %v", err)
|
||||
}
|
||||
file.Close()
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
package indexing
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
liberrors "github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
)
|
||||
|
||||
func setupSymlinkEscapeFixture(t *testing.T) (sourceRoot, userScope string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
sourceRoot = filepath.Join(root, "srv")
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.MkdirAll(userDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsideSecret := filepath.Join(root, "secret-outside.txt")
|
||||
if err := os.WriteFile(outsideSecret, []byte("ROOT_DB_PASSWORD=supersecret"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outsideSecret, filepath.Join(userDir, "secret_link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sibling := filepath.Join(root, "outside-sibling.txt")
|
||||
if err := os.WriteFile(sibling, []byte("outside sibling"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(sibling, filepath.Join(userDir, "sibling_link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inside := filepath.Join(userDir, "allowed.txt")
|
||||
if err := os.WriteFile(inside, []byte("allowed"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sourceRoot, "/user1"
|
||||
}
|
||||
|
||||
func symlinkTestIndex(sourceRoot string) *Index {
|
||||
return &Index{Source: settings.Source{Path: sourceRoot}}
|
||||
}
|
||||
|
||||
func TestPathWithinRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
inside := filepath.Join(root, "inner", "file.txt")
|
||||
if err := os.MkdirAll(filepath.Dir(inside), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(inside, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(filepath.Dir(root), "outside.txt")
|
||||
if err := os.WriteFile(outside, []byte("y"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := iteminfo.PathWithinRoot(root, inside); err != nil {
|
||||
t.Fatalf("expected inside path to be allowed: %v", err)
|
||||
}
|
||||
if err := iteminfo.PathWithinRoot(root, outside); err == nil {
|
||||
t.Fatal("expected outside path to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRealPath_RejectsEscapeOutsideSource(t *testing.T) {
|
||||
sourceRoot, _ := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
_, _, err := idx.GetRealPath("/user1/secret_link")
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope, got %v", err)
|
||||
}
|
||||
_, _, err = idx.GetRealPath("/user1/sibling_link")
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope for sibling link, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRealPathScoped_RejectsEscapeOutsideUserScope(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
insideSource := filepath.Join(sourceRoot, "secret-in-source.txt")
|
||||
if err := os.WriteFile(insideSource, []byte("in source"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.Symlink(insideSource, filepath.Join(userDir, "in_source_link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, _, err := idx.GetRealPathScoped(userScope, "/user1/in_source_link")
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope for in-source escape, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRealPathScoped_AllowsInScopeTarget(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.Symlink("allowed.txt", filepath.Join(userDir, "good_link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
realPath, _, err := idx.GetRealPathScoped(userScope, "/user1/good_link")
|
||||
if err != nil {
|
||||
t.Fatalf("expected in-scope symlink to resolve: %v", err)
|
||||
}
|
||||
want := filepath.Join(userDir, "allowed.txt")
|
||||
realPath, err = filepath.EvalSymlinks(realPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, err = filepath.EvalSymlinks(want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if realPath != want {
|
||||
t.Fatalf("got real path %q, want %q", realPath, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRealPathScoped_CacheKeyDoesNotCollideWithUnscoped(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
insideSource := filepath.Join(sourceRoot, "secret-in-source.txt")
|
||||
if err := os.WriteFile(insideSource, []byte("in source"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.WriteFile(filepath.Join(userDir, "foo"), []byte("legitimate"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
legacyKey := filepath.Join(sourceRoot, "user1", "foo") + ":bound:" + "/user1"
|
||||
RealPathCache.Set(legacyKey, insideSource)
|
||||
IsDirCache.Set(legacyKey+":isdir", false)
|
||||
|
||||
realPath, _, err := idx.GetRealPathScoped(userScope, "/user1/foo")
|
||||
if err != nil {
|
||||
t.Fatalf("scoped in-scope file should resolve: %v", err)
|
||||
}
|
||||
want := filepath.Join(userDir, "foo")
|
||||
want, err = filepath.EvalSymlinks(want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
realPath, err = filepath.EvalSymlinks(realPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if realPath != want {
|
||||
t.Fatalf("scoped lookup returned %q, want in-scope file %q", realPath, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFileInfo_RejectsSymlinkEscapeWithBound(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
_, err := idx.GetFileInfo(FileInfoRequest{
|
||||
IndexPath: "/user1/secret_link",
|
||||
FollowSymlinks: true,
|
||||
BoundIndexPath: userScope,
|
||||
})
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope from GetFileInfo, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFileInfo_RejectsDirectorySymlinkOutsideUserScope(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
otherDir := filepath.Join(sourceRoot, "otheruser")
|
||||
if err := os.MkdirAll(otherDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(otherDir, "leaked.txt"), []byte("leaked"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userDir := filepath.Join(sourceRoot, "user1")
|
||||
if err := os.Symlink(otherDir, filepath.Join(userDir, "escape_dir")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := idx.GetFileInfo(FileInfoRequest{
|
||||
IndexPath: "/user1/escape_dir/",
|
||||
FollowSymlinks: true,
|
||||
BoundIndexPath: userScope,
|
||||
Expand: true,
|
||||
})
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope for directory symlink outside scope, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenScopedPath_RejectsEscapeOutsideUserScope(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
_, _, err := idx.OpenScopedPath(userScope, "/user1/secret_link")
|
||||
if !errors.Is(err, liberrors.ErrPathEscapesScope) {
|
||||
t.Fatalf("expected ErrPathEscapesScope from OpenScopedPath, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenScopedPath_OpensInScopeFile(t *testing.T) {
|
||||
sourceRoot, userScope := setupSymlinkEscapeFixture(t)
|
||||
idx := symlinkTestIndex(sourceRoot)
|
||||
|
||||
file, info, err := idx.OpenScopedPath(userScope, "/user1/allowed.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("expected in-scope open to succeed: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
if info.IsDir() {
|
||||
t.Fatal("expected file, got directory")
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@ package indexing
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
|
||||
@@ -66,7 +66,7 @@ func (idx *Index) handleFile(file os.FileInfo, indexPath string, realFilePath st
|
||||
|
||||
// Use provided realFilePath if available, otherwise construct it
|
||||
if realFilePath == "" {
|
||||
realFilePath = utils.JoinUnderSourceRoot(idx.Path, indexPath)
|
||||
realFilePath = filepath.Join(idx.Path, indexPath)
|
||||
}
|
||||
|
||||
sys := file.Sys()
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
jwt.DecodeStrict = true
|
||||
cmd.StartFilebrowser()
|
||||
}
|
||||
@@ -5784,7 +5784,7 @@ const docTemplate = `{
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "display name, PWA installation name is capped at 30 characters",
|
||||
"description": "display name",
|
||||
"type": "string"
|
||||
},
|
||||
"oidcLoginButtonText": {
|
||||
|
||||
@@ -5773,7 +5773,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "display name, PWA installation name is capped at 30 characters",
|
||||
"description": "display name",
|
||||
"type": "string"
|
||||
},
|
||||
"oidcLoginButtonText": {
|
||||
|
||||
@@ -784,7 +784,7 @@ definitions:
|
||||
description: path to an image file for the login page icon
|
||||
type: string
|
||||
name:
|
||||
description: display name, PWA installation name is capped at 30 characters
|
||||
description: display name
|
||||
type: string
|
||||
oidcLoginButtonText:
|
||||
description: text to display on the OIDC login button
|
||||
|
||||
Generated
+301
-346
File diff suppressed because it is too large.
Load diff
@@ -131,7 +131,7 @@ auth:
|
||||
adminPassword: "admin" # secret: the password of the admin user. If not set, the default is "admin".
|
||||
totpSecret: "" # secret: secret used to encrypt TOTP secrets
|
||||
frontend:
|
||||
name: "FileBrowser Quantum" # display name, PWA installation name is capped at 30 characters
|
||||
name: "FileBrowser Quantum" # display name
|
||||
disableDefaultLinks: false # disable default links in the sidebar
|
||||
disableUsedPercentage: false # disable used percentage for the sources in the sidebar
|
||||
externalLinks:
|
||||
|
||||
@@ -258,7 +258,7 @@ export default {
|
||||
|
||||
// Add keyboard event listener for "/" to activate search
|
||||
this.handleKeydown = (event) => {
|
||||
if ((event.key === '/' || event.key === ' ') && !state.isSearchActive && !getters.currentPrompt()) {
|
||||
if (event.key === '/' || event.key === ' ' && !state.isSearchActive && getters.currentPrompt() === null) {
|
||||
event.preventDefault();
|
||||
this.open();
|
||||
}
|
||||
|
||||
@@ -191,13 +191,14 @@ export default {
|
||||
let sharePath;
|
||||
|
||||
if (isShare && state.shareInfo?.hash) {
|
||||
const shareBase = `${globalVars.baseURL}public/share/${state.shareInfo.hash}`;
|
||||
const shareBase = `/public/share/${state.shareInfo.hash}`;
|
||||
const subPath = state.req?.path && state.req.path !== '/'
|
||||
? url.removeLeadingSlash(state.req.path)
|
||||
: '';
|
||||
sharePath = subPath ? `${shareBase}/${url.encodedPath(subPath)}` : shareBase;
|
||||
}
|
||||
await auth.logout(sharePath);
|
||||
await auth.logout();
|
||||
window.location.href = sharePath || '/login';
|
||||
},
|
||||
beforeEnter(el) {
|
||||
el.style.maxHeight = '0';
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "المدة قبل انتهاء صلاحية السهم. اتركها فارغة للحصة الدائمة.",
|
||||
"passwordDescription": "كلمة المرور الاختيارية مطلوبة للوصول إلى هذه المشاركة، بما في ذلك المستخدمون الذين تمت مصادقتهم.",
|
||||
"shareThemeColorDescription": "قيمة لون CSS المطبقة على سمة المشاركة (على سبيل المثال، أحمر، #0ea5e9، rgb(14,165,233)).",
|
||||
"shareTitleDescription": "عنوان الصفحة المخصص الذي يظهر في صفحة المشاركة.",
|
||||
"shareDescriptionHelp": "وصف قصير يظهر على صفحة المشاركة (يمكن استخدامه في العلامات الوصفية).",
|
||||
"shareBannerDescription": "عنوان URL لصورة الشعار أو المسار الذي يمكن للعميل الوصول إليه - يتم قبول إما المسار المطلق أو مسار الفهرس: على سبيل المثال 'https://domain.com/banner.png' أو '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "عنوان URL أو المسار الذي يمكن للعميل الوصول إليه من قبل العميل - يتم قبول إما المسار المطلق أو مسار الفهرس: على سبيل المثال 'https://domain.com/favicon.png' أو '/path/to/favicon.png'",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "تحديد صورة الشعار",
|
||||
"selectFaviconImage": "تحديد الصورة المفضلة",
|
||||
"deleteFailed": "فشل في حذف المشاركة",
|
||||
"readOnlySourceNotice": "هذا المصدر للقراءة فقط. يتم تعطيل تحميل المشاركات والأذونات التي تعدل الملفات.",
|
||||
"shareTitleDescription": "عنوان الصفحة المخصص الذي يظهر على صفحة المشاركة. إذا تم تثبيت تطبيق المشاركة هذا كتطبيق ويب تقدمي (PWA)، فإن اسم التطبيق يقتصر على 30 حرفًا."
|
||||
"readOnlySourceNotice": "هذا المصدر للقراءة فقط. يتم تعطيل تحميل المشاركات والأذونات التي تعدل الملفات."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "تم الإنشاء في:",
|
||||
|
||||
@@ -162,6 +162,7 @@
|
||||
"shareDurationDescription": "Doba trvání před vypršením platnosti akcie. V případě trvalé akcie ponechte prázdné.",
|
||||
"passwordDescription": "Volitelné heslo vyžadované pro přístup k této sdílené složce, včetně ověřených uživatelů.",
|
||||
"shareThemeColorDescription": "Hodnota barvy CSS použitá na motiv sdílené položky (např. červená, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Vlastní název stránky zobrazený na stránce sdílení.",
|
||||
"shareDescriptionHelp": "Krátký popis zobrazený na stránce sdílení (lze použít v metaznačkách).",
|
||||
"shareBannerDescription": "Adresa URL nebo cesta k obrázku banneru přístupná klientovi - akceptována je buď absolutní, nebo indexová cesta: např. \"https://domain.com/banner.png\" nebo \"/path/to/banner.png\".",
|
||||
"shareFaviconDescription": "Adresa URL nebo cesta k faviconě přístupná klientovi -- akceptována je buď absolutní, nebo indexová cesta: např. \"https://domain.com/favicon.png\" nebo \"/path/to/favicon.png\".",
|
||||
@@ -212,8 +213,7 @@
|
||||
"selectBannerImage": "Výběr obrázku banneru",
|
||||
"selectFaviconImage": "Výběr obrázku favicon",
|
||||
"deleteFailed": "Nepodařilo se odstranit sdílenou složku",
|
||||
"readOnlySourceNotice": "Tento zdroj je určen pouze pro čtení. Sdílení nahrávání a oprávnění, která upravují soubory, jsou zakázána.",
|
||||
"shareTitleDescription": "Vlastní název stránky zobrazený na stránce pro sdílení. Je-li tato aplikace nainstalována jako PWA, délka názvu aplikace je omezena na 30 znaků."
|
||||
"readOnlySourceNotice": "Tento zdroj je určen pouze pro čtení. Sdílení nahrávání a oprávnění, která upravují soubory, jsou zakázána."
|
||||
},
|
||||
"prompts": {
|
||||
"deleteMessageSingle": "Opravdu chcete smazat tento soubor/složku?",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Dauer, bevor die Freigabe abläuft. Für eine dauerhafte Freigabe leer lassen.",
|
||||
"passwordDescription": "Optionales Kennwort, das für den Zugriff auf diese Freigabe erforderlich ist, einschließlich authentifizierter Benutzer.",
|
||||
"shareThemeColorDescription": "CSS-Farbwert, der auf das Thema der Freigabe angewendet wird (z. B. rot, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Benutzerdefinierter Seitentitel, der auf der Freigabeseite angezeigt wird.",
|
||||
"shareDescriptionHelp": "Kurze Beschreibung, die auf der Freigabeseite angezeigt wird (kann in Meta-Tags verwendet werden).",
|
||||
"shareBannerDescription": "URL oder Pfad des Bannerbildes, auf den der Client zugreifen kann - es wird entweder ein absoluter oder ein Indexpfad akzeptiert: z. B. \"https://domain.com/banner.png\" oder \"/pfad/zu/banner.png\".",
|
||||
"shareFaviconDescription": "Favicon-URL oder -Pfad, auf den der Client zugreifen kann - es wird entweder ein absoluter oder ein Indexpfad akzeptiert: z. B. 'https://domain.com/favicon.png' oder '/path/to/favicon.png'.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Bannerbild auswählen",
|
||||
"selectFaviconImage": "Favicon-Bild auswählen",
|
||||
"deleteFailed": "Freigabe konnte nicht gelöscht werden",
|
||||
"readOnlySourceNotice": "Diese Quelle ist schreibgeschützt. Upload-Freigaben und Berechtigungen, die Dateien ändern, sind deaktiviert.",
|
||||
"shareTitleDescription": "Benutzerdefinierter Seitentitel, der auf der Freigabeseite angezeigt wird. Wenn diese Freigabe als PWA installiert ist, ist der App-Name auf 30 Zeichen begrenzt."
|
||||
"readOnlySourceNotice": "Diese Quelle ist schreibgeschützt. Upload-Freigaben und Berechtigungen, die Dateien ändern, sind deaktiviert."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Erstellt am:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Διάρκεια πριν από τη λήξη της μετοχής. Αφήστε το κενό για μόνιμο μερίδιο.",
|
||||
"passwordDescription": "Προαιρετικός κωδικός πρόσβασης που απαιτείται για την πρόσβαση σε αυτό το κοινόχρηστο τμήμα, συμπεριλαμβανομένων των πιστοποιημένων χρηστών.",
|
||||
"shareThemeColorDescription": "Τιμή χρώματος CSS που εφαρμόζεται στο θέμα της μετοχής (π.χ. κόκκινο, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Προσαρμοσμένος τίτλος σελίδας που εμφανίζεται στη σελίδα κοινής χρήσης.",
|
||||
"shareDescriptionHelp": "Σύντομη περιγραφή που εμφανίζεται στη σελίδα κοινοποίησης (μπορεί να χρησιμοποιηθεί σε meta tags).",
|
||||
"shareBannerDescription": "Διεύθυνση URL ή διαδρομή εικόνας πανό προσβάσιμη από τον πελάτη -- γίνονται δεκτές είτε η απόλυτη διαδρομή είτε η διαδρομή ευρετηρίου: π.χ. \"https://domain.com/banner.png\" ή \"/path/to/banner.png\".",
|
||||
"shareFaviconDescription": "Διεύθυνση URL ή διαδρομή Favicon προσβάσιμη από τον πελάτη -- γίνονται δεκτές είτε η απόλυτη διαδρομή είτε η διαδρομή ευρετηρίου: π.χ. 'https://domain.com/favicon.png' ή '/path/to/favicon.png'.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Επιλέξτε εικόνα banner",
|
||||
"selectFaviconImage": "Επιλέξτε εικόνα favicon",
|
||||
"deleteFailed": "Απέτυχε η διαγραφή κοινής χρήσης",
|
||||
"readOnlySourceNotice": "Αυτή η πηγή είναι μόνο για ανάγνωση. Οι μετοχές φόρτωσης και τα δικαιώματα που τροποποιούν αρχεία είναι απενεργοποιημένα.",
|
||||
"shareTitleDescription": "Προσαρμοσμένος τίτλος σελίδας που εμφανίζεται στη σελίδα κοινοποίησης. Εάν αυτή η εφαρμογή κοινοποίησης έχει εγκατασταθεί ως PWA, το όνομα της εφαρμογής περιορίζεται σε 30 χαρακτήρες."
|
||||
"readOnlySourceNotice": "Αυτή η πηγή είναι μόνο για ανάγνωση. Οι μετοχές φόρτωσης και τα δικαιώματα που τροποποιούν αρχεία είναι απενεργοποιημένα."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Δημιουργήθηκε στο:",
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"shareDurationDescription": "Duration before the share expires. Leave blank for a permanent share.",
|
||||
"passwordDescription": "Optional password required to access this share, including authenticated users.",
|
||||
"shareThemeColorDescription": "CSS color value applied to the share's theme (e.g., red, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Custom page title shown on the share page. If this share is installed as a PWA, the app name is limited to 30 characters.",
|
||||
"shareTitleDescription": "Custom page title shown on the share page.",
|
||||
"shareDescriptionHelp": "Short description shown on the share page (may be used in meta tags).",
|
||||
"shareBannerDescription": "Banner image URL or path accessible by the client -- either abosolute or index path are accepted: eg 'https://domain.com/banner.png' or '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "Favicon URL or path accessible by the client -- either abosolute or index path are accepted: eg 'https://domain.com/favicon.png' or '/path/to/favicon.png'",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Tiempo que durará el recurso compartido - puedes dejarlo en blanco para indefinido (o sea, sin expiración).",
|
||||
"passwordDescription": "Contraseña opcional necesaria para acceder al recurso compartido, incluyedo usuarios registrados",
|
||||
"shareThemeColorDescription": "Valor de color CSS aplicado al tema de la acción (por ejemplo: red, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Título de la página que se mostrará en el navegador",
|
||||
"shareDescriptionHelp": "Breve descripción mostrada en la página (que suele aparecer cuando compartes el enlace)",
|
||||
"shareBannerDescription": "Enlace (URL), o ruta de la imagen del banner que se mostrará en el enlace -- por ejemplo, 'https://ejemplo.com/banner.png' o '/ruta/a/banner.png'.",
|
||||
"shareFaviconDescription": "Enlace (URL) del icono (favicon) que se mostrará en el enlace -- por ejemplo 'https://domain.com/favicon.png' o '/ruta/a/favicon.png'",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Seleccionar imagen de banner",
|
||||
"selectFaviconImage": "Seleccionar imagen de favicon",
|
||||
"deleteFailed": "Error al borrar recurso compartido",
|
||||
"readOnlySourceNotice": "Esta fuente es de sólo lectura. Los recursos compartidos de carga y los permisos que modifican archivos están desactivados.",
|
||||
"shareTitleDescription": "Título personalizado de la página que se muestra en la página para compartir. Si esta aplicación para compartir está instalada como PWA, el nombre de la aplicación tiene un límite de 30 caracteres."
|
||||
"readOnlySourceNotice": "Esta fuente es de sólo lectura. Los recursos compartidos de carga y los permisos que modifican archivos están desactivados."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Creado en:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Durée avant l'expiration du partage. Laisser vide pour un partage permanent.",
|
||||
"passwordDescription": "Mot de passe facultatif requis pour accéder à ce partage, y compris pour les utilisateurs authentifiés.",
|
||||
"shareThemeColorDescription": "Valeur de la couleur CSS appliquée au thème du partage (par exemple, rouge, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Titre de page personnalisé affiché sur la page de partage.",
|
||||
"shareDescriptionHelp": "Courte description affichée sur la page de partage (peut être utilisée dans les balises méta).",
|
||||
"shareBannerDescription": "URL de l'image de la bannière ou chemin d'accès accessible par le client - les chemins d'accès absolus ou indexés sont acceptés : par exemple \"https://domain.com/banner.png\" ou \"/path/to/banner.png\".",
|
||||
"shareFaviconDescription": "URL du favicon ou chemin d'accès accessible par le client -- les chemins d'accès absolus ou indexés sont acceptés : par exemple \"https://domain.com/favicon.png\" ou \"/path/to/favicon.png\".",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Sélectionner l'image de la bannière",
|
||||
"selectFaviconImage": "Sélectionner l'image du favicon",
|
||||
"deleteFailed": "Échec de la suppression du partage",
|
||||
"readOnlySourceNotice": "Cette source est en lecture seule. Les partages de téléchargement et les autorisations qui modifient les fichiers sont désactivés.",
|
||||
"shareTitleDescription": "Titre personnalisé de la page affiché sur la page de partage. Si cette fonctionnalité de partage est installée en tant qu'application PWA, le nom de l'application est limité à 30 caractères."
|
||||
"readOnlySourceNotice": "Cette source est en lecture seule. Les partages de téléchargement et les autorisations qui modifient les fichiers sont désactivés."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Créée le :",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "משך הזמן עד לפקיעת תוקף השיתוף. השאר ריק לשיתוף קבוע.",
|
||||
"passwordDescription": "סיסמה אופציונלית נדרשת כדי לגשת לשיתוף זה, כולל משתמשים מאומתים.",
|
||||
"shareThemeColorDescription": "ערך צבע CSS המוחל על ערכת הנושא של השיתוף (לדוגמה, אדום, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "כותרת דף מותאמת אישית המוצגת בדף השיתוף.",
|
||||
"shareDescriptionHelp": "תיאור קצר המופיע בדף השיתוף (יכול לשמש בתגי מטא).",
|
||||
"shareBannerDescription": "כתובת URL או נתיב של תמונת הבאנר הנגישים ללקוח - ניתן להשתמש בכתובת מוחלטת או בנתיב אינדקס: לדוגמה, 'https://domain.com/banner.png' או '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "כתובת URL או נתיב של סמל favicon הנגיש ללקוח - ניתן להשתמש בכתובת מוחלטת או בנתיב אינדקס: לדוגמה, 'https://domain.com/favicon.png' או '/path/to/favicon.png'",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "בחר תמונת באנר",
|
||||
"selectFaviconImage": "בחר תמונת סמל מועדף",
|
||||
"deleteFailed": "לא ניתן למחוק את השיתוף",
|
||||
"readOnlySourceNotice": "מקור זה מוגדר לקריאה בלבד. העלאת קבצים והרשאות המשנות קבצים אינן זמינות.",
|
||||
"shareTitleDescription": "כותרת דף מותאמת אישית המוצגת בדף השיתוף. אם יישום השיתוף הזה מותקן כ-PWA, שם האפליקציה מוגבל ל-30 תווים."
|
||||
"readOnlySourceNotice": "מקור זה מוגדר לקריאה בלבד. העלאת קבצים והרשאות המשנות קבצים אינן זמינות."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "נוצר ב:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "A részvény lejárta előtti időtartam. Állandó megosztás esetén hagyja üresen.",
|
||||
"passwordDescription": "A megosztás eléréséhez szükséges opcionális jelszó, beleértve a hitelesített felhasználókat is.",
|
||||
"shareThemeColorDescription": "A megosztás témájára alkalmazott CSS színérték (pl. piros, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "A megosztási oldalon megjelenő egyéni oldalcím.",
|
||||
"shareDescriptionHelp": "A megosztási oldalon megjelenő rövid leírás (a meta címkékben is használható).",
|
||||
"shareBannerDescription": "A banner kép URL címe vagy az ügyfél által elérhető elérési útvonal -- abszolút vagy index útvonal is elfogadható: pl. 'https://domain.com/banner.png' vagy '/path/to/banner.png'.",
|
||||
"shareFaviconDescription": "A favicon URL címe vagy az ügyfél által elérhető elérési útvonal -- abszolút vagy index útvonal is elfogadható: pl. 'https://domain.com/favicon.png' vagy '/path/to/favicon.png'.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Banner kép kiválasztása",
|
||||
"selectFaviconImage": "Favicon kép kiválasztása",
|
||||
"deleteFailed": "Nem sikerült törölni a megosztást",
|
||||
"readOnlySourceNotice": "Ez a forrás csak olvasható. A feltöltési megosztások és a fájlokat módosító engedélyek letiltva vannak.",
|
||||
"shareTitleDescription": "A megosztási oldalon megjelenő egyéni oldalcím. Ha ezt a megosztási alkalmazást PWA-ként telepítik, az alkalmazás neve legfeljebb 30 karakter lehet."
|
||||
"readOnlySourceNotice": "Ez a forrás csak olvasható. A feltöltési megosztások és a fájlokat módosító engedélyek letiltva vannak."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Létrehozva:",
|
||||
|
||||
@@ -283,6 +283,7 @@
|
||||
"shareDurationDescription": "Durata prima che la condivisione scada. Lascia vuoto per una condivisione permanente.",
|
||||
"passwordDescription": "Password opzionale richiesta per accedere, inclusi gli utenti autenticati.",
|
||||
"shareThemeColorDescription": "Valore colore CSS applicato al tema (es. red, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Titolo personalizzato mostrato sulla pagina di condivisione.",
|
||||
"shareDescriptionHelp": "Breve descrizione mostrata sulla pagina di condivisione (può essere usata nei meta tag).",
|
||||
"shareBannerDescription": "URL o percorso dell'immagine banner accessibile dal client.",
|
||||
"shareFaviconDescription": "URL o percorso della favicon accessibile dal client.",
|
||||
@@ -333,8 +334,7 @@
|
||||
"shareInfoDescription": "Mostra le informazioni della condivisione (titolo, descrizione, banner, QR) in un popup.",
|
||||
"downloadDescription": "Permette di scaricare l'intero contenuto della condivisione come file compresso.",
|
||||
"deleteFailed": "Eliminazione condivisione fallita",
|
||||
"readOnlySourceNotice": "Questa sorgente è di sola lettura. Le azioni di caricamento e le autorizzazioni che modificano i file sono disabilitate.",
|
||||
"shareTitleDescription": "Titolo personalizzato della pagina visualizzato nella pagina di condivisione. Se questa condivisione è installata come PWA, il nome dell'app è limitato a 30 caratteri."
|
||||
"readOnlySourceNotice": "Questa sorgente è di sola lettura. Le azioni di caricamento e le autorizzazioni che modificano i file sono disabilitate."
|
||||
},
|
||||
"prompts": {
|
||||
"operationInProgress": "Operazione in corso, attendere...",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "共有が失効するまでの期間。永続的な共有の場合は空白のままにします。",
|
||||
"passwordDescription": "認証されたユーザーを含め、この共有にアクセスするために必要なオプションのパスワード",
|
||||
"shareThemeColorDescription": "共有テーマに適用されるCSSカラー値(例:red、#0ea5e9、rgb(14,165,233))",
|
||||
"shareTitleDescription": "共有ページに表示されるカスタムページタイトル",
|
||||
"shareDescriptionHelp": "共有ページに表示される短い説明文(メタタグで使用される場合もあります)",
|
||||
"shareBannerDescription": "クライアントがアクセス可能なバナー画像のURLまたはパス -- 絶対パスでもインデックスパスでも可:'https://domain.com/banner.png'または'/path/to/banner.png'など",
|
||||
"shareFaviconDescription": "クライアントからアクセス可能なファビコンのURLまたはパス -- 絶対パスでもインデックスパスでも可:'https://domain.com/favicon.png'または'/path/to/favicon.png'など",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "バナー画像を選択",
|
||||
"selectFaviconImage": "ファビコン画像を選択",
|
||||
"deleteFailed": "共有の削除に失敗しました",
|
||||
"readOnlySourceNotice": "このソースは読み取り専用です。アップロード共有およびファイルを変更するパーミッションは無効です。",
|
||||
"shareTitleDescription": "共有ページに表示されるカスタムページタイトル。この共有機能がPWAとしてインストールされている場合、アプリ名は30文字以内に制限されます。"
|
||||
"readOnlySourceNotice": "このソースは読み取り専用です。アップロード共有およびファイルを変更するパーミッションは無効です。"
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "で作成された:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "공유가 만료되기 전까지의 기간입니다. 영구 공유를 원하시면 비워 두세요.",
|
||||
"passwordDescription": "인증된 사용자를 포함하여 이 공유에 액세스하는 데 필요한 비밀번호(선택 사항)입니다.",
|
||||
"shareThemeColorDescription": "공유의 테마에 적용된 CSS 색상 값(예: 빨간색, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "공유 페이지에 표시되는 사용자 지정 페이지 제목.",
|
||||
"shareDescriptionHelp": "공유 페이지에 표시되는 간단한 설명(메타 태그에 사용할 수 있음).",
|
||||
"shareBannerDescription": "클라이언트가 액세스할 수 있는 배너 이미지 URL 또는 경로 - 절대 경로 또는 인덱스 경로(예: 'https://domain.com/banner.png' 또는 '/path/to/banner.png')가 허용됩니다.",
|
||||
"shareFaviconDescription": "클라이언트가 액세스할 수 있는 파비콘 URL 또는 경로 - 절대 경로 또는 인덱스 경로(예: 'https://domain.com/favicon.png' 또는 '/path/to/favicon.png')가 허용됩니다.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "배너 이미지 선택",
|
||||
"selectFaviconImage": "파비콘 이미지 선택",
|
||||
"deleteFailed": "공유를 삭제하지 못했습니다.",
|
||||
"readOnlySourceNotice": "이 소스는 읽기 전용입니다. 파일을 수정하는 업로드 공유 및 권한은 비활성화됩니다.",
|
||||
"shareTitleDescription": "공유 페이지에 표시되는 사용자 지정 페이지 제목입니다. 이 공유 기능이 PWA로 설치된 경우, 앱 이름은 30자 이내로 제한됩니다."
|
||||
"readOnlySourceNotice": "이 소스는 읽기 전용입니다. 파일을 수정하는 업로드 공유 및 권한은 비활성화됩니다."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "만든 곳:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Duur voordat het aandeel verloopt. Laat leeg voor een permanent aandeel.",
|
||||
"passwordDescription": "Optioneel wachtwoord dat vereist is om toegang te krijgen tot deze share, inclusief geauthenticeerde gebruikers.",
|
||||
"shareThemeColorDescription": "CSS kleurwaarde toegepast op het thema van het aandeel (bijv. rood, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Aangepaste paginatitel die wordt weergegeven op de deelpagina.",
|
||||
"shareDescriptionHelp": "Korte beschrijving die wordt weergegeven op de share-pagina (kan worden gebruikt in metatags).",
|
||||
"shareBannerDescription": "URL van bannerafbeelding of pad dat toegankelijk is voor de client -- zowel abosolute als indexpath worden geaccepteerd: bijv. 'https://domain.com/banner.png' of '/path/to/banner.png'.",
|
||||
"shareFaviconDescription": "Favicon URL of pad toegankelijk door de client -- zowel abosolute als index path worden geaccepteerd: bijv. 'https://domain.com/favicon.png' of '/path/to/favicon.png'.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Selecteer bannerafbeelding",
|
||||
"selectFaviconImage": "Selecteer favicon afbeelding",
|
||||
"deleteFailed": "Share niet verwijderd",
|
||||
"readOnlySourceNotice": "Deze bron is alleen-lezen. Upload shares en rechten om bestanden te wijzigen zijn uitgeschakeld.",
|
||||
"shareTitleDescription": "Aangepaste paginatitel die op de deelpagina wordt weergegeven. Als deze deelfunctie als PWA is geïnstalleerd, mag de app-naam maximaal 30 tekens lang zijn."
|
||||
"readOnlySourceNotice": "Deze bron is alleen-lezen. Upload shares en rechten om bestanden te wijzigen zijn uitgeschakeld."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Gemaakt op:",
|
||||
|
||||
@@ -284,6 +284,7 @@
|
||||
"shareDurationDescription": "Duur voordat de gedeelde map verloopt. Leeg laten voor een permanente gedeelde map.",
|
||||
"passwordDescription": "Optioneel wachtwoord dat vereist is om toegang te krijgen tot deze gedeelde map, inclusief geauthenticeerde gebruikers.",
|
||||
"shareThemeColorDescription": "CSS kleurwaarde toegepast op het thema van de gedeelde map (bijv. rood, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Aangepaste paginatitel die wordt weergegeven op de deelpagina.",
|
||||
"shareDescriptionHelp": "Korte beschrijving die wordt weergegeven op de pagina van de gedeelde map (kan worden gebruikt in metatags).",
|
||||
"shareBannerDescription": "URL van bannerafbeelding of pad dat toegankelijk is voor de client -- zowel abosolute als indexpath worden geaccepteerd: bijv. 'https://domain.com/banner.png' of '/path/to/banner.png'.",
|
||||
"shareFaviconDescription": "Favicon URL of pad toegankelijk door de client -- zowel abosolute als index path worden geaccepteerd: bijv. 'https://domain.com/favicon.png' of '/path/to/favicon.png'.",
|
||||
@@ -333,8 +334,7 @@
|
||||
"shareInfo": "QR-code en info delen",
|
||||
"shareInfoDescription": "Deze koppeling toont de informatie van de gedeelde map, inclusief titel, beschrijving, banner en QR-code in een popup.",
|
||||
"downloadDescription": "Met deze koppeling kunt u de volledige inhoud van de gedeelde map downloaden als een gecomprimeerd bestand.",
|
||||
"deleteFailed": "Share niet verwijderd",
|
||||
"shareTitleDescription": "Aangepaste paginatitel die op de deelpagina wordt weergegeven. Als deze deelfunctie als PWA is geïnstalleerd, mag de app-naam maximaal 30 tekens lang zijn."
|
||||
"deleteFailed": "Share niet verwijderd"
|
||||
},
|
||||
"prompts": {
|
||||
"operationInProgress": "Werk in uitvoering, even geduld...",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Czas trwania przed wygaśnięciem udziału. Pozostaw puste dla stałego udziału.",
|
||||
"passwordDescription": "Opcjonalne hasło wymagane do uzyskania dostępu do tego udziału, w tym dla uwierzytelnionych użytkowników.",
|
||||
"shareThemeColorDescription": "Wartość koloru CSS zastosowana do motywu akcji (np. czerwony, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Niestandardowy tytuł strony wyświetlany na stronie udostępniania.",
|
||||
"shareDescriptionHelp": "Krótki opis wyświetlany na stronie udostępniania (może być użyty w metatagach).",
|
||||
"shareBannerDescription": "Adres URL obrazu baneru lub ścieżka dostępna dla klienta - akceptowana jest ścieżka bezwzględna lub indeksowa: np. \"https://domain.com/banner.png\" lub \"/path/to/banner.png\".",
|
||||
"shareFaviconDescription": "Adres URL Favicon lub ścieżka dostępna dla klienta - akceptowana jest ścieżka bezwzględna lub indeksowa: np. \"https://domain.com/favicon.png\" lub \"/path/to/favicon.png\".",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Wybierz obraz banera",
|
||||
"selectFaviconImage": "Wybierz obraz favicon",
|
||||
"deleteFailed": "Nie udało się usunąć udziału",
|
||||
"readOnlySourceNotice": "To źródło jest tylko do odczytu. Udziały przesyłania i uprawnienia modyfikujące pliki są wyłączone.",
|
||||
"shareTitleDescription": "Niestandardowy tytuł strony wyświetlany na stronie udostępniania. Jeśli ta aplikacja do udostępniania jest zainstalowana jako PWA, nazwa aplikacji nie może przekraczać 30 znaków."
|
||||
"readOnlySourceNotice": "To źródło jest tylko do odczytu. Udziały przesyłania i uprawnienia modyfikujące pliki są wyłączone."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Utworzono w:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Duração antes da expiração do compartilhamento. Deixe em branco para um compartilhamento permanente.",
|
||||
"passwordDescription": "Senha opcional necessária para acessar esse compartilhamento, incluindo usuários autenticados.",
|
||||
"shareThemeColorDescription": "Valor de cor CSS aplicado ao tema do compartilhamento (por exemplo, vermelho, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Título de página personalizado mostrado na página de compartilhamento.",
|
||||
"shareDescriptionHelp": "Descrição curta exibida na página de compartilhamento (pode ser usada em meta tags).",
|
||||
"shareBannerDescription": "URL ou caminho da imagem do banner acessível pelo cliente - são aceitos caminhos abosolutos ou de índice: por exemplo, 'https://domain.com/banner.png' ou '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "URL ou caminho do Favicon acessível pelo cliente - são aceitos caminhos abosolutos ou de índice: por exemplo, \"https://domain.com/favicon.png\" ou \"/path/to/favicon.png\".",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Selecione a imagem do banner",
|
||||
"selectFaviconImage": "Selecione a imagem do favicon",
|
||||
"deleteFailed": "Falha ao excluir o compartilhamento",
|
||||
"readOnlySourceNotice": "Essa fonte é somente leitura. Os compartilhamentos de upload e as permissões que modificam arquivos estão desativados.",
|
||||
"shareTitleDescription": "Título personalizado da página exibido na página de compartilhamento. Se esse aplicativo de compartilhamento estiver instalado como um PWA, o nome do aplicativo é limitado a 30 caracteres."
|
||||
"readOnlySourceNotice": "Essa fonte é somente leitura. Os compartilhamentos de upload e as permissões que modificam arquivos estão desativados."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Criado em:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Duração antes da expiração da ação. Deixar em branco para uma partilha permanente.",
|
||||
"passwordDescription": "Palavra-passe opcional necessária para aceder a esta partilha, incluindo utilizadores autenticados.",
|
||||
"shareThemeColorDescription": "Valor de cor CSS aplicado ao tema da ação (por exemplo, vermelho, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Título de página personalizado apresentado na página de partilha.",
|
||||
"shareDescriptionHelp": "Descrição curta apresentada na página de partilha (pode ser utilizada em meta tags).",
|
||||
"shareBannerDescription": "URL ou caminho da imagem do banner acessível pelo cliente - são aceites caminhos abosolutos ou de índice: por exemplo, \"https://domain.com/banner.png\" ou \"/path/to/banner.png",
|
||||
"shareFaviconDescription": "URL ou caminho do Favicon acessível pelo cliente - são aceites caminhos abosolutos ou de índice: por exemplo, \"https://domain.com/favicon.png\" ou \"/path/to/favicon.png",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Selecionar imagem de banner",
|
||||
"selectFaviconImage": "Selecionar a imagem do favicon",
|
||||
"deleteFailed": "Falha ao eliminar a partilha",
|
||||
"readOnlySourceNotice": "Esta fonte é apenas de leitura. As partilhas de carregamento e as permissões que modificam ficheiros estão desactivadas.",
|
||||
"shareTitleDescription": "Título personalizado da página apresentado na página de partilha. Se esta partilha estiver instalada como uma PWA, o nome da aplicação está limitado a 30 caracteres."
|
||||
"readOnlySourceNotice": "Esta fonte é apenas de leitura. As partilhas de carregamento e as permissões que modificam ficheiros estão desactivadas."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Criado em:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Durata înainte ca partajul să expire. Lăsați în alb pentru o partajare permanentă.",
|
||||
"passwordDescription": "Parola opțională necesară pentru a accesa această partajare, inclusiv utilizatorii autentificați.",
|
||||
"shareThemeColorDescription": "Valoarea culorii CSS aplicată temei acțiunii (de exemplu, roșu, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Titlu de pagină personalizat afișat pe pagina de partajare.",
|
||||
"shareDescriptionHelp": "Scurtă descriere afișată pe pagina de partajare (poate fi utilizată în metaetichete).",
|
||||
"shareBannerDescription": "URL-ul imaginii bannerului sau calea accesibilă de către client - sunt acceptate fie calea abosolută, fie calea index: de exemplu \"https://domain.com/banner.png\" sau \"/path/to/banner.png",
|
||||
"shareFaviconDescription": "Favicon URL sau cale accesibilă de către client - sunt acceptate fie calea abosolută, fie calea index: de exemplu \"https://domain.com/favicon.png\" sau \"/path/to/favicon.png",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Selectați imaginea bannerului",
|
||||
"selectFaviconImage": "Selectați imaginea favicon",
|
||||
"deleteFailed": "Eșec la ștergerea partajului",
|
||||
"readOnlySourceNotice": "Această sursă este numai pentru citire. Acțiunile de încărcare și permisiunile care modifică fișiere sunt dezactivate.",
|
||||
"shareTitleDescription": "Titlul personalizat al paginii afișat pe pagina de partajare. Dacă această funcție de partajare este instalată ca PWA, numele aplicației este limitat la 30 de caractere."
|
||||
"readOnlySourceNotice": "Această sursă este numai pentru citire. Acțiunile de încărcare și permisiunile care modifică fișiere sunt dezactivate."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Creat la:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Длительность до истечения срока действия доступа. Оставьте пустым для постоянного доступа.",
|
||||
"passwordDescription": "Необязательный пароль, требуемый для доступа к этому ресурсу, включая аутентифицированных пользователей.",
|
||||
"shareThemeColorDescription": "Значение цвета CSS, применяемое к теме доступа (например, красный, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Пользовательский заголовок страницы, отображаемый на странице ресурса.",
|
||||
"shareDescriptionHelp": "Краткое описание, отображаемое на странице доступа (может использоваться в метатегах).",
|
||||
"shareBannerDescription": "URL-адрес изображения баннера или путь, доступный клиенту - принимается либо абсолютный, либо индексный путь: например, 'https://domain.com/banner.png' или '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "URL-адрес фавикона или путь, доступный клиенту - принимается либо абсолютный, либо индексный путь: например, 'https://domain.com/favicon.png' или '/path/to/favicon.png'",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Выберите изображение баннера",
|
||||
"selectFaviconImage": "Выберите изображение фавикона",
|
||||
"deleteFailed": "Не удалось удалить общий ресурс",
|
||||
"readOnlySourceNotice": "Этот источник доступен только для чтения. Общие ресурсы загрузки и разрешения, изменяющие файлы, отключены.",
|
||||
"shareTitleDescription": "Пользовательский заголовок страницы, отображаемый на странице публикации. Если данное приложение установлено в качестве PWA, длина названия приложения не должна превышать 30 символов."
|
||||
"readOnlySourceNotice": "Этот источник доступен только для чтения. Общие ресурсы загрузки и разрешения, изменяющие файлы, отключены."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Создан:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Trvanie pred uplynutím platnosti akcie. Pre trvalú akciu nechajte prázdne.",
|
||||
"passwordDescription": "Voliteľné heslo potrebné na prístup k tejto zdieľanej zložke vrátane overených používateľov.",
|
||||
"shareThemeColorDescription": "Hodnota farby CSS použitá na tému akcie (napr. červená, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Vlastný názov stránky zobrazený na stránke zdieľania.",
|
||||
"shareDescriptionHelp": "Krátky popis zobrazený na stránke zdieľania (môže sa použiť v meta značkách).",
|
||||
"shareBannerDescription": "Adresa URL alebo cesta k obrázku banneru prístupná klientovi - akceptuje sa buď absolútna, alebo indexová cesta: napr. \"https://domain.com/banner.png\" alebo \"/path/to/banner.png\".",
|
||||
"shareFaviconDescription": "Adresa URL alebo cesta k ikone Favicon, ktorá je prístupná klientovi -- akceptuje sa buď absolútna, alebo indexová cesta: napr. \"https://domain.com/favicon.png\" alebo \"/path/to/favicon.png\".",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Vyberte obrázok bannera",
|
||||
"selectFaviconImage": "Vyberte obrázok favicon",
|
||||
"deleteFailed": "Nepodarilo sa odstrániť podiel",
|
||||
"readOnlySourceNotice": "Tento zdroj je len na čítanie. Zdieľania nahrávania a oprávnenia, ktoré upravujú súbory, sú zakázané.",
|
||||
"shareTitleDescription": "Vlastný názov stránky zobrazený na stránke zdieľania. Ak je táto aplikácia na zdieľanie nainštalovaná ako PWA, názov aplikácie je obmedzený na 30 znakov."
|
||||
"readOnlySourceNotice": "Tento zdroj je len na čítanie. Zdieľania nahrávania a oprávnenia, ktoré upravujú súbory, sú zakázané."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Vytvorené v:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Varaktighet innan aktien upphör att gälla. Lämna tomt för en permanent delning.",
|
||||
"passwordDescription": "Valfritt lösenord som krävs för att komma åt denna andel, inklusive autentiserade användare.",
|
||||
"shareThemeColorDescription": "CSS-färgvärde som tillämpas på aktiens tema (t.ex. röd, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Anpassad sidtitel som visas på delningssidan.",
|
||||
"shareDescriptionHelp": "Kort beskrivning som visas på aktiesidan (kan användas i metataggar).",
|
||||
"shareBannerDescription": "URL eller sökväg för bannerbilden som är tillgänglig för klienten - antingen abosolute eller index path accepteras: t.ex. \"https://domain.com/banner.png\" eller \"/path/to/banner.png",
|
||||
"shareFaviconDescription": "URL eller sökväg till Favicon som är tillgänglig för klienten - antingen abosolute eller indexsökväg accepteras: t.ex. \"https://domain.com/favicon.png\" eller \"/path/to/favicon.png",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Välj bannerbild",
|
||||
"selectFaviconImage": "Välj favicon-bild",
|
||||
"deleteFailed": "Misslyckades med att ta bort delning",
|
||||
"readOnlySourceNotice": "Denna källa är skrivskyddad. Uppladdningsandelar och behörigheter som ändrar filer är inaktiverade.",
|
||||
"shareTitleDescription": "Anpassad sidtitel som visas på delningssidan. Om denna delningsfunktion är installerad som en PWA får appens namn inte överstiga 30 tecken."
|
||||
"readOnlySourceNotice": "Denna källa är skrivskyddad. Uppladdningsandelar och behörigheter som ändrar filer är inaktiverade."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Skapad på:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Paylaşımın sona ermesinden önceki süre. Kalıcı bir paylaşım için boş bırakın.",
|
||||
"passwordDescription": "Kimliği doğrulanmış kullanıcılar da dahil olmak üzere bu paylaşıma erişmek için gereken isteğe bağlı parola.",
|
||||
"shareThemeColorDescription": "Paylaşımın temasına uygulanan CSS renk değeri (örneğin, kırmızı, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "Paylaşım sayfasında gösterilen özel sayfa başlığı.",
|
||||
"shareDescriptionHelp": "Paylaşım sayfasında gösterilen kısa açıklama (meta etiketlerde kullanılabilir).",
|
||||
"shareBannerDescription": "Banner resmi URL'si veya istemci tarafından erişilebilen yol -- mutlak veya dizin yolu kabul edilir: örneğin 'https://domain.com/banner.png' veya '/path/to/banner.png'",
|
||||
"shareFaviconDescription": "Favicon URL'si veya istemci tarafından erişilebilen yol -- mutlak veya dizin yolu kabul edilir: örneğin 'https://domain.com/favicon.png' veya '/path/to/favicon.png'",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Afiş resmini seçin",
|
||||
"selectFaviconImage": "Favicon resmini seçin",
|
||||
"deleteFailed": "Paylaşım silinemedi",
|
||||
"readOnlySourceNotice": "Bu kaynak salt okunurdur. Yükleme paylaşımları ve dosyaları değiştiren izinler devre dışı bırakılmıştır.",
|
||||
"shareTitleDescription": "Paylaşım sayfasında görüntülenen özel sayfa başlığı. Bu paylaşım bir PWA olarak yüklendiyse, uygulama adı 30 karakterle sınırlıdır."
|
||||
"readOnlySourceNotice": "Bu kaynak salt okunurdur. Yükleme paylaşımları ve dosyaları değiştiren izinler devre dışı bırakılmıştır."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Oluşturuldu:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "Тривалість до закінчення акції. Залиште порожнім для постійної акції.",
|
||||
"passwordDescription": "Необов'язковий пароль, необхідний для доступу до цього ресурсу, в тому числі для авторизованих користувачів.",
|
||||
"shareThemeColorDescription": "Значення кольору CSS, застосоване до теми ресурсу (наприклад, red, #0ea5e9, rgb(14,165,233)).",
|
||||
"shareTitleDescription": "На сторінці спільного доступу відображається власний заголовок сторінки.",
|
||||
"shareDescriptionHelp": "Короткий опис, що відображається на сторінці ресурсу (може використовуватися в метатегах).",
|
||||
"shareBannerDescription": "URL зображення банера або шлях, доступний клієнту - допускається як абсолютний, так і індексний шлях: наприклад, 'https://domain.com/banner.png' або '/path/to/banner.png'.",
|
||||
"shareFaviconDescription": "URL-адреса іконки або шлях, доступний клієнту - допускається як абсолютний, так і індексний шлях: наприклад, 'https://domain.com/favicon.png' або '/путь/до/favicon.png'.",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "Виберіть зображення банера",
|
||||
"selectFaviconImage": "Виберіть зображення іконки",
|
||||
"deleteFailed": "Не вдалося видалити спільний ресурс",
|
||||
"readOnlySourceNotice": "Це джерело доступне лише для читання. Спільні ресурси для завантаження та дозволи, які змінюють файли, вимкнено.",
|
||||
"shareTitleDescription": "Налаштований заголовок сторінки, що відображається на сторінці спільного доступу. Якщо цей додаток для спільного доступу встановлено як PWA, назва додатка не може перевищувати 30 символів."
|
||||
"readOnlySourceNotice": "Це джерело доступне лише для читання. Спільні ресурси для завантаження та дозволи, які змінюють файли, вимкнено."
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "Створено в Ат:",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "共享到期前的持续时间。如果是永久共享,则留空。",
|
||||
"passwordDescription": "访问此共享(包括已通过身份验证的用户)所需的可选密码。",
|
||||
"shareThemeColorDescription": "应用于共享主题的 CSS 颜色值(例如,红色,#0ea5e9,rgb(14,165,233))。",
|
||||
"shareTitleDescription": "共享页面上显示的自定义页面标题。",
|
||||
"shareDescriptionHelp": "共享页面上显示的简短描述(可在元标签中使用)。",
|
||||
"shareBannerDescription": "客户端可访问的横幅图片 URL 或路径--接受绝对路径或索引路径:例如 \"https://domain.com/banner.png \"或\"/path/to/banner.png\"。",
|
||||
"shareFaviconDescription": "客户端可访问的 Favicon URL 或路径--接受绝对路径或索引路径:例如 \"https://domain.com/favicon.png \"或\"/path/to/favicon.png\"。",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "选择横幅图片",
|
||||
"selectFaviconImage": "选择图标图像",
|
||||
"deleteFailed": "删除共享失败",
|
||||
"readOnlySourceNotice": "此源为只读。上传共享和修改文件的权限被禁用。",
|
||||
"shareTitleDescription": "在分享页面上显示的自定义页面标题。如果此分享功能已作为 PWA 安装,则应用名称长度限制为 30 个字符。"
|
||||
"readOnlySourceNotice": "此源为只读。上传共享和修改文件的权限被禁用。"
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "创建于",
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
"shareDurationDescription": "此分享在多久後到期。留空表示永久分享。",
|
||||
"passwordDescription": "存取此分享所需的選填密碼,已驗證的使用者也必須輸入。",
|
||||
"shareThemeColorDescription": "套用到分享主題的 CSS 顏色值(例如:red、#0ea5e9、rgb(14,165,233))。",
|
||||
"shareTitleDescription": "顯示在分享頁面的自訂標題。",
|
||||
"shareDescriptionHelp": "顯示在分享頁面的簡短說明(也可能用於 meta 標籤)。",
|
||||
"shareBannerDescription": "瀏覽器可存取的橫幅圖片 URL 或路徑,可使用絕對網址或站內路徑,例如:https://domain.com/banner.png 或 /path/to/banner.png",
|
||||
"shareFaviconDescription": "瀏覽器可存取的 favicon URL 或路徑,可使用絕對網址或站內路徑,例如:https://domain.com/favicon.png 或 /path/to/favicon.png",
|
||||
@@ -407,8 +408,7 @@
|
||||
"selectBannerImage": "選擇橫幅圖片",
|
||||
"selectFaviconImage": "選擇 Favicon 圖片",
|
||||
"deleteFailed": "刪除分享失敗",
|
||||
"readOnlySourceNotice": "此來源為唯讀。上傳共用和修改檔案的權限已停用。",
|
||||
"shareTitleDescription": "分享頁面上顯示的自訂頁面標題。若此分享功能已安裝為 PWA,應用程式名稱的長度上限為 30 個字元。"
|
||||
"readOnlySourceNotice": "此來源為唯讀。上傳共用和修改檔案的權限已停用。"
|
||||
},
|
||||
"api": {
|
||||
"createdAt": "建立於:",
|
||||
|
||||
@@ -14,21 +14,6 @@ export async function validateLogin(isPublicRoute = false) {
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
// A 401 from the non-public self check means our session cookie (JWT) is no
|
||||
// longer valid — typically it expired. Clear it and redirect to login so the
|
||||
// user can re-authenticate, instead of leaving the stale cookie in place
|
||||
// (which otherwise leaves the app stuck on reload). Only do this for a real,
|
||||
// non-public session: public routes legitimately 401 for anonymous share
|
||||
// visitors, and we skip it when there is no session cookie to clear.
|
||||
if (
|
||||
res.status === 401 &&
|
||||
!isPublicRoute &&
|
||||
document.cookie
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("filebrowser_quantum_jwt="))
|
||||
) {
|
||||
sessionExpired();
|
||||
}
|
||||
throw new Error(`{"status":${res.status},"message":"${await res.text()}"}`);
|
||||
}
|
||||
const userInfo = await res.json();
|
||||
@@ -76,7 +61,7 @@ export function generateRandomCode(length) {
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function logout(redirectUrl) {
|
||||
export async function logout() {
|
||||
try {
|
||||
const res = await fetch(getApiPath("auth/logout"), {
|
||||
method: "POST",
|
||||
@@ -84,17 +69,17 @@ export async function logout(redirectUrl) {
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
let destination = data.logoutUrl || `${globalVars.baseURL}login`;
|
||||
if (redirectUrl) {
|
||||
destination = redirectUrl;
|
||||
}
|
||||
let logoutUrl = data.logoutUrl;
|
||||
// Backend clears the cookie, but frontend does it as fail-safe cleanup
|
||||
document.cookie = "filebrowser_quantum_jwt=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/";
|
||||
void mutations.setCurrentUser(null);
|
||||
// No need to clear state.jwt - cookie is the source of truth
|
||||
if (!logoutUrl) {
|
||||
logoutUrl = `${globalVars.baseURL}login`;
|
||||
}
|
||||
// Add a small delay to ensure cookie deletion completes before redirect
|
||||
setTimeout(() => {
|
||||
window.location.href = destination;
|
||||
window.location.href = logoutUrl;
|
||||
}, 100);
|
||||
return; // Stop execution
|
||||
} else {
|
||||
@@ -106,24 +91,6 @@ export async function logout(redirectUrl) {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle an authenticated request that came back 401 because the session cookie
|
||||
// (JWT) is no longer valid — typically it expired while the tab was idle. Unlike
|
||||
// logout(), this does NOT call the server (which would itself 401 on an expired
|
||||
// token and leave the stale cookie in place); it clears the cookie locally and
|
||||
// redirects to the login page so the user can re-authenticate, instead of being
|
||||
// stuck on a raw "token is expired" error.
|
||||
export function sessionExpired() {
|
||||
document.cookie =
|
||||
"filebrowser_quantum_jwt=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/";
|
||||
void mutations.setCurrentUser(null);
|
||||
// Avoid a redirect loop if we're already on the login page.
|
||||
if (window.location.pathname.endsWith("/login")) {
|
||||
return;
|
||||
}
|
||||
const current = window.location.pathname + window.location.search;
|
||||
window.location.href = `${globalVars.baseURL}login?redirect=${encodeURIComponent(current)}`;
|
||||
}
|
||||
|
||||
// Helper function to retrieve the value of a specific cookie
|
||||
//function getCookie(name) {
|
||||
// return document.cookie
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Hoisted mocks referenced by the vi.mock factories below.
|
||||
const { storeMock } = vi.hoisted(() => ({
|
||||
storeMock: {
|
||||
state: { sessionId: 'sess', user: null },
|
||||
getters: { isLoggedIn: vi.fn(() => true) },
|
||||
mutations: { setCurrentUser: vi.fn(), setSession: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/store', () => storeMock);
|
||||
vi.mock('@/utils/constants', () => ({ globalVars: { baseURL: '/', recaptcha: false } }));
|
||||
vi.mock('@/utils/url.js', () => ({
|
||||
getApiPath: (p, params = {}) =>
|
||||
`/api/${p}${params.id ? `?id=${params.id}` : ''}`,
|
||||
}));
|
||||
|
||||
import { validateLogin } from './auth.js';
|
||||
|
||||
const COOKIE = 'filebrowser_quantum_jwt';
|
||||
|
||||
function respond(status, body = '') {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
status,
|
||||
text: async () => body,
|
||||
json: async () => ({}),
|
||||
});
|
||||
}
|
||||
|
||||
describe('validateLogin session-expiry handling', () => {
|
||||
beforeEach(() => {
|
||||
storeMock.mutations.setCurrentUser.mockClear();
|
||||
document.cookie = `${COOKIE}=stale; path=/`;
|
||||
// Stub navigation via Vitest's global-stub API (jsdom doesn't implement
|
||||
// real navigation). pathname+search feed the redirect; href captures it.
|
||||
vi.stubGlobal('location', { pathname: '/files/', search: '?a=1', href: '' });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('clears the cookie + user and redirects (with encoded return path) on a non-public 401 with a session cookie', async () => {
|
||||
respond(401, 'token is expired');
|
||||
await expect(validateLogin(false)).rejects.toThrow();
|
||||
expect(storeMock.mutations.setCurrentUser).toHaveBeenCalledWith(null);
|
||||
expect(document.cookie.includes(`${COOKIE}=stale`)).toBe(false);
|
||||
// Full redirect contract: login route + correctly encoded current path+query.
|
||||
expect(window.location.href).toBe(
|
||||
`/login?redirect=${encodeURIComponent('/files/?a=1')}`
|
||||
);
|
||||
});
|
||||
|
||||
it('does NOT log out or redirect on a PUBLIC 401 (anonymous share visitor)', async () => {
|
||||
respond(401, 'unauthorized');
|
||||
await expect(validateLogin(true)).rejects.toThrow();
|
||||
expect(storeMock.mutations.setCurrentUser).not.toHaveBeenCalledWith(null);
|
||||
expect(document.cookie.includes(`${COOKIE}=stale`)).toBe(true);
|
||||
expect(window.location.href).toBe('');
|
||||
});
|
||||
|
||||
it('does NOT log out or redirect on a non-public 401 when there is NO session cookie', async () => {
|
||||
document.cookie = `${COOKIE}=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/`;
|
||||
respond(401, 'unauthorized');
|
||||
await expect(validateLogin(false)).rejects.toThrow();
|
||||
expect(storeMock.mutations.setCurrentUser).not.toHaveBeenCalledWith(null);
|
||||
expect(window.location.href).toBe('');
|
||||
});
|
||||
|
||||
it('does NOT log out or redirect on a non-401 error (e.g. 500)', async () => {
|
||||
respond(500, 'server error');
|
||||
await expect(validateLogin(false)).rejects.toThrow();
|
||||
expect(storeMock.mutations.setCurrentUser).not.toHaveBeenCalledWith(null);
|
||||
expect(document.cookie.includes(`${COOKIE}=stale`)).toBe(true);
|
||||
expect(window.location.href).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sanitizeDocxHtml } from "./docxPreview";
|
||||
|
||||
describe("sanitizeDocxHtml", () => {
|
||||
it("strips javascript: hyperlinks", () => {
|
||||
const input =
|
||||
'<p><a href="javascript:alert(document.cookie)">CLICK HERE</a></p>';
|
||||
const output = sanitizeDocxHtml(input);
|
||||
expect(output).not.toContain("javascript:");
|
||||
expect(output).toContain("CLICK HERE");
|
||||
});
|
||||
|
||||
it("preserves normal formatting", () => {
|
||||
const input = "<p>Hello <strong>world</strong></p>";
|
||||
expect(sanitizeDocxHtml(input)).toBe(input);
|
||||
});
|
||||
|
||||
it("preserves embedded data-uri images from mammoth", () => {
|
||||
const input = '<p><img src="data:image/png;base64,abc" alt="chart"></p>';
|
||||
const output = sanitizeDocxHtml(input);
|
||||
expect(output).toContain('src="data:image/png;base64,abc"');
|
||||
expect(output).toContain('alt="chart"');
|
||||
});
|
||||
|
||||
it("strips inline event handlers", () => {
|
||||
const input = '<p onclick="alert(1)">text</p>';
|
||||
const output = sanitizeDocxHtml(input);
|
||||
expect(output).not.toContain("onclick");
|
||||
expect(output).toContain("text");
|
||||
});
|
||||
|
||||
it("preserves https hyperlinks", () => {
|
||||
const input = '<p><a href="https://example.com/doc">link</a></p>';
|
||||
expect(sanitizeDocxHtml(input)).toBe(input);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +0,0 @@
|
||||
import DOMPurify from "dompurify";
|
||||
|
||||
/** Sanitize mammoth DOCX HTML before v-html rendering. */
|
||||
export function sanitizeDocxHtml(html: string): string {
|
||||
return DOMPurify.sanitize(html);
|
||||
}
|
||||
@@ -10,18 +10,13 @@ export function canNativeShare() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the OS/browser share sheet can accept the given File.
|
||||
* navigator.canShare({ files }) validates the specific file being shared
|
||||
* (name, MIME type, size) — many platforms only allow a safe subset
|
||||
* (images, audio, video, plain text, PDF) and reject everything else.
|
||||
*/
|
||||
function canShareFile(file) {
|
||||
function canShareFiles() {
|
||||
if (typeof navigator.canShare !== "function") {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return navigator.canShare({ files: [file] });
|
||||
const probe = new File(["x"], "share-probe.txt", { type: "text/plain" });
|
||||
return navigator.canShare({ files: [probe] });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -48,14 +43,7 @@ export async function nativeShareFile(item) {
|
||||
const url = buildDownloadUrl(item);
|
||||
|
||||
try {
|
||||
// Only attempt to share the file's actual bytes if navigator.canShare
|
||||
// exists at all. We must check the real file (fetched below), not a
|
||||
// synthetic stand-in: this previously probed with a fixed text/plain
|
||||
// file, which always reported success even for file types (e.g.
|
||||
// .xlsx, .docx, .zip) that the OS share sheet then silently rejected
|
||||
// once navigator.share() was actually called, surfacing as an opaque
|
||||
// "permission denied" error to the user (see #2659).
|
||||
if (typeof navigator.canShare === "function") {
|
||||
if (canShareFiles()) {
|
||||
const response = await fetch(url, { credentials: "same-origin" });
|
||||
if (!response.ok) {
|
||||
const detail = response.statusText ? ` (${response.statusText})` : "";
|
||||
@@ -65,15 +53,10 @@ export async function nativeShareFile(item) {
|
||||
const blob = await response.blob();
|
||||
const type = blob.type || item.type || "application/octet-stream";
|
||||
const file = new File([blob], filename, { type });
|
||||
|
||||
if (canShareFile(file)) {
|
||||
await navigator.share({ files: [file], title: filename });
|
||||
return;
|
||||
}
|
||||
await navigator.share({ files: [file], title: filename });
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to sharing a link when the platform can't share the file's
|
||||
// actual bytes/type (or doesn't support file sharing at all).
|
||||
await navigator.share({ url, title: filename });
|
||||
} catch (e) {
|
||||
if (e?.name === "AbortError") {
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const showErrorMock = vi.fn();
|
||||
|
||||
vi.mock("@/api", () => ({
|
||||
resourcesApi: {
|
||||
getDownloadURL: vi.fn(() => "https://example.com/api/raw/report.xlsx"),
|
||||
getDownloadURLPublic: vi.fn(() => "https://example.com/api/public/dl/report.xlsx"),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/notify", () => ({
|
||||
notify: {
|
||||
showError: (...args) => showErrorMock(...args),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/store", () => ({
|
||||
getters: {
|
||||
isShare: () => false,
|
||||
},
|
||||
state: {
|
||||
req: { source: "default" },
|
||||
},
|
||||
}));
|
||||
|
||||
import { canNativeShare, nativeShareFile } from "./nativeShare";
|
||||
|
||||
function mockShare(implementation) {
|
||||
Object.defineProperty(window, "isSecureContext", {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
navigator.share = vi.fn(implementation ?? (() => Promise.resolve()));
|
||||
}
|
||||
|
||||
function stubFetch(blobType) {
|
||||
global.fetch = vi.fn(() =>
|
||||
Promise.resolve({
|
||||
ok: true,
|
||||
statusText: "OK",
|
||||
status: 200,
|
||||
blob: () =>
|
||||
Promise.resolve({
|
||||
type: blobType,
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
showErrorMock.mockClear();
|
||||
delete navigator.canShare;
|
||||
delete navigator.share;
|
||||
global.fetch = undefined;
|
||||
});
|
||||
|
||||
describe("canNativeShare", () => {
|
||||
it("returns false when navigator.share is unavailable", () => {
|
||||
expect(canNativeShare()).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when navigator.share exists and context is secure", () => {
|
||||
mockShare();
|
||||
expect(canNativeShare()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("nativeShareFile", () => {
|
||||
it("shows an error when sharing isn't supported at all", async () => {
|
||||
await nativeShareFile({ name: "report.xlsx", path: "/report.xlsx" });
|
||||
expect(showErrorMock).toHaveBeenCalledWith("Sharing is not supported on this device");
|
||||
});
|
||||
|
||||
it(
|
||||
"falls back to sharing a link (not the file) when the platform rejects the file's real MIME type " +
|
||||
"-- regression test for #2659, where a hardcoded text/plain probe file made canShareFiles() always " +
|
||||
"return true, so navigator.share() was called with an .xlsx/.docx/.zip file the platform then " +
|
||||
"silently rejected, surfacing as 'permission denied'",
|
||||
async () => {
|
||||
mockShare();
|
||||
stubFetch("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
// Platform can share files in general, but rejects this specific
|
||||
// (non-safelisted) MIME type -- exactly what real browsers do for
|
||||
// office/archive formats.
|
||||
navigator.canShare = vi.fn(({ files }) => {
|
||||
const file = files?.[0];
|
||||
return file ? file.type === "text/plain" : false;
|
||||
});
|
||||
|
||||
await nativeShareFile({ name: "report.xlsx", path: "/report.xlsx" });
|
||||
|
||||
expect(navigator.share).toHaveBeenCalledTimes(1);
|
||||
const sharedPayload = navigator.share.mock.calls[0][0];
|
||||
// Must NOT have attempted to share the actual xlsx file bytes.
|
||||
expect(sharedPayload.files).toBeUndefined();
|
||||
expect(sharedPayload.url).toBe("https://example.com/api/raw/report.xlsx");
|
||||
expect(showErrorMock).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it("shares the real file when the platform's canShare accepts its actual type", async () => {
|
||||
mockShare();
|
||||
stubFetch("application/pdf");
|
||||
navigator.canShare = vi.fn(({ files }) => files?.[0]?.type === "application/pdf");
|
||||
|
||||
await nativeShareFile({ name: "doc.pdf", path: "/doc.pdf" });
|
||||
|
||||
expect(navigator.share).toHaveBeenCalledTimes(1);
|
||||
const sharedPayload = navigator.share.mock.calls[0][0];
|
||||
expect(sharedPayload.files).toHaveLength(1);
|
||||
expect(sharedPayload.files[0].name).toBe("doc.pdf");
|
||||
expect(sharedPayload.files[0].type).toBe("application/pdf");
|
||||
});
|
||||
|
||||
it("shares a link directly when the platform has no canShare at all", async () => {
|
||||
mockShare();
|
||||
// No navigator.canShare defined -- older/limited platforms.
|
||||
|
||||
await nativeShareFile({ name: "report.xlsx", path: "/report.xlsx" });
|
||||
|
||||
expect(global.fetch).toBeUndefined();
|
||||
expect(navigator.share).toHaveBeenCalledWith({
|
||||
url: "https://example.com/api/raw/report.xlsx",
|
||||
title: "report.xlsx",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces a download failure instead of silently sharing nothing", async () => {
|
||||
mockShare();
|
||||
navigator.canShare = vi.fn(() => true);
|
||||
global.fetch = vi.fn(() =>
|
||||
Promise.resolve({ ok: false, status: 403, statusText: "Forbidden" })
|
||||
);
|
||||
|
||||
await nativeShareFile({ name: "report.xlsx", path: "/report.xlsx" });
|
||||
|
||||
expect(navigator.share).not.toHaveBeenCalled();
|
||||
expect(showErrorMock).toHaveBeenCalledWith("Download failed (403 (Forbidden))");
|
||||
});
|
||||
|
||||
it("silently ignores the user cancelling the OS share sheet", async () => {
|
||||
mockShare(() => {
|
||||
const err = new Error("cancelled");
|
||||
err.name = "AbortError";
|
||||
return Promise.reject(err);
|
||||
});
|
||||
|
||||
await nativeShareFile({ name: "report.xlsx", path: "/report.xlsx" });
|
||||
|
||||
expect(showErrorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,6 @@ import * as mammoth from "mammoth";
|
||||
import { resourcesApi } from "@/api";
|
||||
import { state, mutations, getters } from "@/store";
|
||||
import { url } from "@/utils";
|
||||
import { sanitizeDocxHtml } from "@/utils/docxPreview";
|
||||
|
||||
export default defineComponent({
|
||||
name: "DocxViewer",
|
||||
@@ -186,7 +185,7 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
const result = await mammoth.convertToHtml({ arrayBuffer });
|
||||
this.docxHtml = sanitizeDocxHtml(result.value);
|
||||
this.docxHtml = result.value;
|
||||
} catch (e) {
|
||||
this.error = e.message || "An unknown error occurred.";
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user