Compare commits

...
82 Commits
Author SHA1 Message Date
Graham SteffaniakandCursor 2c071d1e6e fix(cli): preserve admin credentials in setup-generated config (#3267)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 16:19:34 -05:00
Graham Steffaniak b9afea9368 adjusted symlink extraction behavior to correct edge case (#3266) 2026-10-23 15:45:47 -05:00
a91bff2638 backport preview and share fixes to stable (#3264)
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-10-23 15:29:41 -05:00
e02284183a fix(auth): API token permission handling for customized tokens (#3256)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-22 15:19:49 -05:00
05140f0ae3 fix: resolve staging/v2.0.2 release blockers (access perf revert, prompt cancel, tooltip dark mode) (#3239)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-20 11:25:49 -05:00
735842fd5f fix(sse): lock client registry during source-update delivery (GHSA-p9wm-f5jj-75pj) [stable] (#3208)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-19 19:00:10 -05:00
f0761c6146 fix(shares): preserve share paths when a folder is moved (GHSA-26fh-r34c-qxh6) [stable] (#3210)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-19 18:52:48 -05:00
Graham Steffaniak 9c812913c6 fix(frontend): restore upload guards while uploads are paused (stable) (#3221) 2026-10-19 13:52:07 -05:00
Cursor AgentandGraham Steffaniak e5e4fc4ec4 Merge branch 'staging/v2.0.2' into cursor/fix-upload-prompt-guard-stable-b1a8
Resolve Prompts.vue conflict by keeping upload guards in store mutations
and uploadNavigationGuard (PR refactor). CHANGELOG retains all v2.0.2-stable
security backports and upload guard bug fix entry.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-19 18:47:08 +00:00
Graham Steffaniak f8b7ee1a92 fix(frontend): escape Size Analyzer tooltip content (GHSA-rmjp-pfrq-cc3v) [stable] (#3212) 2026-10-19 12:41:28 -05:00
Graham Steffaniak 9e973c3959 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-rmjp-7fd7 2026-10-19 12:40:56 -05:00
Graham Steffaniak 7e97200e0a fix(auth): require password for passkey lifecycle changes (GHSA-r744-4vm3-2px3) [stable] (#3213) 2026-10-19 12:00:56 -05:00
Graham Steffaniak 44757aae7b Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-r744-7fd7 2026-10-19 12:00:31 -05:00
Graham Steffaniak 2d9eceadd6 fix(access): resolve filesystem aliases for path rules (GHSA-4vrc-935w-xxq2) [stable] (#3214) 2026-10-19 11:39:35 -05:00
Graham Steffaniak d13f5fd39d Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-4vrc-7fd7 2026-10-19 11:39:15 -05:00
Cursor AgentandGraham Steffaniak 3e0c93a435 fix(frontend): use staging api import paths in auth.js
The backport imported @/api/utils.ts and other dev-only module paths.
On staging/v2.0.2 the API layer uses utils.js and barrel imports from
@/store and @/notify.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-19 16:38:18 +00:00
Graham Steffaniak 04ae7b4764 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-r744-7fd7 2026-10-19 11:36:01 -05:00
Graham Steffaniak 22d5441d85 fix(stream): reject cross-context view grants on authenticated view API (GHSA-wxj5-g3qp-g732) [stable] (#3207) 2026-10-19 11:27:08 -05:00
Graham Steffaniak c3f340c7b6 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-wxj5-7fd7 2026-10-19 11:26:59 -05:00
Graham Steffaniak f044bd4266 fix(tools): scope duplicate finder cache per user (GHSA-4fhx-8pf6-5gmr) [stable] (#3209) 2026-10-19 11:26:22 -05:00
Graham Steffaniak 6ad9b8ea47 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-4fhx-7fd7 2026-10-19 11:26:10 -05:00
Cursor AgentandGraham Steffaniak 8e749deff2 fix(access): drop FS path cache; order alias resolution safely
Read directory entries from disk on each Permitted check. Resolve segments
with exact name, then case-fold + SameFile, then identity with ambiguity denied.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 22:37:38 +00:00
Cursor AgentandGraham Steffaniak bf8c18cf89 fix(frontend): clear stale upload navigation approval when idle
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 22:25:09 +00:00
Graham Steffaniak bb05475d83 Merge branch 'staging/v2.0.2' into cursor/fix-upload-prompt-guard-stable-b1a8 2026-10-18 17:22:39 -05:00
Graham Steffaniak db41b621d1 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-rmjp-7fd7 2026-10-18 17:12:01 -05:00
Graham Steffaniak e323f02d9e fix(webdav): require Create for new PUT targets (GHSA-8655-2ph3-q7q7) [stable] (#3211) 2026-10-18 17:11:42 -05:00
Graham Steffaniak c120419016 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-8655-7fd7 2026-10-18 17:11:31 -05:00
Graham Steffaniak 3ae4c2841f fix(auth): trust rightmost X-Forwarded-For for client IP (GHSA-wjp8-g49g-xrhx) [stable] (#3205) 2026-10-18 17:10:49 -05:00
Graham Steffaniak 4c05a913b9 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-wjp8-7fd7 2026-10-18 17:10:38 -05:00
Graham Steffaniak 865a1103c7 Merge branch 'staging/v2.0.2' into cursor/backport-ghsa-rmjp-7fd7 2026-10-18 17:08:53 -05:00
Graham Steffaniak ae2cb9f22a fix(frontend): files route parsing and /files/ default source (stable backport) (#3216) 2026-10-18 17:01:00 -05:00
Cursor AgentandGraham Steffaniak 15e803079f fix(frontend): keep staging router next() API for upload nav guard
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 21:59:48 +00:00
Cursor AgentandGraham Steffaniak dbd845e2e2 fix(frontend): harden upload nav guard and isUploading on queue removal
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 21:58:55 +00:00
Cursor AgentandGraham Steffaniak 177f48e5d7 fix(frontend): harden upload nav guard and isUploading on queue removal
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 21:57:29 +00:00
Cursor AgentandGraham Steffaniak 9e4f391f93 fix(access): resolve FS aliases via ReadDir and SameFile (GHSA-4vrc)
Replace ineffective Lstat().Name() resolution with per-segment directory
listing, SameFile matching, and fail-closed errors; add tests and path cache.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 21:56:45 +00:00
Cursor AgentandGraham Steffaniak 5d483e7953 fix(frontend): use next(false) for upload nav guard on staging router API
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 19:57:40 +00:00
Cursor AgentandGraham Steffaniak 865ccb3ae6 fix(frontend): guard upload prompt while uploads are paused
Treat paused queue items as in-progress for isUploading, centralize
closeTopPrompt protection in the store, add SPA navigation guard, and
keep beforeunload tied to isUploading instead of the Upload component.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 19:07:01 +00:00
Cursor AgentandGraham Steffaniak 74157deb3b fix(frontend): reject passkey password prompt on dismiss
Wire showPrompt cancel when the user closes the password dialog (X/Escape)
via Prompts.vue. Export isPasskeyActorPasswordCancelled and skip error toasts
in passkey settings UI when the user backs out.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 19:03:32 +00:00
Cursor AgentandGraham Steffaniak f168ce087d fix(auth): gate passkey password checks on password login; send X-Password from UI
Mirror GHSA-r744 beta fix (#3198): password-login accounts only for
checkOtpActorPassword; frontend prompts and sends X-Password on register/delete.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:58:17 +00:00
Cursor AgentandGraham Steffaniak c524a7d752 docs(changelog): use v2.0.2-stable section for GHSA-4vrc
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:39 +00:00
Cursor AgentandGraham Steffaniak f79f514a29 docs(changelog): use v2.0.2-stable section for GHSA-r744
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:38 +00:00
Cursor AgentandGraham Steffaniak 93bfa4906d docs(changelog): use v2.0.2-stable section for GHSA-rmjp
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:37 +00:00
Cursor AgentandGraham Steffaniak 18b8ed624f docs(changelog): use v2.0.2-stable section for GHSA-8655
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:36 +00:00
Cursor AgentandGraham Steffaniak a470e65a24 docs(changelog): use v2.0.2-stable section for GHSA-4fhx
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:33 +00:00
Cursor AgentandGraham Steffaniak e18b8683f5 docs(changelog): use v2.0.2-stable section for GHSA-wxj5
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:31 +00:00
Cursor AgentandGraham Steffaniak d03ee259a2 docs(changelog): use v2.0.2-stable section for GHSA-wjp8
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:54:28 +00:00
Graham Steffaniak 8a2f4a25d4 Refactor Tooltip and generic to avoid v-html usage (GHSA-rmjp-pfrq-cc3v) [stable] (#3217) 2026-10-18 13:07:24 -05:00
Cursor AgentandGraham Steffaniak 0d708f3955 fix(frontend): minimal /files/ and source-named-files routing (stable)
Backport #3099 knownSources guard and #3178 single-source fallback at
/files/ without changing multi-source redirect URLs.

Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 18:04:52 +00:00
Kevin B. 55c659e332 Refactor Tooltip.vue and generic.vue 2026-10-18 12:38:22 -05:00
Cursor AgentandGraham Steffaniak f095bc64ee fix(changelog): v2.0.2 security entry for GHSA-4fhx backport
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:43:56 +00:00
Cursor AgentandGraham Steffaniak 96efc21e88 fix(webdav): require Create for new PUT targets (GHSA-8655-2ph3-q7q7)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:42:42 +00:00
Cursor AgentandGraham Steffaniak 7b85410b50 fix(access): resolve filesystem aliases for access rules (GHSA-4vrc-935w-xxq2)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:40:52 +00:00
Cursor AgentandGraham Steffaniak c14a1af81e fix(auth): require password to change passkeys (GHSA-r744-4vm3-2px3)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:40:46 +00:00
Cursor AgentandGraham Steffaniak e8c85e3f90 fix(frontend): escape Size Analyzer tooltip content (GHSA-rmjp-pfrq-cc3v)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:40:45 +00:00
Cursor AgentandGraham Steffaniak c1f0033c65 fix(view): reject share view tokens on authenticated view route (GHSA-wxj5-g3qp-g732)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:40:41 +00:00
Cursor AgentandGraham Steffaniak a2d48144ea fix(tools): scope duplicate finder cache per user (GHSA-4fhx-8pf6-5gmr)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:39:49 +00:00
Cursor AgentandGraham Steffaniak 024d383b14 fix(auth): trust rightmost X-Forwarded-For for client IP (GHSA-wjp8-g49g-xrhx)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-18 16:37:50 +00:00
Graham Steffaniak aa4dd3ae95 updated v2.0.1 changelog (#3141) 2026-10-13 09:53:11 -05:00
Graham Steffaniak 9f4b15442b fix: reject usernames that do not map to their own home directory (#3139) 2026-10-13 09:33:41 -05:00
Graham Steffaniak 759342bef3 updated changelog 2026-10-13 09:12:40 -05:00
dl-pt c4072608d6 fix(auth): prevent collisions between newly issued tokens (#3135) 2026-10-13 09:09:21 -05:00
Graham Steffaniak a29573e706 updated with stable changelog (#3104) 2026-10-09 10:57:05 -05:00
Graham Steffaniak 1071e66a36 updated changelog 2026-10-09 10:45:47 -05:00
Graham Steffaniak 3956ccd859 make sidebar tree view links native hyperlinks (#3080) 2026-10-04 16:19:09 -05:00
Graham Steffaniak 3f756de845 port fix over to dev/v2.0.10 2026-10-04 15:58:39 -05:00
Graham Steffaniak aa98563db7 Merge branch 'dev/v2.0.10' of github.com:gtsteffaniak/filebrowser into dev/v2.0.10 2026-10-04 15:57:57 -05:00
Graham Steffaniak fb7f25b0a8 Fix bugs halloween prompts (#3076) 2026-10-04 15:38:16 -05:00
Graham Steffaniak 7f56deb03b Merge branch 'dev/v2.0.10' of github.com:gtsteffaniak/filebrowser into dev/v2.0.10 2026-10-04 12:27:11 -05:00
Graham Steffaniak 592d8db506 Update version match workflow (#3072) 2026-10-04 12:26:59 -05:00
Graham Steffaniak 0b346bd8c7 Merge branch 'dev/v2.0.10' of github.com:gtsteffaniak/filebrowser into dev/v2.0.10 2026-10-04 12:04:49 -05:00
Graham Steffaniak 8f4e148cf3 updated cli setup command (#3071) 2026-10-04 12:04:37 -05:00
Graham Steffaniak 82ab5957dd updated cli setup command 2026-10-04 11:50:18 -05:00
Graham Steffaniak 033e1a4642 upgrade docker 2026-10-04 11:33:30 -05:00
Graham SteffaniakandCursor 78cb4ca214 Fix GHSA-6gr6-5qpq-888p: API token session renew (#3070)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 11:29:14 -05:00
Graham SteffaniakandCursor b40be3e25e Fix TOTP re-enrollment MFA bypass (GHSA-qx86-4v5r-26g5). (#3067)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 10:49:36 -05:00
Graham Steffaniak e4fc79287d added feature to reset user password on login (#3064) 2026-10-03 20:00:01 -05:00
Graham SteffaniakandCursor 9ae8cc07e6 fix: GHSA-p7x3-p5jj-9xfh - Enforce public share limits on lyrics and subtitle routes. (#3061)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 18:20:01 -05:00
Graham Steffaniak b2936e5c80 Fix token expiration (#3056) 2026-10-03 16:54:11 -05:00
Kevin B. f501c765a6 fix sidebar behind header on iOS (#3060) 2026-10-03 16:18:01 -05:00
Graham SteffaniakandDevin b861660ce9 Fix inflated disk usage on ZFS datasets and btrfs subvolumes; add roo… (#3035)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-02 16:16:31 -05:00
Graham Steffaniak 98c96c3ec4 Case insensitive match ldap (#3048) 2026-10-01 22:05:58 -05:00
Graham Steffaniak b7e06fd333 added support for env vars in config (#3047) 2026-09-30 17:53:01 -05:00
177 changed files with 7305 additions and 1881 deletions

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
set -euo pipefail
IMAGE_REPO="${IMAGE_REPO:-gtstef/filebrowser}"
SLIM_SUFFIX="${SLIM_SUFFIX:-}"
if [[ -z "${GITHUB_OUTPUT:-}" ]]; then
echo "GITHUB_OUTPUT is not set" >&2
exit 1
fi
write_outputs() {
local update_track="$1"
local update_major="$2"
echo "update_track=${update_track}" >> "$GITHUB_OUTPUT"
echo "update_major=${update_major}" >> "$GITHUB_OUTPUT"
}
registry_version() {
local tag="$1"
local ver err err_file
err_file="$(mktemp)"
if ! ver="$(docker buildx imagetools inspect "${IMAGE_REPO}:${tag}" \
--format '{{ with index .Image "linux/amd64" }}{{ index .Config.Labels "org.opencontainers.image.version" }}{{ end }}' 2>"$err_file")"; then
err="$(cat "$err_file")"
rm -f "$err_file"
if grep -qiE 'not found|manifest unknown' <<<"$err"; then
ver=""
else
echo "Failed to inspect ${IMAGE_REPO}:${tag}: ${err}" >&2
exit 1
fi
else
rm -f "$err_file"
if [[ -z "$ver" ]]; then
echo "Missing org.opencontainers.image.version on ${IMAGE_REPO}:${tag} (linux/amd64)" >&2
exit 1
fi
fi
ver="${ver#v}"
printf '%s' "$ver"
}
semver_allows_update() {
local new="$1"
local incumbent="$2"
if [[ -z "$incumbent" ]]; then
return 0
fi
local winner
winner="$(printf '%s\n' "$incumbent" "$new" | sort -V | tail -n1)"
[[ "$winner" == "$new" ]]
}
ref="${GITHUB_REF_NAME:-}"
ref="${ref#v}"
if [[ ! "$ref" =~ ^([0-9]+\.[0-9]+\.[0-9]+)-(.+)$ ]]; then
echo "Tag '${GITHUB_REF_NAME:-}' has no X.Y.Z-suffix form; leaving major-only floats enabled, track floats disabled"
write_outputs false true
exit 0
fi
new_version="$ref"
semver_core="${BASH_REMATCH[1]}"
suffix="${BASH_REMATCH[2]}"
major="$(echo "$semver_core" | cut -d. -f1)"
track=""
case "$suffix" in
beta) track="beta" ;;
stable) track="stable" ;;
*)
echo "Tag suffix '${suffix}' is not beta/stable; leaving major-only floats enabled, track floats disabled"
write_outputs false true
exit 0
;;
esac
track_tag="${track}${SLIM_SUFFIX}"
major_tag="${major}-${track}${SLIM_SUFFIX}"
incumbent_track="$(registry_version "$track_tag")"
incumbent_major="$(registry_version "$major_tag")"
update_track=false
if semver_allows_update "$new_version" "$incumbent_track"; then
update_track=true
fi
update_major=false
if semver_allows_update "$new_version" "$incumbent_major"; then
update_major=true
fi
echo "Floating tag policy (${SLIM_SUFFIX:-full} image):"
echo " New version: ${new_version}"
echo " Track tag: ${track_tag} (incumbent: ${incumbent_track:-<none>}) -> update_track=${update_track}"
echo " Major tag: ${major_tag} (incumbent: ${incumbent_major:-<none>}) -> update_major=${update_major}"
write_outputs "$update_track" "$update_major"
+34 -18
View File
@@ -61,18 +61,23 @@ jobs:
images: |
gtstef/filebrowser
ghcr.io/gtsteffaniak/filebrowser
- name: Decide floating Docker tags
id: floating
run: bash .github/scripts/docker-floating-tag-policy.sh
- name: Modify tags (strip 'v' and add version tags)
id: modify-json
run: |
JSON='${{ steps.meta.outputs.json }}'
MODIFIED_JSON=$(echo "$JSON" | jq '
MODIFIED_JSON=$(echo "$JSON" | jq \
--argjson updateTrack '${{ steps.floating.outputs.update_track == 'true' }}' \
--argjson updateMajor '${{ steps.floating.outputs.update_major == 'true' }}' '
.tags |= map(
sub(":v"; ":") # Strip the 'v'
| select(test(":latest") | not)
) |
# Find all version tags with suffix (X.Y.Z-suffix) and add major.minor and major tags
# Find all version tags with suffix (X.Y.Z-suffix) and add major.minor (always) and major tags (when allowed)
.tags += [
.tags[]
.tags[]
| select(test(":[0-9]+\\.[0-9]+\\.[0-9]+-"))
| split(":")
| .[-1] as $version
@@ -83,18 +88,20 @@ jobs:
| ($version_parts[0]) as $major
| "gtstef/filebrowser:\($major_minor)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major_minor)-\($suffix)",
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
if $updateMajor then
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
else empty end
] |
# Add suffix-only tags for beta (only if tag ends with -beta)
if any(.tags[]; split(":")[-1] | endswith("-beta")) then
# Add suffix-only tags for beta when semver policy allows
if $updateTrack and any(.tags[]; split(":")[-1] | endswith("-beta")) then
.tags += [
"gtstef/filebrowser:beta",
"ghcr.io/gtsteffaniak/filebrowser:beta"
]
else . end |
# Add suffix-only tags for stable (and latest) (only if tag ends with -stable)
if any(.tags[]; split(":")[-1] | endswith("-stable")) then
# Add suffix-only tags for stable (and latest) when semver policy allows
if $updateTrack and any(.tags[]; split(":")[-1] | endswith("-stable")) then
.tags += [
"gtstef/filebrowser:stable",
"ghcr.io/gtsteffaniak/filebrowser:stable",
@@ -146,19 +153,26 @@ jobs:
images: |
gtstef/filebrowser
ghcr.io/gtsteffaniak/filebrowser
- name: Decide floating Docker tags
id: floating
env:
SLIM_SUFFIX: -slim
run: bash .github/scripts/docker-floating-tag-policy.sh
- name: Modify tags (strip 'v' and add 'slim' if needed)
id: modify-json-slim
run: |
JSON='${{ steps.meta.outputs.json }}'
MODIFIED_JSON=$(echo "$JSON" | jq '
MODIFIED_JSON=$(echo "$JSON" | jq \
--argjson updateTrack '${{ steps.floating.outputs.update_track == 'true' }}' \
--argjson updateMajor '${{ steps.floating.outputs.update_major == 'true' }}' '
.tags |= map(
sub(":v"; ":") # Strip the 'v'
| select(test(":latest") | not) # Remove the "latest" tag
| . + "-slim" # Append "-slim" to the versioned tag
) |
# Find all version tags with suffix (X.Y.Z-suffix-slim) and add major.minor and major tags
# Find all version tags with suffix (X.Y.Z-suffix-slim) and add major.minor (always) and major tags (when allowed)
.tags += [
.tags[]
.tags[]
| select(test(":[0-9]+\\.[0-9]+\\.[0-9]+-"))
| split(":")
| .[-1] as $version
@@ -169,18 +183,20 @@ jobs:
| ($version_parts[0]) as $major
| "gtstef/filebrowser:\($major_minor)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major_minor)-\($suffix)",
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
if $updateMajor then
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
else empty end
] |
# Add suffix-only tags for beta-slim (only if tag ends with -beta-slim)
if any(.tags[]; split(":")[-1] | endswith("-beta-slim")) then
# Add suffix-only tags for beta-slim when semver policy allows
if $updateTrack and any(.tags[]; split(":")[-1] | endswith("-beta-slim")) then
.tags += [
"gtstef/filebrowser:beta-slim",
"ghcr.io/gtsteffaniak/filebrowser:beta-slim"
]
else . end |
# Add suffix-only tags for stable-slim (only if tag ends with -stable-slim)
if any(.tags[]; split(":")[-1] | endswith("-stable-slim")) then
# Add suffix-only tags for stable-slim when semver policy allows
if $updateTrack and any(.tags[]; split(":")[-1] | endswith("-stable-slim")) then
.tags += [
"gtstef/filebrowser:stable-slim",
"ghcr.io/gtsteffaniak/filebrowser:stable-slim"
+175
View File
@@ -2,6 +2,181 @@
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).
## v2.0.2-stable
**Security**:
- [Low] SSE source-update and user-targeted delivery hold the client registry lock through nonblocking sends, preventing concurrent map mutation and send-on-closed-channel panics when Realtime clients connect, disconnect, or shut down (GHSA-p9wm-f5jj-75pj) reporter @tao0845
- [Moderate] Moving or renaming a folder updates only shares whose paths are under the moved prefix, preserving per-file share roots instead of retargeting unrelated substring matches (GHSA-26fh-r34c-qxh6) reporters @jayhemnani9910 @dylanzonix
- [High] File Size Analyzer hover tooltips render file paths as plain text instead of HTML, closing stored XSS via crafted file names (GHSA-rmjp-pfrq-cc3v) reporter @U3RhcnQ
- [Moderate] Passkey registration and deletion now require the account password when a passkey is already configured, and passkeys cannot be altered through generic user profile PATCH (GHSA-r744-4vm3-2px3) reporter @tonghuaroot
- [Moderate] Authenticated GET /api/resources/view no longer accepts view tokens minted for a public share when the caller lacks view permission on the requested source (GHSA-wxj5-g3qp-g732) reporter @BlueN0r
- [Low] Duplicate finder results are cached per requesting user so filtered file names from one account are not served to another (GHSA-4fhx-8pf6-5gmr) reporter @Nazarami
- [Moderate] WebDAV PUT now requires Create permission when the target path does not yet exist, so Modify-only users cannot create new files (GHSA-8655-2ph3-q7q7) reporter @levanduy181
- [Low] Failed-login lockout and auth rate limits now use the rightmost `X-Forwarded-For` hop when proxy headers are trusted, so a client cannot spoof the client IP with a leftmost forwarded value (GHSA-wjp8-g49g-xrhx) reporter @LECOQQ
**Bug Fixes**:
- fix(auth): apply stored permission caps for customized API tokens with no global flags enabled; minimal tokens still inherit the owner's permissions
- Preview generation for WebP images (encode as JPEG thumbnail) ([#3259](https://github.com/gtsteffaniak/filebrowser/pull/3259), [#3254](https://github.com/gtsteffaniak/filebrowser/issues/3254))
- Public share pages show configured banner when API returns `bannerUrl` ([#3250](https://github.com/gtsteffaniak/filebrowser/pull/3250), [#3246](https://github.com/gtsteffaniak/filebrowser/issues/3246))
- Tar extraction creates hard-linked files instead of skipping `TypeLink` entries ([#3234](https://github.com/gtsteffaniak/filebrowser/pull/3234))
- Embedded JPEG previews for additional RAW/camera formats (ARW, RW2, RAW, RWL) ([#3243](https://github.com/gtsteffaniak/filebrowser/pull/3243))
- fix(preview): generate WebP image previews by encoding thumbnails as JPEG ([#3259](https://github.com/gtsteffaniak/filebrowser/pull/3259)) ([#3254](https://github.com/gtsteffaniak/filebrowser/issues/3254))
- fix(frontend): show configured share banner on public share pages when API returns `bannerUrl` ([#3250](https://github.com/gtsteffaniak/filebrowser/pull/3250)) ([#3246](https://github.com/gtsteffaniak/filebrowser/issues/3246))
- fix(archive): extract tar hard-linked files instead of skipping `TypeLink` entries ([#3234](https://github.com/gtsteffaniak/filebrowser/pull/3234))
- fix(preview): embedded JPEG previews for additional RAW/camera formats (RTF, RW2, RAW, RWL) ([#3243](https://github.com/gtsteffaniak/filebrowser/pull/3243))
- fix(frontend): keep source named `files` in `extractSourceFromPath` ([#3143](https://github.com/gtsteffaniak/filebrowser/issues/3143), [#3099](https://github.com/gtsteffaniak/filebrowser/pull/3099))
- fix(frontend): load the default source when browsing `/files/` with a single configured source ([#3178](https://github.com/gtsteffaniak/filebrowser/issues/3178)) (related: [#3144](https://github.com/gtsteffaniak/filebrowser/issues/3144))
- fix(frontend): restore upload prompt close, tab-reload, and in-app navigation guards while uploads are active (including paused uploads)
## v2.0.1-stable
**Security**:
- [High] New accounts named with ".." breaks out of scoped folder on creation (GHSA-c84q-q5g6-r47f) -- reporter @dylanzonix
- [Medium] Fixed session token collision issue when multiple users login simultaneously. (GHSA-c9cr-w724-gqj3) (#3135) Thanks @dl-pt reporters: @Ishtiaque-Ahmed-Risat @AlexWhiplash @tonghuaroot
## v2.0.0-stable
This version represents the most significant change to date. It **requires** both a database migration and config structural changes. See the [migration guide](https://filebrowserquantum.com/en/docs/getting-started/v2/migration/) for step-by-step upgrade instructions, [About v2.0.0](https://filebrowserquantum.com/en/docs/getting-started/v2/about/) for a full summary.
Also, consider enabling "analytics" in admin settings which will help me populate an anonymous public dashboard for everyone to see. Currently, theres 60 deployments details populated from beta, so after a percentage of you enable this in staging there should be plenty to make the dashboard useful and available. No private information is used, you can see exactly what data is sent in the UI.
**Breaking Changes**:
- Removed: `GET /api/raw` and `GET /public/api/raw` download routes — use `/api/resources/download` instead.
- Removed: `/share/…` URL redirect to `/public/share/…` — use `/public/share/…` directly.
- Removed: singular `source` search api param (use `sources`), bare `scope` paths without `sourceName:` prefix, and `glob` / `useGlob` aliases (use `useWildcard`).
- Removed `config.conditionals`, source-level `indexingIntervalMinutes` (indexing always uses adaptive scheduling), and deprecated rule fields `fileNames` / `folderNames` / top-level `hidden` — use `config.rules` with `fileName`, `folderName`, and `ignoreHidden` on rules. See [Exclusion rules](https://filebrowserquantum.com/en/docs/user-guides/general-configuration/exclusion-rules/).
- Removed: deprecated `userDefaults` config formats (nested and flat) — use the [config migration tool](https://filebrowserquantum.com/en/docs/getting-started/v2/config-migration/) to convert before upgrading.
- Changed: `PUT /api/users` moved to the more appropriate `PATCH` method and requires specifying `which` in the body. Blank or `all` values are rejected.
- Changed: http related config options in `server` config key moved to `http` config key. See [HTTP settings](https://filebrowserquantum.com/en/docs/configuration/http/).
- Changed (reverse proxy): `http.trustedHeaders` (v1.5.x list) removed — use `http.trustProxyHeaders: true` when behind nginx, Traefik, or Caddy. When enabled, FileBrowser honors `X-Forwarded-Host`, `X-Forwarded-Proto`, `X-Forwarded-For`, and `X-Real-IP` for client IP, cookies, OIDC callbacks, WebAuthn, share URLs, rate limiting, and activity logs. Default is `false` (direct connection values). The [config migration tool](https://filebrowserquantum.com/en/docs/getting-started/v2/config-migration/) converts v1 `trustedHeaders` lists to `trustProxyHeaders: true`. See [Reverse proxy](https://filebrowserquantum.com/en/docs/getting-started/reverse-proxy/) and [HTTP trustProxyHeaders](https://filebrowserquantum.com/en/docs/configuration/http/#trustproxyheaders).
- Changed: `FILEBROWSER_DATABASE` environment variable — use `FILEBROWSER_DATABASE_PATH` instead. See [Environment variables](https://filebrowserquantum.com/en/docs/reference/environment-variables/) and [Server settings](https://filebrowserquantum.com/en/docs/configuration/server/).
- Changed: Moved stream api to `/api/media/stream`. See [API reference](https://filebrowserquantum.com/en/docs/reference/api/).
- Changed: CLI user management — canonical commands are `user set <username> --password [value]` and `user promote <username>`; `set -u username,password` is deprecated. See [CLI reference](https://filebrowserquantum.com/en/docs/reference/cli/).
**Security**:
- [Critical] A forged JWT could authenticate as any known `belongsTo`. Auth signing keys are now persisted in the application database and JWT validation fails closed when no key is configured. (GHSA-8f9r-wg7w-pfw) (#2987) Thanks @d3do-23 and @whoamis3c.
- [High] Restricted custom API tokens can no longer be upgraded to a full-permission session via `POST /api/auth/renew` (GHSA-6gr6-5qpq-888p) -- thanks @tao0845.
- [High] TOTP re-enrollment no longer allows anonymous callers to replace an existing second factor using only the account password; requires an authenticated self or admin session (GHSA-qx86-4v5r-26g5) -- thanks @tao0845.
- [Medium] Public upload shares with `allowReplacements=false` now reject overwrites when clients send `override=true`. (GHSA-3846-gh75-gp3m) Thanks @d3do-23
- [Medium] OnlyOffice callbacks verify the shared `integrations.office.secret` JWT and require the document key to match the cached editor session; document downloads re-validate redirect targets against the configured document-server host (SSRF); public shares with `enableOnlyOffice=false` reject `/office/*` requests server-side.
- [Low] Public share lyrics and subtitle routes honor the share's file-viewer setting, download disable flag, and download limits (GHSA-p7x3-p5jj-9xfh) -- thanks Yves Soete of Blacksight LLC. @yssoe
- Fresh installs with default `admin`/`admin` generate a random initial password and log it once (#2977).
- OIDC login binds OAuth `state` to an HttpOnly cookie and rejects tampered callbacks; login/logout/session-expiry redirects reject open-redirect targets, and signup sends credentials in a JSON body instead of query parameters.
- Startup fails when the configured auth signing key differs from the persisted one; session/API token registrations record JWT expiry and expired mappings are pruned.
**New Features**:
- View grant mechanism to distinguish between UI viewing and download. See [Access control overview](https://filebrowserquantum.com/en/docs/access-control/access-control-overview/).
- granular per-source file permissions (view, download, modify, create, delete) with automatic migration from global permissions
- per-source defaults configurable in `settings > access management`
- `view` permission is automatically set to true unless explicitly set to false. See [Access control overview](https://filebrowserquantum.com/en/docs/access-control/access-control-overview/).
- can be enforced for all users. See [Access control overview](https://filebrowserquantum.com/en/docs/access-control/access-control-overview/).
- New activity logs for user activity.
- charts and historical data
- export to csv reports
- Media player improvements:
- Refreshed playback queue UI: Supports thumbnails, stored into session storage, and has a "clear queue" button (#2575) (#2600).
- Loop now has 3 states (off/single/all) and neither of them will clear the existing queue (#2600).
- New "Audio visualizer" for audio files (desktop-only), you can configure some basic things to your taste (#2575) (#2620).
- The current state of the audio panel now is stored into local storage.
- More gestures: Swipe up to enter/exit fullscreen, long-press to change playback speed, single tap to pause (#2575).
- Videos now will resume fullscreen and PiP when navigating (queue auto-navigation, swipes gestures or next/previous) (#2649).
- Added `F4` shortcut to refresh the current directory and metadata (#2600).
- opt-in feature to send deployment analytics to filebrowser quantum developer servers
- anonymized with a viewer so users can see what info would be sent.
- if opt-in, every month a snapshot of your deployment config would be sent to developer servers
- this will help me know what features are being used and what versions everyone is on over time. I will also provide a public dashboard with this information in the future.
- WebDAV now supports set modification time via the `X-OC-Mtime` header for clients that support it (#2626). See [WebDAV docs](https://filebrowserquantum.com/en/docs/features/webdav/).
- Copy operations now preserve their original modification times (#2642) (#2647):
- WebUI preserves both, files and directories.
- WebDAV `COPY` preserves modification times only for files, is limitation we have with webdav.
- User default enhancements
- Config `userDefaults` seeds SQLite on first run; only fields explicitly set in config stay locked in **Settings → User defaults** (other defaults remain editable)
- Added administrator controls for universal user defaults and enforced preferences in `settings > user management > user defaults`.
- Added configurable default file permissions per source in `settings > access management`.
- Added a User Defaults editor for account, permission, and profile preferences in the edit/create user prompt. See [User management](https://filebrowserquantum.com/en/docs/configuration/users/).
- Database env var rename: `FILEBROWSER_DATABASE` is removed (startup fails if set). Use `FILEBROWSER_DATABASE_PATH` (default `filebrowser.sqlite`) or `server.database.path` in config. See [Environment variables](https://filebrowserquantum.com/en/docs/reference/environment-variables/) and [Server settings](https://filebrowserquantum.com/en/docs/configuration/server/).
- CLI: `user set` with `--password` (inline value, interactive prompt on TTY, or piped stdin); `user promote` for admin grant without password reset. See [CLI reference](https://filebrowserquantum.com/en/docs/reference/cli/).
- Require password change at next login for password-based users: new user setting `requirePasswordChange` (user defaults + per-user admin toggle). Bootstrap admins with a generated initial password get this automatically ([#2977](https://github.com/gtsteffaniak/filebrowser/issues/2977)). Generated bootstrap passwords use a speakable `word-xxxxx-xx` form.
- PWA improvements for installed mobile apps: dedicated maskable icons (192/512), manifest and splash colors that follow the instance default theme, runtime `theme-color` sync on dark-mode toggle, and edge-to-edge safe-area layout for notched devices (#2625) (#2869) -- thanks @APatenaude
- Users can set default view mode and thumbnail size from Profile settings (Listing options). Admins can set the same defaults for existing users and edit all profile preference defaults from the user management panel ([#2884](https://github.com/gtsteffaniak/filebrowser/issues/2884)).
- Added "Upload only what's missing" to the upload conflict prompt (#2985) (#2553)
- Added `init` CLI command, which creates a minimal commented config.yaml instead of a full config (#2957)
- Config YAML expands `$VAR` and `${VAR}` so values such as `userPassword: "${FILEBROWSER_LDAP_USER_PASSWORD}"` work (#3042).
- Sidebar source links can switch between aggregated usage (default) and a root-filesystem-only view via a new "Limit disk usage to source filesystem" toggle.
**Notes**:
- v2.x.x uses a new write-through backend state management. Changes go through a fast memory layer and also write changes to database to stay in sync. See [About v2.0.0](https://filebrowserquantum.com/en/docs/getting-started/v2/about/).
- CLI server start (`./filebrowser`), `setup`, `version`, and `set rule` syntax unchanged; see [CLI docs](https://filebrowserquantum.com/en/docs/reference/cli/)
- new dropdown and input styles
- swipe gestures to dismiss notifications (#2672)
- user updates are more granular, don't include entire user payload.
- `user.id` has been moved to a backend property and all frontend apis now query users by username. Swagger has been updated. See [API reference](https://filebrowserquantum.com/en/docs/reference/api/).
- removed legacy and deprecated properties from API responses and generated config output
- `/api/media/stream` is audio/video only (range-based chunking). Non-media inline viewing uses `GET /api/resources/view`. Both endpoints use the same `viewToken` from file metadata. See [API reference](https://filebrowserquantum.com/en/docs/reference/api/).
- removed exiftool as an optional helper, always built with the supported libraries (requires 64 bit os)
- If migration issues arise, see [Migration troubleshooting](https://filebrowserquantum.com/en/docs/getting-started/migration/troubleshooting/).
- default browser media player option removed, always uses themed plyr
- [docker] upgraded ffmpeg from 8.1.2 to 9.0
- Sidebar navigation tree rows are real hyperlinks: middle-click, Ctrl/Cmd+click, and Shift+click use the browser's default new-tab or new-window behavior.
- Pop-up preview has a 200ms debounce delay so it doesn't flash when moving the cursor across files quickly.
- Improved UI responsiveness for larger directories and Firefox, with marginal memory improvement (#1773) (#2879)
- Improvements to document thumbnail generation performance.
- Changed behavior for typing to select files in listing view; added more actions in advanced search (#2776).
- Session renew is handled by client keep-alive; per-request `X-Renew-Token` header handling removed.
- `defaultEnabled` now means the source is always added to users on startup and login.
- Webdav always shows hidden files, ignores the user preference. (#3004)
- Share download links no longer embed a token; they link to the UI, which prompts for the password before download. For direct downloads use the documented `/api/share/direct` API. (#2888)
- Sidebar links follow source changes: renaming a source updates links, disabling/deleting a user source removes them (#2878) (#2942), and adding a source via scopes auto-adds a link.
- `/api/resources/download` and `/public/api/resources/download` return HTTP 404 for missing files/directories instead of 500 (#2981); `GET /api/resources` returns 400 when `path` is missing or empty (#2801).
- Added risc-v to official releases.
- A CLI password reset returns the user to a password-method user.
**Bugfixes**:
- Long uploads/downloads no longer lose the session mid-transfer; session keep-alive renews before expiry and auto-logout is disabled during active transfers (#2638).
- GroupMap changes are written through to SQL so JWT/OIDC/LDAP group memberships survive restart (#2742).
- OIDC: `groupsClaim` is always requested and falls back to UserInfo; the verified ID-token identifier is preserved on fallback; sessions respect `tokenExpirationHours` (#3006).
- LDAP `userGroups` matching accepts CN-only values against full `memberOf` DNs and is case-insensitive (#3044).
- Sidebar folder links with custom names/icons/styles persist across restarts, and deleted links stay deleted (#2809) (#2935).
- Fixed PDF thumbnail process aborts (#2763), PDF preview blocking uploads (#2752), and 401 on the PDF download button (#2978).
- Fixed ffmpeg unresponsive lock issue (#2996).
- Fixed multiple embedded subtitles with the same language (#2756).
- Fixed Fuji `.raf` thumbnail preview; unsupported image preview formats return HTTP 415 instead of 500.
- Members without download permission could not open text-based files with OnlyOffice enabled (#2777).
- Fixed iOS 26 / WebKit multi-chunk upload stall by isolating chunk connections (#2734).
- Mobile/UI fixes: upload options cut off (#2685), uploaded image cut off (#2765), next/previous buttons hiding on photos (#2767), missing gallery download button (#2767), double-tap to zoom, html viewer height, tooltips on mobile, assorted styling inconsistencies (#2908).
- Public share folder and multi-file ZIP downloads were empty for anonymous visitors on sources with deny-by-default/path rules (#2631) (#2365).
- Preserve Ctrl-click selection with stale keyboard state (#2958) (#2923); avoid false stalls in parallel transfers (#2950) (#2948) thanks @gudcks0305; hide Replace on conflict prompts when the user lacks modify permission (#2837).
- Disk usage: fixed overstatement on virtiofs/Docker Desktop (#2894), inflated usage across ZFS datasets/btrfs subvolumes (#3025) (#2997), capped usage bars at 100% and summed nested mounts on Linux (#2761) (#2238).
- Support non-ASCII share passwords (#2933); fall back to buffered copies when FUSE rejects fast paths (#2938) (#2924); tilde (`~`) source paths expand properly.
- Fixed slow/broken file listing when `http.baseURL` is a subpath.
- SQLite: removed shared cache and set `busy_timeout` on every pooled connection; busy errors no longer reported as success or empty cache results.
## v2.0.10
**Security**:
- [High] Restricted custom API tokens (`minimal=false`) can no longer be upgraded to a full-permission session via `POST /api/auth/renew`; renew accepts only web session tokens registered in `hashed_tokens` (GHSA-6gr6-5qpq-888p) -- thanks @tao0845.
- [High] TOTP re-enrollment via `POST /api/auth/otp/generate` and `POST /api/auth/otp/verify` no longer allows anonymous callers to replace an existing second factor using only the account password; reset or replace requires an authenticated self or admin session (first-time enrollment without MFA unchanged) (GHSA-qx86-4v5r-26g5) -- thanks @tao0845.
- [Low] Public share lyrics and subtitle media routes now honor the share's file-viewer setting, download disable flag, and download limits, matching the public download route (GHSA-p7x3-p5jj-9xfh) -- thanks Yves Soete of Blacksight LLC. @yssoe
**New Features**:
- Require password change at next login for password-based users: new user setting `requirePasswordChange` (user defaults + per-user admin toggle), login blocked until the user sets a new password; bootstrap admins with a generated initial password get this automatically ([#2977](https://github.com/gtsteffaniak/filebrowser/issues/2977)). Generated bootstrap passwords use a speakable `word-xxxxx-xx` form (random word from a fixed list plus a 5-character and 2-character code) instead of a long hex string, for easier handoff before the forced change.
- Config YAML expands `$VAR` and `${VAR}` so values such as `userPassword: "${FILEBROWSER_LDAP_USER_PASSWORD}"` work as documented (#3042).
**Notes**:
- Sidebar navigation tree rows are real hyperlinks: middle-click, Ctrl/Cmd+click, and Shift+click use the browser’s default new-tab or new-window behavior.
- Sidebar source links can now switch between aggregated usage (default) and a root-filesystem-only view via a new "Limit disk usage to source filesystem" toggle.
- [docker] upgraded ffmpeg from 9.0 to 9.0.2
- CLI setup command no longer produces full config, instead a minimal config.yaml with comments.
**Bugfixes**:
- Fixed slow or broken file listing when `http.baseURL` is a subpath (for example `/files/`): the default source redirect navigated to `/files/{source}` on top of the app base URL, producing `/files/files/{source}` and resolving the wrong storage source until the route recovered.
- Anonymous visitors on public shares could not play inline video or audio: `GET /public/api/media/stream` returned 403 because view grants were validated before share context was fully hydrated; playback now works when download and the file viewer are allowed ([#3041](https://github.com/gtsteffaniak/filebrowser/issues/3041)).
- Fixed inflated disk usage for sources spanning multiple ZFS datasets (or btrfs subvolumes): shared-pool filesystems are now grouped by pool and counted once, instead of multiplying capacity by the number of mounted datasets (#3025) (#2997) (#2761).
- LDAP `userGroups` matching now accepts CN-only config values against full `memberOf` DNs and compares case-insensitively, instead of failing the shared auth helper with strict string equality (#3044).
- OIDC session expires despite tokenExpirationHours (#3006).
- Media playback becomes stuck after opening a failing media file since v2.0.8-beta (#3031)
## v2.0.9
**Security**:
+1 -1
View File
@@ -1,4 +1,4 @@
FROM gtstef/ffmpeg:9.0-decode AS ffmpeg
FROM ghcr.io/gtsteffaniak/ffmpeg:9.0.2-decode AS ffmpeg
FROM golang:alpine AS base
ARG VERSION
ARG REVISION
@@ -1,6 +1,9 @@
http:
port: 8080
baseURL: "/files/"
frontend:
styling:
disableEventThemes: true
auth:
adminPassword: "playwright-password"
+38 -20
View File
@@ -8,7 +8,6 @@ import (
"strconv"
"strings"
"github.com/goccy/go-yaml"
"github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
@@ -225,19 +224,11 @@ func createConfig(configpath string, noInput bool) error {
fmt.Printf("Error: '%s' is not a valid port. Please enter a number between 1 and 65535.\n", portStr)
}
for {
levels := askQuestion(reader, "What should the log levels be?", "info|warning|error")
checkLevels := SplitByMultiple(levels)
invalidOptions := []string{}
for _, level := range checkLevels {
if !(level == "info" || level == "warning" || level == "error" || level == "debug") {
invalidOptions = append(invalidOptions, level)
}
}
if len(invalidOptions) == 0 {
break
}
fmt.Printf("Error: invalid options given '%s'. valid options: 'info|warning|error|debug'.\n", invalidOptions)
config.Server.Logging = []settings.LogConfig{
{
Output: "stdout",
Levels: "info|warning|error",
},
}
for {
@@ -250,9 +241,20 @@ func createConfig(configpath string, noInput bool) error {
}
fmt.Printf("Error: '%s' is not a valid path. Please enter a path to a file ending in .sqlite", config.Server.DatabaseV2.Path)
}
config.Frontend.Name = askQuestion(reader, "What should the application brand name be?", "FileBrowser Quantum")
config.Auth.AdminUsername = askQuestion(reader, "What should the default admin username be?", "admin")
config.Auth.AdminPassword = askQuestion(reader, "What should the default admin password be?", "admin")
const defaultFrontendName = "FileBrowser Quantum"
brandName := askQuestion(reader, "What should the application brand name be?", defaultFrontendName)
if brandName != defaultFrontendName {
config.Frontend.Name = brandName
}
adminUsername := askQuestion(reader, "What should the default admin username be?", "admin")
if adminUsername != "admin" {
config.Auth.AdminUsername = adminUsername
}
const adminPasswordGenerateDefault = "generate on startup"
adminPassword := askQuestion(reader, "What should the default admin password be?", adminPasswordGenerateDefault)
if adminPassword != "" && !strings.EqualFold(adminPassword, adminPasswordGenerateDefault) {
config.Auth.AdminPassword = adminPassword
}
modifyDefault := askYesNoQuestion(reader, "Should a new user be able to modify content by default?", "no")
config.Server.Sources[0].Config.DefaultPermissions = settings.NormalizeSourceFilePermissions(users.SourceFilePermissions{
@@ -266,12 +268,12 @@ func createConfig(configpath string, noInput bool) error {
fmt.Println("--- Configuration Complete ---")
yamlData, err := yaml.Marshal(&config)
yamlData, err := generateSetupConfigYAML(&config)
if err != nil {
return fmt.Errorf("marshaling config: %w", err)
return fmt.Errorf("generating config YAML: %w", err)
}
err = os.WriteFile(configpath, yamlData, 0600)
err = os.WriteFile(configpath, []byte(yamlData), 0600)
if err != nil {
return fmt.Errorf("writing config file: %w", err)
}
@@ -291,6 +293,22 @@ func createConfig(configpath string, noInput bool) error {
return nil
}
func generateSetupConfigYAML(config *settings.Settings) (string, error) {
embeddedPaths := []string{
"frontend/public/config.generated.yaml",
"../frontend/public/config.generated.yaml",
"internal/web/dist/config.generated.yaml",
"../internal/web/dist/config.generated.yaml",
}
for _, path := range embeddedPaths {
embeddedYaml, err := os.ReadFile(path)
if err == nil && len(embeddedYaml) > 0 {
return settings.GenerateConfigYamlWithEmbedded(config, true, false, false, string(embeddedYaml), nil)
}
}
return settings.GenerateConfigYaml(config, true, false, false, nil)
}
func generateYaml() {
generateConfig := os.Getenv("FILEBROWSER_GENERATE_CONFIG") == "true"
if generateConfig || settings.Env.IsDevMode {
+24
View File
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/alecthomas/kong"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -191,3 +192,26 @@ func TestSetupNoInputRejected(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "interactive input")
}
func TestGenerateSetupConfigYAML_MinimalWithComments(t *testing.T) {
t.Chdir("..")
cfg := settings.SetDefaults(false)
cfg.Server.Sources = []*settings.Source{{Path: "/var/lib/files"}}
cfg.Server.DatabaseV2.Path = "./filebrowser.sqlite"
cfg.Http.Port = 8080
cfg.Server.Logging = []settings.LogConfig{
{Output: "stdout", Levels: "info|warning|error"},
}
out, err := generateSetupConfigYAML(&cfg)
require.NoError(t, err)
assert.Contains(t, out, "#")
assert.Contains(t, out, "/var/lib/files")
assert.Contains(t, out, "8080")
assert.NotContains(t, out, "FileBrowser Quantum")
assert.NotContains(t, out, "darkMode")
assert.NotContains(t, out, "minSearchLength:")
assert.NotContains(t, out, "frontend:")
assert.NotContains(t, out, "rules:")
}
@@ -1,6 +1,9 @@
http:
port: 8080
baseURL: "/"
frontend:
styling:
disableEventThemes: true
server:
logging:
- levels: "info|warning|error"
+1 -1
View File
@@ -53,7 +53,7 @@ func TestUserUpdateChangesFiltersUnchangedFields(t *testing.T) {
which := []string{
"preview", "stickySidebar", "darkMode", "locale", "singleClick", "sorting",
"showHidden", "dateFormat", "themeColor", "quickDownload", "fileLoading",
"sidebarLinks", "deleteAfterArchive", "preferEditorForMarkdown", "showFirstLogin",
"sidebarLinks", "deleteAfterArchive", "preferEditorForMarkdown", "showFirstLogin", "requirePasswordChange",
}
changes := UserUpdateChanges(before, &after, which, false)
@@ -0,0 +1,30 @@
package fileutils
// PartitionUsage is a capacity view of a source path: total and used bytes.
type PartitionUsage struct {
Total uint64 `json:"total"`
Used uint64 `json:"used"`
}
// singlePathPartitionUsage statfs's a single path: the filesystem covering it.
func singlePathPartitionUsage(path string) (PartitionUsage, error) {
total, err := GetPartitionSize(path)
if err != nil {
return PartitionUsage{}, err
}
used, err := GetPartitionUsed(path)
if err != nil {
return PartitionUsage{}, err
}
return PartitionUsage{Total: total, Used: used}, nil
}
// GetAggregatedPartitionUsage returns total and used bytes summed across distinct
// capacity groups mounted at or under root. See GetPartitionUsageVariants.
func GetAggregatedPartitionUsage(root string) (total, used uint64, err error) {
aggregate, _, err := GetPartitionUsageVariants(root)
if err != nil {
return 0, 0, err
}
return aggregate.Total, aggregate.Used, nil
}
@@ -0,0 +1,188 @@
//go:build freebsd
package fileutils
import (
"fmt"
"path/filepath"
"strings"
"golang.org/x/sys/unix"
)
// bsdMount is one Getfsstat record reduced to what capacity aggregation
// needs: fstype, source, mountpoint, usage, and the mount's own fsid.
type bsdMount struct {
fstype string
source string
mountpoint string
usage rawUsage
fsid unix.Fsid
}
// resolvedMount is what a path lookup reports for a mountpoint: the
// mountpoint of the filesystem that actually owns the path and that
// filesystem's fsid.
type resolvedMount struct {
mountpoint string
fsid unix.Fsid
ok bool
}
// statfsMountpoint resolves which filesystem a mountpoint path lands on.
func statfsMountpoint(mp string) resolvedMount {
var st unix.Statfs_t
if err := unix.Statfs(mp, &st); err != nil {
return resolvedMount{}
}
return resolvedMount{
mountpoint: filepath.Clean(unix.ByteSliceToString(st.Mntonname[:])),
fsid: st.Fsid,
ok: true,
}
}
// GetPartitionUsageVariants returns the aggregate and root-only capacity views
// of root. FreeBSD has no mountinfo; Getfsstat already carries per-mount statfs
// data, so grouping happens on the result set directly (ZFS datasets grouped by
// pool name, everything else by fsid).
func GetPartitionUsageVariants(root string) (aggregate, rootOnly PartitionUsage, err error) {
if root == "" {
return aggregate, rootOnly, fmt.Errorf("empty path")
}
root = filepath.Clean(root)
rootOnly, rootErr := singlePathPartitionUsage(root)
count, statErr := unix.Getfsstat(nil, unix.MNT_WAIT)
if statErr != nil || count <= 0 {
if rootErr != nil {
return aggregate, rootOnly, rootErr
}
return rootOnly, rootOnly, nil
}
stats := make([]unix.Statfs_t, count)
if _, statErr = unix.Getfsstat(stats, unix.MNT_WAIT); statErr != nil {
if rootErr != nil {
return aggregate, rootOnly, rootErr
}
return rootOnly, rootOnly, nil
}
var mounts []bsdMount
for i := range stats {
s := &stats[i]
avail := uint64(0)
if s.Bavail > 0 {
avail = uint64(s.Bavail)
}
mounts = append(mounts, bsdMount{
fstype: unix.ByteSliceToString(s.Fstypename[:]),
source: unix.ByteSliceToString(s.Mntfromname[:]),
mountpoint: filepath.Clean(unix.ByteSliceToString(s.Mntonname[:])),
usage: rawUsage{
total: s.Blocks * s.Bsize,
avail: avail * s.Bsize,
},
fsid: s.Fsid,
})
}
covering, nested := selectCapacityMounts(mounts, root, statfsMountpoint)
key := func(m bsdMount) string {
if isZFSType(m.fstype) {
return "zfs:" + zfsPoolName(m.source)
}
if m.fsid.Val[0] == 0 && m.fsid.Val[1] == 0 {
// fsid-less filesystems (e.g. some tmpfs mounts): keep per mountpoint.
return "mp:" + m.mountpoint
}
return fmt.Sprintf("fsid:%x:%x", m.fsid.Val[0], m.fsid.Val[1])
}
groups := make(map[string][]rawUsage)
fstypes := make(map[string]string)
add := func(m bsdMount) {
k := key(m)
fstypes[k] = m.fstype
groups[k] = append(groups[k], m.usage)
}
if covering != nil {
add(*covering)
}
for _, m := range nested {
add(m)
}
if len(groups) == 0 {
if rootErr != nil {
return aggregate, rootOnly, rootErr
}
return rootOnly, rootOnly, nil
}
for k, stats := range groups {
u := combineGroupUsage(stats)
if !isZFSType(fstypes[k]) && len(stats) > 1 {
// Non-shared-pool mounts dedupe to a single measurement.
u = combineGroupUsage(stats[:1])
}
aggregate.Total += u.Total
aggregate.Used += u.Used
}
return aggregate, rootOnly, rootErr
}
// selectCapacityMounts picks the mounts contributing capacity under root: the
// filesystem covering root plus mounts nested beneath it.
//
// Getfsstat retains records that path lookups no longer reach: mounts stacked
// under a later mount at the same mountpoint, and mounts below an overmounted
// ancestor (stacked records have no documented order, so position cannot
// identify the visible one). A record counts only when a lookup on its
// mountpoint still lands on it: the resolved mountpoint must equal the
// record's and, for filesystems carrying an fsid, the resolved fsid must match
// the record's (every stacked record resolves to the topmost fsid). fsid-less
// records keep the first match at a mountpoint; stacked fsid-less mounts are
// indistinguishable.
func selectCapacityMounts(mounts []bsdMount, root string, lookup func(string) resolvedMount) (*bsdMount, []bsdMount) {
var covering *bsdMount
var nested []bsdMount
claimed := make(map[string]bool)
resolved := make(map[string]resolvedMount)
for i := range mounts {
m := mounts[i]
covers := m.mountpoint == root || m.mountpoint == "/" || strings.HasPrefix(root, m.mountpoint+"/")
nests := strings.HasPrefix(m.mountpoint, root+"/")
if !covers && !nests {
continue
}
r, seen := resolved[m.mountpoint]
if !seen {
r = lookup(m.mountpoint)
resolved[m.mountpoint] = r
}
if !r.ok || r.mountpoint != m.mountpoint {
continue
}
if m.fsid.Val[0] != 0 || m.fsid.Val[1] != 0 {
if r.fsid != m.fsid {
continue
}
} else if claimed[m.mountpoint] {
continue
}
claimed[m.mountpoint] = true
if covers && (covering == nil || len(m.mountpoint) > len(covering.mountpoint)) {
c := m
covering = &c
}
if nests {
if isZFSType(m.fstype) && isZFSSnapshotMount(m.source, m.mountpoint) {
continue
}
nested = append(nested, m)
}
}
return covering, nested
}
@@ -0,0 +1,161 @@
//go:build freebsd
package fileutils
import (
"testing"
"golang.org/x/sys/unix"
)
func fsidVal(a, b int32) unix.Fsid {
return unix.Fsid{Val: [2]int32{a, b}}
}
func resolvedOK(mp string, fsid unix.Fsid) resolvedMount {
return resolvedMount{mountpoint: mp, fsid: fsid, ok: true}
}
// TestSelectCapacityMountsOvermountedAncestorHidesNested reproduces the
// reviewed layout: /srv/child was mounted first, then /srv was overmounted.
// Getfsstat still reports the unique /srv/child record, but a lookup of that
// path lands inside the covering filesystem, so its usage must be excluded.
func TestSelectCapacityMountsOvermountedAncestorHidesNested(t *testing.T) {
rootFs, childFs, coverFs := fsidVal(1, 1), fsidVal(2, 2), fsidVal(3, 3)
mounts := []bsdMount{
{fstype: "ufs", source: "/dev/da0p2", mountpoint: "/", fsid: rootFs, usage: rawUsage{total: 100, avail: 50}},
{fstype: "ufs", source: "/dev/da1p1", mountpoint: "/srv/child", fsid: childFs, usage: rawUsage{total: 200, avail: 100}},
{fstype: "ufs", source: "/dev/da2p1", mountpoint: "/srv", fsid: coverFs, usage: rawUsage{total: 300, avail: 150}},
}
lookup := func(mp string) resolvedMount {
switch mp {
case "/":
return resolvedOK("/", rootFs)
case "/srv":
return resolvedOK("/srv", coverFs)
case "/srv/child":
// Hidden: resolves to the covering filesystem at /srv.
return resolvedOK("/srv", coverFs)
}
return resolvedMount{}
}
covering, nested := selectCapacityMounts(mounts, "/srv", lookup)
if covering == nil || covering.mountpoint != "/srv" {
t.Fatalf("covering = %+v, want mountpoint /srv", covering)
}
if len(nested) != 0 {
t.Fatalf("nested = %+v, want hidden /srv/child excluded", nested)
}
}
// TestSelectCapacityMountsUnreachableNestedSkipped covers the same hidden
// layout when the covered path no longer exists in the new filesystem: the
// lookup fails outright and the stale record is dropped.
func TestSelectCapacityMountsUnreachableNestedSkipped(t *testing.T) {
rootFs, coverFs := fsidVal(1, 1), fsidVal(3, 3)
mounts := []bsdMount{
{fstype: "ufs", mountpoint: "/", fsid: rootFs},
{fstype: "ufs", source: "/dev/da2p1", mountpoint: "/srv", fsid: coverFs},
{fstype: "ufs", source: "/dev/da1p1", mountpoint: "/srv/gone", fsid: fsidVal(2, 2), usage: rawUsage{total: 200, avail: 100}},
}
lookup := func(mp string) resolvedMount {
switch mp {
case "/":
return resolvedOK("/", rootFs)
case "/srv":
return resolvedOK("/srv", coverFs)
}
return resolvedMount{} // ENOENT under the overmount
}
_, nested := selectCapacityMounts(mounts, "/srv", lookup)
if len(nested) != 0 {
t.Fatalf("nested = %+v, want unreachable /srv/gone excluded", nested)
}
}
// TestSelectCapacityMountsStackedTopmostOnly checks that of several records
// at one mountpoint only the one a lookup resolves to is counted.
func TestSelectCapacityMountsStackedTopmostOnly(t *testing.T) {
rootFs, lowerFs, upperFs := fsidVal(1, 1), fsidVal(4, 4), fsidVal(5, 5)
mounts := []bsdMount{
{fstype: "ufs", mountpoint: "/", fsid: rootFs},
{fstype: "ufs", source: "/dev/da1p1", mountpoint: "/srv/data", fsid: lowerFs, usage: rawUsage{total: 200, avail: 100}},
{fstype: "tmpfs", source: "tmpfs", mountpoint: "/srv/data", fsid: upperFs, usage: rawUsage{total: 60, avail: 30}},
}
lookup := func(mp string) resolvedMount {
switch mp {
case "/":
return resolvedOK("/", rootFs)
case "/srv/data":
return resolvedOK("/srv/data", upperFs)
}
return resolvedMount{}
}
_, nested := selectCapacityMounts(mounts, "/srv", lookup)
if len(nested) != 1 || nested[0].fsid != upperFs {
t.Fatalf("nested = %+v, want only the topmost /srv/data record", nested)
}
}
// TestSelectCapacityMountsHiddenCoveringAncestor: when the deepest ancestor
// mount of root is itself hidden by an overmount, covering must fall back to
// the deepest visible ancestor.
func TestSelectCapacityMountsHiddenCoveringAncestor(t *testing.T) {
rootFs, overFs, staleFs := fsidVal(1, 1), fsidVal(8, 8), fsidVal(9, 9)
mounts := []bsdMount{
{fstype: "ufs", mountpoint: "/", fsid: rootFs},
{fstype: "ufs", source: "/dev/da2p1", mountpoint: "/x", fsid: overFs},
{fstype: "ufs", source: "/dev/da1p1", mountpoint: "/x/y", fsid: staleFs, usage: rawUsage{total: 200, avail: 100}},
}
// /x was mounted over the parent chain of /x/y: lookups of /x/y resolve
// inside the /x filesystem.
lookup := func(mp string) resolvedMount {
switch mp {
case "/":
return resolvedOK("/", rootFs)
case "/x":
return resolvedOK("/x", overFs)
case "/x/y":
return resolvedOK("/x", overFs)
}
return resolvedMount{}
}
covering, nested := selectCapacityMounts(mounts, "/x/y/z", lookup)
if covering == nil || covering.mountpoint != "/x" {
t.Fatalf("covering = %+v, want deepest visible ancestor /x", covering)
}
if len(nested) != 0 {
t.Fatalf("nested = %+v, want none", nested)
}
}
// TestSelectCapacityMountsNestedVisibleKept is the baseline: a nested mount
// that still resolves to itself contributes its usage.
func TestSelectCapacityMountsNestedVisibleKept(t *testing.T) {
rootFs, zfsFs := fsidVal(1, 1), fsidVal(7, 7)
mounts := []bsdMount{
{fstype: "ufs", mountpoint: "/", fsid: rootFs},
{fstype: "zfs", source: "tank/data", mountpoint: "/srv/data", fsid: zfsFs, usage: rawUsage{total: 400, avail: 200}},
}
lookup := func(mp string) resolvedMount {
switch mp {
case "/":
return resolvedOK("/", rootFs)
case "/srv/data":
return resolvedOK("/srv/data", zfsFs)
}
return resolvedMount{}
}
covering, nested := selectCapacityMounts(mounts, "/srv", lookup)
if covering == nil || covering.mountpoint != "/" {
t.Fatalf("covering = %+v, want /", covering)
}
if len(nested) != 1 || nested[0].mountpoint != "/srv/data" {
t.Fatalf("nested = %+v, want [/srv/data]", nested)
}
}
@@ -7,94 +7,64 @@ import (
"os"
"path/filepath"
"syscall"
"golang.org/x/sys/unix"
)
// GetAggregatedPartitionUsage returns total and used bytes summed across distinct
// filesystems mounted at or under root (deduped by major:minor from mountinfo).
// Falls back to a single-path probe when mountinfo cannot be read.
func GetAggregatedPartitionUsage(root string) (total, used uint64, err error) {
// GetPartitionUsageVariants returns two capacity views of root:
// - aggregate: total/used summed across distinct capacity groups mounted at or
// under root, deduped so shared-pool filesystems (ZFS datasets, btrfs
// subvolumes) are counted once per pool.
// - rootOnly: a single statfs of root, ignoring nested mounts.
//
// Falls back to the single-path probe for both when mountinfo cannot be read.
func GetPartitionUsageVariants(root string) (aggregate, rootOnly PartitionUsage, err error) {
if root == "" {
return 0, 0, fmt.Errorf("empty path")
return aggregate, rootOnly, fmt.Errorf("empty path")
}
root = filepath.Clean(root)
paths, parseErr := distinctMountPathsUnder(root)
if parseErr != nil || len(paths) == 0 {
return singlePathPartitionUsage(root)
rootOnly, rootErr := singlePathPartitionUsage(root)
groups, parseErr := mountGroupsUnder(root)
if parseErr != nil || len(groups) == 0 {
if rootErr != nil {
return aggregate, rootOnly, rootErr
}
return rootOnly, rootOnly, nil
}
var firstErr error
for _, path := range paths {
t, u, stErr := partitionUsageAt(path)
if stErr != nil {
if firstErr == nil {
firstErr = stErr
for _, group := range groups {
stats := make([]rawUsage, 0, len(group.paths))
for _, p := range group.paths {
stat, stErr := partitionStatfs(p)
if stErr != nil {
if firstErr == nil {
firstErr = stErr
}
continue
}
continue
stats = append(stats, stat)
}
total += t
used += u
u := combineGroupUsage(stats)
aggregate.Total += u.Total
aggregate.Used += u.Used
}
if total == 0 && used == 0 {
if aggregate.Total == 0 && aggregate.Used == 0 {
if firstErr != nil {
return 0, 0, firstErr
return aggregate, rootOnly, firstErr
}
return singlePathPartitionUsage(root)
aggregate = rootOnly
}
return total, used, nil
return aggregate, rootOnly, rootErr
}
func singlePathPartitionUsage(root string) (total, used uint64, err error) {
total, err = GetPartitionSize(root)
if err != nil {
return 0, 0, err
}
used, err = GetPartitionUsed(root)
if err != nil {
return 0, 0, err
}
return total, used, nil
}
func distinctMountPathsUnder(root string) ([]string, error) {
func mountGroupsUnder(root string) ([]mountGroup, error) {
data, err := readMountinfo()
if err != nil {
return nil, err
}
paths, err := distinctMountPathsFromMountinfo(data, root)
if err != nil {
return nil, err
}
// If mountinfo had no covering mount for root, ensure root is probed.
if len(paths) == 0 {
return []string{root}, nil
}
hasRoot := false
for _, p := range paths {
if p == root {
hasRoot = true
break
}
}
if !hasRoot {
if dev, stErr := deviceIDFromPath(root); stErr == nil {
// Avoid duplicating a device already selected under another path.
already := false
for _, p := range paths {
if d, e := deviceIDFromPath(p); e == nil && d == dev {
already = true
break
}
}
if !already {
paths = append(paths, root)
}
}
}
return paths, nil
return mountGroupsFromMountinfo(data, root)
}
func readMountinfo() (string, error) {
@@ -107,24 +77,14 @@ func readMountinfo() (string, error) {
return "", fmt.Errorf("mountinfo not available")
}
func deviceIDFromPath(path string) (string, error) {
var st unix.Stat_t
if err := unix.Stat(path, &st); err != nil {
return "", err
}
return fmt.Sprintf("%d:%d", unix.Major(uint64(st.Dev)), unix.Minor(uint64(st.Dev))), nil
}
func partitionUsageAt(path string) (total, used uint64, err error) {
func partitionStatfs(path string) (rawUsage, error) {
var stat syscall.Statfs_t
if err := syscall.Statfs(path, &stat); err != nil {
return 0, 0, err
return rawUsage{}, err
}
bsize := blockSize(&stat)
total = uint64(stat.Blocks) * bsize
free := uint64(stat.Bavail) * bsize
if total >= free {
used = total - free
}
return total, used, nil
return rawUsage{
total: uint64(stat.Blocks) * bsize,
avail: uint64(stat.Bavail) * bsize,
}, nil
}
@@ -12,55 +12,111 @@ import (
type mountEntry struct {
deviceID string
mountpoint string
fstype string
source string
}
// distinctMountPathsFromMountinfo selects one path per distinct filesystem that
// contributes capacity for root: the FS that owns root, plus nested mounts under
// root. Deduped by major:minor from mountinfo.
func distinctMountPathsFromMountinfo(mountinfo string, root string) ([]string, error) {
// mountGroup is a set of mountpoints that share one capacity pool. Groups keyed
// by filesystem identity get one probe path; shared-pool filesystems (zfs) keep
// every dataset mountpoint so per-dataset used space can be summed.
type mountGroup struct {
key string
fstype string
paths []string
}
// capacityKey identifies mounts that share the same underlying capacity.
// - zfs: every dataset has its own device ID but draws from the pool; group by pool.
// - btrfs: subvolume mounts have distinct device IDs but report the whole
// filesystem; group by mount source.
// - everything else: device major:minor, as before.
func (e *mountEntry) capacityKey() string {
switch e.fstype {
case "zfs", "zfsfuse":
return "zfs:" + zfsPoolName(e.source)
case "btrfs":
return "btrfs:" + e.source
default:
return "dev:" + e.deviceID
}
}
// mountGroupsFromMountinfo selects the mounts contributing capacity for root:
// the filesystem that owns root, plus nested mounts under root, grouped by
// capacity key. ZFS snapshot mounts are excluded.
func mountGroupsFromMountinfo(mountinfo string, root string) ([]mountGroup, error) {
root = path.Clean(root)
entries, err := parseAllMounts(mountinfo)
if err != nil {
return nil, err
}
seen := make(map[string]string)
groupIndex := make(map[string]int)
var groups []mountGroup
addPath := func(e *mountEntry, p string) {
key := e.capacityKey()
i, ok := groupIndex[key]
if !ok {
i = len(groups)
groupIndex[key] = i
groups = append(groups, mountGroup{key: key, fstype: e.fstype})
}
// Only shared-pool filesystems (zfs) need every mountpoint; other groups
// report identical statfs per mount, so one probe path suffices.
if !isZFSType(groups[i].fstype) && len(groups[i].paths) > 0 {
return
}
for _, existing := range groups[i].paths {
if existing == p {
return
}
}
groups[i].paths = append(groups[i].paths, p)
}
var covering *mountEntry
for i := range entries {
e := &entries[i]
mp := e.mountpoint
if mp == root || strings.HasPrefix(root, mp+"/") || mp == "/" {
if covering == nil || len(mp) > len(covering.mountpoint) {
// >= keeps the later entry: stacked mounts at one mountpoint are
// shadowed by the topmost (last in mountinfo order).
if covering == nil || len(mp) >= len(covering.mountpoint) {
covering = e
}
}
}
if covering != nil {
seen[covering.deviceID] = root
// Probe root itself for the covering filesystem: root may be a plain
// directory inside a mount whose mountpoint is an ancestor.
addPath(covering, root)
} else {
// No mount covers root (e.g. hidden bind mount); probe it directly so
// it is not dropped when nested mounts under root do exist.
groups = append(groups, mountGroup{key: "self:" + root, paths: []string{root}})
}
for _, e := range entries {
// Stacked mounts: only the topmost (last in mountinfo order) is reachable.
lastAtMountpoint := make(map[string]int)
for i := range entries {
lastAtMountpoint[entries[i].mountpoint] = i
}
for i := range entries {
e := &entries[i]
mp := e.mountpoint
if mp != root && !strings.HasPrefix(mp, root+"/") {
continue
}
if _, ok := seen[e.deviceID]; ok {
if lastAtMountpoint[mp] != i {
continue
}
seen[e.deviceID] = mp
if isZFSType(e.fstype) && isZFSSnapshotMount(e.source, mp) {
continue
}
addPath(e, mp)
}
out := make([]string, 0, len(seen))
uniq := make(map[string]struct{}, len(seen))
for _, p := range seen {
if _, ok := uniq[p]; ok {
continue
}
uniq[p] = struct{}{}
out = append(out, p)
}
return out, nil
return groups, nil
}
func parseAllMounts(mountinfo string) ([]mountEntry, error) {
@@ -88,9 +144,16 @@ func parseMountinfoLine(line string) (mountEntry, bool) {
if len(fields) < 5 {
return mountEntry{}, false
}
// After " - ": "fstype source super-options".
post := strings.Fields(parts[1])
if len(post) < 2 {
return mountEntry{}, false
}
return mountEntry{
deviceID: fields[2],
mountpoint: unescapeFstab(fields[4]),
fstype: post[0],
source: unescapeFstab(post[1]),
}, true
}
@@ -7,6 +7,25 @@ import (
"testing"
)
// allGroupPaths flattens groups into a sorted list of probe paths.
func allGroupPaths(groups []mountGroup) []string {
var out []string
for _, g := range groups {
out = append(out, g.paths...)
}
sort.Strings(out)
return out
}
func findGroup(groups []mountGroup, prefix string) *mountGroup {
for i := range groups {
if len(groups[i].key) >= len(prefix) && groups[i].key[:len(prefix)] == prefix {
return &groups[i]
}
}
return nil
}
func TestDistinctMountPathsNestedDisk(t *testing.T) {
// /srv lives on rootfs 8:1; /srv/data is a separate 2TB disk 8:16.
mountinfo := "" +
@@ -14,11 +33,11 @@ func TestDistinctMountPathsNestedDisk(t *testing.T) {
"45 22 8:16 /data /srv/data rw - btrfs /dev/sdb1 rw\n" +
"50 22 0:47 / /proc rw - proc proc rw\n"
paths, err := distinctMountPathsFromMountinfo(mountinfo, "/srv")
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
sort.Strings(paths)
paths := allGroupPaths(groups)
want := []string{"/srv", "/srv/data"}
if len(paths) != len(want) {
t.Fatalf("paths = %v, want %v", paths, want)
@@ -37,11 +56,11 @@ func TestDistinctMountPathsOvermountSamePathDeduped(t *testing.T) {
"45 40 8:16 / /srv/data rw - btrfs /dev/sdb1 rw\n" +
"46 45 0:47 / /srv/data rw - tmpfs tmpfs rw\n"
paths, err := distinctMountPathsFromMountinfo(mountinfo, "/srv")
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
sort.Strings(paths)
paths := allGroupPaths(groups)
want := []string{"/srv", "/srv/data"}
if len(paths) != len(want) {
t.Fatalf("paths = %v, want %v (no duplicate probe paths)", paths, want)
@@ -56,15 +75,15 @@ func TestDistinctMountPathsOvermountSamePathDeduped(t *testing.T) {
func TestDistinctMountPathsBindSameDeviceNotDuplicated(t *testing.T) {
mountinfo := "" +
"22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" +
"45 22 8:16 / /srv/data rw - btrfs /dev/sdb1 rw\n" +
"46 22 8:16 / /srv/data/bind rw,bind - btrfs /dev/sdb1 rw\n"
"45 22 8:16 / /srv/data rw - ext4 /dev/sdb1 rw\n" +
"46 22 8:16 / /srv/data/bind rw,bind - ext4 /dev/sdb1 rw\n"
paths, err := distinctMountPathsFromMountinfo(mountinfo, "/srv")
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
if len(paths) != 2 {
t.Fatalf("expected 2 distinct devices, got %v", paths)
if len(groups) != 2 {
t.Fatalf("expected 2 distinct capacity groups, got %v", groups)
}
}
@@ -74,11 +93,11 @@ func TestDistinctMountPathsSourceIsOwnMount(t *testing.T) {
"40 22 8:2 / /srv rw - ext4 /dev/sda2 rw\n" +
"45 40 8:16 / /srv/data rw - btrfs /dev/sdb1 rw\n"
paths, err := distinctMountPathsFromMountinfo(mountinfo, "/srv")
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
sort.Strings(paths)
paths := allGroupPaths(groups)
want := []string{"/srv", "/srv/data"}
if len(paths) != 2 || paths[0] != want[0] || paths[1] != want[1] {
t.Fatalf("paths = %v, want %v", paths, want)
@@ -90,10 +109,11 @@ func TestDistinctMountPathsIgnoresUnrelated(t *testing.T) {
"22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" +
"30 22 8:3 / /home rw - ext4 /dev/sda3 rw\n"
paths, err := distinctMountPathsFromMountinfo(mountinfo, "/srv")
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
paths := allGroupPaths(groups)
if len(paths) != 1 || paths[0] != "/srv" {
t.Fatalf("paths = %v, want [/srv]", paths)
}
@@ -110,4 +130,124 @@ func TestParseMountinfoEscapedSpace(t *testing.T) {
if entry.deviceID != "98:0" {
t.Fatalf("deviceID = %q, want 98:0", entry.deviceID)
}
if entry.fstype != "ext3" {
t.Fatalf("fstype = %q, want ext3", entry.fstype)
}
if entry.source != "/dev/root" {
t.Fatalf("source = %q, want /dev/root", entry.source)
}
}
// TestMountGroupsZFSPoolDatasetsGrouped reproduces issue #3025: every ZFS
// dataset gets its own device ID, so major:minor dedup counts pool capacity
// once per dataset. They must share one capacity group.
func TestMountGroupsZFSPoolDatasetsGrouped(t *testing.T) {
mountinfo := "" +
"22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" +
"40 22 0:55 / /srv/pool rw - zfs pool rw\n" +
"41 40 0:56 / /srv/pool/ds01 rw - zfs pool/ds01 rw\n" +
"42 41 0:57 / /srv/pool/ds01/a rw - zfs pool/ds01/a rw\n" +
"43 40 0:58 / /srv/pool/ds02 rw - zfs pool/ds02 rw\n" +
"44 22 0:59 / /other/pool2 rw - zfs pool2 rw\n"
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv/pool")
if err != nil {
t.Fatal(err)
}
g := findGroup(groups, "zfs:pool")
if g == nil || g.key != "zfs:pool" {
t.Fatalf("expected one zfs:pool group, got %v", groups)
}
want := []string{"/srv/pool", "/srv/pool/ds01", "/srv/pool/ds01/a", "/srv/pool/ds02"}
got := append([]string{}, g.paths...)
sort.Strings(got)
sort.Strings(want)
if len(got) != len(want) {
t.Fatalf("zfs group paths = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("zfs group paths = %v, want %v", got, want)
}
}
// The unrelated second pool must not join the group.
if g2 := findGroup(groups, "zfs:pool2"); g2 != nil {
t.Fatalf("unrelated pool2 should not be included: %v", groups)
}
}
func TestMountGroupsZFSSnapshotsSkipped(t *testing.T) {
mountinfo := "" +
"22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" +
"40 22 0:55 / /srv/pool rw - zfs pool rw\n" +
"41 40 0:56 / /srv/pool/ds01 rw - zfs pool/ds01 rw\n" +
"42 41 0:57 / /srv/pool/ds01/.zfs/snapshot/snap1 rw - zfs pool/ds01@snap1 rw\n"
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv/pool")
if err != nil {
t.Fatal(err)
}
paths := allGroupPaths(groups)
for _, p := range paths {
if p == "/srv/pool/ds01/.zfs/snapshot/snap1" {
t.Fatalf("snapshot mount should be skipped: %v", paths)
}
}
if len(paths) != 2 {
t.Fatalf("paths = %v, want 2 live datasets", paths)
}
}
func TestMountGroupsBtrfsSubvolumesDeduped(t *testing.T) {
// Each btrfs subvolume mount has a distinct anonymous device but reports
// whole-filesystem statfs; they must collapse into one group.
mountinfo := "" +
"22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" +
"40 22 0:33 /@ /srv rw - btrfs /dev/sdb1 rw\n" +
"41 40 0:34 /@home /srv/home rw - btrfs /dev/sdb1 rw\n" +
"42 40 0:35 /@data /srv/data rw - btrfs /dev/sdb1 rw\n"
groups, err := mountGroupsFromMountinfo(mountinfo, "/srv")
if err != nil {
t.Fatal(err)
}
g := findGroup(groups, "btrfs:")
if g == nil || g.key != "btrfs:/dev/sdb1" {
t.Fatalf("expected one btrfs group, got %v", groups)
}
// Subvolume mounts report identical fs-wide statfs; one probe path suffices.
if len(g.paths) != 1 || g.paths[0] != "/srv" {
t.Fatalf("btrfs group paths = %v, want [/srv]", g.paths)
}
if len(groups) != 1 {
t.Fatalf("expected exactly 1 group for /srv, got %v", groups)
}
}
// TestCombineGroupUsageZFSPool verifies the arithmetic from #3025: 26 datasets
// each reporting ~19.7T avail must yield used+19.7T total, not 26*19.7T+used.
func TestCombineGroupUsageZFSPool(t *testing.T) {
const avail = uint64(19_700_000_000_000) // ~19.7 TiB pool free
stats := []rawUsage{{total: 20_000_000_000_000, avail: avail}} // root ds: 0.3T used
for i := 0; i < 25; i++ {
stats = append(stats, rawUsage{total: avail + 100_000_000_000, avail: avail})
}
// One quota'd child: reports a smaller avail; must not shrink the pool.
stats = append(stats, rawUsage{total: 1_000_000_000_000, avail: 500_000_000_000})
u := combineGroupUsage(stats)
wantUsed := uint64(300_000_000_000) + 25*uint64(100_000_000_000) + 500_000_000_000
if u.Used != wantUsed {
t.Fatalf("used = %d, want %d", u.Used, wantUsed)
}
if u.Total != wantUsed+avail {
t.Fatalf("total = %d, want %d (used+single pool avail)", u.Total, wantUsed+avail)
}
}
func TestCombineGroupUsageSingleMountIdentity(t *testing.T) {
u := combineGroupUsage([]rawUsage{{total: 1000, avail: 400}})
if u.Total != 1000 || u.Used != 600 {
t.Fatalf("single mount = %+v, want total 1000 used 600", u)
}
}
@@ -1,17 +1,14 @@
//go:build !linux
//go:build !linux && !freebsd
package fileutils
// GetAggregatedPartitionUsage returns total and used bytes for the filesystem
// that owns root. Non-Linux builds use a single statfs/GetDiskFreeSpaceEx path.
func GetAggregatedPartitionUsage(root string) (total, used uint64, err error) {
total, err = GetPartitionSize(root)
// GetPartitionUsageVariants returns the aggregate and root-only capacity views
// of root. Without mount info only a single statfs of the source path is
// available, so both variants are identical.
func GetPartitionUsageVariants(root string) (aggregate, rootOnly PartitionUsage, err error) {
u, err := singlePathPartitionUsage(root)
if err != nil {
return 0, 0, err
return aggregate, rootOnly, err
}
used, err = GetPartitionUsed(root)
if err != nil {
return 0, 0, err
}
return total, used, nil
return u, u, nil
}
@@ -0,0 +1,50 @@
//go:build linux || freebsd
package fileutils
import "strings"
// rawUsage is a single filesystem measurement in bytes.
type rawUsage struct {
total uint64
avail uint64
}
// combineGroupUsage folds statfs results for mounts that share one capacity pool
// into a single total/used pair. Per-mount used (total-avail) is summed, while
// shared free space is counted once via the largest reported avail. This keeps
// ZFS datasets or btrfs subvolumes from multiplying the pool's capacity by the
// number of mounts under a source.
func combineGroupUsage(stats []rawUsage) PartitionUsage {
var used, avail uint64
for _, s := range stats {
if s.total > s.avail {
used += s.total - s.avail
}
if s.avail > avail {
avail = s.avail
}
}
return PartitionUsage{Total: used + avail, Used: used}
}
// isZFSType reports whether fstype is a ZFS variant whose datasets share pool
// capacity across mounts (kernel zfs or zfsfuse).
func isZFSType(fstype string) bool {
return fstype == "zfs" || fstype == "zfsfuse"
}
// zfsPoolName returns the pool component of a ZFS mount source ("pool/ds@snap" -> "pool").
func zfsPoolName(source string) string {
if i := strings.IndexAny(source, "/@"); i >= 0 {
return source[:i]
}
return source
}
// isZFSSnapshotMount reports whether a ZFS mount is a snapshot (.zfs snapdir or
// an "@snapshot" source). Snapshots share pool space with the live datasets and
// are excluded from capacity aggregation.
func isZFSSnapshotMount(source, mountpoint string) bool {
return strings.Contains(source, "@") || strings.Contains(mountpoint, "/.zfs/")
}
+8 -1
View File
@@ -6,9 +6,10 @@ import (
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/access"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
// Auther is the authentication interface.
@@ -39,18 +40,24 @@ func MakeSignedTokenAPI(user *users.User, name string, duration time.Duration, p
if _, ok := user.Tokens[name]; ok {
return "", users.AuthToken{}, fmt.Errorf("key already exists with same name %v ", name)
}
id, err := utils.RandomHex(16)
if err != nil {
return "", users.AuthToken{}, fmt.Errorf("generate token id: %w", err)
}
now := time.Now()
expires := now.Add(duration)
// Create minimal token with only JWT standard claims
claim := users.AuthToken{
MinimalAuthToken: users.MinimalAuthToken{
RegisteredClaims: jwt.RegisteredClaims{
ID: id,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(expires),
Issuer: FB_ISSUER,
},
},
}
claim.Minimal = &minimal
if !minimal {
claim.Permissions = users.SanitizeTokenPermissions(perms)
}
+1 -1
View File
@@ -14,5 +14,5 @@ type JSONAuth struct {
// Auth authenticates the user via a json in content body (legacy method for compatibility).
func (auther JSONAuth) Auth(r *http.Request, _ *users.Storage) (*users.User, error) {
return AuthenticatePassword(r, auther.ReCaptcha)
return AuthenticatePassword(r, auther.ReCaptcha, false)
}
+7 -3
View File
@@ -30,7 +30,8 @@ func SetDefault(s *Service) {
}
// AuthenticatePassword authenticates the user via password in request headers.
func (s *Service) AuthenticatePassword(r *http.Request, disableOtp bool) (*users.User, error) {
// When skipRequirePasswordChange is true, a valid password is accepted even if RequirePasswordChange is set (change-required flow).
func (s *Service) AuthenticatePassword(r *http.Request, disableOtp bool, skipRequirePasswordChange bool) (*users.User, error) {
if s == nil || s.users == nil {
return nil, fmt.Errorf("auth service not configured")
}
@@ -63,6 +64,9 @@ func (s *Service) AuthenticatePassword(r *http.Request, disableOtp bool) (*users
if getErr != nil {
return nil, fmt.Errorf("unable to get user from store: %v", err)
}
if user.RequirePasswordChange && user.LoginMethod == users.LoginMethodPassword && !skipRequirePasswordChange {
return nil, errors.ErrPasswordChangeRequired
}
if user.TOTPSecret != "" && !disableOtp {
if totpCode == "" {
return nil, errors.ErrNoTotpProvided
@@ -80,9 +84,9 @@ func (s *Service) AuthenticatePassword(r *http.Request, disableOtp bool) (*users
}
// AuthenticatePassword authenticates via the default service.
func AuthenticatePassword(r *http.Request, disableOtp bool) (*users.User, error) {
func AuthenticatePassword(r *http.Request, disableOtp bool, skipRequirePasswordChange bool) (*users.User, error) {
if defaultService != nil {
return defaultService.AuthenticatePassword(r, disableOtp)
return defaultService.AuthenticatePassword(r, disableOtp, skipRequirePasswordChange)
}
return nil, fmt.Errorf("auth service not configured")
}
@@ -0,0 +1,56 @@
package auth
import (
"testing"
"testing/synctest"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func TestSignedTokensAreUniqueAtSameTime(t *testing.T) {
origKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "test-signing-key-for-token-uniqueness"
t.Cleanup(func() { settings.Config.Auth.Key = origKey })
// Freeze the clock so every token has identical issue and expiry times.
synctest.Test(t, func(t *testing.T) {
now := time.Now()
tokens := make(map[string]users.AuthToken)
for _, userID := range []uint64{1, 2} {
user := &users.User{ID: userID}
for _, minimal := range []bool{true, false} {
for range 2 {
tokenString, claim, err := MakeSignedTokenAPI(user, "test-token", time.Hour, users.Permissions{Api: true}, minimal)
if err != nil {
t.Fatal(err)
}
if _, exists := tokens[tokenString]; exists {
t.Fatalf("token collision for user %d with minimal=%v", userID, minimal)
}
tokens[tokenString] = claim
}
}
}
ids := make(map[string]bool)
for tokenString, claim := range tokens {
var parsed users.MinimalAuthToken
if _, err := jwt.ParseWithClaims(tokenString, &parsed, JWTSigningKeyFunc()); err != nil {
t.Fatalf("parse signed token: %v", err)
}
if parsed.ID == "" || ids[parsed.ID] {
t.Fatal("each signed token must have a unique nonempty id")
}
ids[parsed.ID] = true
if parsed.ID != claim.ID {
t.Fatal("signed token id must match returned metadata")
}
if parsed.IssuedAt == nil || !parsed.IssuedAt.Equal(now) || parsed.ExpiresAt == nil || !parsed.ExpiresAt.Equal(now.Add(time.Hour)) {
t.Fatal("token uniqueness must not depend on changing timestamps")
}
assertMinimalJWTClaims(t, tokenString)
}
})
}
@@ -21,6 +21,9 @@ type IndexInfo struct {
UsedAsIndexed uint64 `json:"used"`
UsedDisk uint64 `json:"usedAlt"`
DiskTotal uint64 `json:"total"`
// Root-filesystem-only view (no nested mount aggregation)
UsedDiskRoot uint64 `json:"usedAltRoot"`
DiskTotalRoot uint64 `json:"totalRoot"`
// Scanner information - map of scanner path to scanner stats
Scanners map[string]*PersistedScannerInfo `json:"scanners"`
+5 -11
View File
@@ -4,13 +4,12 @@ import (
stderrors "errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/crud"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/go-logger/logger"
)
@@ -137,23 +136,18 @@ func (s *Storage) UpdateShares(oldSource, oldPath, newSource, newPath string) (i
return 0, err
}
oldPath = utils.AddTrailingSlashIfNotExists(oldPath)
newPath = utils.AddTrailingSlashIfNotExists(newPath)
updated := 0
for _, l := range links {
if l == nil || l.SourcePath != oldSource {
continue
}
l.Path = utils.AddTrailingSlashIfNotExists(l.Path)
pos := strings.Index(l.Path, oldPath)
if pos < 0 {
rewrittenPath, matches := utils.RewritePathPrefix(l.Path, oldPath, newPath)
if !matches {
continue
}
l.SourcePath = newSource
l.Path = newPath
l.Path = rewrittenPath
if err := s.back.Save(l); err != nil {
logger.Error("failed to save updated share", "hash", l.Hash, "error", err)
@@ -11,8 +11,14 @@ const (
SidebarLinkSourceAlt SidebarLinkCategory = "source-alt"
SidebarLinkSourceHybrid SidebarLinkCategory = "source-hybrid"
SidebarLinkSourceHybrid2 SidebarLinkCategory = "source-hybrid-2"
SidebarLinkTool SidebarLinkCategory = "tool"
SidebarLinkCustom SidebarLinkCategory = "custom"
// "-root" variants display the root-filesystem-only disk usage (no nested
// mount aggregation) instead of the aggregated multi-mount totals.
SidebarLinkSourceRoot SidebarLinkCategory = "source-root"
SidebarLinkSourceAltRoot SidebarLinkCategory = "source-alt-root"
SidebarLinkSourceHybridRoot SidebarLinkCategory = "source-hybrid-root"
SidebarLinkSourceHybrid2Root SidebarLinkCategory = "source-hybrid-2-root"
SidebarLinkTool SidebarLinkCategory = "tool"
SidebarLinkCustom SidebarLinkCategory = "custom"
)
// NormalizeSidebarLinkCategory returns a known category string, preserving source-* variants.
@@ -23,7 +29,10 @@ func NormalizeSidebarLinkCategory(category string) string {
}
switch SidebarLinkCategory(c) {
case SidebarLinkSource, SidebarLinkSourceMinimal, SidebarLinkSourceAlt,
SidebarLinkSourceHybrid, SidebarLinkSourceHybrid2, SidebarLinkTool, SidebarLinkCustom:
SidebarLinkSourceHybrid, SidebarLinkSourceHybrid2,
SidebarLinkSourceRoot, SidebarLinkSourceAltRoot,
SidebarLinkSourceHybridRoot, SidebarLinkSourceHybrid2Root,
SidebarLinkTool, SidebarLinkCustom:
return c
}
if strings.HasPrefix(c, "source") {
@@ -36,3 +45,14 @@ func NormalizeSidebarLinkCategory(category string) string {
func IsSourceSidebarCategory(category string) bool {
return strings.HasPrefix(NormalizeSidebarLinkCategory(category), "source")
}
// SidebarLinkDiskScopeRoot reports whether the category shows the
// root-filesystem-only disk usage rather than the aggregated nested-mount usage.
func SidebarLinkDiskScopeRoot(category string) bool {
return strings.HasSuffix(NormalizeSidebarLinkCategory(category), "-root")
}
// BaseSidebarLinkCategory strips the root-only "-root" suffix from a category.
func BaseSidebarLinkCategory(category string) string {
return strings.TrimSuffix(NormalizeSidebarLinkCategory(category), "-root")
}
@@ -24,7 +24,11 @@ func HasAnyGlobalPermission(p Permissions) bool {
}
// IsMinimalApiToken reports whether the token inherits the owner's globals at auth time
// rather than embedding its own global permission caps in the JWT.
// rather than applying stored global permission caps.
func IsMinimalApiToken(t AuthToken) bool {
if t.Minimal != nil {
return *t.Minimal
}
// Legacy tokens lack minimal; empty stored global caps implied minimal (WebDAV-style).
return !HasAnyGlobalPermission(t.Permissions)
}
@@ -45,6 +45,14 @@ func TestIsMinimalApiToken(t *testing.T) {
t.Fatal("custom token with global caps should not be minimal")
}
if !IsMinimalApiToken(AuthToken{Permissions: Permissions{Modify: true}}) {
t.Fatal("token without global caps should be minimal")
t.Fatal("legacy token without global caps should be minimal")
}
minimal := true
if !IsMinimalApiToken(AuthToken{Minimal: &minimal}) {
t.Fatal("explicit minimal token should be minimal")
}
customized := false
if IsMinimalApiToken(AuthToken{Minimal: &customized}) {
t.Fatal("explicit customized token with empty caps should not be minimal")
}
}
@@ -21,3 +21,16 @@ func TestValidateUsernameAcceptsNormalName(t *testing.T) {
t.Fatalf("expected valid username, got %v", err)
}
}
func TestValidateUsernameRejectsUnsafeNames(t *testing.T) {
for _, username := range []string{"..", "....", ".", "-", "al..ice", "bob/", "./bob", `bob\`, "alice/docs", " alice", "alice "} {
if err := ValidateUsername(username); err == nil {
t.Fatalf("expected %q to be rejected", username)
}
}
for _, username := range []string{"alice", "first.last", "j.r.r", "a-b_c", "user@example.com", "José", "李雷", ".alice", "users"} {
if err := ValidateUsername(username); err != nil {
t.Fatalf("expected %q to be accepted, got %v", username, err)
}
}
}
+35 -25
View File
@@ -47,8 +47,10 @@ var reservedUsernames = map[string]struct{}{
strings.ToLower(AnonymousUserName): {},
}
// ValidateUsername rejects empty and reserved login names.
// ValidateUsername rejects empty and reserved login names, and names that do not map to their
// own createUserDir home directory.
func ValidateUsername(username string) error {
raw := username
username = strings.TrimSpace(username)
if username == "" {
return fmt.Errorf("username is empty")
@@ -56,6 +58,11 @@ func ValidateUsername(username string) error {
if _, reserved := reservedUsernames[strings.ToLower(username)]; reserved {
return fmt.Errorf("username %q is reserved", username)
}
// The per-user home directory is derived from CleanUsername(username), so reject names
// that it would rewrite, the names "." and "-", and names containing path separators.
if CleanUsername(raw) != raw || raw == "." || raw == "-" || strings.ContainsAny(raw, `/\`) {
return fmt.Errorf("username %q contains characters that are not allowed", raw)
}
return nil
}
@@ -97,6 +104,8 @@ type AuthToken struct {
BelongsTo uint64 `json:"belongsTo,omitempty"` // legacy stored metadata only, never trusted for auth; identity is always the hashed_tokens lookup
IssuedAt int64 `json:"issuedAt,omitempty"`
ExpiresAt int64 `json:"expiresAt,omitempty"`
// Minimal distinguishes owner-inheriting tokens from customized caps. Nil means legacy (infer from stored permissions).
Minimal *bool `json:"minimal,omitempty"`
Permissions Permissions `json:"Permissions,omitempty"`
}
@@ -106,11 +115,11 @@ type MinimalAuthToken struct {
}
type Permissions struct {
Api bool `json:"api"` // allow api access
Admin bool `json:"admin"` // allow admin access
Api bool `json:"api"` // allow api access
Admin bool `json:"admin"` // allow admin access
Modify bool `json:"modify,omitempty"` // deprecated: legacy user migration only; not used for API tokens
Share bool `json:"share"` // allow sharing files
Realtime bool `json:"realtime"` // allow realtime updates
Share bool `json:"share"` // allow sharing files
Realtime bool `json:"realtime"` // allow realtime updates
Delete bool `json:"delete,omitempty"` // deprecated: legacy user migration only; not used for API tokens
Create bool `json:"create,omitempty"` // deprecated: legacy user migration only; not used for API tokens
Download bool `json:"download,omitempty"` // deprecated: legacy user migration only; not used for API tokens
@@ -119,12 +128,12 @@ type Permissions struct {
// SourceFilePermissions holds per-source file operation permissions (v4+).
type SourceFilePermissions struct {
View bool `json:"view"`
Download bool `json:"download"`
Modify bool `json:"modify"`
Delete bool `json:"delete"`
Create bool `json:"create"`
Configured bool `json:"configured,omitempty"` // true when explicitly set (allows intentional deny-all)
View bool `json:"view"`
Download bool `json:"download"`
Modify bool `json:"modify"`
Delete bool `json:"delete"`
Create bool `json:"create"`
Configured bool `json:"configured,omitempty"` // true when explicitly set (allows intentional deny-all)
}
// MarkSourceFilePermissionsConfigured marks permissions as explicitly set (including deny-all).
@@ -173,16 +182,17 @@ type Preview struct {
// FrontendUser holds fields safe to return from user APIs (embedded on User).
type FrontendUser struct {
NonAdminEditable
DisableSettings bool `json:"disableSettings"`
Username string `json:"username"`
FrontendScopes []FrontendScope `json:"scopes"`
LockPassword bool `json:"lockPassword"`
Permissions Permissions `json:"permissions"` // global: admin, api, share, realtime
SourcePermissions map[string]SourceFilePermissions `json:"sourcePermissions,omitempty"` // deprecated: use scopes[].permissions
LoginMethod LoginMethod `json:"loginMethod"`
OtpEnabled bool `json:"otpEnabled"`
ShowFirstLogin bool `json:"showFirstLogin"`
Perm Permissions `json:"perm,omitzero"`
DisableSettings bool `json:"disableSettings"`
Username string `json:"username"`
FrontendScopes []FrontendScope `json:"scopes"`
LockPassword bool `json:"lockPassword"`
RequirePasswordChange bool `json:"requirePasswordChange"`
Permissions Permissions `json:"permissions"` // global: admin, api, share, realtime
SourcePermissions map[string]SourceFilePermissions `json:"sourcePermissions,omitempty"` // deprecated: use scopes[].permissions
LoginMethod LoginMethod `json:"loginMethod"`
OtpEnabled bool `json:"otpEnabled"`
ShowFirstLogin bool `json:"showFirstLogin"`
Perm Permissions `json:"perm,omitzero"`
}
// PinnedItems maps source filesystem path -> index directory path -> pinned item names.
@@ -211,14 +221,14 @@ type User struct {
}
type FrontendScope struct {
Name string `json:"name"` // Bolt: filesystem path; JSON API: display name after prepForFrontend
Scope string `json:"scope"` // index path within that source
Name string `json:"name"` // Bolt: filesystem path; JSON API: display name after prepForFrontend
Scope string `json:"scope"` // index path within that source
Permissions *SourceFilePermissions `json:"permissions,omitempty"`
}
type BackendScope struct {
Path string `json:"path"` // real path for the source
Scope string `json:"scope"` // index path within that source
Path string `json:"path"` // real path for the source
Scope string `json:"scope"` // index path within that source
Permissions SourceFilePermissions `json:"permissions,omitempty"`
}
+2 -1
View File
@@ -18,7 +18,8 @@ var (
ErrAccessDenied = errors.New("access denied")
ErrInvalidRequestParams = errors.New("invalid request params")
ErrSourceIsParent = errors.New("source is parent")
ErrNoTotpProvided = errors.New("OTP code is required for user")
ErrNoTotpProvided = errors.New("OTP code is required for user")
ErrPasswordChangeRequired = errors.New("password change is required for user")
ErrNoTotpConfigured = errors.New("OTP is enforced, but user is not configured")
ErrUnauthorized = errors.New("user unauthorized")
ErrNotIndexed = errors.New("directory or item excluded from indexing")
+4 -20
View File
@@ -41,15 +41,13 @@ func handleUserEvents() {
for ue := range userEventChan {
for _, user := range ue.users {
userClientsMu.RLock()
conns := userClients[user]
userClientsMu.RUnlock()
for _, ch := range conns {
for _, ch := range userClients[user] {
select {
case ch <- ue.event:
default:
}
}
userClientsMu.RUnlock()
}
}
}
@@ -135,28 +133,14 @@ func DebouncedBroadcast(eventType, message string) {
func handleSourceUpdates() {
for update := range sourceUpdateChan {
sourceClientsMu.RLock()
clients := sourceClients[update.source]
clientCount := len(clients)
sourceClientsMu.RUnlock()
if clientCount == 0 {
// No clients registered for this source - this is normal if no one is connected
continue
}
sentCount := 0
for ch := range clients {
for ch := range sourceClients[update.source] {
select {
case ch <- update.event:
sentCount++
default:
// Channel full, message dropped
}
}
// Log if we have clients but couldn't send to all
//if sentCount < clientCount {
// // Some messages were dropped due to full channels
//}
sourceClientsMu.RUnlock()
}
}
@@ -0,0 +1,74 @@
package events
import (
"sync"
"testing"
"time"
)
func TestConcurrentRegisterUnregisterSourceUpdates(t *testing.T) {
stop := make(chan struct{})
go func() {
for {
select {
case <-stop:
return
default:
ch := Register("stress-user", []string{"stress-source"})
Unregister("stress-user", ch)
}
}
}()
for i := 0; i < 200; i++ {
SendSourceUpdate("stress-source", "tick")
}
close(stop)
time.Sleep(50 * time.Millisecond)
}
func TestConcurrentSSEClientLifecycleRace(t *testing.T) {
stop := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
user := "race-user-" + string(rune('a'+id))
source := "race-source-" + string(rune('a'+id%2))
for {
select {
case <-stop:
return
default:
ch := Register(user, []string{source, "shared-source"})
SendSourceUpdate(source, "tick")
SendSourceUpdate("shared-source", "tick")
SendToUsers("ping", "msg", []string{user})
Unregister(user, ch)
}
}
}(i)
}
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-stop:
return
default:
SendSourceUpdate("shared-source", "broadcast")
SendToUsers("broadcast", "all", []string{"race-user-a", "race-user-b"})
}
}
}()
time.Sleep(100 * time.Millisecond)
Shutdown()
close(stop)
wg.Wait()
time.Sleep(50 * time.Millisecond)
}
+6 -5
View File
@@ -78,12 +78,10 @@ func extractTIFFEmbeddedPreview(f *os.File) ([]byte, error) {
return nil, err
}
ex, err := extimagemeta.Decode(f)
if err != nil {
return nil, err
var candidates []previewCandidate
if ex, err := extimagemeta.Decode(f); err == nil {
candidates = previewCandidates(ex)
}
candidates := previewCandidates(ex)
if scanCandidates, scanErr := collectTIFFPreviewCandidates(f); scanErr == nil {
candidates = append(candidates, scanCandidates...)
}
@@ -115,6 +113,9 @@ func previewCandidates(ex exif.Exif) []previewCandidate {
out = append(out, previewCandidate{offset: ifd.ImageOffset, length: ifd.ImageLength})
}
}
for _, sub := range ex.SubIFDs {
appendIFD(sub)
}
appendIFD(ex.IFD1)
appendIFD(ex.IFD2)
+8 -7
View File
@@ -47,15 +47,16 @@ func GetOrientation(ctx context.Context, path string) string {
default:
ex, err = extimagemeta.Decode(f)
}
if err != nil {
return ""
}
if ctx.Err() != nil {
return ""
}
if ex.IFD0.Orientation == 0 {
return ""
if err == nil && ex.IFD0.Orientation != 0 {
return tag.ValueNameFor(tag.IFD0, tag.TagOrientation, uint32(ex.IFD0.Orientation))
}
return tag.ValueNameFor(tag.IFD0, tag.TagOrientation, uint32(ex.IFD0.Orientation))
if !isHEICExtension(ext) {
if orient := extractTIFFOrientation(f); orient != 0 {
return tag.ValueNameFor(tag.IFD0, tag.TagOrientation, uint32(orient))
}
}
return ""
}
+109 -9
View File
@@ -9,15 +9,23 @@ import (
)
const (
tiffTagStripOffsets = 0x0111
tiffTagOrientation = 0x0112
tiffTagStripByteCounts = 0x0117
tiffTagSubIFDs = 0x014a
tiffTagJpgFromRaw = 0x002e
tiffTagJPEGInterchange = 0x0201
tiffTagJPEGInterchangeLen = 0x0202
tiffIFDScanLimit = 4 * 1024 * 1024
tiffMagicStandard = 42
tiffMagicPanasonicRW2 = 0x0055
tiffMagicOlympusORF1 = 0x4f52
tiffMagicOlympusORF2 = 0x5352
tiffTypeByte = 1
tiffTypeASCII = 2
tiffTypeShort = 3
tiffTypeLong = 4
tiffTypeIFD = 13
tiffTypeUndefined = 7
maxTIFFIFDsVisited = 128
maxTIFFIFDQueueLen = 128
@@ -96,6 +104,7 @@ func collectTIFFPreviewCandidates(f *os.File) ([]previewCandidate, error) {
for _, ifd := range ifds {
out = appendPreviewCandidates(out, jpgFromRawCandidates(ifd))
out = appendPreviewCandidates(out, jpegInterchangeCandidates(ifd))
out = appendPreviewCandidates(out, stripPreviewCandidates(ifd, order))
if len(out) >= maxTIFFPreviewCandidates {
break
}
@@ -103,6 +112,42 @@ func collectTIFFPreviewCandidates(f *os.File) ([]previewCandidate, error) {
return out, nil
}
// extractTIFFOrientation reads standard TIFF IFD0 Orientation (0x0112) as a fallback
// when full EXIF decoding fails.
func extractTIFFOrientation(f *os.File) uint16 {
info, err := f.Stat()
if err != nil {
return 0
}
scanSize := info.Size()
if scanSize > tiffIFDScanLimit {
scanSize = tiffIFDScanLimit
}
if scanSize < 8 {
return 0
}
header := make([]byte, scanSize)
n, err := f.ReadAt(header, 0)
if err != nil && err != io.EOF {
return 0
}
header = header[:n]
order, ifd0, ok := tiffHeaderIFD0(header)
if !ok || ifd0 == 0 {
return 0
}
ifd, _, _, err := parseTIFFIFD(header, order, ifd0)
if err != nil {
return 0
}
tag, ok := ifd.tags[tiffTagOrientation]
if !ok || tag.count == 0 {
return 0
}
return tiffTagFirstUint16(tag, order)
}
func appendPreviewCandidates(dst, src []previewCandidate) []previewCandidate {
remaining := maxTIFFPreviewCandidates - len(dst)
if remaining <= 0 {
@@ -143,6 +188,48 @@ func jpegInterchangeCandidates(ifd tiffIFD) []previewCandidate {
return []previewCandidate{{offset: offset, length: length}}
}
func stripPreviewCandidates(ifd tiffIFD, order binary.ByteOrder) []previewCandidate {
offTag, okOff := ifd.tags[tiffTagStripOffsets]
lenTag, okLen := ifd.tags[tiffTagStripByteCounts]
if !okOff || !okLen || offTag.count != 1 || lenTag.count != 1 {
return nil
}
offset := tiffTagScalarUint32(offTag, order)
length := tiffTagScalarUint32(lenTag, order)
if offset == 0 || length <= 4 || length > maxPreviewReadSize {
return nil
}
return []previewCandidate{{offset: offset, length: length}}
}
func tiffTagScalarUint32(t tiffTag, order binary.ByteOrder) uint32 {
switch t.typ {
case tiffTypeLong, tiffTypeIFD:
return t.valueOffset
case tiffTypeShort:
return uint32(tiffTagFirstUint16(t, order))
default:
return 0
}
}
func tiffTagFirstUint16(t tiffTag, order binary.ByteOrder) uint16 {
switch t.typ {
case tiffTypeShort:
if order == binary.BigEndian {
return uint16(t.valueOffset >> 16)
}
return uint16(t.valueOffset & 0xffff)
case tiffTypeLong:
if t.valueOffset > 0xffff {
return 0
}
return uint16(t.valueOffset)
default:
return 0
}
}
func tiffHeaderIFD0(data []byte) (binary.ByteOrder, uint32, bool) {
if len(data) < 8 {
return nil, 0, false
@@ -156,7 +243,9 @@ func tiffHeaderIFD0(data []byte) (binary.ByteOrder, uint32, bool) {
default:
return nil, 0, false
}
if order.Uint16(data[2:4]) != 42 {
switch order.Uint16(data[2:4]) {
case tiffMagicStandard, tiffMagicPanasonicRW2, tiffMagicOlympusORF1, tiffMagicOlympusORF2:
default:
return nil, 0, false
}
return order, order.Uint32(data[4:8]), true
@@ -205,19 +294,23 @@ func tiffTagUint32s(data []byte, order binary.ByteOrder, typ uint16, count uint3
if count > maxTIFFSubIFDsPerEntry {
count = maxTIFFSubIFDsPerEntry
}
elemSize := tiffTagByteSize(typ)
if elemSize <= 0 {
return nil
}
var raw []byte
switch {
case typ == tiffTypeLong && count == 1:
var b [4]byte
order.PutUint32(b[:], valueOffset)
raw = b[:]
case tiffTagByteSize(typ)*int(count) <= 4:
case elemSize*int(count) <= 4:
var b [4]byte
order.PutUint32(b[:], valueOffset)
raw = b[:count*uint32(tiffTagByteSize(typ))]
raw = b[:count*uint32(elemSize)]
default:
off := int(valueOffset)
n := int(count) * tiffTagByteSize(typ)
n := int(count) * elemSize
if off < 0 || off+n > len(data) {
return nil
}
@@ -225,11 +318,18 @@ func tiffTagUint32s(data []byte, order binary.ByteOrder, typ uint16, count uint3
}
out := make([]uint32, 0, count)
for i := 0; i < int(count); i++ {
pos := i * 4
if pos+4 > len(raw) {
pos := i * elemSize
if pos+elemSize > len(raw) {
break
}
out = append(out, order.Uint32(raw[pos:pos+4]))
switch typ {
case tiffTypeShort:
out = append(out, uint32(order.Uint16(raw[pos:pos+2])))
case tiffTypeLong, tiffTypeIFD:
out = append(out, order.Uint32(raw[pos:pos+4]))
default:
return nil
}
}
return out
}
@@ -240,9 +340,9 @@ func tiffTagByteSize(typ uint16) int {
return 1
case tiffTypeShort:
return 2
case tiffTypeLong:
case tiffTypeLong, tiffTypeIFD:
return 4
default:
return 1
return 0
}
}
+161 -4
View File
@@ -62,7 +62,7 @@ func TestCollectTIFFPreviewCandidatesIgnoresMalformedOffsets(t *testing.T) {
func TestCollectTIFFPreviewCandidatesIgnoresMalformedSubIFDOffset(t *testing.T) {
data := buildSyntheticTIFF(tiffFixture{
thumbnailJPEG: smallJPEG,
subIFDJPEG: largeJPEG,
subIFDJPEG: largeJPEG,
badJpgFromRaw: true,
})
f := openBytesFile(t, data)
@@ -93,9 +93,163 @@ func TestCollectTIFFPreviewCandidatesBoundsIFDTraversal(t *testing.T) {
}
}
func TestTiffTagUint32sSupportsIFDType(t *testing.T) {
data := buildSyntheticTIFF(tiffFixture{
thumbnailJPEG: smallJPEG,
subIFDJPEG: largeJPEG,
subIFDType: tiffTypeIFD,
})
f := openBytesFile(t, data)
candidates, err := collectTIFFPreviewCandidates(f)
if err != nil {
t.Fatal(err)
}
preview, err := readLargestJPEGPreview(f, candidates)
if err != nil {
t.Fatal(err)
}
if len(preview) != len(largeJPEG) {
t.Fatalf("preview size = %d, want %d (SubIFD type IFD)", len(preview), len(largeJPEG))
}
}
func TestExtractEmbeddedPreviewFallbackWhenDecodeFails(t *testing.T) {
// Synthetic ARW where SubIFD offset is placed after IFD2, and a SubIFD tag
// points past EOF so extimagemeta.Decode fails with EOF, while IFD2 holds a
// valid JPEGInterchangeFormat preview.
order := binary.LittleEndian
buf := make([]byte, 32*1024)
copy(buf[0:2], []byte("II"))
order.PutUint16(buf[2:4], tiffMagicStandard)
ifd0Off := uint32(8)
order.PutUint32(buf[4:8], ifd0Off)
thumbOff := uint32(4096)
copy(buf[thumbOff:], smallJPEG)
largeOff := uint32(8192)
copy(buf[largeOff:], largeJPEG)
ifd1Off := uint32(256)
ifd2Off := uint32(512)
subIFDOff := uint32(768)
writeIFD := func(offset uint32, entries []tiffEntry, next uint32) {
off := int(offset)
order.PutUint16(buf[off:off+2], uint16(len(entries)))
entryBase := off + 2
for i, entry := range entries {
pos := entryBase + i*12
order.PutUint16(buf[pos:pos+2], entry.tag)
order.PutUint16(buf[pos+2:pos+4], entry.typ)
order.PutUint32(buf[pos+4:pos+8], entry.count)
order.PutUint32(buf[pos+8:pos+12], entry.value)
}
order.PutUint32(buf[entryBase+len(entries)*12:entryBase+len(entries)*12+4], next)
}
writeIFD(ifd0Off, []tiffEntry{
{tag: tiffTagOrientation, typ: tiffTypeShort, count: 1, value: 6},
{tag: tiffTagSubIFDs, typ: tiffTypeLong, count: 1, value: subIFDOff},
{tag: tiffTagJPEGInterchange, typ: tiffTypeLong, count: 1, value: thumbOff},
{tag: tiffTagJPEGInterchangeLen, typ: tiffTypeLong, count: 1, value: uint32(len(smallJPEG))},
}, ifd1Off)
writeIFD(ifd1Off, []tiffEntry{
{tag: tiffTagJPEGInterchange, typ: tiffTypeLong, count: 1, value: thumbOff},
{tag: tiffTagJPEGInterchangeLen, typ: tiffTypeLong, count: 1, value: uint32(len(smallJPEG))},
}, ifd2Off)
writeIFD(ifd2Off, []tiffEntry{
{tag: tiffTagJPEGInterchange, typ: tiffTypeLong, count: 1, value: largeOff},
{tag: tiffTagJPEGInterchangeLen, typ: tiffTypeLong, count: 1, value: uint32(len(largeJPEG))},
}, 0)
// SubIFD has a StripOffsets tag with count=2 pointing beyond file end so Decode fails with EOF.
writeIFD(subIFDOff, []tiffEntry{
{tag: tiffTagStripOffsets, typ: tiffTypeLong, count: 2, value: uint32(len(buf) + 4096)},
}, 0)
path := filepath.Join(t.TempDir(), "sample.arw")
if err := os.WriteFile(path, buf[:int(largeOff)+len(largeJPEG)], 0o600); err != nil {
t.Fatal(err)
}
preview, err := ExtractEmbeddedPreview(t.Context(), path)
if err != nil {
t.Fatalf("ExtractEmbeddedPreview() err = %v", err)
}
if len(preview) != len(largeJPEG) {
t.Fatalf("ExtractEmbeddedPreview() len = %d, want %d", len(preview), len(largeJPEG))
}
if got := GetOrientation(t.Context(), path); got != "Rotate 90 CW" {
t.Fatalf("GetOrientation() = %q, want %q", got, "Rotate 90 CW")
}
}
func TestExtractEmbeddedPreviewSupportsRW2AndStripPreview(t *testing.T) {
order := binary.LittleEndian
buf := make([]byte, 16*1024)
copy(buf[0:2], []byte("II"))
order.PutUint16(buf[2:4], tiffMagicPanasonicRW2)
ifd0Off := uint32(8)
order.PutUint32(buf[4:8], ifd0Off)
largeOff := uint32(4096)
copy(buf[largeOff:], largeJPEG)
entries := []tiffEntry{
{tag: tiffTagStripOffsets, typ: tiffTypeLong, count: 1, value: largeOff},
{tag: tiffTagStripByteCounts, typ: tiffTypeLong, count: 1, value: uint32(len(largeJPEG))},
}
order.PutUint16(buf[ifd0Off:ifd0Off+2], uint16(len(entries)))
for i, entry := range entries {
pos := int(ifd0Off) + 2 + i*12
order.PutUint16(buf[pos:pos+2], entry.tag)
order.PutUint16(buf[pos+2:pos+4], entry.typ)
order.PutUint32(buf[pos+4:pos+8], entry.count)
order.PutUint32(buf[pos+8:pos+12], entry.value)
}
path := filepath.Join(t.TempDir(), "sample.rw2")
if err := os.WriteFile(path, buf[:int(largeOff)+len(largeJPEG)], 0o600); err != nil {
t.Fatal(err)
}
preview, err := ExtractEmbeddedPreview(t.Context(), path)
if err != nil {
t.Fatalf("ExtractEmbeddedPreview() err = %v", err)
}
if len(preview) != len(largeJPEG) {
t.Fatalf("ExtractEmbeddedPreview() len = %d, want %d", len(preview), len(largeJPEG))
}
}
func TestExtractEmbeddedPreviewDSC02672(t *testing.T) {
path := "/Users/steffag/Downloads/DSC02672-first-4MB.ARW"
if _, err := os.Stat(path); err != nil {
t.Skip(path)
}
got, err := ExtractEmbeddedPreview(t.Context(), path)
if err != nil {
t.Fatal(err)
}
if !IsJPEG(got) {
t.Fatalf("expected JPEG preview, got %d bytes", len(got))
}
if len(got) != 2954147 {
t.Fatalf("preview size = %d, want 2954147", len(got))
}
if orient := GetOrientation(t.Context(), path); orient != "Horizontal (normal)" {
t.Fatalf("GetOrientation() = %q, want Horizontal (normal)", orient)
}
}
type tiffFixture struct {
thumbnailJPEG []byte
subIFDJPEG []byte
subIFDType uint16
badJpgFromRaw bool
badJPEGInterchg bool
}
@@ -116,6 +270,9 @@ func openBytesFile(t *testing.T, data []byte) *os.File {
func buildSyntheticTIFF(fix tiffFixture) []byte {
order := binary.LittleEndian
if fix.subIFDType == 0 {
fix.subIFDType = tiffTypeLong
}
buf := make([]byte, 64*1024)
thumbOff := uint32(4096)
@@ -149,7 +306,7 @@ func buildSyntheticTIFF(fix tiffFixture) []byte {
writeIFD(ifd1Off, ifd1Entries, 0)
ifd0Entries := []tiffEntry{
{tag: tiffTagSubIFDs, typ: tiffTypeLong, count: 1, value: ifd1Off},
{tag: tiffTagSubIFDs, typ: fix.subIFDType, count: 1, value: ifd1Off},
{tag: tiffTagJPEGInterchange, typ: tiffTypeLong, count: 1, value: thumbOff},
{tag: tiffTagJPEGInterchangeLen, typ: tiffTypeLong, count: 1, value: uint32(len(fix.thumbnailJPEG))},
}
@@ -170,8 +327,8 @@ func buildSyntheticTIFF(fix tiffFixture) []byte {
}
type tiffEntry struct {
tag, typ uint16
count, value uint32
tag, typ uint16
count, value uint32
}
func buildChainedTIFF(chainLen int) []byte {
+15 -1
View File
@@ -76,6 +76,18 @@ func (x Format) toImaging() imaging.Format {
}
}
// encodable reports whether imaging can encode this format.
// imaging only encodes JPEG, PNG, GIF, TIFF and BMP; webp and the netpbm
// formats are decode-only, so previews for them must be written as JPEG.
func (x Format) encodable() bool {
switch x {
case FormatJpeg, FormatPng, FormatGif, FormatTiff, FormatBmp:
return true
default:
return false
}
}
/*
ENUM(
high
@@ -203,7 +215,9 @@ func (s *Service) resizeWithSize(in io.Reader, out io.Writer, fileSize int64, op
var wrappedReader = in
var err error
if opts.Format == FormatHeic {
// HEIC has no encoder and webp/netpbm are decode-only in imaging; fall back
// to JPEG so preview generation does not fail with ErrUnsupportedFormat.
if !opts.Format.encodable() {
opts.Format = FormatJpeg
}
// Ensure JPEG quality is set based on quality setting
+8
View File
@@ -159,6 +159,14 @@ func TestService_Resize(t *testing.T) {
},
matcher: sizeMatcher(100, 100),
},
"resize webp falls back to jpeg": {
options: ResizeOptions{Width: 100, Height: 100, ResizeMode: ResizeModeFill, Format: FormatWebp},
source: func(t *testing.T) afero.File {
t.Helper()
return openFile(t, "testdata/gray-sample.webp")
},
matcher: formatMatcher(FormatJpeg),
},
"resize with high quality": {
options: ResizeOptions{Width: 100, Height: 100, ResizeMode: ResizeModeFill, Quality: QualityHigh},
source: func(t *testing.T) afero.File {
-9
View File
@@ -272,15 +272,6 @@ func (s *Service) generateRawPreview(ctx context.Context, file iteminfo.Extended
case previewTypeImage:
ext := strings.ToLower(filepath.Ext(file.Name))
if iteminfo.IsRawImage(ext) {
if s.ffmpegService != nil {
previewBytes, err := s.convertImageWithFFmpeg(ctx, file.RealPath, previewSize)
if err == nil && len(previewBytes) >= minPreviewSize {
return previewBytes, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
}
return nil, ErrUnsupportedFormat
}
return s.generateImagePreview(ctx, file, previewSize)
@@ -1,24 +1,23 @@
package state
import (
"crypto/rand"
"fmt"
"math/big"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/go-logger/logger"
)
const bootstrapAdminPasswordHexBytes = 6 // 12 hex characters
// bootstrapDefaultAdminPassword returns the plaintext password for initial admin creation.
// When config adminPassword is blank or "admin", a random password is generated and logged once.
// When config adminPassword is blank or "admin", a random speakable password is generated and logged once.
func bootstrapDefaultAdminPassword(username string) (plaintext string, generated bool, err error) {
cfg := settings.Config.Auth.AdminPassword
if cfg != "" && cfg != "admin" {
return cfg, false, nil
}
plaintext, err = utils.RandomHex(bootstrapAdminPasswordHexBytes)
plaintext, err = generateSpeakableBootstrapPassword()
if err != nil {
return "", false, fmt.Errorf("generate bootstrap admin password: %w", err)
}
@@ -29,3 +28,37 @@ func bootstrapDefaultAdminPassword(username string) (plaintext string, generated
)
return plaintext, true, nil
}
func generateSpeakableBootstrapPassword() (string, error) {
if len(bootstrapWords) == 0 {
return "", fmt.Errorf("bootstrap word list is empty")
}
wordIdx, err := rand.Int(rand.Reader, big.NewInt(int64(len(bootstrapWords))))
if err != nil {
return "", err
}
word := bootstrapWords[wordIdx.Int64()]
primary, err := randomSpeakableCode(bootstrapSpeakablePrimaryCodeLen)
if err != nil {
return "", err
}
secondary, err := randomSpeakableCode(bootstrapSpeakableSecondaryCodeLen)
if err != nil {
return "", err
}
return fmt.Sprintf("%s-%s-%s", word, string(primary), string(secondary)), nil
}
func randomSpeakableCode(n int) ([]byte, error) {
codeRunes := make([]byte, n)
charsetLen := big.NewInt(int64(len(bootstrapSpeakableCharset)))
for i := range codeRunes {
idx, err := rand.Int(rand.Reader, charsetLen)
if err != nil {
return nil, err
}
codeRunes[i] = bootstrapSpeakableCharset[idx.Int64()]
}
return codeRunes, nil
}
@@ -1,12 +1,19 @@
package state
import (
"regexp"
"strings"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func TestBootstrapWordsCount(t *testing.T) {
if len(bootstrapWords) != 100 {
t.Fatalf("bootstrapWords len = %d, want 100", len(bootstrapWords))
}
}
func TestBootstrapDefaultAdminPasswordUsesConfigWhenSet(t *testing.T) {
orig := settings.Config.Auth.AdminPassword
defer func() { settings.Config.Auth.AdminPassword = orig }()
@@ -24,6 +31,8 @@ func TestBootstrapDefaultAdminPasswordUsesConfigWhenSet(t *testing.T) {
}
}
var speakableBootstrapPasswordPattern = regexp.MustCompile(`^[a-z]+-[abcdefghjkmnpqrstuvwxyz23456789]{5}-[abcdefghjkmnpqrstuvwxyz23456789]{2}$`)
func TestBootstrapDefaultAdminPasswordGeneratesWhenDefault(t *testing.T) {
orig := settings.Config.Auth.AdminPassword
defer func() { settings.Config.Auth.AdminPassword = orig }()
@@ -40,11 +49,31 @@ func TestBootstrapDefaultAdminPasswordGeneratesWhenDefault(t *testing.T) {
if plain == "" || plain == "admin" {
t.Fatalf("cfg=%q: unexpected password %q", cfg, plain)
}
if len(plain) != bootstrapAdminPasswordHexBytes*2 {
t.Fatalf("cfg=%q: password length %d, want %d", cfg, len(plain), bootstrapAdminPasswordHexBytes*2)
if !speakableBootstrapPasswordPattern.MatchString(plain) {
t.Fatalf("cfg=%q: password %q does not match speakable pattern", cfg, plain)
}
if strings.Trim(plain, "0123456789abcdef") != "" {
t.Fatalf("cfg=%q: expected hex password, got %q", cfg, plain)
word := strings.Split(plain, "-")[0]
found := false
for _, w := range bootstrapWords {
if w == word {
found = true
break
}
}
if !found {
t.Fatalf("cfg=%q: word %q not in bootstrap word list", cfg, word)
}
}
}
func TestGenerateSpeakableBootstrapPassword(t *testing.T) {
for i := 0; i < 20; i++ {
plain, err := generateSpeakableBootstrapPassword()
if err != nil {
t.Fatal(err)
}
if !speakableBootstrapPasswordPattern.MatchString(plain) {
t.Fatalf("password %q does not match speakable pattern", plain)
}
}
}
@@ -0,0 +1,23 @@
package state
// bootstrapWords is a fixed list of short, common English nouns for one-time bootstrap passwords.
// Words are chosen to be easy to say, spell, and type (including for non-native English speakers).
var bootstrapWords = []string{
"apple", "ball", "barn", "bean", "bed", "belt", "bike", "bird", "boat", "book",
"boot", "bowl", "box", "bus", "cake", "camp", "cart", "cat", "clock", "cloud",
"coat", "coin", "corn", "cup", "desk", "dog", "door", "duck", "egg", "farm",
"fish", "flag", "food", "foot", "game", "gift", "goat", "gold", "grass", "hand",
"hat", "hill", "home", "horse", "house", "ice", "jar", "key", "kid", "lake",
"lamp", "land", "leaf", "leg", "light", "line", "lion", "list", "mail", "map",
"milk", "moon", "mouse", "nest", "net", "night", "nose", "note", "page", "park",
"path", "pen", "pet", "pie", "pig", "pin", "pipe", "plan", "plant", "pot",
"rain", "red", "ring", "road", "rock", "room", "rope", "rose", "sand", "sea",
"ship", "shoe", "shop", "sky", "snow", "sock", "star", "stone", "sun", "tree",
}
// bootstrapSpeakableCharset excludes ambiguous characters for read-aloud (no 0/o, 1/i/l).
const bootstrapSpeakableCharset = "abcdefghjkmnpqrstuvwxyz23456789"
// bootstrapSpeakablePrimaryCodeLen and bootstrapSpeakableSecondaryCodeLen form the code after the word (e.g. word-xxxxx-xx).
const bootstrapSpeakablePrimaryCodeLen = 5
const bootstrapSpeakableSecondaryCodeLen = 2
+4 -1
View File
@@ -55,10 +55,13 @@ func QuickSetup() error {
logger.Debugf("Creating user as admin: %v", user.Username)
plainPassword, _, err := bootstrapDefaultAdminPassword(user.Username)
plainPassword, generated, err := bootstrapDefaultAdminPassword(user.Username)
if err != nil {
return err
}
if generated {
user.RequirePasswordChange = true
}
hashedPassword, hashErr := utils.HashPwd(plainPassword)
if hashErr != nil {
+4 -7
View File
@@ -6,9 +6,9 @@ import (
"strings"
"time"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/share"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/go-logger/logger"
)
@@ -312,23 +312,20 @@ func UpdateSharesForMovedResource(oldSource, oldPath, newSource, newPath string)
sharesMux.Lock()
defer sharesMux.Unlock()
oldPath = utils.AddTrailingSlashIfNotExists(oldPath)
newPath = utils.AddTrailingSlashIfNotExists(newPath)
var updatedHashes []string
for _, l := range sharesByHash {
if l == nil || l.SourcePath != oldSource {
continue
}
norm := utils.AddTrailingSlashIfNotExists(l.Path)
if !strings.Contains(norm, oldPath) {
rewrittenPath, matches := utils.RewritePathPrefix(l.Path, oldPath, newPath)
if !matches {
continue
}
removeShareFromPathIndexLocked(l.SourcePath, l.Path, l.Hash)
l.SourcePath = newSource
l.Path = newPath
l.Path = rewrittenPath
if err := sqlDb.SaveShare(l); err != nil {
logger.Error("failed to save updated share after resource move", "hash", l.Hash, "error", err)
+140
View File
@@ -0,0 +1,140 @@
package state
import (
"path/filepath"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/share"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/sqldb"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
)
// newShareMoveTestStore opens an isolated SQLite store, points the package-level
// sqlDb at it, and resets the share caches so shares can be seeded via CreateShare.
func newShareMoveTestStore(t *testing.T) *sqldb.SQLStore {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.sqlite")
store, _, err := sqldb.NewSQLStoreWithOptions(dbPath, sqldb.NewSQLStoreOpts{SkipQuickSetup: true})
if err != nil {
t.Fatal(err)
}
prevDB := sqlDb
prevByHash := sharesByHash
prevByPath := sharesByPath
sqlDb = store
sharesByHash = make(map[string]*share.Share)
sharesByPath = make(map[string][]string)
t.Cleanup(func() {
_ = store.Close()
sqlDb = prevDB
sharesByHash = prevByHash
sharesByPath = prevByPath
})
return store
}
func TestRewritePathPrefix(t *testing.T) {
cases := []struct {
name string
sharePath string
want string
matches bool
}{
{"file under moved dir", "/photos/2024/one.jpg", "/archive/photos/2024/one.jpg", true},
{"directory keeps trailing slash", "/photos/2024/", "/archive/photos/2024/", true},
{"exact dir match", "/photos/", "/archive/photos/", true},
{"exact file-form match", "/photos", "/archive/photos", true},
{"substring sibling does not match", "/backup/photos/", "/backup/photos/", false},
}
for _, tc := range cases {
got, matches := utils.RewritePathPrefix(tc.sharePath, "/photos/", "/archive/photos/")
if matches != tc.matches || got != tc.want {
t.Errorf("%s: RewritePathPrefix(%q) = (%q, %v), want (%q, %v)",
tc.name, tc.sharePath, got, matches, tc.want, tc.matches)
}
}
}
// TestUpdateSharesForMovedResource exercises the production updater end to end:
// seeded shares are rewritten in the cache, the path index, and SQL.
func TestUpdateSharesForMovedResource(t *testing.T) {
store := newShareMoveTestStore(t)
const oldSource = "/srv/photos"
const newSource = "/srv/archive"
seed := []share.Share{
{ShareColumns: share.ShareColumns{Hash: "file", Path: "/photos/2024/one.jpg"}, SourcePath: oldSource},
{ShareColumns: share.ShareColumns{Hash: "dir", Path: "/photos/2024/"}, SourcePath: oldSource},
{ShareColumns: share.ShareColumns{Hash: "exact", Path: "/photos/"}, SourcePath: oldSource},
{ShareColumns: share.ShareColumns{Hash: "sibling", Path: "/backup/photos/"}, SourcePath: oldSource},
{ShareColumns: share.ShareColumns{Hash: "othersrc", Path: "/photos/2024/"}, SourcePath: "/srv/other"},
}
for i := range seed {
s := seed[i]
if err := CreateShare(&s); err != nil {
t.Fatalf("seed share %s: %v", s.Hash, err)
}
}
updated, err := UpdateSharesForMovedResource(oldSource, "/photos", newSource, "/archive/photos/")
if err != nil {
t.Fatal(err)
}
updatedSet := make(map[string]bool, len(updated))
for _, h := range updated {
updatedSet[h] = true
}
for _, want := range []string{"file", "dir", "exact"} {
if !updatedSet[want] {
t.Fatalf("expected share %s in updated hashes %v", want, updated)
}
}
if len(updated) != 3 {
t.Fatalf("expected 3 updated shares, got %v", updated)
}
check := func(hash, wantPath, wantSource string) {
t.Helper()
s, getErr := GetShare(hash)
if getErr != nil {
t.Fatalf("GetShare(%s): %v", hash, getErr)
}
if s.Path != wantPath || s.SourcePath != wantSource {
t.Fatalf("share %s = (path %q, source %q), want (path %q, source %q)",
hash, s.Path, s.SourcePath, wantPath, wantSource)
}
}
check("file", "/archive/photos/2024/one.jpg", newSource)
check("dir", "/archive/photos/2024/", newSource)
check("exact", "/archive/photos/", newSource)
check("sibling", "/backup/photos/", oldSource)
check("othersrc", "/photos/2024/", "/srv/other")
// Writes went through to SQL, not just the cache.
persisted, err := store.ListAllShares()
if err != nil {
t.Fatal(err)
}
persistedPaths := make(map[string]string, len(persisted))
for _, l := range persisted {
persistedPaths[l.Hash] = l.Path
}
for hash, want := range map[string]string{
"file": "/archive/photos/2024/one.jpg",
"dir": "/archive/photos/2024/",
"exact": "/archive/photos/",
} {
if persistedPaths[hash] != want {
t.Fatalf("persisted share %s path = %q, want %q", hash, persistedPaths[hash], want)
}
}
// The path index tracks the new location.
moved, err := GetSharesByPath(newSource+"/", "/archive/photos/2024/")
if err != nil {
t.Fatal(err)
}
if len(moved) != 1 || moved[0].Hash != "dir" {
t.Fatalf("GetSharesByPath(new dir) = %+v, want dir share", moved)
}
}
+10
View File
@@ -189,6 +189,9 @@ func CreateUser(user *users.User, plaintextPassword string) error {
}
// Hash password if provided
if plaintextPassword != "" {
if err := settings.ValidatePasswordPolicy(plaintextPassword); err != nil {
return err
}
hashedPassword, err := utils.HashPwd(plaintextPassword)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
@@ -202,7 +205,11 @@ func CreateUser(user *users.User, plaintextPassword string) error {
}
// If still no BackendScopes (omitted or invalid API names), same defaults as ApplyUserDefaults.
preserveRequirePasswordChange := user.RequirePasswordChange
ApplyUserDefaults(user)
if preserveRequirePasswordChange {
user.RequirePasswordChange = true
}
defaults := EffectiveUserDefaults()
enforced := EffectiveEnforced()
settings.ApplyEnforcedDefaultsFrom(user, defaults, enforced)
@@ -289,6 +296,9 @@ func UpdateUser(user *users.User, plaintextPassword string, fields ...string) er
if plaintextPassword == "" {
return fmt.Errorf("password field requires a non-empty plaintext password")
}
if err := settings.ValidatePasswordPolicy(plaintextPassword); err != nil {
return err
}
hashedPassword, hashErr := utils.HashPwd(plaintextPassword)
if hashErr != nil {
return fmt.Errorf("failed to hash password: %w", hashErr)
+7 -2
View File
@@ -23,8 +23,13 @@ func FrontendLinks(links []users.SidebarLink, showToolsInSidebar bool) []users.S
}
if full, ok := settings.Config.Server.SourceMap[source.Path]; ok {
category := users.NormalizeSidebarLinkCategory(link.Category)
if full.Config.ResolvedRules.IndexingDisabled && category == string(users.SidebarLinkSource) {
link.Category = string(users.SidebarLinkSourceAlt)
if full.Config.ResolvedRules.IndexingDisabled &&
users.BaseSidebarLinkCategory(category) == string(users.SidebarLinkSource) {
if users.SidebarLinkDiskScopeRoot(category) {
link.Category = string(users.SidebarLinkSourceAltRoot)
} else {
link.Category = string(users.SidebarLinkSourceAlt)
}
}
}
link.SourceName = source.Name
+20
View File
@@ -84,3 +84,23 @@ func AddTrailingSlashIfNotExists(indexPath string) string {
}
return indexPath
}
// RewritePathPrefix rewrites sharePath when it is exactly oldPrefix or beneath it, swapping the
// prefix for newPrefix. Comparison is slash-aware (trailing slashes normalized), so a sibling path
// that merely shares a leading substring ("/backup/photos/" vs oldPrefix "/photos") does not match.
// A trailing slash on sharePath (directory convention) is preserved. Returns matches=false with the
// input unchanged on no match.
func RewritePathPrefix(sharePath, oldPrefix, newPrefix string) (rewritten string, matches bool) {
oldPrefix = AddTrailingSlashIfNotExists(oldPrefix)
newPrefix = AddTrailingSlashIfNotExists(newPrefix)
norm := AddTrailingSlashIfNotExists(sharePath)
if !strings.HasPrefix(norm, oldPrefix) {
return sharePath, false
}
suffix := strings.TrimPrefix(norm, oldPrefix)
rewritten = strings.TrimSuffix(newPrefix+suffix, "/")
if strings.HasSuffix(sharePath, "/") {
rewritten = AddTrailingSlashIfNotExists(rewritten)
}
return rewritten, true
}
+68
View File
@@ -1073,6 +1073,22 @@ func extractArchivedDir(destPath string, mode fs.FileMode, modTime time.Time) er
return applyArchivedTimesAndPerm(destPath, mode, modTime)
}
// removeSymlinkDestination removes destPath when it is a symlink so a regular-file
// write creates the entry at destPath instead of following the link.
func removeSymlinkDestination(destPath string) error {
info, err := os.Lstat(destPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if info.Mode()&fs.ModeSymlink == 0 {
return nil
}
return os.Remove(destPath)
}
// extractArchivedRegularFile writes one regular file from src (closed by this function) and reapplies mode and mtime.
func extractArchivedRegularFile(destPath string, mode fs.FileMode, modTime time.Time, src io.ReadCloser) error {
defer func() { _ = src.Close() }()
@@ -1080,6 +1096,9 @@ func extractArchivedRegularFile(destPath string, mode fs.FileMode, modTime time.
if err := os.MkdirAll(parent, fileutils.EffectiveDirPerm()); err != nil {
return fmt.Errorf("mkdir %q: %w", parent, err)
}
if err := removeSymlinkDestination(destPath); err != nil {
return err
}
perm := mode.Perm()
if perm == 0 {
perm = fileutils.EffectiveFilePerm()
@@ -1118,6 +1137,47 @@ func extractArchivedSymlink(destRoot, destPath, target string, modTime time.Time
return applyArchivedTimesAndPerm(destPath, fs.ModeSymlink, modTime)
}
// extractArchivedHardLink writes a copy of a regular file extracted earlier from the same
// archive, which is what a tar hard link entry stands for.
func extractArchivedHardLink(destRoot, destPath string, h *tar.Header, extracted map[string]os.FileInfo) error {
targetPath, err := safeExtractPath(destRoot, h.Linkname)
if err != nil {
return err
}
notExtracted := fmt.Errorf("hard link %q points to %q, which is not a file earlier in the archive", h.Name, h.Linkname)
written, ok := extracted[targetPath]
if !ok {
return notExtracted
}
src, err := os.Open(targetPath)
if err != nil {
logger.Debugf("unarchive: open hard link target: %v", err)
return fmt.Errorf("failed to write file from archive entry")
}
// A later entry may have replaced the target, e.g. with a symlink to another file.
info, err := src.Stat()
if err != nil || !info.Mode().IsRegular() || !os.SameFile(info, written) {
_ = src.Close()
return notExtracted
}
// The entry may name its own target, directly (GNU tar does this for a file archived
// twice). Writing it would truncate the file it copies from. Symlinks at destPath
// are replaced by extractArchivedRegularFile instead of being left in place.
if dest, err := os.Lstat(destPath); err == nil && dest.Mode().IsRegular() && os.SameFile(dest, info) {
return src.Close()
}
return extractArchivedRegularFile(destPath, h.FileInfo().Mode(), h.ModTime, src)
}
// recordExtractedFile remembers the regular file written at destPath for later hard links.
func recordExtractedFile(extracted map[string]os.FileInfo, destPath string) {
if info, err := os.Lstat(destPath); err == nil && info.Mode().IsRegular() {
extracted[destPath] = info
} else {
delete(extracted, destPath)
}
}
func extractZip(archivePath, destDir string) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
@@ -1221,6 +1281,8 @@ func extractTarGz(archivePath, destDir string) error {
defer gz.Close()
tr := tar.NewReader(gz)
// Regular files written so far, for hard links to point at.
extracted := make(map[string]os.FileInfo)
for {
h, err := tr.Next()
if err == io.EOF {
@@ -1246,6 +1308,12 @@ func extractTarGz(archivePath, destDir string) error {
if err = extractArchivedRegularFile(destPath, mode, h.ModTime, io.NopCloser(tr)); err != nil {
return err
}
recordExtractedFile(extracted, destPath)
case tar.TypeLink:
if err = extractArchivedHardLink(destDir, destPath, h, extracted); err != nil {
return err
}
recordExtractedFile(extracted, destPath)
case tar.TypeSymlink:
if err = extractArchivedSymlink(destDir, destPath, h.Linkname, h.ModTime); err != nil {
return err
+247
View File
@@ -1,13 +1,38 @@
package web
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
func writeTestTarGz(t *testing.T, path string, write func(tw *tar.Writer) error) {
t.Helper()
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
if err := write(tw); err != nil {
t.Fatal(err)
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
if err := gz.Close(); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
}
func TestNormalizeArchiveEntryName(t *testing.T) {
t.Parallel()
@@ -279,6 +304,228 @@ func TestExtractZip_nestedBackslashes(t *testing.T) {
}
}
func TestExtractTarGz_hardLinks(t *testing.T) {
archivePath := filepath.Join(t.TempDir(), "links.tar.gz")
writeTestTarGz(t, archivePath, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "proj/a.txt", Mode: 0o644, Size: 4, Typeflag: tar.TypeReg}); err != nil {
return err
}
if _, err := io.WriteString(tw, "same"); err != nil {
return err
}
return tw.WriteHeader(&tar.Header{Name: "proj/sub/b.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "proj/a.txt"})
})
destDir := t.TempDir()
if err := extractTarGz(archivePath, destDir); err != nil {
t.Fatalf("extract: %v", err)
}
got, err := os.ReadFile(filepath.Join(destDir, "proj", "sub", "b.txt"))
if err != nil || string(got) != "same" {
t.Fatalf("hard link entry: got %q, %v", got, err)
}
missing := filepath.Join(t.TempDir(), "missing.tar.gz")
writeTestTarGz(t, missing, func(tw *tar.Writer) error {
return tw.WriteHeader(&tar.Header{Name: "b.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "a.txt"})
})
if err := extractTarGz(missing, t.TempDir()); err == nil {
t.Fatal("expected an error for a hard link to a file that is not in the archive")
}
// A symlink entry replaces the extracted file before the hard link names it.
replaced := filepath.Join(t.TempDir(), "replaced.tar.gz")
writeTestTarGz(t, replaced, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "a.txt", Mode: 0o644, Size: 4, Typeflag: tar.TypeReg}); err != nil {
return err
}
if _, err := io.WriteString(tw, "mine"); err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: "a.txt", Mode: 0o777, Typeflag: tar.TypeSymlink, Linkname: "private/secret.txt"}); err != nil {
return err
}
return tw.WriteHeader(&tar.Header{Name: "b.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "a.txt"})
})
replacedDest := t.TempDir()
if err := os.MkdirAll(filepath.Join(replacedDest, "private"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(replacedDest, "private", "secret.txt"), []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
if err := extractTarGz(replaced, replacedDest); err == nil {
t.Fatal("expected an error for a hard link whose target was replaced by a symlink")
}
if got, err := os.ReadFile(filepath.Join(replacedDest, "b.txt")); err == nil {
t.Fatalf("hard link entry copied the symlink target: %q", got)
}
// A hard link names its own target, as GNU tar writes for a file archived twice,
// or names it through a symlink.
self := filepath.Join(t.TempDir(), "self.tar.gz")
writeTestTarGz(t, self, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "a.txt", Mode: 0o644, Size: 4, Typeflag: tar.TypeReg}); err != nil {
return err
}
if _, err := io.WriteString(tw, "same"); err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: "c.txt", Mode: 0o777, Typeflag: tar.TypeSymlink, Linkname: "a.txt"}); err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: "a.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "a.txt"}); err != nil {
return err
}
return tw.WriteHeader(&tar.Header{Name: "c.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "a.txt"})
})
selfDest := t.TempDir()
if err := extractTarGz(self, selfDest); err != nil {
t.Fatalf("extract: %v", err)
}
if got, err := os.ReadFile(filepath.Join(selfDest, "a.txt")); err != nil || string(got) != "same" {
t.Fatalf("hard link to itself: got %q, %v", got, err)
}
}
func TestExtractTarGz_symlinkDestination(t *testing.T) {
t.Run("pre-existing symlink at destination", func(t *testing.T) {
destDir := t.TempDir()
victim := filepath.Join(destDir, "victim.txt")
if err := os.WriteFile(victim, []byte("untouched"), 0o644); err != nil {
t.Fatal(err)
}
outPath := filepath.Join(destDir, "out.txt")
if err := os.Symlink("victim.txt", outPath); err != nil {
t.Fatal(err)
}
archivePath := filepath.Join(t.TempDir(), "out.tar.gz")
writeTestTarGz(t, archivePath, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "out.txt", Mode: 0o644, Size: 7, Typeflag: tar.TypeReg}); err != nil {
return err
}
_, err := io.WriteString(tw, "payload")
return err
})
if err := extractTarGz(archivePath, destDir); err != nil {
t.Fatalf("extract: %v", err)
}
got, err := os.ReadFile(outPath)
if err != nil || string(got) != "payload" {
t.Fatalf("out.txt: got %q, %v", got, err)
}
victimData, err := os.ReadFile(victim)
if err != nil || string(victimData) != "untouched" {
t.Fatalf("victim.txt should be unchanged: %q, %v", victimData, err)
}
info, err := os.Lstat(outPath)
if err != nil || info.Mode()&os.ModeSymlink != 0 {
t.Fatalf("out.txt should be a regular file, mode=%v err=%v", info.Mode(), err)
}
})
t.Run("symlink entry then regular file at same path", func(t *testing.T) {
destDir := t.TempDir()
other := filepath.Join(destDir, "other.txt")
if err := os.WriteFile(other, []byte("keep"), 0o644); err != nil {
t.Fatal(err)
}
archivePath := filepath.Join(t.TempDir(), "link_then_reg.tar.gz")
writeTestTarGz(t, archivePath, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "link", Mode: 0o777, Typeflag: tar.TypeSymlink, Linkname: "other.txt"}); err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: "link", Mode: 0o644, Size: 7, Typeflag: tar.TypeReg}); err != nil {
return err
}
_, err := io.WriteString(tw, "written")
return err
})
if err := extractTarGz(archivePath, destDir); err != nil {
t.Fatalf("extract: %v", err)
}
linkPath := filepath.Join(destDir, "link")
got, err := os.ReadFile(linkPath)
if err != nil || string(got) != "written" {
t.Fatalf("link: got %q, %v", got, err)
}
otherData, err := os.ReadFile(other)
if err != nil || string(otherData) != "keep" {
t.Fatalf("other.txt should be unchanged: %q, %v", otherData, err)
}
})
t.Run("hard link onto symlink to source", func(t *testing.T) {
destDir := t.TempDir()
archivePath := filepath.Join(t.TempDir(), "hardlink_symlink_dest.tar.gz")
writeTestTarGz(t, archivePath, func(tw *tar.Writer) error {
if err := tw.WriteHeader(&tar.Header{Name: "a.txt", Mode: 0o644, Size: 4, Typeflag: tar.TypeReg}); err != nil {
return err
}
if _, err := io.WriteString(tw, "same"); err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: "b.txt", Mode: 0o777, Typeflag: tar.TypeSymlink, Linkname: "a.txt"}); err != nil {
return err
}
return tw.WriteHeader(&tar.Header{Name: "c.txt", Mode: 0o644, Typeflag: tar.TypeLink, Linkname: "a.txt"})
})
if err := extractTarGz(archivePath, destDir); err != nil {
t.Fatalf("extract: %v", err)
}
cPath := filepath.Join(destDir, "c.txt")
got, err := os.ReadFile(cPath)
if err != nil || string(got) != "same" {
t.Fatalf("c.txt: got %q, %v", got, err)
}
info, err := os.Lstat(cPath)
if err != nil || info.Mode()&os.ModeSymlink != 0 {
t.Fatalf("c.txt should be a regular file")
}
})
}
func TestExtractZip_symlinkDestination(t *testing.T) {
destDir := t.TempDir()
victim := filepath.Join(destDir, "victim.txt")
if err := os.WriteFile(victim, []byte("untouched"), 0o644); err != nil {
t.Fatal(err)
}
outPath := filepath.Join(destDir, "out.txt")
if err := os.Symlink("victim.txt", outPath); err != nil {
t.Fatal(err)
}
zipPath := filepath.Join(t.TempDir(), "out.zip")
f, err := os.Create(zipPath)
if err != nil {
t.Fatal(err)
}
zw := zip.NewWriter(f)
w, err := zw.Create("out.txt")
if err != nil {
t.Fatal(err)
}
if _, err = w.Write([]byte("payload")); err != nil {
t.Fatal(err)
}
if err = zw.Close(); err != nil {
t.Fatal(err)
}
if err = f.Close(); err != nil {
t.Fatal(err)
}
if err = extractZip(zipPath, destDir); err != nil {
t.Fatalf("extract: %v", err)
}
got, err := os.ReadFile(outPath)
if err != nil || string(got) != "payload" {
t.Fatalf("out.txt: got %q, %v", got, err)
}
victimData, err := os.ReadFile(victim)
if err != nil || string(victimData) != "untouched" {
t.Fatalf("victim.txt should be unchanged: %q, %v", victimData, err)
}
}
// Benchmarks (optional, keep small)
func BenchmarkNormalizeArchiveEntryName(b *testing.B) {
const name = `PRO1000\Winx64\NDIS65\e1c65x64.cat`
+97 -23
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/golang-jwt/jwt/v4/request"
"golang.org/x/crypto/bcrypt"
@@ -80,6 +81,10 @@ func ExtractToken(r *http.Request) (string, error) {
// getOrCreateAuthenticatedUser is a common helper for retrieving or auto-creating users
// across different authentication methods (proxy, JWT, LDAP, OIDC)
func getOrCreateAuthenticatedUser(username string, loginMethod users.LoginMethod, isAdmin bool, groups []string) (*users.User, error) {
if err := ensureUserInAllowedGroups(loginMethod, groups); err != nil {
return nil, err
}
// Try to get existing user
userValue, err := state.GetUserByUsername(username)
if err != nil {
@@ -113,27 +118,6 @@ func getOrCreateAuthenticatedUser(username string, loginMethod users.LoginMethod
return nil, err
}
}
allowedGroups := []string{}
switch loginMethod {
case users.LoginMethodJwt:
allowedGroups = settings.Config.Auth.Methods.JwtAuth.UserGroups
case users.LoginMethodLdap:
allowedGroups = settings.Config.Auth.Methods.LdapAuth.UserGroups
case users.LoginMethodOidc:
allowedGroups = settings.Config.Auth.Methods.OidcAuth.UserGroups
}
allowed := len(allowedGroups) == 0
for _, userGroup := range groups {
for _, allowedGroup := range allowedGroups {
if userGroup == allowedGroup {
allowed = true
break
}
}
}
if !allowed {
return nil, fmt.Errorf("user is not in allowed groups")
}
// Sync admin status if needed (in case admin username changed)
if isAdmin && !userValue.Permissions.Admin {
userValue.Permissions.Admin = true
@@ -159,6 +143,36 @@ func getOrCreateAuthenticatedUser(username string, loginMethod users.LoginMethod
return &userValue, nil
}
// ensureUserInAllowedGroups rejects login when userGroups is configured and none
// of the IdP groups are allowed. Must run before auto-create so denied users
// leave no account behind.
func ensureUserInAllowedGroups(loginMethod users.LoginMethod, groups []string) error {
allowedGroups := []string{}
switch loginMethod {
case users.LoginMethodJwt:
allowedGroups = settings.Config.Auth.Methods.JwtAuth.UserGroups
case users.LoginMethodLdap:
allowedGroups = settings.Config.Auth.Methods.LdapAuth.UserGroups
case users.LoginMethodOidc:
allowedGroups = settings.Config.Auth.Methods.OidcAuth.UserGroups
}
if len(allowedGroups) == 0 {
return nil
}
for _, userGroup := range groups {
for _, allowedGroup := range allowedGroups {
if loginMethod == users.LoginMethodLdap {
if ldapGroupMatches(userGroup, allowedGroup) {
return nil
}
} else if userGroup == allowedGroup {
return nil
}
}
}
return fmt.Errorf("user is not in allowed groups")
}
func SetupProxyUser(r *http.Request, data *Context, proxyUser string) (*users.User, error) {
// Check if username matches admin username
isAdmin := proxyUser == settings.Config.Auth.AdminUsername
@@ -207,6 +221,9 @@ func loginHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, erro
if d.User.HasPasskeyMFA() && d.User.TOTPSecret == "" {
return http.StatusForbidden, errors.ErrPasskeyMFARequired
}
if passwordUser && d.User.RequirePasswordChange {
return http.StatusForbidden, errors.ErrPasswordChangeRequired
}
status, err := printToken(w, r, d.User, "")
if err != nil || status != 0 {
return status, err
@@ -307,6 +324,9 @@ func signupHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, err
if username == "" || password == "" {
return http.StatusBadRequest, fmt.Errorf("username and password are required")
}
if err := settings.ValidatePasswordPolicy(password); err != nil {
return http.StatusBadRequest, err
}
user := users.User{
FrontendUser: users.FrontendUser{
@@ -355,12 +375,66 @@ func parseSignupCredentials(r *http.Request) (username, password string, err err
// @Produce json
// @Success 200 {string} string "New JWT token generated"
// @Failure 401 {object} map[string]string "Unauthorized - invalid token"
// @Failure 403 {object} map[string]string "Forbidden - non-session token"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/auth/renew [post]
func renewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
if settings.Config.Auth.Methods.NoAuth {
w.Header().Set("Content-Type", "text/plain")
if d.Token != "" {
if _, err := w.Write([]byte(d.Token)); err != nil {
return 401, errors.ErrUnauthorized
}
}
return 0, nil
}
token := d.Token
if token == "" {
extracted, err := ExtractToken(r)
if err != nil || extracted == "" {
return http.StatusUnauthorized, errors.ErrUnauthorized
}
token = extracted
d.Token = token
}
_, isSession, ok := state.HashedTokenOwner(token)
if ok && !isSession {
return http.StatusForbidden, fmt.Errorf("renew requires a session token")
}
if !ok {
return http.StatusUnauthorized, errors.ErrUnauthorized
}
// Renew is idempotent while the presented session token is still fresh:
// without this every page load rotates the token (the frontend tracks exp
// in memory only), churning token state. Rotation happens only inside the
// refresh window, matching the frontend's renew threshold.
var tk users.AuthToken
if _, err := jwt.ParseWithClaims(d.Token, &tk, auth.JWTSigningKeyFunc()); err == nil &&
tk.RegisteredClaims.ExpiresAt != nil &&
time.Until(tk.RegisteredClaims.ExpiresAt.Time) > sessionRenewWindow {
// Do not re-emit the cookie when the request already carried this token.
// A concurrent renew may have rotated the jar; an in-flight idempotent
// response would otherwise revert the browser to a retiring token.
if c, err := r.Cookie(sessionCookieName); err != nil || c.Value == "" || c.Value != d.Token {
SetSessionCookie(w, r, d.Token, tk.RegisteredClaims.ExpiresAt.Add(sessionCookieBuffer))
}
w.Header().Set("Content-Type", "text/plain")
if _, err := w.Write([]byte(d.Token)); err != nil {
return 401, errors.ErrUnauthorized
}
return 0, nil
}
return printToken(w, r, d.User, d.Token)
}
// sessionRenewWindow mirrors the frontend SESSION_REFRESH_BEFORE_MS: renews
// arriving while the session token has more than this left return it unchanged.
const sessionRenewWindow = 30 * time.Minute
// sessionCookieBuffer keeps the browser cookie briefly past JWT expiry so an
// in-flight renew can still authenticate against the just-expired token.
const sessionCookieBuffer = 30 * time.Minute
func printToken(w http.ResponseWriter, r *http.Request, user *users.User, priorToken string) (int, error) {
expires := time.Hour * time.Duration(settings.Config.Auth.TokenExpirationHours)
tokenString, err := replaceSessionToken(priorToken, user)
@@ -371,7 +445,7 @@ func printToken(w http.ResponseWriter, r *http.Request, user *users.User, priorT
return 401, errors.ErrUnauthorized
}
expiresTime := time.Now().Add(expires).Add(time.Minute * 30)
expiresTime := time.Now().Add(expires).Add(sessionCookieBuffer)
SetSessionCookie(w, r, tokenString, expiresTime)
@@ -513,7 +587,7 @@ func applyNamedApiTokenGlobalCaps(user *users.User, tokenName string) {
if !ok {
return
}
if !users.HasAnyGlobalPermission(stored.Permissions) {
if users.IsMinimalApiToken(stored) {
return
}
user.Permissions = users.IntersectGlobalPermissions(user.Permissions, stored.Permissions)
+74 -1
View File
@@ -61,6 +61,79 @@ func TestGetOrCreateAuthenticatedUserRejectsPasswordUserForOIDCAccount(t *testin
}
}
func TestGetOrCreateAuthenticatedUserLDAPUserGroupsCNMatch(t *testing.T) {
setupTestEnv(t)
orig := settings.Config.Auth.Methods.LdapAuth.UserGroups
settings.Config.Auth.Methods.LdapAuth.UserGroups = []string{"employees"}
t.Cleanup(func() {
settings.Config.Auth.Methods.LdapAuth.UserGroups = orig
})
ldapUser := &users.User{
FrontendUser: users.FrontendUser{
Username: "ldap-user",
LoginMethod: users.LoginMethodLdap,
},
}
if err := state.CreateUser(ldapUser, ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
groups := []string{"cn=Employees,ou=groups,dc=example,dc=com"}
_, err := getOrCreateAuthenticatedUser("ldap-user", users.LoginMethodLdap, false, groups)
if err != nil {
t.Fatalf("getOrCreateAuthenticatedUser() with CN-only userGroups: %v", err)
}
}
func TestGetOrCreateAuthenticatedUserLDAPUserGroupsDenied(t *testing.T) {
setupTestEnv(t)
orig := settings.Config.Auth.Methods.LdapAuth.UserGroups
settings.Config.Auth.Methods.LdapAuth.UserGroups = []string{"employees"}
t.Cleanup(func() {
settings.Config.Auth.Methods.LdapAuth.UserGroups = orig
})
ldapUser := &users.User{
FrontendUser: users.FrontendUser{
Username: "ldap-user",
LoginMethod: users.LoginMethodLdap,
},
}
if err := state.CreateUser(ldapUser, ""); err != nil {
t.Fatalf("CreateUser: %v", err)
}
groups := []string{"cn=Contractors,ou=groups,dc=example,dc=com"}
_, err := getOrCreateAuthenticatedUser("ldap-user", users.LoginMethodLdap, false, groups)
if err == nil || err.Error() != "user is not in allowed groups" {
t.Fatalf("getOrCreateAuthenticatedUser() err = %v, want user is not in allowed groups", err)
}
}
func TestGetOrCreateAuthenticatedUserLDAPDeniedFirstLoginCreatesNoAccount(t *testing.T) {
setupTestEnv(t)
orig := settings.Config.Auth.Methods.LdapAuth.UserGroups
settings.Config.Auth.Methods.LdapAuth.UserGroups = []string{"employees"}
t.Cleanup(func() {
settings.Config.Auth.Methods.LdapAuth.UserGroups = orig
})
groups := []string{"cn=Contractors,ou=groups,dc=example,dc=com"}
_, err := getOrCreateAuthenticatedUser("denied-ldap-user", users.LoginMethodLdap, false, groups)
if err == nil || err.Error() != "user is not in allowed groups" {
t.Fatalf("getOrCreateAuthenticatedUser() err = %v, want user is not in allowed groups", err)
}
_, getErr := state.GetUserByUsername("denied-ldap-user")
if !errors.Is(getErr, fberrors.ErrNotExist) {
t.Fatalf("GetUserByUsername after denied login: %v, want ErrNotExist", getErr)
}
}
func TestAuthenticatePasswordRejectsWrongLoginMethod(t *testing.T) {
setupTestEnv(t)
@@ -77,7 +150,7 @@ func TestAuthenticatePasswordRejectsWrongLoginMethod(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/auth/login?username=graham", nil)
req.Header.Set("X-Password", url.QueryEscape("secret"))
_, err := auth.AuthenticatePassword(req, true)
_, err := auth.AuthenticatePassword(req, true, false)
if !errors.Is(err, fberrors.ErrWrongLoginMethod) {
t.Fatalf("AuthenticatePassword() err = %v, want ErrWrongLoginMethod", err)
}
+18
View File
@@ -197,9 +197,11 @@ func TestApplyNamedApiTokenGlobalCaps(t *testing.T) {
t.Run("custom api token caps globals", func(t *testing.T) {
user := *owner
customized := false
user.Tokens = map[string]users.AuthToken{
"customized": {
Name: "customized",
Minimal: &customized,
Permissions: users.Permissions{
Admin: false,
Api: true,
@@ -216,4 +218,20 @@ func TestApplyNamedApiTokenGlobalCaps(t *testing.T) {
t.Fatalf("expected api and share, got %#v", user.Permissions)
}
})
t.Run("customized zero global caps", func(t *testing.T) {
user := *owner
customized := false
user.Tokens = map[string]users.AuthToken{
"locked-down": {
Name: "locked-down",
Minimal: &customized,
Permissions: users.Permissions{},
},
}
applyNamedApiTokenGlobalCaps(&user, "locked-down")
if user.Permissions.Admin || user.Permissions.Api || user.Permissions.Share {
t.Fatalf("customized empty caps should clear globals, got %#v", user.Permissions)
}
})
}
@@ -0,0 +1,40 @@
package web
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
)
func createTokenAuthUser(t *testing.T, username string, perms users.Permissions) *users.User {
t.Helper()
u := &users.User{FrontendUser: users.FrontendUser{Username: username}}
if err := state.CreateUser(u, ""); err != nil {
t.Fatal(err)
}
stored, err := state.GetUserByUsername(username)
if err != nil {
t.Fatal(err)
}
stored.Permissions = perms
if err = state.UpdateUser(&stored, "", "permissions"); err != nil {
t.Fatal(err)
}
reloaded, err := state.GetUserByUsername(username)
if err != nil {
t.Fatal(err)
}
return &reloaded
}
func cookieRequest(t *testing.T, handler http.HandlerFunc, token string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/users", http.NoBody)
req.AddCookie(&http.Cookie{Name: "filebrowser_quantum_jwt", Value: token})
handler(rec, req)
return rec
}
+53 -19
View File
@@ -151,25 +151,8 @@ func downloadHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, e
// @Failure 501 {object} map[string]string "Downloads disabled for upload shares"
// @Router /public/api/resources/download [get]
func publicDownloadHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("downloads are disabled for upload shares")
}
if d.Share.DisableDownload {
return http.StatusForbidden, fmt.Errorf("downloads are not allowed for this share")
}
if !d.Share.PerUserDownloadLimit && d.Share.DownloadsLimit > 0 && d.Share.Downloads >= d.Share.DownloadsLimit {
return http.StatusForbidden, fmt.Errorf("share downloads limit reached")
}
if d.Share.PerUserDownloadLimit {
if d.User.Username == "anonymous" {
return http.StatusForbidden, fmt.Errorf("anonymous downloads are not allowed with per-user limits")
}
if d.Share.HasReachedUserLimit(d.User.Username) {
return http.StatusForbidden, fmt.Errorf("user download limit reached for this share")
}
if status, err := publicShareDownloadGate(d); err != nil {
return status, err
}
files := r.URL.Query()["file"]
@@ -213,6 +196,57 @@ func publicDownloadHandler(w http.ResponseWriter, r *http.Request, d *Context) (
return status, nil
}
// publicShareDownloadGate enforces upload-share, disable-download, and download-counter rules for public share byte egress.
func publicShareDownloadGate(d *Context) (int, error) {
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("downloads are disabled for upload shares")
}
if d.Share.DisableDownload {
return http.StatusForbidden, fmt.Errorf("downloads are not allowed for this share")
}
if status, err := publicShareDownloadLimits(d); err != nil {
return status, err
}
return 0, nil
}
func publicShareDownloadLimits(d *Context) (int, error) {
if !d.Share.PerUserDownloadLimit && d.Share.DownloadsLimit > 0 && d.Share.Downloads >= d.Share.DownloadsLimit {
return http.StatusForbidden, fmt.Errorf("share downloads limit reached")
}
if d.Share.PerUserDownloadLimit {
if d.User.Username == "anonymous" {
return http.StatusForbidden, fmt.Errorf("anonymous downloads are not allowed with per-user limits")
}
if d.Share.HasReachedUserLimit(d.User.Username) {
return http.StatusForbidden, fmt.Errorf("user download limit reached for this share")
}
}
return 0, nil
}
// publicShareMediaContentPolicy applies the same share view/download flags and download limits as other public content routes.
func publicShareMediaContentPolicy(d *Context) (int, error) {
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("browsing is disabled for upload shares")
}
sourceInfo, ok := settings.Config.Server.SourceMap[d.Share.SourcePath]
if !ok {
return http.StatusNotFound, fmt.Errorf("source not found")
}
filePerms, err := effectiveFilePerms(d, sourceInfo.Name)
if err != nil {
return http.StatusForbidden, err
}
if !filePerms.View {
return http.StatusForbidden, fmt.Errorf("user is not allowed to view files in this source")
}
if !filePerms.Download {
return http.StatusForbidden, fmt.Errorf("downloads are not allowed for this share")
}
return publicShareDownloadLimits(d)
}
func RawFilesHandler(w http.ResponseWriter, r *http.Request, d *Context, source string, fileList []string) (int, error) {
if d.Share.Hash == "" {
filePerms, err := effectiveFilePerms(d, source)
+1 -1
View File
@@ -203,7 +203,7 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *Context) (int,
// Generate cache key from all input parameters that affect results
// Checksums are always enabled, so cache key doesn't need to include that flag
cacheKey := fmt.Sprintf("%s:%s:%d", index.Path, opts.combinedPath, opts.minSize)
cacheKey := fmt.Sprintf("%s:%s:%s:%d", index.Path, opts.combinedPath, opts.username, opts.minSize)
// Check cache first (before acquiring mutex)
if cachedResults, ok := duplicateResultsCache.Get(cacheKey); ok {
+5 -2
View File
@@ -242,8 +242,11 @@ func GetRemoteIP(r *http.Request) string {
xff := r.Header.Get("X-Forwarded-For")
if cfg.Http.TrustProxyHeaders && xff != "" {
ips := strings.Split(xff, ",")
return strings.TrimSpace(ips[0])
// Use the rightmost hop: the trusted proxy appends the connecting client, so the
// leftmost value is attacker-controlled when clients send X-Forwarded-For.
if ip := lastForwardedValue(xff); ip != "" {
return ip
}
}
xri := r.Header.Get("X-Real-IP")
+1
View File
@@ -35,6 +35,7 @@ func configureHTTPRouter(router, api, publicRoutes, publicApi *http.ServeMux) {
// Auth Routes - /api/auth/
// ========================================
api.HandleFunc("POST /auth/login", withRateLimit(AuthRateLimitCredentialLockout, loginHelper(loginHandler)))
api.HandleFunc("POST /auth/password/change-required", withoutUser(withRateLimitChain(AuthRateLimitCredentialLockout, changeRequiredPasswordHandler)))
api.HandleFunc("POST /auth/logout", withOrWithoutUser(withRateLimitChain(AuthRateLimitModerate, logoutHandler)))
api.HandleFunc("POST /auth/signup", withoutUser(withRateLimitChain(AuthRateLimitModerate, signupHandler)))
api.HandleFunc("POST /auth/otp/generate", withOrWithoutUser(withRateLimitChain(AuthRateLimitModerate, generateOTPHandler)))
+48 -36
View File
@@ -158,56 +158,68 @@ func pickUserEntry(entries []*ldap.Entry) *ldap.Entry {
return user
}
// ldapGroupMatchesAdmin returns true if the LDAP group DN matches the configured admin group (full DN or CN value).
func ldapGroupMatchesAdmin(groupDN, adminGroup string) bool {
g := strings.TrimSpace(groupDN)
if g == adminGroup {
return true
}
dn, err := ldap.ParseDN(g)
if err != nil {
// ldapGroupMatches reports whether an LDAP group membership value matches a
// configured group. Matching is case-insensitive and accepts a full DN or a
// CN-only value. When both sides are DNs, the complete DN must match (case-
// insensitive); CN-only fallback applies only when one side is not a DN, so
// groups that share a CN under different parents cannot authorize each other.
func ldapGroupMatches(member, configured string) bool {
member = strings.TrimSpace(member)
configured = strings.TrimSpace(configured)
if configured == "" {
return false
}
for _, rdn := range dn.RDNs {
for _, attr := range rdn.Attributes {
if strings.EqualFold(attr.Type, "cn") && attr.Value == adminGroup {
return true
}
}
if strings.EqualFold(member, configured) {
return true
}
memberIsDN := ldapIsDN(member)
configuredIsDN := ldapIsDN(configured)
memberCN := ldapCN(member)
configuredCN := ldapCN(configured)
// Config CN-only vs member full DN.
if memberIsDN && !configuredIsDN && memberCN != "" && strings.EqualFold(memberCN, configured) {
return true
}
// Config full DN vs member CN-only.
if configuredIsDN && !memberIsDN && configuredCN != "" && strings.EqualFold(member, configuredCN) {
return true
}
return false
}
// ldapIsDN reports whether s parses as an LDAP distinguished name.
func ldapIsDN(s string) bool {
_, err := ldap.ParseDN(s)
return err == nil
}
// ldapCN returns the first CN RDN value from an LDAP DN string, or "" if none.
func ldapCN(s string) string {
dn, err := ldap.ParseDN(s)
if err != nil {
return ""
}
for _, rdn := range dn.RDNs {
for _, attr := range rdn.Attributes {
if strings.EqualFold(attr.Type, "cn") {
return attr.Value
}
}
}
return ""
}
// getOrCreateLdapUser returns the filebrowser user for an LDAP-authenticated username, creating one if configured.
// userGroups authorization is enforced in getOrCreateAuthenticatedUser via ldapGroupMatches.
func getOrCreateLdapUser(username string, groups []string) (*users.User, error) {
logger.Debugf("getting or creating ldap user %s", username)
ldapCfg := settings.Config.Auth.Methods.LdapAuth
// Check if user is in required groups (if userGroups is configured)
if len(ldapCfg.UserGroups) > 0 {
userInAllowedGroup := false
for _, allowedGroup := range ldapCfg.UserGroups {
for _, userGroup := range groups {
if ldapGroupMatchesAdmin(userGroup, allowedGroup) {
userInAllowedGroup = true
break
}
}
if userInAllowedGroup {
break
}
}
if !userInAllowedGroup {
logger.Warningf("User %s is not in any of the required groups %v. Access denied.", username, ldapCfg.UserGroups)
return nil, fmt.Errorf("user %s is not authorized to access this application (not in required groups)", username)
}
logger.Debugf("User %s is in required group, allowing access.", username)
}
isAdmin := false
if ldapCfg.AdminGroup != "" {
for _, g := range groups {
if ldapGroupMatchesAdmin(g, ldapCfg.AdminGroup) {
if ldapGroupMatches(g, ldapCfg.AdminGroup) {
isAdmin = true
break
}
+44 -20
View File
@@ -90,61 +90,85 @@ func TestPickUserEntry(t *testing.T) {
}
}
func TestLdapGroupMatchesAdmin(t *testing.T) {
func TestLdapGroupMatches(t *testing.T) {
tests := []struct {
name string
groupDN string
adminGroup string
member string
configured string
want bool
}{
{
name: "exact DN match",
groupDN: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
adminGroup: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
member: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
configured: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
want: true,
},
{
name: "CN match",
groupDN: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
adminGroup: "authentik Admins",
member: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
configured: "authentik Admins",
want: true,
},
{
name: "CN match case-insensitive",
member: "cn=it department,ou=groups,dc=example,dc=com",
configured: "IT Department",
want: true,
},
{
name: "full DN match case-insensitive",
member: "CN=Employees,OU=Groups,DC=Example,DC=COM",
configured: "cn=employees,ou=groups,dc=example,dc=com",
want: true,
},
{
name: "config full DN vs member CN-only",
member: "Employees",
configured: "cn=Employees,ou=groups,dc=example,dc=com",
want: true,
},
{
name: "CN no match",
groupDN: "cn=Other Group,ou=groups,dc=test",
adminGroup: "authentik Admins",
member: "cn=Other Group,ou=groups,dc=test",
configured: "authentik Admins",
want: false,
},
{
name: "exact no match",
groupDN: "cn=admins,ou=groups,dc=test",
adminGroup: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
member: "cn=admins,ou=groups,dc=test",
configured: "cn=authentik Admins,ou=groups,dc=ldap,dc=goauthentik,dc=io",
want: false,
},
{
name: "same CN different parents rejected",
member: "cn=Admins,ou=Other,dc=example,dc=com",
configured: "cn=Admins,ou=Privileged,dc=example,dc=com",
want: false,
},
{
name: "whitespace trimmed",
groupDN: " cn=admins,ou=groups,dc=test ",
adminGroup: "cn=admins,ou=groups,dc=test",
member: " cn=admins,ou=groups,dc=test ",
configured: "cn=admins,ou=groups,dc=test",
want: true,
},
{
name: "invalid DN returns false",
groupDN: "not-a-valid-dn",
adminGroup: "admins",
member: "not-a-valid-dn",
configured: "admins",
want: false,
},
{
name: "empty adminGroup no match",
groupDN: "cn=admins,ou=groups,dc=test",
adminGroup: "",
name: "empty configured no match",
member: "cn=admins,ou=groups,dc=test",
configured: "",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ldapGroupMatchesAdmin(tt.groupDN, tt.adminGroup)
got := ldapGroupMatches(tt.member, tt.configured)
if got != tt.want {
t.Errorf("ldapGroupMatchesAdmin(%q, %q) = %v, want %v", tt.groupDN, tt.adminGroup, got, tt.want)
t.Errorf("ldapGroupMatches(%q, %q) = %v, want %v", tt.member, tt.configured, got, tt.want)
}
})
}
+23 -35
View File
@@ -2,7 +2,6 @@ package web
import (
"bytes"
"errors"
"fmt"
"net/http"
"path/filepath"
@@ -242,7 +241,15 @@ func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *Context) (
func lyricsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
path := r.URL.Query().Get("path")
source := r.URL.Query().Get("source")
if path == "" || source == "" {
fileUser := d.User
if d.Share.Hash != "" {
source = d.Share.GetSourceName()
if source == "" {
return http.StatusNotFound, fmt.Errorf("source not found")
}
path = d.IndexPath
fileUser = d.ShareUser
} else if path == "" || source == "" {
return http.StatusBadRequest, fmt.Errorf("path and source are required")
}
filePerms, err := effectiveFilePerms(d, source)
@@ -253,17 +260,22 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, err
return http.StatusForbidden, fmt.Errorf("user is not allowed to view files in this source")
}
showHidden := d.User.ShowHidden
hideFileExt := d.User.HideFileExt
if d.Share.Hash != "" {
showHidden = d.Share.ShowHidden
}
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
FollowSymlinks: true,
FollowSymlinks: d.Share.Hash == "",
Path: path,
Source: source,
Expand: true,
Content: false,
Metadata: false,
ShowHidden: d.User.ShowHidden,
HideFileExt: d.User.HideFileExt,
ShowHidden: showHidden,
HideFileExt: hideFileExt,
SkipExtendedAttrs: false,
}, d.User)
}, fileUser)
if err != nil {
return ErrToStatus(err), err
}
@@ -289,34 +301,10 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, err
// @Failure 404 {object} map[string]string "Not found"
// @Router /public/api/media/lyrics [get]
func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
sourceCfg, ok := settings.Config.Server.SourceMap[d.Share.SourcePath]
if !ok {
return http.StatusNotFound, fmt.Errorf("source not found")
if status, err := publicShareMediaContentPolicy(d); err != nil {
return status, err
}
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Path: d.IndexPath,
Source: sourceCfg.Name,
Expand: true,
Content: false,
Metadata: false,
ShowHidden: d.Share.ShowHidden,
HideFileExt: d.User.HideFileExt,
FollowSymlinks: false,
SkipExtendedAttrs: false,
}, d.ShareUser)
if err != nil {
return ErrToStatus(err), err
}
if !strings.HasPrefix(fileInfo.Type, "audio") {
return http.StatusNotFound, fmt.Errorf("file is not an audio file")
}
lyrics, err := files.ExtractLyrics(fileInfo.RealPath)
if err != nil {
return http.StatusInternalServerError, errors.New("failed to extract lyrics")
}
return RenderJSON(w, r, map[string]any{"lyrics": lyrics})
return lyricsHandler(w, r, d)
}
// publicSubtitlesHandler is the share-link variant of subtitlesHandler.
@@ -330,8 +318,8 @@ func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *Context) (in
// @Success 200 {string} string "Raw subtitle content"
// @Router /public/api/media/subtitles [get]
func publicSubtitlesHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("browsing is disabled for upload shares")
if status, err := publicShareMediaContentPolicy(d); err != nil {
return status, err
}
return subtitlesHandler(w, r, d)
}
+96
View File
@@ -0,0 +1,96 @@
package web
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/share"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
)
func publicMediaShareContext(owner *users.User, sourceRoot string, editable share.ShareEditable) *Context {
link := share.Share{
ShareColumns: share.ShareColumns{
Hash: "mediashare",
Path: "/shared",
},
FrontendShareInfo: editable.FrontendShareInfo,
ShareLimits: editable.ShareLimits,
SourcePath: sourceRoot,
}
return &Context{
User: &users.User{
FrontendUser: users.FrontendUser{Username: users.AnonymousUserName},
},
ShareUser: owner,
IndexPath: "/shared/song.mp3",
Share: link,
}
}
func TestPublicLyricsHandler_BlocksWhenFileViewerDisabled(t *testing.T) {
sourceRoot, _, owner := setupShareArchiveDownloadTest(t)
d := publicMediaShareContext(owner, sourceRoot, share.ShareEditable{DisableFileViewer: true})
req := httptest.NewRequest(http.MethodGet, "/public/api/media/lyrics?hash=mediashare&path=/song.mp3", nil)
rec := httptest.NewRecorder()
status, err := publicLyricsHandler(rec, req, d)
if err == nil {
t.Fatal("expected error when file viewer is disabled")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got status=%d err=%v", status, err)
}
}
func TestPublicLyricsHandler_BlocksWhenDownloadLimitReached(t *testing.T) {
sourceRoot, _, owner := setupShareArchiveDownloadTest(t)
d := publicMediaShareContext(owner, sourceRoot, share.ShareEditable{
DownloadsLimit: 1,
})
d.Share.Downloads = 1
req := httptest.NewRequest(http.MethodGet, "/public/api/media/lyrics?hash=mediashare&path=/song.mp3", nil)
rec := httptest.NewRecorder()
status, err := publicLyricsHandler(rec, req, d)
if err == nil {
t.Fatal("expected error when download limit is exhausted")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got status=%d err=%v", status, err)
}
}
func TestPublicSubtitlesHandler_BlocksWhenDownloadLimitReached(t *testing.T) {
sourceRoot, _, owner := setupShareArchiveDownloadTest(t)
d := publicMediaShareContext(owner, sourceRoot, share.ShareEditable{
DownloadsLimit: 1,
})
d.Share.Downloads = 1
req := httptest.NewRequest(http.MethodGet, "/public/api/media/subtitles?hash=mediashare&path=/movie.mp4&name=movie.srt&embedded=false", nil)
rec := httptest.NewRecorder()
status, err := publicSubtitlesHandler(rec, req, d)
if err == nil {
t.Fatal("expected error when download limit is exhausted")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got status=%d err=%v", status, err)
}
}
func TestPublicSubtitlesHandler_BlocksWhenDownloadDisabled(t *testing.T) {
sourceRoot, _, owner := setupShareArchiveDownloadTest(t)
d := publicMediaShareContext(owner, sourceRoot, share.ShareEditable{DisableDownload: true})
req := httptest.NewRequest(http.MethodGet, "/public/api/media/subtitles?hash=mediashare&path=/movie.mp4&name=movie.srt&embedded=false", nil)
rec := httptest.NewRecorder()
status, err := publicSubtitlesHandler(rec, req, d)
if err == nil {
t.Fatal("expected error when downloads are disabled")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got status=%d err=%v", status, err)
}
}
+14 -5
View File
@@ -70,8 +70,9 @@ func withHashFileHelper(fn handleFunc) handleFunc {
if link.DisableAnonymous && data.User.Username == "anonymous" {
return http.StatusForbidden, fmt.Errorf("share is not available to anonymous users")
}
// Block anonymous users if per-user download limit is enabled
if link.PerUserDownloadLimit && data.User.Username == "anonymous" {
// Block anonymous users from download routes when per-user download limits are enabled.
// View/stream routes still need view grants so anonymous visitors can play media inline.
if link.PerUserDownloadLimit && data.User.Username == "anonymous" && shareRequestAllowsDownload(r) {
return http.StatusForbidden, fmt.Errorf("anonymous downloads are not allowed with per-user limits")
}
if len(link.AllowedUsernames) > 0 {
@@ -406,12 +407,15 @@ func LoginHelper(disableOtp bool, fn handleFunc) handleFunc {
logger.Debug("ldap auth failed, calling password auth", err)
}
if settings.Config.Auth.Methods.PasswordAuth.Enabled {
user, err := auth.AuthenticatePassword(r, disableOtp)
user, err := auth.AuthenticatePassword(r, disableOtp, false)
if err != nil {
logger.Debug("password auth failed, calling handler:", err)
if err == errors.ErrNoTotpProvided {
return 403, err
}
if err == errors.ErrPasswordChangeRequired {
return 403, err
}
if status, mapped := loginMethodHTTPStatus(err); status != 0 {
return status, mapped
}
@@ -493,9 +497,14 @@ func withUserHelper(fn handleFunc) handleFunc {
}
data.User = userValue
// Set cookie. Some clients like gvfs relies on it for concurrent uploads
// Plant the session cookie only when the request didn't already carry
// one. Some clients like gvfs rely on it for concurrent uploads, but a
// request that presented a stale cookie must not re-emit it or it could
// revert the jar to a token retired by a concurrent renew.
if tk.RegisteredClaims.ExpiresAt != nil {
SetSessionCookie(w, r, data.Token, tk.RegisteredClaims.ExpiresAt.Time)
if c, err := r.Cookie(sessionCookieName); err != nil || c.Value == "" || c.Value != data.Token {
SetSessionCookie(w, r, data.Token, tk.RegisteredClaims.ExpiresAt.Time)
}
}
SetUserInResponseWriter(w, data.User)
if data.User.Username == "" {
+2
View File
@@ -18,9 +18,11 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"golang.org/x/crypto/bcrypt"
)
func setupTestEnv(t *testing.T) {
utils.BcryptCost = bcrypt.MinCost
dbPath := filepath.Join(t.TempDir(), "test.sqlite")
// Initialize state with SQLite database
@@ -0,0 +1,104 @@
package web
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/gtsteffaniak/filebrowser/backend/internal/activity"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
type changeRequiredPasswordBody struct {
Password string `json:"password"`
PasswordConfirm string `json:"passwordConfirm"`
}
// changeRequiredPasswordHandler sets a new password when RequirePasswordChange is enabled, then issues a session token.
// @Summary Change required password at login
// @Description Verifies the current password and sets a new password when requirePasswordChange is set. Issues a JWT on success.
// @Tags Auth
// @Accept json
// @Produce json
// @Param username query string true "Username"
// @Param X-Password header string true "URL-encoded current password"
// @Param X-Secret header string false "TOTP code (if 2FA is enabled)"
// @Param body body changeRequiredPasswordBody true "New password and confirmation"
// @Success 200 {string} string "JWT token for authentication"
// @Failure 400 {object} map[string]string "Bad request"
// @Failure 401 {object} map[string]string "Unauthorized"
// @Failure 403 {object} map[string]string "Forbidden"
// @Router /api/auth/password/change-required [post]
func changeRequiredPasswordHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
user, err := auth.AuthenticatePassword(r, false, true)
if err != nil {
if err == errors.ErrNoTotpProvided {
return http.StatusForbidden, err
}
return http.StatusUnauthorized, errors.ErrUnauthorized
}
if settings.Config.Auth.Methods.PasswordAuth.EnforcedOtp && user.TOTPSecret == "" {
return http.StatusForbidden, errors.ErrNoTotpConfigured
}
if user.HasPasskeyMFA() && user.TOTPSecret == "" {
return http.StatusForbidden, errors.ErrPasskeyMFARequired
}
if user.LoginMethod != users.LoginMethodPassword {
return http.StatusBadRequest, fmt.Errorf("password change is only available for password login users")
}
if !user.RequirePasswordChange {
return http.StatusForbidden, fmt.Errorf("password change is not required for this user")
}
var body changeRequiredPasswordBody
if err = json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&body); err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid request body")
}
if body.Password == "" {
return http.StatusBadRequest, errors.ErrEmptyPassword
}
if body.Password != body.PasswordConfirm {
return http.StatusBadRequest, fmt.Errorf("passwords do not match")
}
if err = settings.ValidatePasswordPolicy(body.Password); err != nil {
return http.StatusBadRequest, err
}
currentPassword := r.Header.Get("X-Password")
currentPassword, decErr := url.QueryUnescape(currentPassword)
if decErr != nil {
return http.StatusBadRequest, fmt.Errorf("invalid password encoding")
}
if err = utils.CheckPwd(currentPassword, user.Password); err != nil {
return http.StatusUnauthorized, errors.ErrUnauthorized
}
if body.Password == currentPassword {
return http.StatusBadRequest, fmt.Errorf("new password must differ from the current password")
}
patch := *user
patch.RequirePasswordChange = false
if err = state.UpdateUser(&patch, body.Password, "password", "requirePasswordChange"); err != nil {
return http.StatusInternalServerError, err
}
updated, getErr := state.GetUserByUsername(user.Username)
if getErr != nil {
return http.StatusInternalServerError, getErr
}
d.User = &updated
status, err := printToken(w, r, d.User, "")
if err != nil || status != 0 {
return status, err
}
activity.RecordLogin(r, d.User)
return 0, nil
}
@@ -0,0 +1,88 @@
package web
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func TestLoginBlocksRequirePasswordChange(t *testing.T) {
setupTestEnv(t)
origPasswordAuth := settings.Config.Auth.Methods.PasswordAuth.Enabled
settings.Config.Auth.Methods.PasswordAuth.Enabled = true
t.Cleanup(func() { settings.Config.Auth.Methods.PasswordAuth.Enabled = origPasswordAuth })
user := &users.User{
FrontendUser: users.FrontendUser{
Username: "mustchange",
LoginMethod: users.LoginMethodPassword,
RequirePasswordChange: true,
},
}
if err := state.CreateUser(user, "tempPass"); err != nil {
t.Fatalf("create user: %v", err)
}
handler := wrapHandler(loginHelper(loginHandler))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login?username=mustchange", nil)
req.Header.Set("X-Password", "tempPass")
handler(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("login status = %d, want 403", rec.Code)
}
}
func TestChangeRequiredPasswordHandler(t *testing.T) {
setupTestEnv(t)
origPasswordAuth := settings.Config.Auth.Methods.PasswordAuth.Enabled
settings.Config.Auth.Methods.PasswordAuth.Enabled = true
t.Cleanup(func() { settings.Config.Auth.Methods.PasswordAuth.Enabled = origPasswordAuth })
user := &users.User{
FrontendUser: users.FrontendUser{
Username: "mustchange2",
LoginMethod: users.LoginMethodPassword,
RequirePasswordChange: true,
},
}
if err := state.CreateUser(user, "tempPass"); err != nil {
t.Fatalf("create user: %v", err)
}
body, _ := json.Marshal(map[string]string{
"password": "newSecurePass",
"passwordConfirm": "newSecurePass",
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/password/change-required?username=mustchange2", bytes.NewReader(body))
req.Header.Set("X-Password", "tempPass")
req.Header.Set("Content-Type", "application/json")
handler := wrapHandler(withoutUserHelper(changeRequiredPasswordHandler))
handler(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("change-required status = %d body = %s", rec.Code, rec.Body.String())
}
updated, err := state.GetUserByUsername("mustchange2")
if err != nil {
t.Fatal(err)
}
if updated.RequirePasswordChange {
t.Fatal("expected requirePasswordChange cleared")
}
loginReq := httptest.NewRequest(http.MethodPost, "/?username=mustchange2", nil)
loginReq.Header.Set("X-Password", "newSecurePass")
if _, err = auth.AuthenticatePassword(loginReq, true, false); err != nil {
t.Fatalf("login with new password: %v", err)
}
}
+11
View File
@@ -19,6 +19,17 @@ func normalizeHTTPScheme(proto string) string {
}
}
func lastForwardedValue(v string) string {
parts := strings.Split(v, ",")
for i := len(parts) - 1; i >= 0; i-- {
ip := strings.TrimSpace(parts[i])
if ip != "" {
return ip
}
}
return ""
}
func firstForwardedValue(v string) string {
v = strings.TrimSpace(v)
if i := strings.Index(v, ","); i >= 0 {
+12
View File
@@ -8,6 +8,18 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func TestGetRemoteIPUsesRightmostForwardedFor(t *testing.T) {
settings.Config.Http.TrustProxyHeaders = true
t.Cleanup(func() { settings.Config.Http.TrustProxyHeaders = false })
req := httptest.NewRequest("GET", "http://example.com/", nil)
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("X-Forwarded-For", "203.0.113.50, 198.51.100.7")
if got := GetRemoteIP(req); got != "198.51.100.7" {
t.Fatalf("GetRemoteIP = %q, want 198.51.100.7", got)
}
}
func TestGetScheme(t *testing.T) {
t.Run("trusted proto", func(t *testing.T) {
settings.Config.Http.TrustProxyHeaders = true
+346
View File
@@ -1,13 +1,92 @@
package web
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func TestSessionTokensRemainIndependent(t *testing.T) {
setupTestEnv(t)
origKey := settings.Config.Auth.Key
origExp := settings.Config.Auth.TokenExpirationHours
settings.Config.Auth.Key = "test-signing-key-for-independent-sessions"
settings.Config.Auth.TokenExpirationHours = 2
t.Cleanup(func() {
settings.Config.Auth.Key = origKey
settings.Config.Auth.TokenExpirationHours = origExp
})
user := createTokenAuthUser(t, "session-user", users.Permissions{Api: true})
admin := createTokenAuthUser(t, "session-admin", users.Permissions{Admin: true, Api: true})
owners := []*users.User{user, user, admin}
tokens := make([]string, len(owners))
for i, owner := range owners {
var err error
tokens[i], err = mintAndRegisterSessionToken(owner)
if err != nil {
t.Fatal(err)
}
}
for i, token := range tokens {
if userID, isSession, ok := state.HashedTokenOwner(token); !ok || !isSession || userID != owners[i].ID {
t.Fatalf("session %d lost its owner: userID=%d isSession=%v ok=%v", i, userID, isSession, ok)
}
want := http.StatusForbidden
if owners[i].Permissions.Admin {
want = http.StatusOK
}
if rec := cookieRequest(t, withAdmin(mockHandler), token); rec.Code != want {
t.Fatalf("session %d: got status %d, want %d", i, rec.Code, want)
}
}
if err := state.RevokeToken(tokens[0]); err != nil {
t.Fatal(err)
}
for i, token := range tokens {
want := http.StatusOK
if i == 0 {
want = http.StatusUnauthorized
}
if rec := cookieRequest(t, withUser(mockHandler), token); rec.Code != want {
t.Fatalf("session %d after revocation: got status %d, want %d", i, rec.Code, want)
}
}
}
func TestSessionTokenWithoutIDRemainsValid(t *testing.T) {
setupTestEnv(t)
origKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "test-signing-key-for-legacy-session"
t.Cleanup(func() { settings.Config.Auth.Key = origKey })
user := createTokenAuthUser(t, "legacy-session-user", users.Permissions{Api: true})
now := time.Now()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(time.Hour)),
Issuer: auth.FB_ISSUER,
}).SignedString([]byte(settings.Config.Auth.Key))
if err != nil {
t.Fatal(err)
}
if err := state.RegisterSessionToken(token, user.ID); err != nil {
t.Fatal(err)
}
if rec := cookieRequest(t, withUser(mockHandler), token); rec.Code != http.StatusOK {
t.Fatalf("legacy session: got status %d, want %d", rec.Code, http.StatusOK)
}
}
func TestReplaceSessionTokenKeepsOldTokenWhenMintFails(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "rotation-user", users.Permissions{Api: true})
@@ -50,3 +129,270 @@ func TestReplaceSessionTokenRetiresOldWithGrace(t *testing.T) {
t.Fatal("old token mapping must remain during the grace window")
}
}
// Regression test for #3006: a request that already carried the session cookie
// must not re-emit Set-Cookie. Otherwise an in-flight response carrying a
// just-rotated-out token reverts the browser jar to a token that dies when its
// retirement grace expires.
func TestWithUserDoesNotEchoCookieToken(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "echo-user", users.Permissions{Api: true})
token := testSessionToken(t, user, time.Hour)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/users", http.NoBody)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
withUser(mockHandler)(recorder, req)
if recorder.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", recorder.Code)
}
if setCookie := recorder.Header().Values("Set-Cookie"); len(setCookie) != 0 {
t.Fatalf("cookie-carried request must not re-emit Set-Cookie, got %v", setCookie)
}
}
// Clients that authenticate without a session cookie (gvfs, Bearer, ?auth=)
// still get the token planted so subsequent requests stay authenticated.
func TestWithUserPlantsCookieForBearerClients(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "bearer-user", users.Permissions{Api: true})
token := testSessionToken(t, user, time.Hour)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/users", http.NoBody)
req.Header.Set("Authorization", "Bearer "+token)
withUser(mockHandler)(recorder, req)
if recorder.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", recorder.Code)
}
cookies := recorder.Result().Cookies()
var session *http.Cookie
for _, c := range cookies {
if c.Name == sessionCookieName {
session = c
}
}
if session == nil {
t.Fatal("cookie-less authenticated request must receive Set-Cookie")
}
if session.Value != token {
t.Fatal("planted cookie must contain the presented token")
}
}
func TestRenewHandlerNoopWhenNoAuth(t *testing.T) {
setupTestEnv(t)
orig := settings.Config.Auth.Methods.NoAuth
settings.Config.Auth.Methods.NoAuth = true
t.Cleanup(func() { settings.Config.Auth.Methods.NoAuth = orig })
user := createTokenAuthUser(t, "noauth-renew", users.Permissions{Admin: true})
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: ""})
if err != nil {
t.Fatalf("renewHandler: %v", err)
}
if status != 0 && status != http.StatusOK {
t.Fatalf("expected success status, got %d", status)
}
}
// Restricted API tokens must not call renew: rotation registers a session hash
// and would grant the token owner's full permissions (GHSA-6gr6-5qpq-888p).
func TestRenewHandlerRejectsApiToken(t *testing.T) {
setupTestEnv(t)
originalAuthKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "key"
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
user := createTokenAuthUser(t, "renew-api-user", users.Permissions{Admin: true, Api: true})
tokenString, tokenMeta, err := auth.MakeSignedTokenAPI(user, "capped-key", time.Hour, users.Permissions{Api: true}, false)
if err != nil {
t.Fatal(err)
}
tokenMeta.Name = "capped-key"
tokenMeta.Token = tokenString
if err = state.AddUserToken(user.Username, tokenMeta); err != nil {
t.Fatal(err)
}
if err = state.AddApiToken(tokenString, user.ID); err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
req.Header.Set("Authorization", "Bearer "+tokenString)
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: tokenString})
if err == nil {
t.Fatal("expected renew to fail for API token")
}
if status != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, status)
}
if _, isSession, ok := state.HashedTokenOwner(tokenString); !ok || isSession {
t.Fatalf("API token must remain non-session: ok=%v isSession=%v", ok, isSession)
}
}
// Renew while the presented token is still fresh returns it unchanged instead
// of rotating: routine page loads must not churn session-token state.
func TestRenewHandlerFreshTokenIsIdempotent(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "renew-fresh-user", users.Permissions{Api: true})
token := testSessionToken(t, user, 2*time.Hour)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: token})
if err != nil {
t.Fatalf("renewHandler: %v", err)
}
if status != 0 && status != http.StatusOK {
t.Fatalf("expected success status, got %d", status)
}
if got := recorder.Body.String(); got != token {
t.Fatal("renew on a fresh token must return the same token")
}
if state.IsTokenRevoked(token) {
t.Fatal("fresh token must not be retired by a no-op renew")
}
if setCookie := recorder.Header().Values("Set-Cookie"); len(setCookie) != 0 {
t.Fatalf("idempotent renew with matching cookie must not re-emit Set-Cookie, got %v", setCookie)
}
}
func TestRenewHandlerFreshTokenPlantsCookieWithoutJar(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "renew-fresh-no-cookie", users.Permissions{Api: true})
token := testSessionToken(t, user, 2*time.Hour)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
req.Header.Set("Authorization", "Bearer "+token)
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: token})
if err != nil {
t.Fatalf("renewHandler: %v", err)
}
if status != 0 && status != http.StatusOK {
t.Fatalf("expected success status, got %d", status)
}
if len(recorder.Header().Values("Set-Cookie")) == 0 {
t.Fatal("idempotent renew without session cookie must plant Set-Cookie")
}
}
// Concurrent renew ordering: an in-flight idempotent renew must not revert a
// jar that a later rotation already upgraded.
func TestRenewHandlerIdempotentDoesNotRevertRotatedJar(t *testing.T) {
setupTestEnv(t)
user := createTokenAuthUser(t, "renew-order-user", users.Permissions{Api: true})
oldToken := testSessionToken(t, user, 2*time.Hour)
newToken, err := replaceSessionToken(oldToken, user)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: oldToken})
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: oldToken})
if err != nil {
t.Fatalf("renewHandler: %v", err)
}
if status != 0 && status != http.StatusOK {
t.Fatalf("expected success status, got %d", status)
}
if got := recorder.Body.String(); got != oldToken {
t.Fatal("idempotent renew must still return the presented token")
}
if setCookie := recorder.Header().Values("Set-Cookie"); len(setCookie) != 0 {
t.Fatalf("must not Set-Cookie old token after jar already rotated, got %v", setCookie)
}
if _, isSession, ok := state.HashedTokenOwner(newToken); !ok || !isSession {
t.Fatalf("rotated token must remain registered: ok=%v isSession=%v", ok, isSession)
}
}
func TestWithUserRefreshesCookieWhenBearerMismatchesJar(t *testing.T) {
setupTestEnv(t)
origExp := settings.Config.Auth.TokenExpirationHours
t.Cleanup(func() { settings.Config.Auth.TokenExpirationHours = origExp })
settings.Config.Auth.TokenExpirationHours = 2
user := createTokenAuthUser(t, "bearer-mismatch-user", users.Permissions{Api: true})
stale := testSessionToken(t, user, time.Hour)
fresh, err := replaceSessionToken(stale, user)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/users", http.NoBody)
req.Header.Set("Authorization", "Bearer "+fresh)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: stale})
withUser(mockHandler)(recorder, req)
if recorder.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d body=%s", recorder.Code, recorder.Body.String())
}
cookies := recorder.Result().Cookies()
var session *http.Cookie
for _, c := range cookies {
if c.Name == sessionCookieName {
session = c
}
}
if session == nil {
t.Fatalf("Bearer auth with stale cookie jar must refresh Set-Cookie, headers=%v", recorder.Header().Values("Set-Cookie"))
}
if session.Value != fresh {
t.Fatal("planted cookie must match the Bearer token")
}
}
// Inside the refresh window renew rotates: new token registered, old retired
// but still resolvable during the grace window.
func TestRenewHandlerNearExpiryRotates(t *testing.T) {
setupTestEnv(t)
origExp := settings.Config.Auth.TokenExpirationHours
t.Cleanup(func() { settings.Config.Auth.TokenExpirationHours = origExp })
settings.Config.Auth.TokenExpirationHours = 2
user := createTokenAuthUser(t, "renew-rotate-user", users.Permissions{Api: true})
token := testSessionToken(t, user, 10*time.Minute)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/renew", http.NoBody)
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
status, err := renewHandler(recorder, req, &requestContext{User: user, Token: token})
if err != nil {
t.Fatalf("renewHandler: %v", err)
}
if status != 0 && status != http.StatusOK {
t.Fatalf("expected success status, got %d", status)
}
newToken := recorder.Body.String()
if newToken == token {
t.Fatal("renew inside the refresh window must rotate the token")
}
if _, isSession, ok := state.HashedTokenOwner(newToken); !ok || !isSession {
t.Fatalf("rotated token must be registered as a session: ok=%v isSession=%v", ok, isSession)
}
if state.IsTokenRevoked(token) {
t.Fatal("rotated-out token must remain valid during the grace window")
}
}
+9
View File
@@ -224,6 +224,15 @@ func shareRequestAllowsDownloadToken(r *http.Request) bool {
return shareRouteAllowsDownloadToken(r.URL.Path)
}
// shareRequestAllowsDownload reports metered download routes (not inline view/stream).
func shareRequestAllowsDownload(r *http.Request) bool {
if r == nil {
return false
}
path := r.URL.Path
return strings.Contains(path, "/resources/download") || strings.Contains(path, "/raw")
}
// directDownloadURL builds a public download URL with an ephemeral token query parameter.
func directDownloadURL(host, scheme, hash, token string) string {
tokenParam := ""
+3 -3
View File
@@ -17,7 +17,7 @@ func TestAuthenticateShareRequestUISessionCookie(t *testing.T) {
settings.Config.Auth.Key = "test-auth-key"
t.Cleanup(func() { settings.Config.Auth.Key = origKey })
passwordHash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.DefaultCost)
passwordHash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
@@ -62,7 +62,7 @@ func TestAuthenticateShareRequestDownloadTokenDoesNotMintUISession(t *testing.T)
settings.Config.Auth.Key = "test-auth-key"
t.Cleanup(func() { settings.Config.Auth.Key = origKey })
passwordHash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.DefaultCost)
passwordHash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
@@ -93,7 +93,7 @@ func TestAuthenticateShareRequestDownloadTokenWrongPasswordNoUISession(t *testin
settings.Config.Auth.Key = "test-auth-key"
t.Cleanup(func() { settings.Config.Auth.Key = origKey })
passwordHash, bcryptErr := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.DefaultCost)
passwordHash, bcryptErr := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
if bcryptErr != nil {
t.Fatalf("bcrypt: %v", bcryptErr)
}
+1
View File
@@ -260,6 +260,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
"jwtAvailable": settings.Config.Auth.Methods.JwtAuth.Enabled,
"proxyAvailable": settings.Config.Auth.Methods.ProxyAuth.Enabled,
"passwordAvailable": settings.Config.Auth.Methods.PasswordAuth.Enabled,
"passwordMinLength": settings.PasswordMinLength(),
"ldapAvailable": settings.Config.Auth.Methods.LdapAuth.Enabled,
"mediaAvailable": settings.MediaEnabled(),
"muPdfAvailable": settings.Env.MuPdfAvailable,
+74 -4
View File
@@ -232,18 +232,24 @@ func ValidateViewGrant(token string, d *Context, sourceName string) error {
utils.ViewGrantsCache.Delete(token)
return fmt.Errorf("view token expired")
}
if grant.Source != viewGrantScope(d, sourceName) {
viewCtx := d
if d.Share.Hash != "" {
viewCtx = contextForViewGrantValidation(d, grant.Source)
} else if sourceName == "" || grant.Source != sourceName {
return fmt.Errorf("view token scope mismatch")
}
if !viewGrantScopeMatches(viewCtx, grant.Source, sourceName) {
return fmt.Errorf("view token scope mismatch")
}
internalSource := sourceName
if d.Share.Hash != "" {
if viewCtx.Share.Hash != "" {
var err error
internalSource, err = shareSourceName(d)
internalSource, err = shareSourceName(viewCtx)
if err != nil {
return err
}
}
perms, err := effectiveFilePerms(d, internalSource)
perms, err := effectiveFilePerms(viewCtx, internalSource)
if err != nil || !perms.View {
return fmt.Errorf("view permission required")
}
@@ -252,6 +258,69 @@ func ValidateViewGrant(token string, d *Context, sourceName string) error {
return nil
}
// contextForViewGrantValidation hydrates share metadata when optional-auth middleware
// left only a hash stub on the context (anonymous public share visitors).
func contextForViewGrantValidation(d *Context, grantSource string) *Context {
if d == nil {
return d
}
if d.Share.Hash != "" {
return d
}
hash := strings.TrimSpace(grantSource)
if hash == "" {
return d
}
link, err := state.GetShare(hash)
if err != nil || link.Hash == "" {
return d
}
out := *d
out.Share = link
if out.ShareUser == nil {
if u, err := state.UserForShareOwner(link); err == nil {
out.ShareUser = &u
}
}
return &out
}
func viewGrantScopeMatches(d *Context, grantSource, sourceName string) bool {
expected := viewGrantScope(d, sourceName)
if grantSource == expected {
return true
}
if d == nil || d.Share.Hash == "" {
return false
}
internalSource, err := shareSourceName(d)
if err != nil {
return false
}
// Accept source-scoped grants on share routes (e.g. minted before share context was hydrated).
return grantSource == internalSource && expected == d.Share.Hash
}
// hydratePublicShareContext ensures public share handlers have full share + owner context.
func hydratePublicShareContext(d *Context, r *http.Request) {
if d == nil || r == nil {
return
}
if d.Share.Hash == "" {
hash := strings.TrimSpace(r.URL.Query().Get("hash"))
if hash != "" {
if link, err := state.GetShare(hash); err == nil {
d.Share = link
}
}
}
if d.Share.Hash != "" && d.ShareUser == nil {
if u, err := state.UserForShareOwner(d.Share); err == nil {
d.ShareUser = &u
}
}
}
func canMintViewToken(d *Context, source string) bool {
if d.Share.Hash != "" && d.Share.ShareType == "upload" {
return false
@@ -583,6 +652,7 @@ func streamHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, err
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /public/api/media/stream [get]
func publicStreamHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
hydratePublicShareContext(d, r)
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("streaming is disabled for upload shares")
}
+60
View File
@@ -226,6 +226,39 @@ func TestValidateViewGrantShareBinding(t *testing.T) {
}
}
func TestValidateViewGrantRejectsShareTokenOnAuthenticatedRoute(t *testing.T) {
initStreamTestSources(t)
settings.Config.Server.SourceMap = map[string]*settings.Source{
"/srv": {Path: "/srv", Name: "srv"},
}
t.Cleanup(func() { settings.Config.Server.SourceMap = nil })
shareCtx := &requestContext{
User: testUserWithView(1, "srv"),
Share: share.Share{ShareColumns: share.ShareColumns{Hash: "abc123"}, SourcePath: "/srv"},
}
token, err := mintViewGrant(shareCtx, "")
if err != nil {
t.Fatal(err)
}
denied := &requestContext{
User: &users.User{
FrontendUser: users.FrontendUser{Username: "bob"},
ID: 2,
BackendScopes: []users.BackendScope{
{Path: "/srv", Scope: "/", Permissions: users.DenyAllSourceFilePermissions()},
},
BackendSourcePermissions: map[string]users.SourceFilePermissions{
"/srv": users.DenyAllSourceFilePermissions(),
},
Version: users.SourcePermissionsMigrationVersion,
},
}
if err := ValidateViewGrant(token, denied, "srv"); err == nil {
t.Fatal("expected share view token to be rejected on authenticated view route")
}
}
func TestAttachViewTokenForAllFileTypes(t *testing.T) {
t.Parallel()
initStreamTestSources(t)
@@ -801,3 +834,30 @@ func TestViewTokenHandlerExtendsExistingToken(t *testing.T) {
t.Fatalf("expected extended expiry, before=%d after=%d", almostExpired, grantAfter.ExpiresAt)
}
}
func TestValidateViewGrantSourceScopedGrantOnPublicShare(t *testing.T) {
initStreamTestSources(t)
settings.Config.Server.SourceMap = map[string]*settings.Source{
"/srv": {Path: "/srv", Name: "srv"},
}
token, err := utils.RandomHex(16)
if err != nil {
t.Fatal(err)
}
utils.ViewGrantsCache.Set(token, utils.ViewGrant{
Source: "srv",
ExpiresAt: time.Now().Add(time.Hour).Unix(),
})
d := &requestContext{
User: &users.User{
FrontendUser: users.FrontendUser{Username: users.AnonymousUserName},
},
Share: share.Share{
ShareColumns: share.ShareColumns{Hash: "sharehash"},
SourcePath: "/srv",
},
}
if err := ValidateViewGrant(token, d, ""); err != nil {
t.Fatalf("ValidateViewGrant: %v", err)
}
}
+17
View File
@@ -0,0 +1,17 @@
package web
import (
"os"
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"golang.org/x/crypto/bcrypt"
)
func TestMain(m *testing.M) {
utils.BcryptCost = bcrypt.MinCost
if err := utils.SetInvalidPasswordHash(); err != nil {
panic(err)
}
os.Exit(m.Run())
}
-271
View File
@@ -1,271 +0,0 @@
package web
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
)
func createTokenAuthUser(t *testing.T, username string, perms users.Permissions) *users.User {
t.Helper()
u := &users.User{FrontendUser: users.FrontendUser{Username: username}}
if err := state.CreateUser(u, ""); err != nil {
t.Fatal(err)
}
stored, err := state.GetUserByUsername(username)
if err != nil {
t.Fatal(err)
}
stored.Permissions = perms
if err = state.UpdateUser(&stored, "", "permissions"); err != nil {
t.Fatal(err)
}
reloaded, err := state.GetUserByUsername(username)
if err != nil {
t.Fatal(err)
}
return &reloaded
}
func cookieRequest(t *testing.T, handler http.HandlerFunc, token string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/users", http.NoBody)
req.AddCookie(&http.Cookie{Name: "filebrowser_quantum_jwt", Value: token})
handler(rec, req)
return rec
}
// A non-session bearer token whose hash has no stored permission metadata must be
// rejected rather than granted the owner's uncapped permissions.
func TestApiTokenWithoutMetadataRejected(t *testing.T) {
setupTestEnv(t)
originalAuthKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "key"
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
user := createTokenAuthUser(t, "metadata-less-admin", users.Permissions{Admin: true, Api: true})
tokenString, _, err := auth.MakeSignedTokenAPI(user, "orphan-key", time.Hour, users.Permissions{}, true)
if err != nil {
t.Fatal(err)
}
// Register the hash mapping without any user.Tokens metadata.
if err := state.AddApiToken(tokenString, user.ID); err != nil {
t.Fatal(err)
}
rec := cookieRequest(t, withAdmin(mockHandler), tokenString)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("metadata-less API token: got status %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
// A named API token with stored caps must have those caps applied at auth time.
func TestApiTokenCapsAppliedFromStoredMetadata(t *testing.T) {
setupTestEnv(t)
originalAuthKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "key"
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
user := createTokenAuthUser(t, "capped-admin", users.Permissions{Admin: true, Api: true})
// The token cap excludes admin, so the resolved user must lose admin.
tokenString, tokenMeta, err := auth.MakeSignedTokenAPI(user, "capped-key", time.Hour, users.Permissions{Share: true}, false)
if err != nil {
t.Fatal(err)
}
tokenMeta.Name = "capped-key"
tokenMeta.Token = tokenString
if err := state.AddUserToken(user.Username, tokenMeta); err != nil {
t.Fatal(err)
}
if err := state.AddApiToken(tokenString, user.ID); err != nil {
t.Fatal(err)
}
rec := cookieRequest(t, withAdmin(mockHandler), tokenString)
if rec.Code != http.StatusForbidden {
t.Fatalf("capped API token: got status %d, want %d", rec.Code, http.StatusForbidden)
}
}
// JwtAuth must reuse the session cookie it already issued instead of minting
// and registering a new session hash on every request.
func TestJwtAuthReusesSessionCookie(t *testing.T) {
setupTestEnv(t)
origAuthKey := settings.Config.Auth.Key
origJwtAuth := settings.Config.Auth.Methods.JwtAuth
origExp := settings.Config.Auth.TokenExpirationHours
t.Cleanup(func() {
settings.Config.Auth.Key = origAuthKey
settings.Config.Auth.Methods.JwtAuth = origJwtAuth
settings.Config.Auth.TokenExpirationHours = origExp
})
settings.Config.Auth.Key = "key"
settings.Config.Auth.TokenExpirationHours = 2
settings.Config.Auth.Methods.JwtAuth.Secret = "jwt-secret"
settings.Config.Auth.Methods.JwtAuth.Algorithm = "HS256"
settings.Config.Auth.Methods.JwtAuth.UserIdentifier = "sub"
externalJWT, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "jwt-user",
}).SignedString([]byte("jwt-secret"))
if err != nil {
t.Fatal(err)
}
call := func(cookieToken, authHeader, authQuery string) (*requestContext, *httptest.ResponseRecorder) {
t.Helper()
url := "/api/resources"
if authQuery != "" {
url += "?auth=" + authQuery
}
req := httptest.NewRequest(http.MethodGet, url, nil)
if authHeader != "" {
req.Header.Set("Authorization", "Bearer "+authHeader)
}
if cookieToken != "" {
req.AddCookie(&http.Cookie{Name: "filebrowser_quantum_jwt", Value: cookieToken})
}
rec := httptest.NewRecorder()
d := &requestContext{Ctx: req.Context()}
status, err := getJwtUser(rec, req, d, mockHandler, externalJWT)
if err != nil || status != http.StatusOK {
t.Fatalf("getJwtUser: status=%d err=%v", status, err)
}
return d, rec
}
// First request without a cookie mints a session token and sets the cookie.
d1, rec1 := call("", "", "")
if d1.Token == "" {
t.Fatal("expected a session token on first JwtAuth request")
}
if rec1.Header().Get("Set-Cookie") == "" {
t.Fatal("expected session cookie on first JwtAuth request")
}
// Follow-up requests carrying the session cookie must reuse it instead of
// minting and registering a new session.
d2, _ := call(d1.Token, "", "")
if d2.Token != d1.Token {
t.Fatal("expected JwtAuth to reuse the existing session token")
}
d3, _ := call(d1.Token, "", "")
if d3.Token != d1.Token {
t.Fatal("expected repeated JwtAuth requests to reuse the session token")
}
// When the external JWT also travels in the Authorization header or the
// auth query param, ExtractToken would prefer it over the session cookie.
// Reuse must still pick the cookie so those deployments don't mint a new
// session on every request.
d4, _ := call(d1.Token, externalJWT, "")
if d4.Token != d1.Token {
t.Fatal("expected JwtAuth to reuse the session cookie when the external JWT is in the Authorization header")
}
d5, _ := call(d1.Token, "", externalJWT)
if d5.Token != d1.Token {
t.Fatal("expected JwtAuth to reuse the session cookie when the external JWT is in the auth query param")
}
}
// A session cookie belonging to a different user must not be adopted by the
// JwtAuth user; a fresh session is minted instead.
func TestJwtAuthDoesNotReuseOtherUsersSessionCookie(t *testing.T) {
setupTestEnv(t)
origAuthKey := settings.Config.Auth.Key
origJwtAuth := settings.Config.Auth.Methods.JwtAuth
origExp := settings.Config.Auth.TokenExpirationHours
t.Cleanup(func() {
settings.Config.Auth.Key = origAuthKey
settings.Config.Auth.Methods.JwtAuth = origJwtAuth
settings.Config.Auth.TokenExpirationHours = origExp
})
settings.Config.Auth.Key = "key"
settings.Config.Auth.TokenExpirationHours = 2
settings.Config.Auth.Methods.JwtAuth.Secret = "jwt-secret"
settings.Config.Auth.Methods.JwtAuth.Algorithm = "HS256"
settings.Config.Auth.Methods.JwtAuth.UserIdentifier = "sub"
other := createTokenAuthUser(t, "other-user", users.Permissions{})
otherToken := testSessionToken(t, other, time.Hour)
externalJWT, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "jwt-user",
}).SignedString([]byte("jwt-secret"))
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodGet, "/api/resources", nil)
req.AddCookie(&http.Cookie{Name: "filebrowser_quantum_jwt", Value: otherToken})
rec := httptest.NewRecorder()
d := &requestContext{Ctx: req.Context()}
status, err := getJwtUser(rec, req, d, mockHandler, externalJWT)
if err != nil || status != http.StatusOK {
t.Fatalf("getJwtUser: status=%d err=%v", status, err)
}
if d.Token == "" || d.Token == otherToken {
t.Fatal("expected a new session token, not the other user's cookie token")
}
}
// WebDAV authenticates with Basic Auth where the password is the raw API JWT.
// A minimal named token with a hashed_tokens row and stored metadata must pass;
// the same JWT without a hash mapping must 401 (the 2.0.8-beta regression).
func TestApiTokenBasicAuthRoundTrip(t *testing.T) {
setupTestEnv(t)
originalAuthKey := settings.Config.Auth.Key
settings.Config.Auth.Key = "key"
t.Cleanup(func() { settings.Config.Auth.Key = originalAuthKey })
user := createTokenAuthUser(t, "webdav-user", users.Permissions{Api: true})
tokenString, tokenMeta, err := auth.MakeSignedTokenAPI(user, "obsidian-sync", time.Hour, users.Permissions{}, true)
if err != nil {
t.Fatal(err)
}
tokenMeta.Name = "obsidian-sync"
tokenMeta.Token = tokenString
if err = state.AddUserToken(user.Username, tokenMeta); err != nil {
t.Fatal(err)
}
if err = state.AddApiToken(tokenString, user.ID); err != nil {
t.Fatal(err)
}
basicRequest := func(token string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest("PROPFIND", "/dav/source1/", nil)
req.SetBasicAuth("webdav-user", token)
withBasicAuth(mockHandler)(rec, req)
return rec
}
if rec := basicRequest(tokenString); rec.Code != http.StatusOK {
t.Fatalf("backfilled API token over basic auth: got status %d, want %d", rec.Code, http.StatusOK)
}
// Same JWT shape with no hashed_tokens row must be rejected, never resolved
// via legacy BelongsTo claims. A different duration guarantees a distinct
// raw JWT (minimal claims carry only iss/iat/exp, so same-second mints
// would otherwise be byte-identical).
orphanString, _, err := auth.MakeSignedTokenAPI(user, "orphan-sync", 2*time.Hour, users.Permissions{}, true)
if err != nil {
t.Fatal(err)
}
rec := basicRequest(orphanString)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("unmapped API token over basic auth: got status %d, want %d", rec.Code, http.StatusUnauthorized)
}
if rec.Header().Get("WWW-Authenticate") == "" {
t.Fatal("expected WWW-Authenticate challenge on basic auth 401")
}
}
+52 -20
View File
@@ -6,6 +6,7 @@ import (
"net/url"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
)
@@ -23,14 +24,17 @@ import (
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/auth/otp/generate [post]
func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
err := checkPassword(r, d)
if err != nil {
return http.StatusUnauthorized, err
}
user, getErr := state.GetUserByUsername(r.URL.Query().Get("username"))
targetUsername := r.URL.Query().Get("username")
user, getErr := state.GetUserByUsername(targetUsername)
if getErr != nil {
return http.StatusNotFound, fmt.Errorf("user not found: %w", getErr)
}
if status, err := requireOtpEnrollmentAuthorized(&user, d); err != nil {
return status, err
}
if err := checkOtpActorPassword(r, d, user.Username); err != nil {
return http.StatusUnauthorized, err
}
url, err := auth.GenerateOtpForUser(&user)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("error generating OTP secret: %w", err)
@@ -60,16 +64,18 @@ func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *Context) (int,
if code == "" {
return http.StatusUnauthorized, fmt.Errorf("code is required")
}
err := checkPassword(r, d)
if err != nil {
return http.StatusUnauthorized, err
}
user, getErr := state.GetUserByUsername(r.URL.Query().Get("username"))
targetUsername := r.URL.Query().Get("username")
user, getErr := state.GetUserByUsername(targetUsername)
if getErr != nil {
return http.StatusNotFound, fmt.Errorf("user not found: %w", getErr)
}
err = auth.VerifyTotpCode(&user, code)
if err != nil {
if status, err := requireOtpEnrollmentAuthorized(&user, d); err != nil {
return status, err
}
if err := checkOtpActorPassword(r, d, user.Username); err != nil {
return http.StatusUnauthorized, err
}
if err := auth.VerifyTotpCode(&user, code); err != nil {
return http.StatusUnauthorized, fmt.Errorf("invalid OTP token")
}
if err := state.UpdateUser(&user, "", "TOTPSecret", "TOTPNonce", "OtpEnabled"); err != nil {
@@ -83,13 +89,40 @@ func verifyOTPHandler(w http.ResponseWriter, r *http.Request, d *Context) (int,
return RenderJSON(w, r, response)
}
func checkPassword(r *http.Request, d *Context) error {
providedPassword := r.Header.Get("X-Password")
username := r.URL.Query().Get("username")
if d.User.Permissions.Admin {
username = d.User.Username
// userConfiguredMFA reports whether the account already has a second factor that must not be reset anonymously.
func userConfiguredMFA(u *users.User) bool {
if u == nil {
return false
}
if u.HasPasskeyMFA() {
return true
}
return u.TOTPSecret != ""
}
// requireOtpEnrollmentAuthorized allows password-only OTP enrollment only for first-time setup (no MFA).
// Replacing or adding TOTP when MFA exists requires an authenticated self or admin session.
func requireOtpEnrollmentAuthorized(target *users.User, d *Context) (int, error) {
if !userConfiguredMFA(target) {
return 0, nil
}
if d.User == nil || d.User.Username == "" || d.User.Username == "anonymous" {
return http.StatusForbidden, fmt.Errorf("authentication required to reset two-factor authentication")
}
if d.User.Permissions.Admin || d.User.Username == target.Username {
return 0, nil
}
return http.StatusForbidden, fmt.Errorf("not authorized to reset two-factor authentication for this user")
}
// checkOtpActorPassword verifies X-Password for the account that must prove knowledge of the password.
// For admin sessions resetting another user, the admin's password is checked.
func checkOtpActorPassword(r *http.Request, d *Context, targetUsername string) error {
providedPassword := r.Header.Get("X-Password")
actorUsername := targetUsername
if d.User != nil && d.User.Permissions.Admin && d.User.Username != targetUsername {
actorUsername = d.User.Username
}
// url decode
providedPassword, err := url.QueryUnescape(providedPassword)
if err != nil {
return fmt.Errorf("invalid password encoding: %v", err)
@@ -97,14 +130,13 @@ func checkPassword(r *http.Request, d *Context) error {
if providedPassword == "" {
return fmt.Errorf("password is required")
}
user, getErr := state.GetUserByUsername(username)
user, getErr := state.GetUserByUsername(actorUsername)
var passwordHash string
if getErr != nil {
passwordHash = utils.InvalidPasswordHash
} else {
passwordHash = user.Password
}
// always run checkPwd to prevent timing attacks
err = utils.CheckPwd(providedPassword, passwordHash)
if err != nil {
return fmt.Errorf("invalid password or user not found")
+67 -6
View File
@@ -24,7 +24,15 @@ func otpRequest(username, password, code, path string) *http.Request {
return req
}
func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) {
func anonymousContext() *Context {
u := &users.User{
FrontendUser: users.FrontendUser{Username: "anonymous"},
}
state.ApplyUserDefaults(u)
return &Context{User: u}
}
func TestVerifyOTP_CachedSecretTakesPrecedenceWhenAuthenticatedSelf(t *testing.T) {
setupTestEnv(t)
const oldSecret = "SOMEOLDSECRET234"
@@ -41,15 +49,19 @@ func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) {
}
t.Cleanup(func() { auth.TotpCache.Delete(user.Username) })
d := &Context{User: user}
reloaded, reloadErr := state.GetUserByUsername(user.Username)
if reloadErr != nil {
t.Fatalf("failed to reload user: %v", reloadErr)
}
d := &Context{User: &reloaded}
rec := httptest.NewRecorder()
if _, err := generateOTPHandler(rec, otpRequest(user.Username, "testPass", "", "/api/auth/otp/generate"), d); err != nil {
t.Fatalf("generation failed: %v", err)
if _, genErr := generateOTPHandler(rec, otpRequest(user.Username, "testPass", "", "/api/auth/otp/generate"), d); genErr != nil {
t.Fatalf("generation failed: %v", genErr)
}
var resp map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
if unmarshalErr := json.Unmarshal(rec.Body.Bytes(), &resp); unmarshalErr != nil {
t.Fatalf("failed to decode response: %v", unmarshalErr)
}
u, err := url.Parse(resp["url"])
if err != nil {
@@ -85,6 +97,55 @@ func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) {
}
}
func TestRequireOtpEnrollmentAuthorized(t *testing.T) {
withMFA := &users.User{
FrontendUser: users.FrontendUser{Username: "victim"},
TOTPSecret: "SOMEOLDSECRET234",
}
status, err := requireOtpEnrollmentAuthorized(withMFA, anonymousContext())
if err == nil {
t.Fatal("expected anonymous MFA reset to be rejected")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got %d err=%v", status, err)
}
noMFA := &users.User{
FrontendUser: users.FrontendUser{Username: "new"},
}
if status, err = requireOtpEnrollmentAuthorized(noMFA, anonymousContext()); err != nil {
t.Fatalf("expected first-time enrollment to be allowed: status=%d err=%v", status, err)
}
self := &users.User{
FrontendUser: users.FrontendUser{Username: "victim"},
}
if status, err = requireOtpEnrollmentAuthorized(withMFA, &Context{User: self}); err != nil {
t.Fatalf("expected self reset to be allowed: status=%d err=%v", status, err)
}
admin := &users.User{
FrontendUser: users.FrontendUser{
Username: "admin",
Permissions: users.Permissions{Admin: true},
},
}
if status, err = requireOtpEnrollmentAuthorized(withMFA, &Context{User: admin}); err != nil {
t.Fatalf("expected admin reset to be allowed: status=%d err=%v", status, err)
}
other := &users.User{
FrontendUser: users.FrontendUser{Username: "other"},
}
status, err = requireOtpEnrollmentAuthorized(withMFA, &Context{User: other})
if err == nil {
t.Fatal("expected non-admin other user to be rejected")
}
if status != http.StatusForbidden {
t.Fatalf("expected 403, got %d err=%v", status, err)
}
}
func TestLogin_RequiresOTPWhenTOTPSecretSet(t *testing.T) {
setupTestEnv(t)
+4 -1
View File
@@ -282,6 +282,9 @@ func validateNonAdminSelfPatchWhich(which []string) error {
if f == "" {
return fmt.Errorf("which must not contain empty field names")
}
if strings.EqualFold(f, "PasskeyCredentials") {
return fmt.Errorf("passkeys can only be managed through the passkey registration endpoints")
}
if strings.EqualFold(f, "Password") || strings.EqualFold(f, "OtpEnabled") {
continue
}
@@ -304,7 +307,7 @@ func userPutOnlyNonAdminEditableFields(which []string) bool {
if f == "" {
return false
}
if strings.EqualFold(f, "Password") {
if strings.EqualFold(f, "Password") || strings.EqualFold(f, "PasskeyCredentials") {
return false
}
if _, ok := allowed[f]; !ok {
+1
View File
@@ -82,6 +82,7 @@ func viewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /public/api/resources/view [get]
func PublicViewHandler(w http.ResponseWriter, r *http.Request, d *Context) (int, error) {
hydratePublicShareContext(d, r)
if d.Share.ShareType == "upload" {
return http.StatusNotImplemented, fmt.Errorf("viewing is disabled for upload shares")
}
+16
View File
@@ -11,6 +11,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/internal/activity"
"github.com/gtsteffaniak/filebrowser/backend/internal/auth"
activitydb "github.com/gtsteffaniak/filebrowser/backend/internal/database/activity"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
)
@@ -110,6 +111,11 @@ func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *
if !auth.IsWebAuthnEnabled() {
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
if d.User.LoginMethod == users.LoginMethodPassword && d.User.HasPasskeyMFA() {
if err := checkOtpActorPassword(r, d, d.User.Username); err != nil {
return http.StatusUnauthorized, err
}
}
registerRequestOrigin(r)
@@ -144,6 +150,11 @@ func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d
if !auth.IsWebAuthnEnabled() {
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
if d.User.LoginMethod == users.LoginMethodPassword && d.User.HasPasskeyMFA() {
if err := checkOtpActorPassword(r, d, d.User.Username); err != nil {
return http.StatusUnauthorized, err
}
}
registerRequestOrigin(r)
@@ -188,6 +199,11 @@ func deletePasskeyCredentialHandler(w http.ResponseWriter, r *http.Request, d *C
if !auth.IsWebAuthnEnabled() {
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
if d.User.LoginMethod == users.LoginMethodPassword {
if err := checkOtpActorPassword(r, d, d.User.Username); err != nil {
return http.StatusUnauthorized, err
}
}
credentialID := r.PathValue("id")
if credentialID == "" {
+17
View File
@@ -206,6 +206,17 @@ func (ffs *filteredFileSystem) checkAccess(requestPath string) error {
return nil
}
func (ffs *filteredFileSystem) requireCreatePermissionForNewFile(ctx context.Context, requestPath string) error {
_, err := ffs.fs.Stat(ctx, requestPath)
if err == nil {
return nil
}
if os.IsNotExist(err) {
return fmt.Errorf("create permission required")
}
return err
}
// filteredFile wraps a webdav.File and filters Readdir results based on FileInfoFaster
type filteredFile struct {
webdav.File
@@ -322,6 +333,12 @@ func (ffs *filteredFileSystem) OpenFile(ctx context.Context, requestPath string,
logger.Debugf("OpenFile: write access denied for %s: %v", requestPath, err)
return nil, err
}
if (flag&os.O_CREATE) != 0 && !ffs.sourceFilePerms().Create {
if err := ffs.requireCreatePermissionForNewFile(ctx, requestPath); err != nil {
return nil, err
}
}
}
file, err := ffs.fs.OpenFile(ctx, requestPath, flag, perm)
+19 -6
View File
@@ -9,12 +9,13 @@ import (
"sync"
"time"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/dbindex"
dbsql "github.com/gtsteffaniak/filebrowser/backend/internal/database/sql"
"github.com/gtsteffaniak/filebrowser/backend/internal/errors"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/go-cache/cache"
"github.com/gtsteffaniak/go-logger/logger"
"golang.org/x/net/webdav"
@@ -89,6 +90,10 @@ type Stats struct {
UsedAsIndexed uint64 `json:"used"`
UsedDisk uint64 `json:"usedAlt"`
DiskTotal uint64 `json:"total"`
// UsedDiskRoot/DiskTotalRoot are the root-filesystem-only view: a single
// statfs of the source path without aggregating nested mounts.
UsedDiskRoot uint64 `json:"usedAltRoot"`
DiskTotalRoot uint64 `json:"totalRoot"`
// UsageScopeMismatch is true when indexed used exceeds partition total at the
// source root (e.g. nested mounts under the source path). Display-only signal.
UsageScopeMismatch bool `json:"usageScopeMismatch,omitempty"`
@@ -1563,15 +1568,17 @@ func (idx *Index) IsNeverWatchPath(adjustedPath string) bool {
return exists
}
func (idx *Index) SetUsage(totalDiskSize, partitionUsed, UsedAsIndexed uint64) {
func (idx *Index) SetUsage(aggregate, rootOnly fileutils.PartitionUsage, UsedAsIndexed uint64) {
if settings.Config.Frontend.DisableUsedPercentage {
return
}
idx.mu.Lock()
defer idx.mu.Unlock()
idx.DiskTotal = totalDiskSize
idx.DiskTotal = aggregate.Total
idx.UsedAsIndexed = UsedAsIndexed
idx.UsedDisk = partitionUsed
idx.UsedDisk = aggregate.Used
idx.DiskTotalRoot = rootOnly.Total
idx.UsedDiskRoot = rootOnly.Used
}
func (idx *Index) SetStatus(status IndexStatus) error {
@@ -1670,6 +1677,8 @@ func (idx *Index) writePersistedIndexInfo() error {
usedAsIndexed := idx.UsedAsIndexed
usedDisk := idx.UsedDisk
diskTotal := idx.DiskTotal
usedDiskRoot := idx.UsedDiskRoot
diskTotalRoot := idx.DiskTotalRoot
idx.mu.RUnlock()
info := &dbindex.IndexInfo{
@@ -1681,6 +1690,8 @@ func (idx *Index) writePersistedIndexInfo() error {
UsedAsIndexed: usedAsIndexed,
UsedDisk: usedDisk,
DiskTotal: diskTotal,
UsedDiskRoot: usedDiskRoot,
DiskTotalRoot: diskTotalRoot,
Scanners: scanners,
}
@@ -1714,6 +1725,8 @@ func (idx *Index) Load() error {
idx.UsedAsIndexed = info.UsedAsIndexed
idx.UsedDisk = info.UsedDisk
idx.DiskTotal = info.DiskTotal
idx.UsedDiskRoot = info.UsedDiskRoot
idx.DiskTotalRoot = info.DiskTotalRoot
// Restore scanner information (will be applied when scanners are created)
// Store in a temporary map that setupMultiScanner can use
+5 -3
View File
@@ -6,9 +6,9 @@ import (
"strings"
"github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/filebrowser/backend/internal/utils"
"github.com/gtsteffaniak/filebrowser/backend/pkg/indexing/iteminfo"
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
"github.com/gtsteffaniak/go-logger/logger"
)
@@ -276,7 +276,7 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro
_, ok = utils.DiskUsageCache.Get(cacheKey)
if !ok {
// Only fetch disk total and used if not cached (this is expensive, so we cache it)
totalPartitionSize, partitionUsed, err := fileutils.GetAggregatedPartitionUsage(sourcePath)
aggregate, rootOnly, err := fileutils.GetPartitionUsageVariants(sourcePath)
if err != nil {
logger.Errorf("Failed to get partition usage for index %s: %v", sourceName, err)
}
@@ -298,7 +298,7 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro
indexedSizeFromDB += uint64(item.Size)
}
}
idx.SetUsage(totalPartitionSize, partitionUsed, indexedSizeFromDB)
idx.SetUsage(aggregate, rootOnly, indexedSizeFromDB)
utils.DiskUsageCache.Set(cacheKey, true)
if metaStoreConfigured() {
if err := idx.writePersistedIndexInfo(); err != nil {
@@ -333,6 +333,8 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro
reducedIdx.UsedAsIndexed = idx.UsedAsIndexed
reducedIdx.UsedDisk = idx.UsedDisk
reducedIdx.DiskTotal = idx.DiskTotal
reducedIdx.UsedDiskRoot = idx.UsedDiskRoot
reducedIdx.DiskTotalRoot = idx.DiskTotalRoot
reducedIdx.UsageScopeMismatch = idx.DiskTotal > 0 && idx.UsedAsIndexed > idx.DiskTotal
reducedIdx.Scanners = scannerInfos
reducedIdx.NumDirs = idx.getNumDirsUnlocked()
+15 -3
View File
@@ -24,6 +24,11 @@ import (
"github.com/gtsteffaniak/go-logger/logger"
)
const (
defaultMinSearchLength = 3
defaultFrontendDescription = "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server"
)
var Config Settings
const (
@@ -279,7 +284,7 @@ func setupFrontend(generate bool) {
// Load login icon configuration at startup
loadLoginIcon()
if Config.Server.MinSearchLength == 0 {
Config.Server.MinSearchLength = 3
Config.Server.MinSearchLength = defaultMinSearchLength
}
if !Config.Frontend.DisableDefaultLinks {
Config.Frontend.ExternalLinks = append(Config.Frontend.ExternalLinks, ExternalLink{
@@ -293,7 +298,7 @@ func setupFrontend(generate bool) {
})
}
if Config.Frontend.Description == "" {
Config.Frontend.Description = "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server"
Config.Frontend.Description = defaultFrontendDescription
}
Config.Frontend.Styling.LightBackground = FallbackColor(Config.Frontend.Styling.LightBackground, "#f5f5f5")
Config.Frontend.Styling.DarkBackground = FallbackColor(Config.Frontend.Styling.DarkBackground, "#141D24")
@@ -643,6 +648,10 @@ func loadConfigWithDefaults(configFile string, generate bool) error {
return fmt.Errorf("error parsing YAML data: %v", err)
}
// Expand $VAR / ${VAR} in decoded string scalars only (after parse) so
// secrets may contain quotes, backslashes, or newlines safely.
expandConfigEnv(rawConfig)
// Filter to only keep valid top-level Settings struct fields
// This removes anchor definitions that are just templates (e.g., "test_server: &test_server")
validFields := map[string]bool{
@@ -850,6 +859,7 @@ func SetDefaults(generate bool) Settings {
BaseURL: "",
},
Server: Server{
MinSearchLength: defaultMinSearchLength,
NumImageProcessors: 4,
DatabaseV2: Database{
Path: databaseV2,
@@ -887,7 +897,8 @@ func SetDefaults(generate bool) Settings {
},
},
Frontend: Frontend{
Name: "FileBrowser Quantum",
Name: "FileBrowser Quantum",
Description: defaultFrontendDescription,
},
UserDefaults: UserDefaults{
// New organized structure
@@ -954,6 +965,7 @@ func SetDefaults(generate bool) Settings {
Realtime: false,
},
LockPassword: false,
RequirePasswordChange: false,
DisableSettings: false,
LoginMethod: "",
DisableUpdateNotifications: false,
+106
View File
@@ -0,0 +1,106 @@
package settings
import (
"os"
"strconv"
"strings"
)
// expandConfigEnv walks a decoded YAML value tree and substitutes $VAR / ${VAR}
// in string scalars using the process environment. Non-string scalars (numbers,
// booleans, null) are left unchanged so typed config fields stay intact.
// Expansion happens after YAML decode so secrets may contain quotes, backslashes,
// or newlines without breaking the document.
// Maps and slices are mutated in place.
func expandConfigEnv(v interface{}) {
switch x := v.(type) {
case map[string]interface{}:
for k, val := range x {
x[k] = expandConfigEnvValue(val)
}
case []interface{}:
for i, val := range x {
x[i] = expandConfigEnvValue(val)
}
}
}
func expandConfigEnvValue(v interface{}) interface{} {
switch x := v.(type) {
case map[string]interface{}:
expandConfigEnv(x)
return x
case []interface{}:
expandConfigEnv(x)
return x
case string:
return expandConfigEnvString(x)
default:
// int, float, bool, nil, etc.
return v
}
}
// expandConfigEnvString expands environment references in a YAML string scalar.
// When the entire scalar is a single ${VAR} or $VAR reference, the expanded
// value is coerced to bool/int/float when unambiguous so config fields of those
// types keep working (e.g. port: ${PORT}). Partial expansions and ordinary
// strings always remain strings so secrets like "true" or "123" stay safe.
func expandConfigEnvString(s string) interface{} {
if !strings.ContainsAny(s, "$") {
return s
}
expanded := os.ExpandEnv(s)
if isSingleEnvReference(s) {
if coerced, ok := coerceEnvScalar(expanded); ok {
return coerced
}
}
return expanded
}
func isSingleEnvReference(s string) bool {
s = strings.TrimSpace(s)
if strings.HasPrefix(s, "${") && strings.HasSuffix(s, "}") {
inner := s[2 : len(s)-1]
return isEnvName(inner)
}
if strings.HasPrefix(s, "$") && !strings.HasPrefix(s, "${") {
return isEnvName(s[1:])
}
return false
}
func isEnvName(name string) bool {
if name == "" {
return false
}
for i, r := range name {
if i == 0 {
if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && r != '_' {
return false
}
continue
}
if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
return false
}
}
return true
}
func coerceEnvScalar(s string) (interface{}, bool) {
switch s {
case "true", "True", "TRUE":
return true, true
case "false", "False", "FALSE":
return false, true
}
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
return i, true
}
if f, err := strconv.ParseFloat(s, 64); err == nil {
return f, true
}
return nil, false
}
+184
View File
@@ -0,0 +1,184 @@
package settings
import (
"os"
"path/filepath"
"testing"
)
func TestExpandConfigEnvStrings(t *testing.T) {
t.Setenv("TEST_EXPAND_ENV_VAR", "from-env")
in := map[string]interface{}{
"password": "${TEST_EXPAND_ENV_VAR}",
"plain": "no-expansion",
"nested": map[string]interface{}{
"value": "$TEST_EXPAND_ENV_VAR",
},
"list": []interface{}{"${TEST_EXPAND_ENV_VAR}", "keep"},
"port": 8080,
"on": true,
}
expandConfigEnv(in)
if in["password"] != "from-env" {
t.Fatalf("password = %#v, want from-env", in["password"])
}
if in["plain"] != "no-expansion" {
t.Fatalf("plain = %#v", in["plain"])
}
nested, ok := in["nested"].(map[string]interface{})
if !ok {
t.Fatalf("nested = %#v, want map", in["nested"])
}
if nested["value"] != "from-env" {
t.Fatalf("nested.value = %#v", nested["value"])
}
list, ok := in["list"].([]interface{})
if !ok {
t.Fatalf("list = %#v, want slice", in["list"])
}
if list[0] != "from-env" || list[1] != "keep" {
t.Fatalf("list = %#v", list)
}
if in["port"] != 8080 {
t.Fatalf("port = %#v, want typed int 8080", in["port"])
}
if in["on"] != true {
t.Fatalf("on = %#v, want typed bool true", in["on"])
}
}
func TestExpandConfigEnvCoercesWholeReference(t *testing.T) {
t.Setenv("TEST_ENV_PORT", "9090")
t.Setenv("TEST_ENV_FLAG", "true")
t.Setenv("TEST_ENV_FLOAT", "1.5")
in := map[string]interface{}{
"port": "${TEST_ENV_PORT}",
"flag": "${TEST_ENV_FLAG}",
"rate": "${TEST_ENV_FLOAT}",
// Partial expansion must stay a string (and not coerce "true"-like secrets).
"msg": "prefix-${TEST_ENV_FLAG}",
}
expandConfigEnv(in)
if in["port"] != int64(9090) {
t.Fatalf("port = %#v (%T), want int64 9090", in["port"], in["port"])
}
if in["flag"] != true {
t.Fatalf("flag = %#v, want bool true", in["flag"])
}
if in["rate"] != 1.5 {
t.Fatalf("rate = %#v, want float64 1.5", in["rate"])
}
if in["msg"] != "prefix-true" {
t.Fatalf("msg = %#v, want string prefix-true", in["msg"])
}
}
func TestConfigLoadYamlEnvSubstitution(t *testing.T) {
testDir := t.TempDir()
const secret = "ldap-bind-secret"
t.Setenv("FILEBROWSER_LDAP_USER_PASSWORD", secret)
configContent := []byte(`
auth:
methods:
ldap:
enabled: true
server: "ldap://ldap.example.com:389"
baseDN: "dc=example,dc=com"
userDN: "cn=admin,dc=example,dc=com"
userPassword: "${FILEBROWSER_LDAP_USER_PASSWORD}"
server:
sources:
- path: "."
`)
configFile := filepath.Join(testDir, "config.yaml")
if err := os.WriteFile(configFile, configContent, 0644); err != nil {
t.Fatalf("failed to write test config: %v", err)
}
if err := loadConfigWithDefaults(configFile, true); err != nil {
t.Fatalf("loadConfigWithDefaults: %v", err)
}
if Config.Auth.Methods.LdapAuth.UserPassword != secret {
t.Fatalf("userPassword = %q, want %q", Config.Auth.Methods.LdapAuth.UserPassword, secret)
}
}
func TestConfigLoadYamlEnvSpecialCharacters(t *testing.T) {
tests := []struct {
name string
secret string
}{
{name: "quotes", secret: `p@ss"word'with"quotes`},
{name: "backslashes", secret: `path\to\secret\and\\more`},
{name: "multiline", secret: "line1\nline2\nline3"},
{name: "yaml_special", secret: `a: b # not yaml : [true]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testDir := t.TempDir()
t.Setenv("FILEBROWSER_LDAP_USER_PASSWORD", tt.secret)
configContent := []byte(`
auth:
methods:
ldap:
enabled: true
server: "ldap://ldap.example.com:389"
baseDN: "dc=example,dc=com"
userDN: "cn=admin,dc=example,dc=com"
userPassword: "${FILEBROWSER_LDAP_USER_PASSWORD}"
server:
sources:
- path: "."
`)
configFile := filepath.Join(testDir, "config.yaml")
if err := os.WriteFile(configFile, configContent, 0644); err != nil {
t.Fatalf("failed to write test config: %v", err)
}
if err := loadConfigWithDefaults(configFile, true); err != nil {
t.Fatalf("loadConfigWithDefaults: %v", err)
}
if Config.Auth.Methods.LdapAuth.UserPassword != tt.secret {
t.Fatalf("userPassword = %q, want %q", Config.Auth.Methods.LdapAuth.UserPassword, tt.secret)
}
})
}
}
func TestConfigLoadYamlEnvPreservesTypedScalars(t *testing.T) {
testDir := t.TempDir()
t.Setenv("TEST_HTTP_PORT", "8443")
t.Setenv("TEST_TRUST_PROXY", "true")
configContent := []byte(`
http:
port: ${TEST_HTTP_PORT}
trustProxyHeaders: ${TEST_TRUST_PROXY}
auth:
methods:
password:
enabled: true
server:
sources:
- path: "."
`)
configFile := filepath.Join(testDir, "config.yaml")
if err := os.WriteFile(configFile, configContent, 0644); err != nil {
t.Fatalf("failed to write test config: %v", err)
}
if err := loadConfigWithDefaults(configFile, true); err != nil {
t.Fatalf("loadConfigWithDefaults: %v", err)
}
if Config.Http.Port != 8443 {
t.Fatalf("http.port = %d, want 8443", Config.Http.Port)
}
if !Config.Http.TrustProxyHeaders {
t.Fatal("expected http.trustProxyHeaders to be true")
}
}
+17 -1
View File
@@ -15,6 +15,22 @@ var AuthManagedEnforcementPaths = map[string]struct{}{
"account.permissions.admin": {},
}
// TransientAccountEnforcementPaths are enforced defaults that seed account state but must not
// block updates when the user satisfies a one-time requirement (e.g. clearing requirePasswordChange).
var TransientAccountEnforcementPaths = map[string]struct{}{
"account.requirePasswordChange": {},
}
func enforcementPathExcludedFromUserSync(path string) bool {
if _, ok := AuthManagedEnforcementPaths[path]; ok {
return true
}
if _, ok := TransientAccountEnforcementPaths[path]; ok {
return true
}
return false
}
// EnforcementAppliesToUser reports whether user-default enforcement should affect u.
// Admins are exempt; anonymous and nil users are not subject to enforcement.
func EnforcementAppliesToUser(u *users.User) bool {
@@ -30,7 +46,7 @@ func withoutAuthManagedEnforcementPaths(paths map[string]struct{}) map[string]st
}
out := make(map[string]struct{}, len(paths))
for path := range paths {
if _, authManaged := AuthManagedEnforcementPaths[path]; authManaged {
if enforcementPathExcludedFromUserSync(path) {
continue
}
out[path] = struct{}{}
@@ -83,6 +83,39 @@ func TestValidateUserAgainstEnforcedDefaults_skipsAdmin(t *testing.T) {
}
}
func TestValidateUserAgainstEnforcedDefaults_skipsRequirePasswordChange(t *testing.T) {
u := &users.User{
FrontendUser: users.FrontendUser{
Username: "alice",
RequirePasswordChange: false,
},
}
defaults := UserDefaults{Account: UserDefaultsAccount{RequirePasswordChange: true}}
enforced := UserDefaultsEnforcement{
Account: UserDefaultsAccountEnforcement{RequirePasswordChange: true},
}
if err := ValidateUserAgainstEnforcedDefaults(u, defaults, enforced); err != nil {
t.Fatalf("cleared requirePasswordChange should not fail enforced validation: %v", err)
}
}
func TestApplyEnforcedDefaultsFrom_skipsRequirePasswordChange(t *testing.T) {
u := &users.User{
FrontendUser: users.FrontendUser{
Username: "alice",
RequirePasswordChange: false,
},
}
defaults := UserDefaults{Account: UserDefaultsAccount{RequirePasswordChange: true}}
enforced := UserDefaultsEnforcement{
Account: UserDefaultsAccountEnforcement{RequirePasswordChange: true},
}
ApplyEnforcedDefaultsFrom(u, defaults, enforced)
if u.RequirePasswordChange {
t.Fatal("expected requirePasswordChange not re-applied after user cleared it")
}
}
func TestApplyEnforcedDefaultsFrom_onlyEnforcedSubset(t *testing.T) {
u := &users.User{
FrontendUser: users.FrontendUser{
@@ -75,6 +75,7 @@ type UserDefaultsFileLoadingEnforcement struct {
type UserDefaultsAccountEnforcement struct {
LockPassword bool `json:"lockPassword,omitempty"`
RequirePasswordChange bool `json:"requirePasswordChange,omitempty"`
DisableSettings bool `json:"disableSettings,omitempty"`
DisableUpdateNotifications bool `json:"disableUpdateNotifications,omitempty"`
Permissions UserDefaultsAccountPermissionsEnforcement `json:"permissions,omitempty"`
+58 -19
View File
@@ -571,6 +571,18 @@ func BuildNode(v reflect.Value, comm CommentsMap) (*yaml.Node, error) {
return buildNodeWithDefaults(v, comm, reflect.Value{}, SecretFieldsMap{}, DeprecatedFieldsMap{})
}
func conditionalRulesAreUnset(rules []ConditionalRule) bool {
if len(rules) == 0 {
return true
}
for _, rule := range rules {
if rule != (ConditionalRule{}) {
return false
}
}
return true
}
// buildNodeWithDefaults constructs a yaml.Node for any Go value, skipping fields that match defaults, redacting secrets, and filtering deprecated fields
func buildNodeWithDefaults(v reflect.Value, comm CommentsMap, defaults reflect.Value, secrets SecretFieldsMap, deprecated DeprecatedFieldsMap) (*yaml.Node, error) {
// Dereference pointers
@@ -619,6 +631,18 @@ func buildNodeWithDefaults(v reflect.Value, comm CommentsMap, defaults reflect.V
currentField := v.Field(i)
// Unset source display names are derived at startup; omit from minimal YAML export.
if defaults.IsValid() && typeName == "Source" && sf.Name == "Name" && currentField.Kind() == reflect.String && currentField.String() == "" {
continue
}
// Empty conditional rules are omitted from minimal YAML (template may include a sample row).
if defaults.IsValid() && typeName == "SourceConfig" && sf.Name == "Rules" {
if rules, ok := currentField.Interface().([]ConditionalRule); ok && conditionalRulesAreUnset(rules) {
continue
}
}
// Check if this is an inline/embedded field
yamlTag := sf.Tag.Get("yaml")
jsonTag := sf.Tag.Get("json")
@@ -957,8 +981,32 @@ func GenerateYaml() {
fmt.Printf("Generated YAML with comments (deprecated fields filtered): %s\n", output)
}
// finalizeSecretFields returns secret field metadata for YAML redaction.
// With no overrides, collected metadata is used (with reflection fallback). Pass nil to disable redaction.
func finalizeSecretFields(collected SecretFieldsMap, config *Settings, secretFields ...SecretFieldsMap) SecretFieldsMap {
if len(secretFields) > 0 {
return secretFields[0]
}
secrets := collected
secretsEmpty := true
for typeName := range secrets {
if len(secrets[typeName]) > 0 {
secretsEmpty = false
break
}
}
if secretsEmpty {
if secrets == nil {
secrets = make(SecretFieldsMap)
}
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
}
return secrets
}
// GenerateConfigYaml generates YAML from a given config with options for comments and filtering
func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filterDeprecated bool) (string, error) {
func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filterDeprecated bool, secretFields ...SecretFieldsMap) (string, error) {
// Try different source paths to handle both runtime and test scenarios
sourcePaths := []string{
".", // When running tests from settings directory
@@ -967,7 +1015,7 @@ func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filt
}
for _, sourcePath := range sourcePaths {
yamlOutput, err := GenerateConfigYamlWithSource(config, showComments, showFull, filterDeprecated, sourcePath)
yamlOutput, err := GenerateConfigYamlWithSource(config, showComments, showFull, filterDeprecated, sourcePath, secretFields...)
if err == nil {
return yamlOutput, nil
}
@@ -978,11 +1026,11 @@ func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filt
}
// If all paths failed, try with empty maps to at least generate basic YAML
return GenerateConfigYamlWithEmptyMaps(config, showFull)
return GenerateConfigYamlWithEmptyMaps(config, showFull, secretFields...)
}
// GenerateConfigYamlWithEmbedded generates YAML from a given config using embedded YAML content as comment source
func GenerateConfigYamlWithEmbedded(config *Settings, showComments bool, showFull bool, filterDeprecated bool, embeddedYaml string) (string, error) {
func GenerateConfigYamlWithEmbedded(config *Settings, showComments bool, showFull bool, filterDeprecated bool, embeddedYaml string, secretFields ...SecretFieldsMap) (string, error) {
var comm CommentsMap
var secrets SecretFieldsMap
var deprecated DeprecatedFieldsMap
@@ -1011,6 +1059,8 @@ func GenerateConfigYamlWithEmbedded(config *Settings, showComments bool, showFul
deprecated = make(DeprecatedFieldsMap)
}
secrets = finalizeSecretFields(secrets, config, secretFields...)
var node *yaml.Node
if showFull {
@@ -1141,14 +1191,13 @@ func identifyDeprecatedFieldsByReflection(v reflect.Value, typeName string, depr
}
// GenerateConfigYamlWithEmptyMaps generates YAML without comment parsing when source files are unavailable
func GenerateConfigYamlWithEmptyMaps(config *Settings, showFull bool) (string, error) {
func GenerateConfigYamlWithEmptyMaps(config *Settings, showFull bool, secretFields ...SecretFieldsMap) (string, error) {
// Create empty maps
comm := make(CommentsMap)
secrets := make(SecretFieldsMap)
deprecated := make(DeprecatedFieldsMap)
// Identify secret fields by reflection since we can't parse source files
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
secrets = finalizeSecretFields(secrets, config, secretFields...)
var node *yaml.Node
var err error
@@ -1193,7 +1242,7 @@ func GenerateConfigYamlWithEmptyMaps(config *Settings, showFull bool) (string, e
}
// GenerateConfigYamlWithSource generates YAML from a given config with options for comments and filtering, using a custom source path
func GenerateConfigYamlWithSource(config *Settings, showComments bool, showFull bool, filterDeprecated bool, sourcePath string) (string, error) {
func GenerateConfigYamlWithSource(config *Settings, showComments bool, showFull bool, filterDeprecated bool, sourcePath string, secretFields ...SecretFieldsMap) (string, error) {
var comm CommentsMap
var secrets SecretFieldsMap
var deprecated DeprecatedFieldsMap
@@ -1215,17 +1264,7 @@ func GenerateConfigYamlWithSource(config *Settings, showComments bool, showFull
comm = make(CommentsMap)
}
// If secrets map is empty (directory parsing failed), use reflection to identify secrets
secretsEmpty := true
for typeName := range secrets {
if len(secrets[typeName]) > 0 {
secretsEmpty = false
break
}
}
if secretsEmpty {
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
}
secrets = finalizeSecretFields(secrets, config, secretFields...)
// If deprecated map is empty (directory parsing failed), use reflection to identify deprecated fields
deprecatedEmpty := true
+48
View File
@@ -493,3 +493,51 @@ func TestGenerateConfigYaml_defaultPermissionsDocumentsView(t *testing.T) {
t.Fatalf("expected defaultPermissions to include view, got excerpt around block")
}
}
func TestGenerateConfigYaml_OmitsEmptyRulesWhenFiltered(t *testing.T) {
t.Chdir(".")
cfg := SetDefaults(true)
cfg.Server.Sources = []*Source{{
Path: "./",
Config: SourceConfig{
DefaultPermissions: BuiltinDefaultSourceFilePermissions(),
},
}}
cfg.Server.DatabaseV2.Path = "./filebrowser.sqlite"
cfg.Server.Logging = []LogConfig{{Output: "stdout", Levels: "info|warning|error"}}
out, err := GenerateConfigYamlWithSource(&cfg, true, false, false, ".")
if err != nil {
t.Fatal(err)
}
if strings.Contains(out, "rules:") {
t.Fatalf("expected empty rules to be omitted from filtered YAML, got:\n%s", out)
}
}
func TestGenerateSetupConfigYaml_IncludesSecretValues(t *testing.T) {
cfg := SetDefaults(false)
cfg.Server.Sources = []*Source{{Path: "./"}}
cfg.Auth.AdminUsername = "setup-admin"
cfg.Auth.AdminPassword = "setup-pass"
out, err := GenerateConfigYaml(&cfg, true, false, false, nil)
if err != nil {
t.Fatal(err)
}
if strings.Contains(out, "**hidden**") {
t.Fatalf("expected setup YAML to include secret values, got:\n%s", out)
}
if !strings.Contains(out, "setup-admin") || !strings.Contains(out, "setup-pass") {
t.Fatalf("expected admin credentials in setup YAML, got:\n%s", out)
}
hidden, err := GenerateConfigYaml(&cfg, true, false, false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(hidden, "**hidden**") {
t.Fatal("expected secrets to be redacted in default config YAML export")
}
}
+21
View File
@@ -0,0 +1,21 @@
package settings
import "fmt"
// PasswordMinLength returns the configured minimum password length (default 5).
func PasswordMinLength() int {
n := Config.Auth.Methods.PasswordAuth.MinLength
if n < 1 {
return 5
}
return n
}
// ValidatePasswordPolicy checks plaintext passwords against server auth.password settings.
func ValidatePasswordPolicy(password string) error {
min := PasswordMinLength()
if len(password) < min {
return fmt.Errorf("password must be at least %d characters", min)
}
return nil
}
@@ -0,0 +1,24 @@
package settings
import "testing"
func TestValidatePasswordPolicy(t *testing.T) {
orig := Config.Auth.Methods.PasswordAuth.MinLength
defer func() { Config.Auth.Methods.PasswordAuth.MinLength = orig }()
Config.Auth.Methods.PasswordAuth.MinLength = 8
if err := ValidatePasswordPolicy("short"); err == nil {
t.Fatal("expected error for short password")
}
if err := ValidatePasswordPolicy("longenough"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
Config.Auth.Methods.PasswordAuth.MinLength = 0
if PasswordMinLength() != 5 {
t.Fatalf("default min length = %d, want 5", PasswordMinLength())
}
if err := ValidatePasswordPolicy("1234"); err == nil {
t.Fatal("expected default min length 5 to reject 4 chars")
}
}
+1
View File
@@ -402,6 +402,7 @@ type UserDefaultsUI struct {
type UserDefaultsAccount struct {
Permissions UserDefaultsAccountPermissions `json:"permissions"`
LockPassword bool `json:"lockPassword"` // disable the user from changing their password
RequirePasswordChange bool `json:"requirePasswordChange"` // force password change at next password login
DisableSettings bool `json:"disableSettings"` // disable the user from viewing the settings page
LoginMethod string `json:"loginMethod,omitempty"` // login method to use: eg. password, proxy, oidc
DisableUpdateNotifications bool `json:"disableUpdateNotifications"` // disable update notifications banner for admin users
@@ -64,6 +64,7 @@ func ProfileFromUser(u *users.User) UserProfile {
FileLoading: u.FileLoading,
Account: UserDefaultsAccount{
LockPassword: u.LockPassword,
RequirePasswordChange: u.RequirePasswordChange,
DisableSettings: u.DisableSettings,
DisableUpdateNotifications: u.DisableUpdateNotifications,
Permissions: UserDefaultsAccountPermissions{
@@ -83,6 +84,7 @@ func ExpandProfileIntoUser(u *users.User, p UserProfile) {
}
u.DisableSettings = p.Account.DisableSettings
u.LockPassword = p.Account.LockPassword
u.RequirePasswordChange = p.Account.RequirePasswordChange
u.DisableUpdateNotifications = p.Account.DisableUpdateNotifications
u.Permissions.Api = p.Account.Permissions.Api
u.Permissions.Admin = p.Account.Permissions.Admin
+14 -2
View File
@@ -1,6 +1,7 @@
package settings
import (
"path"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
@@ -22,12 +23,23 @@ func ExpandBackendScopesForCreateUserDir(u *users.User) {
if !ok {
continue
}
if source.Config.CreateUserDir && scopeBaseName(scope.Scope) != cleanedUserName {
u.BackendScopes[i].Scope = joinUnixScopePath(scope.Scope, cleanedUserName)
if !source.Config.CreateUserDir {
continue
}
// This runs more than once for a new user, so a scope that already ends in the user's
// directory is left alone. The source's defaultUserScope itself is not a user's home:
// a user named after its last element ("users" with "/users") gets "/users/users".
if scopeBaseName(scope.Scope) == cleanedUserName && !sameScopePath(scope.Scope, source.Config.DefaultUserScope) {
continue
}
u.BackendScopes[i].Scope = joinUnixScopePath(scope.Scope, cleanedUserName)
}
}
func sameScopePath(a, b string) bool {
return path.Clean("/"+a) == path.Clean("/"+b)
}
func scopeBaseName(scope string) string {
scope = strings.TrimSuffix(scope, "/")
if scope == "" || scope == "/" {
+36
View File
@@ -0,0 +1,36 @@
package settings
import (
"testing"
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
)
func TestExpandBackendScopesForCreateUserDirNeverKeepsDefaultScope(t *testing.T) {
saved := Config
defer func() { Config = saved }()
Config = Settings{Server: Server{SourceMap: map[string]*Source{
"/srv": {Path: "/srv", Name: "main", Config: SourceConfig{CreateUserDir: true, DefaultUserScope: "/users"}},
}}}
cases := map[string]string{"bob": "/users/bob", "users": "/users/users", "first.last": "/users/first.last"}
for name, want := range cases {
u := &users.User{
FrontendUser: users.FrontendUser{Username: name},
BackendScopes: []users.BackendScope{{Path: "/srv", Scope: "/users"}},
}
ExpandBackendScopesForCreateUserDir(u)
ExpandBackendScopesForCreateUserDir(u) // runs more than once per new user; must be idempotent
if got := u.BackendScopes[0].Scope; got != want {
t.Fatalf("%s: scope=%q want %q", name, got, want)
}
}
// An admin-assigned scope that already ends in the username is kept.
u := &users.User{
FrontendUser: users.FrontendUser{Username: "bob"},
BackendScopes: []users.BackendScope{{Path: "/srv", Scope: "/users/bob"}},
}
ExpandBackendScopesForCreateUserDir(u)
if got := u.BackendScopes[0].Scope; got != "/users/bob" {
t.Fatalf("explicit scope changed: %q", got)
}
}
+115
View File
@@ -770,6 +770,87 @@ const docTemplate = `{
]
}
},
"/api/auth/password/change-required": {
"post": {
"description": "Verifies the current password and sets a new password when requirePasswordChange is set. Issues a JWT on success.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Auth"
],
"summary": "Change required password at login",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded current password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code (if 2FA is enabled)",
"name": "X-Secret",
"in": "header"
},
{
"description": "New password and confirmation",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/web.changeRequiredPasswordBody"
}
}
],
"responses": {
"200": {
"description": "JWT token for authentication",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"401": {
"description": "Unauthorized",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/auth/renew": {
"post": {
"description": "Refresh the authentication token for a logged-in user.",
@@ -799,6 +880,15 @@ const docTemplate = `{
}
}
},
"403": {
"description": "Forbidden - non-session token",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
@@ -6480,6 +6570,10 @@ const docTemplate = `{
},
"permissions": {
"$ref": "#/definitions/settings.UserDefaultsAccountPermissions"
},
"requirePasswordChange": {
"description": "force password change at next password login",
"type": "boolean"
}
}
},
@@ -7201,6 +7295,10 @@ const docTemplate = `{
"description": "for backward compatibility",
"type": "string"
},
"minimal": {
"description": "Minimal distinguishes owner-inheriting tokens from customized caps. Nil means legacy (infer from stored permissions).",
"type": "boolean"
},
"name": {
"type": "string"
},
@@ -7391,6 +7489,9 @@ const docTemplate = `{
"description": "show icon to download in one click",
"type": "boolean"
},
"requirePasswordChange": {
"type": "boolean"
},
"scopes": {
"type": "array",
"items": {
@@ -7785,6 +7886,9 @@ const docTemplate = `{
"description": "show icon to download in one click",
"type": "boolean"
},
"requirePasswordChange": {
"type": "boolean"
},
"scopes": {
"type": "array",
"items": {
@@ -8164,6 +8268,17 @@ const docTemplate = `{
}
}
},
"web.changeRequiredPasswordBody": {
"type": "object",
"properties": {
"password": {
"type": "string"
},
"passwordConfirm": {
"type": "string"
}
}
},
"web.duplicateGroup": {
"type": "object",
"properties": {
+115
View File
@@ -759,6 +759,87 @@
]
}
},
"/api/auth/password/change-required": {
"post": {
"description": "Verifies the current password and sets a new password when requirePasswordChange is set. Issues a JWT on success.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Auth"
],
"summary": "Change required password at login",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded current password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code (if 2FA is enabled)",
"name": "X-Secret",
"in": "header"
},
{
"description": "New password and confirmation",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/web.changeRequiredPasswordBody"
}
}
],
"responses": {
"200": {
"description": "JWT token for authentication",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"401": {
"description": "Unauthorized",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/auth/renew": {
"post": {
"description": "Refresh the authentication token for a logged-in user.",
@@ -788,6 +869,15 @@
}
}
},
"403": {
"description": "Forbidden - non-session token",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
@@ -6469,6 +6559,10 @@
},
"permissions": {
"$ref": "#/definitions/settings.UserDefaultsAccountPermissions"
},
"requirePasswordChange": {
"description": "force password change at next password login",
"type": "boolean"
}
}
},
@@ -7190,6 +7284,10 @@
"description": "for backward compatibility",
"type": "string"
},
"minimal": {
"description": "Minimal distinguishes owner-inheriting tokens from customized caps. Nil means legacy (infer from stored permissions).",
"type": "boolean"
},
"name": {
"type": "string"
},
@@ -7380,6 +7478,9 @@
"description": "show icon to download in one click",
"type": "boolean"
},
"requirePasswordChange": {
"type": "boolean"
},
"scopes": {
"type": "array",
"items": {
@@ -7774,6 +7875,9 @@
"description": "show icon to download in one click",
"type": "boolean"
},
"requirePasswordChange": {
"type": "boolean"
},
"scopes": {
"type": "array",
"items": {
@@ -8153,6 +8257,17 @@
}
}
},
"web.changeRequiredPasswordBody": {
"type": "object",
"properties": {
"password": {
"type": "string"
},
"passwordConfirm": {
"type": "string"
}
}
},
"web.duplicateGroup": {
"type": "object",
"properties": {
+79
View File
@@ -1017,6 +1017,9 @@ definitions:
type: string
permissions:
$ref: '#/definitions/settings.UserDefaultsAccountPermissions'
requirePasswordChange:
description: force password change at next password login
type: boolean
type: object
settings.UserDefaultsAccountPermissions:
properties:
@@ -1519,6 +1522,10 @@ definitions:
key:
description: for backward compatibility
type: string
minimal:
description: Minimal distinguishes owner-inheriting tokens from customized
caps. Nil means legacy (infer from stored permissions).
type: boolean
name:
type: string
token:
@@ -1653,6 +1660,8 @@ definitions:
quickDownload:
description: show icon to download in one click
type: boolean
requirePasswordChange:
type: boolean
scopes:
items:
$ref: '#/definitions/users.FrontendScope'
@@ -1943,6 +1952,8 @@ definitions:
quickDownload:
description: show icon to download in one click
type: boolean
requirePasswordChange:
type: boolean
scopes:
items:
$ref: '#/definitions/users.FrontendScope'
@@ -2212,6 +2223,13 @@ definitions:
default: fromSource). Example: "backups"'
type: string
type: object
web.changeRequiredPasswordBody:
properties:
password:
type: string
passwordConfirm:
type: string
type: object
web.duplicateGroup:
properties:
count:
@@ -2832,6 +2850,61 @@ paths:
summary: Verify OTP
tags:
- Auth
/api/auth/password/change-required:
post:
consumes:
- application/json
description: Verifies the current password and sets a new password when requirePasswordChange
is set. Issues a JWT on success.
parameters:
- description: Username
in: query
name: username
required: true
type: string
- description: URL-encoded current password
in: header
name: X-Password
required: true
type: string
- description: TOTP code (if 2FA is enabled)
in: header
name: X-Secret
type: string
- description: New password and confirmation
in: body
name: body
required: true
schema:
$ref: '#/definitions/web.changeRequiredPasswordBody'
produces:
- application/json
responses:
"200":
description: JWT token for authentication
schema:
type: string
"400":
description: Bad request
schema:
additionalProperties:
type: string
type: object
"401":
description: Unauthorized
schema:
additionalProperties:
type: string
type: object
"403":
description: Forbidden
schema:
additionalProperties:
type: string
type: object
summary: Change required password at login
tags:
- Auth
/api/auth/renew:
post:
consumes:
@@ -2850,6 +2923,12 @@ paths:
additionalProperties:
type: string
type: object
"403":
description: Forbidden - non-session token
schema:
additionalProperties:
type: string
type: object
"500":
description: Internal server error
schema:
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more